diff --git a/Cargo.lock b/Cargo.lock index f70b6c1b..f53e31a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,16 +2,75 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "bytemuck" version = "1.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "ec-ac3" +version = "0.1.0" +dependencies = [ + "ec-core", + "ec-dsp", +] + +[[package]] +name = "ec-ass" +version = "0.1.0" +dependencies = [ + "ec-core", + "ec-subs", +] + +[[package]] +name = "ec-av1-syntax" +version = "0.1.0" +dependencies = [ + "ec-core", +] + [[package]] name = "ec-core" version = "0.1.0" +[[package]] +name = "ec-dsp" +version = "0.1.0" +dependencies = [ + "ec-core", + "wide", +] + +[[package]] +name = "ec-flac" +version = "0.1.0" +dependencies = [ + "ec-core", +] + [[package]] name = "ec-h264" version = "0.1.0" @@ -28,10 +87,209 @@ dependencies = [ "ec-core", ] +[[package]] +name = "ec-inflate" +version = "0.1.0" +dependencies = [ + "ec-core", + "flate2", +] + +[[package]] +name = "ec-matroska" +version = "0.1.0" +dependencies = [ + "ec-core", + "ec-inflate", +] + +[[package]] +name = "ec-mp3" +version = "0.1.0" +dependencies = [ + "ec-core", + "ec-dsp", +] + +[[package]] +name = "ec-mp4" +version = "0.1.0" +dependencies = [ + "ec-core", +] + +[[package]] +name = "ec-ogg" +version = "0.1.0" +dependencies = [ + "ec-core", +] + +[[package]] +name = "ec-opus" +version = "0.1.0" +dependencies = [ + "ec-core", + "ec-dsp", + "ec-ogg", + "wide", +] + +[[package]] +name = "ec-pgs" +version = "0.1.0" +dependencies = [ + "ec-core", +] + +[[package]] +name = "ec-riff" +version = "0.1.0" +dependencies = [ + "ec-core", +] + +[[package]] +name = "ec-subs" +version = "0.1.0" +dependencies = [ + "ec-ass", + "ec-core", + "ec-pgs", +] + +[[package]] +name = "ec-va" +version = "0.1.0" + +[[package]] +name = "ec-vorbis" +version = "0.1.0" +dependencies = [ + "ec-core", + "ec-dsp", + "ec-ogg", +] + +[[package]] +name = "ec-vp9-syntax" +version = "0.1.0" +dependencies = [ + "ec-core", +] + +[[package]] +name = "flacenc" +version = "0.5.1" +dependencies = [ + "ec-flac", +] + +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "crc32fast", + "miniz_oxide 0.8.9 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "hound" +version = "3.5.1" +dependencies = [ + "ec-riff", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +dependencies = [ + "ec-inflate", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "opus-rs" +version = "0.1.26" +dependencies = [ + "ec-opus", +] + [[package]] name = "oracle" version = "0.1.0" +[[package]] +name = "oxideav-ass" +version = "0.0.9" +dependencies = [ + "ec-ass", + "ec-subs", + "oxideav-core", +] + +[[package]] +name = "oxideav-core" +version = "0.1.34" +dependencies = [ + "ec-core", +] + +[[package]] +name = "oxideav-ogg" +version = "0.1.8" +dependencies = [ + "ec-core", + "ec-ogg", + "oxideav-core", +] + +[[package]] +name = "oxideav-sub-image" +version = "0.0.7" +dependencies = [ + "ec-pgs", + "oxideav-ass", + "oxideav-core", + "oxideav-subtitle", +] + +[[package]] +name = "oxideav-subtitle" +version = "0.1.2" +dependencies = [ + "ec-subs", + "oxideav-core", +] + +[[package]] +name = "rusty_mp3" +version = "0.6.1" +dependencies = [ + "ec-core", + "ec-mp3", +] + +[[package]] +name = "rusty_vorbis" +version = "0.1.1" +dependencies = [ + "ec-core", + "ec-ogg", + "ec-vorbis", +] + [[package]] name = "safe_arch" version = "1.1.0" @@ -41,6 +299,12 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "wide" version = "1.6.1" diff --git a/crates/ec-opus/Cargo.toml b/crates/ec-opus/Cargo.toml index c6b36b12..6d68c1a2 100644 --- a/crates/ec-opus/Cargo.toml +++ b/crates/ec-opus/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ec-opus" -description = "Opus decoder (RFC 6716): SILK, CELT, hybrid and multistream, built on the edith_codecs IR." +description = "Opus codec (RFC 6716): SILK+CELT+hybrid+multistream decoder and CELT fullband encoder (mono, stereo, multistream), built on the edith_codecs IR." version.workspace = true edition.workspace = true license.workspace = true @@ -9,6 +9,8 @@ authors.workspace = true [dependencies] ec-core.workspace = true ec-dsp.workspace = true +wide.workspace = true [dev-dependencies] ec-dsp.workspace = true +ec-ogg.workspace = true diff --git a/crates/ec-opus/src/celt.rs b/crates/ec-opus/src/celt.rs index a54bc11d..0f99a30a 100644 --- a/crates/ec-opus/src/celt.rs +++ b/crates/ec-opus/src/celt.rs @@ -29,13 +29,13 @@ use crate::range::RangeDecoder; /// Bands in the 48 kHz mode. pub const NB_BANDS: usize = 21; /// Band boundaries in units of 2.5 ms MDCT bins (Table 55). -const E_BANDS: [usize; NB_BANDS + 1] = [ +pub(crate) const E_BANDS: [usize; NB_BANDS + 1] = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100, ]; /// MDCT bins in a 2.5 ms frame; the window overlap is the same length. -const SHORT_MDCT: usize = 120; +pub(crate) const SHORT_MDCT: usize = 120; /// Samples of overlap between consecutive frames. -const OVERLAP: usize = 120; +pub(crate) const OVERLAP: usize = 120; /// Longest post-filter period, and the history the comb filter needs. #[allow(dead_code)] const MAX_PERIOD: usize = 1024; @@ -44,26 +44,26 @@ const MIN_PERIOD: usize = 15; /// Synthesis history kept per channel. const DECODE_BUFFER: usize = 2048; /// Allocation resolution: 1/8 bit. -const BITRES: u32 = 3; +pub(crate) const BITRES: u32 = 3; /// Most fine-energy bits a band can get. -const MAX_FINE_BITS: i32 = 8; -const FINE_OFFSET: i32 = 21; -const QTHETA_OFFSET: i32 = 4; -const QTHETA_OFFSET_TWOPHASE: i32 = 16; +pub(crate) const MAX_FINE_BITS: i32 = 8; +pub(crate) const FINE_OFFSET: i32 = 21; +pub(crate) const QTHETA_OFFSET: i32 = 4; +pub(crate) const QTHETA_OFFSET_TWOPHASE: i32 = 16; /// `logN400`: `log2(N)` per band in 1/8 bits, for the fine-energy offset. -const LOG_N: [i32; NB_BANDS] = [ +pub(crate) const LOG_N: [i32; NB_BANDS] = [ 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36, ]; /// Mean energy per band, subtracted before quantisation (`eMeans`, in log2). -const E_MEANS: [f32; NB_BANDS] = [ +pub(crate) const E_MEANS: [f32; NB_BANDS] = [ 6.4375, 6.25, 5.75, 5.3125, 5.0625, 4.8125, 4.5, 4.375, 4.875, 4.6875, 4.5625, 4.4375, 4.875, 4.625, 4.3125, 4.5, 4.375, 4.625, 4.75, 4.4375, 3.75, ]; /// Static allocation table (Table 57), `[quality][band]`, 1/32 bit per bin. -const BAND_ALLOCATION: [[u8; NB_BANDS]; 11] = [ +pub(crate) const BAND_ALLOCATION: [[u8; NB_BANDS]; 11] = [ [0; NB_BANDS], [ 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, @@ -100,7 +100,7 @@ const BAND_ALLOCATION: [[u8; NB_BANDS]; 11] = [ ]; /// Laplace parameters for coarse energy, `[LM][intra][2*band]` (`e_prob_model`). -const E_PROB_MODEL: [[[u8; 42]; 2]; 4] = [ +pub(crate) const E_PROB_MODEL: [[[u8; 42]; 2]; 4] = [ [ [ 72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79, @@ -152,25 +152,25 @@ const E_PROB_MODEL: [[[u8; 42]; 2]; 4] = [ ]; /// Inter-frame prediction gain for coarse energy, per LM (`pred_coef`). -const PRED_COEF: [f32; 4] = [ +pub(crate) const PRED_COEF: [f32; 4] = [ 29440.0 / 32768.0, 26112.0 / 32768.0, 21248.0 / 32768.0, 16384.0 / 32768.0, ]; /// Intra-frame (across bands) prediction gain, per LM (`beta_coef`). -const BETA_COEF: [f32; 4] = [ +pub(crate) const BETA_COEF: [f32; 4] = [ 30147.0 / 32768.0, 22282.0 / 32768.0, 12124.0 / 32768.0, 6554.0 / 32768.0, ]; /// The same for an intra frame. -const BETA_INTRA: f32 = 4915.0 / 32768.0; +pub(crate) const BETA_INTRA: f32 = 4915.0 / 32768.0; /// TF resolution adjustment, `[LM][4*transient + 2*tf_select + tf_change]` /// (Tables 60-63). -const TF_SELECT: [[i32; 8]; 4] = [ +pub(crate) const TF_SELECT: [[i32; 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], @@ -178,7 +178,7 @@ const TF_SELECT: [[i32; 8]; 4] = [ ]; /// Conservative `log2` in 1/8 bits, used to reserve the intensity parameter. -const LOG2_FRAC: [i32; 24] = [ +pub(crate) const LOG2_FRAC: [i32; 24] = [ 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37, ]; @@ -193,7 +193,7 @@ const CACHE_INDEX: [i16; 105] = [ ]; /// Bits (minus one) to code `k` pulses in each band size (`cache_bits50`). -const CACHE_BITS: [u8; 392] = [ +pub(crate) const CACHE_BITS: [u8; 392] = [ 40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28, 31, 34, 36, 38, 39, 41, 42, 43, 44, 45, 46, 47, 47, 49, 50, 51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62, 63, 63, 65, 66, 67, 68, 69, 70, 71, @@ -216,7 +216,7 @@ const CACHE_BITS: [u8; 392] = [ ]; /// Per-band allocation ceiling, `[2*LM + stereo][band]` (`cache_caps50`). -const CACHE_CAPS: [u8; 168] = [ +pub(crate) const CACHE_CAPS: [u8; 168] = [ 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, 224, 224, 224, 224, 224, 224, 224, 224, 240, 240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, 160, 160, 160, 160, 160, 160, 160, 160, 185, 185, 185, 185, 193, 193, 193, @@ -236,10 +236,10 @@ const ORDERY: [usize; 30] = [ 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5, ]; -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]; +pub(crate) const TRIM_ICDF: [u8; 11] = [126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0]; +pub(crate) const SPREAD_ICDF: [u8; 4] = [25, 23, 2, 0]; const TAPSET_ICDF: [u8; 3] = [2, 1, 0]; -const SMALL_ENERGY_ICDF: [u8; 3] = [2, 1, 0]; +pub(crate) const SMALL_ENERGY_ICDF: [u8; 3] = [2, 1, 0]; /// Post-filter tap sets (Section 4.3.7.1). const POSTFILTER_GAINS: [[f32; 3]; 3] = [ @@ -249,17 +249,17 @@ const POSTFILTER_GAINS: [[f32; 3]; 3] = [ ]; /// De-emphasis coefficient, `1/(1 - 0.85 z^-1)` at 48 kHz. -const PREEMPH: f32 = 0.850_006_1; +pub(crate) const PREEMPH: f32 = 0.850_006_1; /// Internal signal scale; the output is divided by this. -const SIG_SCALE: f32 = 32768.0; +pub(crate) const SIG_SCALE: f32 = 32768.0; -const SPREAD_NONE: usize = 0; -const SPREAD_NORMAL: usize = 2; +pub(crate) const SPREAD_NONE: usize = 0; +pub(crate) const SPREAD_NORMAL: usize = 2; const SPREAD_AGGRESSIVE: usize = 3; /// `ilog(x)`: index of the highest set bit plus one. #[inline] -fn ilog(x: u32) -> i32 { +pub(crate) fn ilog(x: u32) -> i32 { (32 - x.leading_zeros()) as i32 } @@ -299,7 +299,7 @@ pub(crate) fn overlap_window() -> Vec { /// decimation stage, so the whole transform stays `O(n log n)` without a /// mixed-radix kernel in the DSP crate. #[derive(Clone, Debug)] -struct Fft15 { +pub(crate) struct Fft15 { n: usize, /// Sub-transform of length `n/15`. sub: Fft, @@ -311,7 +311,7 @@ struct Fft15 { } impl Fft15 { - fn new(n: usize) -> Fft15 { + pub(crate) fn new(n: usize) -> Fft15 { assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two()); let l = n / 15; let mut tw_re = vec![0.0; n]; @@ -334,7 +334,7 @@ impl Fft15 { } /// Unscaled inverse transform: `X[k] = sum x[n] exp(+2 pi i n k / N)`. - fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) { + pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) { let n = self.n; let l = n / 15; debug_assert_eq!(re.len(), n); @@ -574,7 +574,7 @@ fn pvq_urow(n: usize, k: usize, u: &mut [u32]) -> u32 { } /// Steps a `U` row up one dimension in place. -fn unext(u: &mut [u32], mut ui0: u32) { +pub(crate) fn unext(u: &mut [u32], mut ui0: u32) { for j in 1..u.len() { let ui1 = u[j].wrapping_add(u[j - 1]).wrapping_add(ui0); u[j - 1] = ui0; @@ -596,7 +596,13 @@ fn uprev(u: &mut [u32], mut ui0: u32) { } /// Decodes one PVQ codeword of `k` pulses in `n` dimensions. -fn decode_pulses(dec: &mut RangeDecoder, n: usize, k: usize, y: &mut [i32], u: &mut [u32]) { +pub(crate) fn decode_pulses( + dec: &mut RangeDecoder, + n: usize, + k: usize, + y: &mut [i32], + u: &mut [u32], +) { let v = pvq_urow(n, k, u); let mut i = dec.dec_uint(v.max(2)); let mut k = k; @@ -679,7 +685,7 @@ fn celt_lcg_rand(seed: u32) -> u32 { } /// Start of a band's pulse-cache row. `lm` is `-1` for a twice-split band. -fn cache_index(band: usize, lm: i32) -> usize { +pub(crate) fn cache_index(band: usize, lm: i32) -> usize { let row = (lm + 1) as usize; let idx = CACHE_INDEX[row * NB_BANDS + band]; debug_assert!(idx >= 0, "no pulse cache for band {band} at LM {lm}"); @@ -2345,7 +2351,7 @@ impl CeltDecoder { } /// `ec_laplace_decode()`: the coarse-energy prediction error. -fn laplace_decode(dec: &mut RangeDecoder, fs0: u32, decay: i32) -> i32 { +pub(crate) fn laplace_decode(dec: &mut RangeDecoder, fs0: u32, decay: i32) -> i32 { const MINP: u32 = 1; const NMIN: u32 = 16; let mut val = 0i32; @@ -2380,7 +2386,7 @@ fn laplace_decode(dec: &mut RangeDecoder, fs0: u32, decay: i32) -> i32 { /// `bitexact_cos()`: a cosine that must round identically everywhere, because /// the bit allocation depends on it. -fn bitexact_cos(x: i16) -> i16 { +pub(crate) fn bitexact_cos(x: i16) -> i16 { let tmp = (4096 + (x as i32) * (x as i32)) >> 13; let mut x2 = tmp as i16; x2 = (32767 - x2 as i32 @@ -2391,11 +2397,11 @@ fn bitexact_cos(x: i16) -> i16 { 1 + x2 } -fn frac_mul16(a: i16, b: i16) -> i32 { +pub(crate) fn frac_mul16(a: i16, b: i16) -> i32 { (16384 + (a as i32) * (b as i32)) >> 15 } -fn bitexact_log2tan(isin: i32, icos: i32) -> i32 { +pub(crate) fn bitexact_log2tan(isin: i32, icos: i32) -> i32 { let lc = ilog(icos as u32); let ls = ilog(isin as u32); let isin = (isin << (15 - ls)) as i16; @@ -2404,7 +2410,7 @@ fn bitexact_log2tan(isin: i32, icos: i32) -> i32 { - frac_mul16(icos, (frac_mul16(icos, -2597) + 7932) as i16) } -fn compute_qn(n: i32, b: i32, offset: i32, pulse_cap: i32, stereo: bool) -> i32 { +pub(crate) fn compute_qn(n: i32, b: i32, offset: i32, pulse_cap: i32, stereo: bool) -> i32 { const EXP2_TABLE8: [i32; 8] = [16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048]; let mut n2 = 2 * n - 1; if stereo && n == 2 { @@ -2420,7 +2426,7 @@ fn compute_qn(n: i32, b: i32, offset: i32, pulse_cap: i32, stereo: bool) -> i32 } } -fn get_pulses(i: i32) -> i32 { +pub(crate) fn get_pulses(i: i32) -> i32 { if i < 8 { i } else { @@ -2428,7 +2434,7 @@ fn get_pulses(i: i32) -> i32 { } } -fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 { +pub(crate) fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 { let cache = &CACHE_BITS[cache_index(band, lm)..]; let mut lo = 0i32; let mut hi = cache[0] as i32; @@ -2453,7 +2459,7 @@ fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 { } } -fn pulses2bits(band: usize, lm: i32, pulses: i32) -> i32 { +pub(crate) fn pulses2bits(band: usize, lm: i32, pulses: i32) -> i32 { if pulses == 0 { return 0; } @@ -2462,7 +2468,7 @@ fn pulses2bits(band: usize, lm: i32, pulses: i32) -> i32 { } /// One level of the Haar transform, used for the time/frequency changes. -fn haar1(x: &mut [f32], n0: usize, stride: usize) { +pub(crate) fn haar1(x: &mut [f32], n0: usize, stride: usize) { let n0 = n0 >> 1; const S: f32 = core::f32::consts::FRAC_1_SQRT_2; for i in 0..stride { @@ -2475,7 +2481,13 @@ fn haar1(x: &mut [f32], n0: usize, stride: usize) { } } -fn deinterleave_hadamard(x: &mut [f32], tmp: &mut [f32], n0: usize, stride: usize, hadamard: bool) { +pub(crate) fn deinterleave_hadamard( + x: &mut [f32], + tmp: &mut [f32], + n0: usize, + stride: usize, + hadamard: bool, +) { let n = n0 * stride; let tmp = &mut tmp[..n]; if hadamard { @@ -2556,7 +2568,14 @@ fn stereo_merge(buf: &mut [f32], x: usize, y: usize, mid: f32, n: usize) { } /// The spreading rotation (Section 4.3.4.3), applied in the decode direction. -fn exp_rotation(x: &mut [f32], len: usize, dir: i32, stride: usize, k: usize, spread: usize) { +pub(crate) fn exp_rotation( + x: &mut [f32], + len: usize, + dir: i32, + stride: usize, + k: usize, + spread: usize, +) { const SPREAD_FACTOR: [usize; 3] = [15, 10, 5]; if 2 * k >= len || spread == SPREAD_NONE { return; diff --git a/crates/ec-opus/src/celt_enc.rs b/crates/ec-opus/src/celt_enc.rs new file mode 100644 index 00000000..053fabca --- /dev/null +++ b/crates/ec-opus/src/celt_enc.rs @@ -0,0 +1,2073 @@ +//! The CELT encoder — RFC 6716 Section 5.3, throughput-first. +//! +//! The *coding* path — every symbol written, every `tell()` the bit allocation +//! reads — mirrors the normative reference (RFC 6716 Appendix A) exactly, +//! because the decoder derives the allocation from the same arithmetic and one +//! bit of drift desynchronises the frame. The *analysis* path is where this +//! encoder buys its speed, with fast deterministic heuristics in place of the +//! reference's searches: +//! +//! - **No pitch prefilter.** The postfilter-off bit is coded every frame, +//! which removes the most expensive analysis in the reference encoder (an +//! autocorrelation search over 1024 lags). Same choice the reference makes +//! below complexity 5. +//! - **No time/frequency Viterbi.** `tf_res` is all zeros: long-block frames +//! keep full frequency resolution, transient frames get the tf-table's +//! maximum time resolution — the two defaults the search almost always +//! lands on. +//! - **Fixed spreading.** `SPREAD_NORMAL` every frame, coded explicitly. +//! - **Single-pass coarse energy** with the reference's own delayed-intra +//! heuristic, not the two-pass encode-both-and-compare. +//! +//! What stays: transient detection, the closed-form allocation-trim and +//! dynalloc spike heuristics, the stereo-mode analysis, intensity thresholds +//! and constrained-VBR reservoir — all cheap O(frame) arithmetic that decides +//! *rates*, not searches. +//! +//! Steady state allocates nothing: every buffer is owned by the encoder and +//! sized at construction. + +use ec_core::{Error, Result}; + +use crate::celt::{ + self, BITRES, E_BANDS, E_MEANS, E_PROB_MODEL, FINE_OFFSET, LOG_N, LOG2_FRAC, MAX_FINE_BITS, + NB_BANDS, OVERLAP, PREEMPH, QTHETA_OFFSET, QTHETA_OFFSET_TWOPHASE, SHORT_MDCT, SIG_SCALE, + SMALL_ENERGY_ICDF, SPREAD_ICDF, SPREAD_NORMAL, TF_SELECT, TRIM_ICDF, +}; +use crate::range::RangeEncoder; + +/// `BAND_ALLOCATION` and friends live in the decoder module; local aliases +/// keep the transcription below readable. +use crate::celt::{ + BAND_ALLOCATION, BETA_COEF, BETA_INTRA, CACHE_CAPS, PRED_COEF, bitexact_cos, bitexact_log2tan, + bits2pulses, cache_index, compute_qn, deinterleave_hadamard, exp_rotation, frac_mul16, + get_pulses, haar1, pulses2bits, unext, +}; + +const CACHE_BITS: &[u8] = &crate::celt::CACHE_BITS; + +// --------------------------------------------------------------------------- +// Forward MDCT +// --------------------------------------------------------------------------- + +/// One forward-MDCT plan, the exact adjoint of the decoder's `ImdctPlan`: +/// window-fold, pre-rotation, an `l/2`-point FFT and post-rotation, scaled by +/// `2/l` so that decode(encode(x)) reconstructs at unit gain. +#[derive(Clone, Debug)] +struct MdctPlan { + l: usize, + fft: celt::Fft15, + rot_re: Vec, + rot_im: Vec, + fre: Vec, + fim: Vec, + t: Vec, +} + +impl MdctPlan { + fn new(l: usize) -> MdctPlan { + let n = 2 * l; + let quarter = l / 2; + let mut rot_re = vec![0.0; quarter]; + let mut rot_im = vec![0.0; quarter]; + for i in 0..quarter { + let a = 2.0 * core::f64::consts::PI * (i as f64 + 0.125) / n as f64; + rot_re[i] = a.cos() as f32; + rot_im[i] = a.sin() as f32; + } + MdctPlan { + l, + fft: celt::Fft15::new(quarter), + rot_re, + rot_im, + fre: vec![0.0; quarter], + fim: vec![0.0; quarter], + t: vec![0.0; l], + } + } + + /// Transforms `l + OVERLAP` time samples starting at `input[off]` — the + /// support of the low-overlap window — into `l` MDCT coefficients written + /// at `out[out_off + k*stride]`. + fn forward( + &mut self, + input: &[f32], + off: usize, + window: &[f32], + out: &mut [f32], + out_off: usize, + stride: usize, + ) { + let l = self.l; + let quarter = l / 2; + let flat = quarter - OVERLAP / 2; + let mirror = quarter + OVERLAP / 2; + let t = &mut self.t; + // Window fold: the adjoint of the inverse's scatter, so every + // coefficient, sign and window position matches by construction. + for i in 0..flat { + t[quarter - 1 - i] = input[off + mirror - 1 - i]; + } + for i in flat..quarter { + let w = i - flat; + t[quarter - 1 - i] = + -window[w] * input[off + w] + window[OVERLAP - 1 - w] * input[off + mirror - 1 - i]; + } + for i in 0..flat { + t[quarter + i] = input[off + mirror + i]; + } + for i in flat..quarter { + let w = i - flat; + t[quarter + i] = window[w] * input[off + l + OVERLAP - 1 - w] + + window[OVERLAP - 1 - w] * input[off + mirror + i]; + } + // Shuffle into the complex FFT input. + for i in 0..quarter { + self.fre[i] = -t[2 * i]; + self.fim[i] = t[2 * (quarter - 1 - i) + 1]; + } + // Rotate by -theta (adjoint of the inverse's post-rotation). + for i in 0..quarter { + let (c, s) = (self.rot_re[i], self.rot_im[i]); + let (re, im) = (self.fre[i], self.fim[i]); + self.fre[i] = re * c + im * s; + self.fim[i] = im * c - re * s; + } + // Forward FFT = conjugate, +i-convention FFT, conjugate. + for v in self.fim.iter_mut() { + *v = -*v; + } + self.fft.inverse(&mut self.fre, &mut self.fim); + for v in self.fim.iter_mut() { + *v = -*v; + } + // Adjoint of the pre-rotation, with the 2/l forward scaling CELT puts + // on this side of the transform. + let scale = 2.0 / l as f32; + for i in 0..quarter { + let (c, s) = (self.rot_re[i], self.rot_im[i]); + let (re, im) = (self.fre[i], self.fim[i]); + out[out_off + (2 * i) * stride] = scale * (s * re - c * im); + out[out_off + (l - 1 - 2 * i) * stride] = scale * (-c * re - s * im); + } + } +} + +// --------------------------------------------------------------------------- +// Symbol-level helpers +// --------------------------------------------------------------------------- + +/// `ec_laplace_encode()`: the coarse-energy prediction error. May clamp +/// `value`, which is why it is passed back. +fn laplace_encode(enc: &mut RangeEncoder, value: &mut i32, mut fs: u32, decay: i32) -> i32 { + const MINP: u32 = 1; + const NMIN: u32 = 16; + let mut fl = 0u32; + let mut val = *value; + if val != 0 { + let s = if val < 0 { -1i32 } else { 0 }; + val = (val + s) ^ s; + fl = fs; + let fs0 = fs; + fs = ((32768 - MINP * (2 * NMIN) - fs0) * (16384 - decay as u32)) >> 15; + // Search the decaying part of the pdf. + let mut i = 1i32; + while fs > 0 && i < val { + fs *= 2; + fl += fs + 2 * MINP; + fs = (fs * decay as u32) >> 15; + i += 1; + } + if fs == 0 { + // Everything beyond has probability MINP. + let mut ndi_max = (32768 - fl + MINP - 1) as i32; + ndi_max = (ndi_max - s) >> 1; + let di = (val - i).min(ndi_max - 1); + fl += ((2 * di + 1 + s) as u32) * MINP; + fs = MINP.min(32768 - fl); + *value = (i + di + s) ^ s; + } else { + fs += MINP; + if s == 0 { + fl += fs; + } + } + debug_assert!(fl + fs <= 32768); + debug_assert!(fs > 0); + } + enc.encode_bin(fl, fl + fs, 15); + *value +} + +/// `encode_pulses()` for the general case: index the pulse vector in the +/// V(N,K) enumeration and code it as one uniform symbol (Section 5.3.4). +fn encode_pulses(enc: &mut RangeEncoder, iy: &[i32], n: usize, k: usize, u: &mut [u32]) { + debug_assert!(n >= 2 && k > 0); + u[0] = 0; + for (kk, slot) in u.iter_mut().enumerate().take(k + 2).skip(1) { + *slot = (2 * kk - 1) as u32; + } + let mut i = u32::from(iy[n - 1] < 0); + let mut kk = iy[n - 1].unsigned_abs() as usize; + let j = n - 2; + i = i.wrapping_add(u[kk]); + kk += iy[j].unsigned_abs() as usize; + if iy[j] < 0 { + i = i.wrapping_add(u[kk + 1]); + } + let mut j = j; + while j > 0 { + j -= 1; + unext(&mut u[..k + 2], 0); + i = i.wrapping_add(u[kk]); + kk += iy[j].unsigned_abs() as usize; + if iy[j] < 0 { + i = i.wrapping_add(u[kk + 1]); + } + } + let nc = u[kk].wrapping_add(u[kk + 1]); + enc.enc_uint(i, nc.max(2)); +} + +/// `stereo_itheta()`: the angle between mid and side (or the two halves of a +/// split mono band), in Q14 (0..16384). +fn stereo_itheta(x: &[f32], y: &[f32], stereo: bool, n: usize) -> i32 { + let mut emid = 1e-15f32; + let mut eside = 1e-15f32; + if stereo { + for j in 0..n { + let m = x[j] + y[j]; + let s = x[j] - y[j]; + emid += m * m; + eside += s * s; + } + } else { + for j in 0..n { + emid += x[j] * x[j]; + eside += y[j] * y[j]; + } + } + let mid = emid.sqrt(); + let side = eside.sqrt(); + // 0.63662 is the reference's own 2/pi literal (vq.c, stereo_itheta); the + // exact constant would round a boundary theta differently. + #[allow(clippy::approx_constant)] + const TWO_OVER_PI: f64 = 0.63662; + (0.5 + 16384.0 * TWO_OVER_PI * (side as f64).atan2(mid as f64)).floor() as i32 +} + +// --------------------------------------------------------------------------- +// The encoder +// --------------------------------------------------------------------------- + +/// Arguments threaded through the band-encode recursion; the encode-side +/// mirror of the decoder's `BandArgs`, minus everything only resynthesis +/// needs (folding sources, gains, collapse fill). +#[derive(Clone, Copy, Debug)] +struct EncBand { + i: usize, + x: usize, + y: Option, + n: usize, + b: i32, + spread: usize, + blocks: usize, + intensity: usize, + tf_change: i32, + level: i32, + lm: i32, +} + +/// A CELT-layer encoder for one elementary Opus stream (mono or stereo), +/// fullband at 48 kHz. +#[derive(Clone, Debug)] +pub struct CeltEncoder { + channels: usize, + window: Vec, + plans: Vec, + /// Preemphasised history, `channels * OVERLAP`. + in_mem: Vec, + preemph_mem: [f32; 2], + /// Coarse-energy prediction state, `2 * NB_BANDS`. + old_band_e: Vec, + delayed_intra: f32, + consec_transient: u32, + last_coded_bands: usize, + force_intra: bool, + // Constrained-VBR reservoir. + vbr_reservoir: i32, + vbr_drift: i32, + vbr_offset: i32, + vbr_count: i32, + // Per-frame scratch, allocated once. + in_buf: Vec, + freq: Vec, + x: Vec, + band_e: Vec, + band_log_e: Vec, + error: Vec, + transient_tmp: Vec, + hadamard_tmp: Vec, + tf_res: [i32; NB_BANDS], + pulses: [i32; NB_BANDS], + fine_quant: [i32; NB_BANDS], + fine_priority: [i32; NB_BANDS], + offsets: [i32; NB_BANDS], + caps: [i32; NB_BANDS], + iy: Vec, + pvq_y: Vec, + pvq_sign: Vec, + urow: Vec, +} + +impl CeltEncoder { + /// An encoder for `channels` channels (1 or 2) at 48 kHz. + pub fn new(channels: usize) -> CeltEncoder { + assert!((1..=2).contains(&channels)); + let max_n = SHORT_MDCT * 8; + CeltEncoder { + channels, + window: celt::overlap_window(), + plans: (0..4).map(|lm| MdctPlan::new(SHORT_MDCT << lm)).collect(), + in_mem: vec![0.0; channels * OVERLAP], + preemph_mem: [0.0; 2], + old_band_e: vec![0.0; 2 * NB_BANDS], + delayed_intra: 1.0, + consec_transient: 0, + last_coded_bands: 0, + force_intra: true, + vbr_reservoir: 0, + vbr_drift: 0, + vbr_offset: 0, + vbr_count: 0, + in_buf: vec![0.0; channels * (max_n + OVERLAP)], + freq: vec![0.0; channels * max_n], + x: vec![0.0; channels * max_n], + band_e: vec![0.0; 2 * NB_BANDS], + band_log_e: vec![0.0; 2 * NB_BANDS], + error: vec![0.0; 2 * NB_BANDS], + transient_tmp: vec![0.0; max_n + OVERLAP], + hadamard_tmp: vec![0.0; max_n], + tf_res: [0; NB_BANDS], + pulses: [0; NB_BANDS], + fine_quant: [0; NB_BANDS], + fine_priority: [0; NB_BANDS], + offsets: [0; NB_BANDS], + caps: [0; NB_BANDS], + iy: vec![0; max_n], + pvq_y: vec![0.0; max_n], + pvq_sign: vec![0; max_n], + urow: vec![0; 1280], + } + } + + /// Channels this encoder codes. + pub fn channels(&self) -> usize { + self.channels + } + + /// Drops all inter-frame state. + pub fn reset(&mut self) { + self.in_mem.fill(0.0); + self.preemph_mem = [0.0; 2]; + self.old_band_e.fill(0.0); + self.delayed_intra = 1.0; + self.consec_transient = 0; + self.last_coded_bands = 0; + self.force_intra = true; + self.vbr_reservoir = 0; + self.vbr_drift = 0; + self.vbr_offset = 0; + self.vbr_count = 0; + } + + /// Encodes one frame of interleaved `f32` (`frame_size` samples per + /// channel at 48 kHz, `frame_size` one of 120/240/480/960) into `enc`, + /// which must have been `reset` to the frame's byte budget. With + /// `vbr_rate_bps` set, the frame may be shrunk below that budget + /// (constrained VBR); the return value is the final frame size in bytes. + pub fn encode( + &mut self, + enc: &mut RangeEncoder, + pcm: &[f32], + frame_size: usize, + vbr_rate_bps: u32, + ) -> Result { + let lm: usize = match frame_size { + 120 => 0, + 240 => 1, + 480 => 2, + 960 => 3, + _ => { + return Err(Error::unsupported( + format!("celt frame of {frame_size} samples"), + "CELT frames are 2.5, 5, 10 or 20 ms at 48 kHz", + )); + } + }; + let m = 1usize << lm; + let n = frame_size; + let c = self.channels; + if pcm.len() < n * c { + return Err(Error::corrupt(format!( + "celt encode: {} samples for a {}-channel {frame_size}-sample frame", + pcm.len(), + c + ))); + } + let (start, end) = (0usize, NB_BANDS); + + let mut nb_compressed = enc.storage(); + let mut nb_available = nb_compressed as i32; + // The target rate in 1/8-bit units per frame, VBR only. + let (vbr_rate, mut effective_bytes) = if vbr_rate_bps > 0 { + let den = 48000i64 >> BITRES; + let vr = ((vbr_rate_bps as i64 * n as i64 + (den >> 1)) / den) as i32; + (vr, vr >> (3 + BITRES)) + } else { + (0, nb_compressed as i32) + }; + + if vbr_rate > 0 { + // Constrained VBR: cap this frame so the reservoir never dips + // below one frame of buffering. + let vbr_bound = vbr_rate; + let max_allowed = (2i32 + .max((vbr_rate + vbr_bound - self.vbr_reservoir) >> (BITRES + 3))) + .min(nb_available); + if max_allowed < nb_available { + nb_compressed = max_allowed as usize; + nb_available = max_allowed; + enc.shrink(nb_compressed); + } + } + let mut total_bits = (nb_compressed * 8) as i32; + + // --- Preemphasis ---------------------------------------------------- + let stride = n + OVERLAP; + let mut silence = true; + for ch in 0..c { + let base = ch * stride; + self.in_buf[base..base + OVERLAP] + .copy_from_slice(&self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]); + let mut mem = self.preemph_mem[ch]; + for i in 0..n { + let mut x = pcm[i * c + ch] * SIG_SCALE; + if !x.is_finite() { + x = 0.0; + } + x = x.clamp(-65536.0, 65536.0); + let v = x + mem; + mem = -PREEMPH * x; + self.in_buf[base + OVERLAP + i] = v; + silence &= v == 0.0; + } + self.preemph_mem[ch] = mem; + self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP] + .copy_from_slice(&self.in_buf[base + n..base + n + OVERLAP]); + } + + // --- Silence flag (first symbol of the frame) ----------------------- + enc.enc_bit_logp(silence, 15); + if silence { + if vbr_rate > 0 { + nb_compressed = nb_compressed.min(2); + total_bits = (nb_compressed * 8) as i32; + nb_available = 2; + enc.shrink(nb_compressed); + } + enc.pad_to_end(); + } + + // --- Postfilter: always off (throughput-first, = complexity < 5) ---- + if enc.tell() as i32 + 16 <= total_bits { + enc.enc_bit_logp(false, 1); + } + + // --- Transient flag ------------------------------------------------- + let mut is_transient = false; + let mut short_blocks = 0usize; + if lm > 0 && enc.tell() as i32 + 3 <= total_bits { + is_transient = self.transient_analysis(n + OVERLAP, c, stride); + if is_transient { + short_blocks = m; + } + enc.enc_bit_logp(is_transient, 3); + } + + // --- Forward MDCTs, energies, normalisation ------------------------- + self.compute_mdcts(short_blocks, lm, n, c); + for ch in 0..c { + for i in 0..end { + let mut sum = 1e-27f32; + for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { + let v = self.freq[ch * n + j]; + sum += v * v; + } + self.band_e[i + ch * NB_BANDS] = sum.sqrt(); + self.band_log_e[i + ch * NB_BANDS] = + (self.band_e[i + ch * NB_BANDS] as f64).log2() as f32 - E_MEANS[i]; + } + for i in 0..end { + let g = 1.0 / (1e-27 + self.band_e[i + ch * NB_BANDS]); + for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { + self.x[ch * n + j] = self.freq[ch * n + j] * g; + } + } + } + + // --- tf_res: all zeros (throughput-first) --------------------------- + self.tf_res = [0; NB_BANDS]; + let tf_select = 0usize; + + // --- Coarse energy -------------------------------------------------- + let two_pass = false; + let mut intra = self.force_intra + || (!two_pass + && self.delayed_intra > (2 * c * (end - start)) as f32 + && nb_available > ((end - start) * c) as i32); + let new_distortion = { + let mut dist = 0.0f32; + for ch in 0..c { + for i in start..end { + let d = self.band_log_e[i + ch * NB_BANDS] - self.old_band_e[i + ch * NB_BANDS]; + dist += d * d; + } + } + dist.min(200.0) + }; + let tell = enc.tell(); + if tell + 3 > total_bits as u32 { + intra = false; + } + let max_decay = 16.0f32.min(0.125 * nb_available as f32); + self.quant_coarse_energy(enc, start, end, intra, c, lm, total_bits, max_decay); + self.delayed_intra = if intra { + new_distortion + } else { + PRED_COEF[lm] * PRED_COEF[lm] * self.delayed_intra + new_distortion + }; + + // --- tf encode ------------------------------------------------------ + self.tf_encode(enc, start, end, is_transient, lm, tf_select, nb_compressed); + + // --- Spread: fixed NORMAL ------------------------------------------- + if enc.tell() as i32 + 4 <= total_bits { + enc.enc_icdf(SPREAD_NORMAL, &SPREAD_ICDF, 5); + } + + // --- Caps + dynalloc ------------------------------------------------ + for i in 0..NB_BANDS { + let bw = (E_BANDS[i + 1] - E_BANDS[i]) << lm; + self.caps[i] = + ((CACHE_CAPS[NB_BANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * bw as i32) + >> 2; + } + self.offsets = [0; NB_BANDS]; + if effective_bytes > 50 && lm >= 1 { + let (t1, t2) = if lm <= 1 { + (3.0f32, 5.0f32) + } else { + (2.0, 4.0) + }; + for i in start + 1..end - 1 { + let mut d2 = + 2.0 * self.band_log_e[i] - self.band_log_e[i - 1] - self.band_log_e[i + 1]; + if c == 2 { + d2 = 0.5 + * (d2 + 2.0 * self.band_log_e[i + NB_BANDS] + - self.band_log_e[i - 1 + NB_BANDS] + - self.band_log_e[i + 1 + NB_BANDS]); + } + if d2 > t1 { + self.offsets[i] += 1; + } + if d2 > t2 { + self.offsets[i] += 1; + } + } + } + let mut dynalloc_logp = 6u32; + let total_bits_frac = total_bits << BITRES; + let mut total_boost = 0i32; + let mut tell_frac = enc.tell_frac() as i32; + for i in start..end { + let width = ((c * (E_BANDS[i + 1] - E_BANDS[i])) << lm) as i32; + let quanta = (width << BITRES).min((6 << BITRES).max(width)); + let mut loop_logp = dynalloc_logp; + let mut boost = 0i32; + let mut j = 0i32; + while tell_frac + ((loop_logp as i32) << BITRES) < total_bits_frac - total_boost + && boost < self.caps[i] + { + let flag = j < self.offsets[i]; + enc.enc_bit_logp(flag, loop_logp); + tell_frac = enc.tell_frac() as i32; + if !flag { + break; + } + boost += quanta; + total_boost += quanta; + loop_logp = 1; + j += 1; + } + if j > 0 { + dynalloc_logp = dynalloc_logp.saturating_sub(1).max(2); + } + self.offsets[i] = boost; + } + + // --- Allocation trim ------------------------------------------------ + let mut alloc_trim = 5i32; + if tell_frac + (6 << BITRES) <= total_bits_frac - total_boost { + alloc_trim = self.alloc_trim_analysis(end, lm, c, n); + enc.enc_icdf(alloc_trim as usize, &TRIM_ICDF, 7); + tell_frac = enc.tell_frac() as i32; + } + + // --- Constrained VBR ------------------------------------------------ + if vbr_rate > 0 { + let lm_diff = 3 - lm as i32; + let mut target = + vbr_rate + (self.vbr_offset >> lm_diff) - ((40 * c as i32 + 20) << BITRES); + // tf_sum is zero with tf analysis disabled, so only the transient + // boost of the reference's ladder applies. + if short_blocks != 0 { + target = 7 * target / 4; + } else if m > 1 { + target -= (target + 14) / 28; + } + target += tell_frac; + let min_allowed = + ((tell_frac + total_boost + (1 << (BITRES + 3)) - 1) >> (BITRES + 3)) + 2; + let mut nb_avail = (target + (1 << (BITRES + 2))) >> (BITRES + 3); + nb_avail = nb_avail.max(min_allowed); + nb_avail = nb_avail.min(nb_compressed as i32); + let mut delta = target - vbr_rate; + target = nb_avail << (BITRES + 3); + if silence { + nb_avail = 2; + delta = 0; + } + let alpha = if self.vbr_count < 970 { + self.vbr_count += 1; + 1.0 / (self.vbr_count + 20) as f32 + } else { + 0.001 + }; + self.vbr_reservoir += target - vbr_rate; + self.vbr_drift += (alpha + * ((delta * (1 << lm_diff)) as f32 + - self.vbr_offset as f32 + - self.vbr_drift as f32)) as i32; + self.vbr_offset = -self.vbr_drift; + if self.vbr_reservoir < 0 { + let adjust = (-self.vbr_reservoir) / (8 << BITRES); + if !silence { + nb_avail += adjust; + } + self.vbr_reservoir = 0; + } + let shrunk = (nb_compressed as i32).min(nb_avail).max(2) as usize; + if shrunk < nb_compressed { + nb_compressed = shrunk; + enc.shrink(nb_compressed); + } + } + + // --- Stereo decisions ----------------------------------------------- + let mut intensity = 0usize; + let mut dual_stereo = false; + if c == 2 { + if lm != 0 { + dual_stereo = self.stereo_analysis(lm, n); + } + let effective_rate = 2 * (((8 * effective_bytes - 80) >> lm) as i32) / 5; + intensity = if effective_rate < 35 { + 8 + } else if effective_rate < 50 { + 12 + } else if effective_rate < 68 { + 16 + } else if effective_rate < 84 { + 18 + } else if effective_rate < 102 { + 19 + } else if effective_rate < 130 { + 20 + } else { + 100 + }; + intensity = intensity.clamp(start, end); + } + let _ = &mut effective_bytes; + + // --- Bit allocation ------------------------------------------------- + let mut bits = (((nb_compressed * 8) as i32) << BITRES) - enc.tell_frac() as i32 - 1; + let anti_collapse_rsv = if is_transient && lm >= 2 && bits >= ((lm as i32 + 2) << BITRES) { + 1 << BITRES + } else { + 0 + }; + bits -= anti_collapse_rsv; + let mut balance = 0i32; + let coded_bands = self.compute_allocation( + enc, + start, + end, + alloc_trim, + &mut intensity, + &mut dual_stereo, + bits, + &mut balance, + c, + lm, + ); + self.last_coded_bands = coded_bands; + + // --- Fine energy ---------------------------------------------------- + for i in start..end { + if self.fine_quant[i] <= 0 { + continue; + } + let frac = 1 << self.fine_quant[i]; + for ch in 0..c { + let e = &mut self.error[i + ch * NB_BANDS]; + let q2 = (((*e + 0.5) * frac as f32).floor() as i32).clamp(0, frac - 1); + enc.enc_bits(q2 as u32, self.fine_quant[i] as u32); + let offset = (q2 as f32 + 0.5) / frac as f32 - 0.5; + self.old_band_e[i + ch * NB_BANDS] += offset; + *e -= offset; + } + } + + // --- Shapes --------------------------------------------------------- + self.quant_all_bands( + enc, + start, + end, + short_blocks, + SPREAD_NORMAL, + dual_stereo, + intensity, + (nb_compressed as i32 * (8 << BITRES)) - anti_collapse_rsv, + balance, + lm, + coded_bands, + c, + n, + ); + + // --- Anti-collapse -------------------------------------------------- + if anti_collapse_rsv > 0 { + let on = self.consec_transient < 2; + enc.enc_bits(u32::from(on), 1); + } + + // --- Leftover fine bits --------------------------------------------- + let mut bits_left = nb_compressed as i32 * 8 - enc.tell() as i32; + for prio in 0..2 { + for i in start..end { + if bits_left < c as i32 { + break; + } + if self.fine_quant[i] >= MAX_FINE_BITS || self.fine_priority[i] != prio { + continue; + } + for ch in 0..c { + let q2 = i32::from(self.error[i + ch * NB_BANDS] >= 0.0); + enc.enc_bits(q2 as u32, 1); + let offset = (q2 as f32 - 0.5) / (1 << (self.fine_quant[i] + 1)) as f32; + self.old_band_e[i + ch * NB_BANDS] += offset; + bits_left -= 1; + } + } + } + + if silence { + for e in self.old_band_e.iter_mut() { + *e = -28.0; + } + } + if c == 1 { + for i in 0..NB_BANDS { + self.old_band_e[NB_BANDS + i] = self.old_band_e[i]; + } + } + if is_transient { + self.consec_transient += 1; + } else { + self.consec_transient = 0; + } + self.force_intra = false; + + enc.done(); + if enc.error() { + return Err(Error::corrupt("celt encode: busted the frame budget")); + } + Ok(nb_compressed) + } + + // -- Analysis ------------------------------------------------------------ + + /// `transient_analysis()`: a high-passed peak-decay detector, straight + /// from the reference. + fn transient_analysis(&mut self, len: usize, c: usize, stride: usize) -> bool { + let tmp = &mut self.transient_tmp[..len]; + if c == 1 { + tmp.copy_from_slice(&self.in_buf[..len]); + } else { + for (i, v) in tmp.iter_mut().enumerate() { + *v = self.in_buf[i] + self.in_buf[stride + i]; + } + } + let mut mem0 = 0.0f32; + let mut mem1 = 0.0f32; + for v in tmp.iter_mut() { + let x = *v; + let y = mem0 + x; + mem0 = mem1 + y - 2.0 * x; + mem1 = x - 0.5 * y; + *v = y; + } + for v in tmp.iter_mut().take(12) { + *v = 0.0; + } + let block = OVERLAP / 2; + let nbins = len / block; + let mut bins = [0.0f32; 20]; + for (i, bin) in bins.iter_mut().enumerate().take(nbins) { + let mut max_abs = 0.0f32; + for j in 0..block { + max_abs = max_abs.max(tmp[i * block + j].abs()); + } + *bin = max_abs; + } + let mut is_transient = false; + #[allow(clippy::needless_range_loop)] + for i in 0..nbins { + let t1 = 0.15 * bins[i]; + let t2 = 0.4 * bins[i]; + let t3 = 0.15 * bins[i]; + let mut conseq = 0; + for &b in bins.iter().take(i) { + if b < t1 { + conseq += 1; + } + if b < t2 { + conseq += 1; + } else { + conseq = 0; + } + } + if conseq >= 3 { + is_transient = true; + } + conseq = 0; + for &b in bins.iter().take(nbins).skip(i + 1) { + if b < t3 { + conseq += 1; + } else { + conseq = 0; + } + } + if conseq >= 7 { + is_transient = true; + } + } + is_transient + } + + fn compute_mdcts(&mut self, short_blocks: usize, lm: usize, n: usize, c: usize) { + let stride = n + OVERLAP; + let (n2, blocks, plan_lm) = if short_blocks != 0 { + (SHORT_MDCT, short_blocks, 0) + } else { + (n, 1, lm) + }; + for ch in 0..c { + for b in 0..blocks { + let plan = &mut self.plans[plan_lm]; + plan.forward( + &self.in_buf, + ch * stride + b * n2, + &self.window, + &mut self.freq, + ch * n + b, + blocks, + ); + } + } + } + + /// `alloc_trim_analysis()`: stereo correlation plus spectral tilt. + fn alloc_trim_analysis(&self, end: usize, lm: usize, c: usize, n0: usize) -> i32 { + let mut trim = 5i32; + if c == 2 { + let mut sum = 0.0f32; + for i in 0..8 { + let mut partial = 0.0f32; + for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) { + partial += self.x[j] * self.x[n0 + j]; + } + sum += partial; + } + sum *= 1.0 / 8.0; + if sum > 0.995 { + trim -= 4; + } else if sum > 0.92 { + trim -= 3; + } else if sum > 0.85 { + trim -= 2; + } else if sum > 0.8 { + trim -= 1; + } + } + let mut diff = 0.0f32; + for ch in 0..c { + for i in 0..end - 1 { + diff += self.band_log_e[i + ch * NB_BANDS] + * (2 + 2 * i as i32 - NB_BANDS as i32) as f32; + } + } + diff /= (2 * c * (end - 1)) as f32; + if diff > 2.0 { + trim -= 1; + } + if diff > 8.0 { + trim -= 1; + } + if diff < -4.0 { + trim += 1; + } + if diff < -10.0 { + trim += 1; + } + trim.clamp(0, 10) + } + + /// `stereo_analysis()`: L1 entropy model of L/R against M/S. + fn stereo_analysis(&self, lm: usize, n0: usize) -> bool { + let mut sum_lr = 1e-15f64; + let mut sum_ms = 1e-15f64; + for i in 0..13 { + for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) { + let l = self.x[j] as f64; + let r = self.x[n0 + j] as f64; + sum_lr += l.abs() + r.abs(); + sum_ms += (l + r).abs() + (l - r).abs(); + } + } + // The reference's own literal (bands.c, stereo_analysis), kept as such. + #[allow(clippy::approx_constant)] + const SQRT_HALF: f64 = 0.707107; + sum_ms *= SQRT_HALF; + let mut thetas = 13; + if lm <= 1 { + thetas -= 8; + } + ((E_BANDS[13] << (lm + 1)) + thetas) as f64 * sum_ms + > ((E_BANDS[13] << (lm + 1)) as f64) * sum_lr + } + + // -- Energy -------------------------------------------------------------- + + #[allow(clippy::too_many_arguments)] + fn quant_coarse_energy( + &mut self, + enc: &mut RangeEncoder, + start: usize, + end: usize, + intra: bool, + c: usize, + lm: usize, + budget: i32, + max_decay: f32, + ) { + let tell = enc.tell() as i32; + if tell + 3 <= budget { + enc.enc_bit_logp(intra, 3); + } + let 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 prev = [0.0f32; 2]; + for i in start..end { + for (ch, prev) in prev.iter_mut().enumerate().take(c) { + let x = self.band_log_e[i + ch * NB_BANDS]; + let old_raw = self.old_band_e[i + ch * NB_BANDS]; + let old = old_raw.max(-9.0); + let f = x - coef * old - *prev; + let mut qi = (0.5 + f).floor() as i32; + let decay_bound = old_raw.max(-28.0) - max_decay; + // Prevent the energy from dropping faster than the decoder + // can follow. + if qi < 0 && x < decay_bound { + qi += (decay_bound - x) as i32; + if qi > 0 { + qi = 0; + } + } + let tell = enc.tell() as i32; + let bits_left = budget - tell - 3 * (c 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, + (model[pi] as u32) << 7, + (model[pi + 1] as i32) << 6, + ); + } else if budget - tell >= 2 { + qi = qi.clamp(-1, 1); + enc.enc_icdf( + ((2 * qi) ^ -i32::from(qi < 0)) as usize, + &SMALL_ENERGY_ICDF, + 2, + ); + } else if budget - tell >= 1 { + qi = qi.min(0); + enc.enc_bit_logp(qi != 0, 1); + } else { + qi = -1; + } + self.error[i + ch * NB_BANDS] = f - qi as f32; + let q = qi as f32; + self.old_band_e[i + ch * NB_BANDS] = coef * old + *prev + q; + *prev += q - beta * q; + } + } + } + + #[allow(clippy::too_many_arguments)] + fn tf_encode( + &mut self, + enc: &mut RangeEncoder, + start: usize, + end: usize, + transient: bool, + lm: usize, + mut tf_select: usize, + len: usize, + ) { + let mut budget = (len * 8) as i32; + let mut tell = enc.tell() as i32; + let mut logp: u32 = if transient { 2 } else { 4 }; + let tf_select_rsv = lm > 0 && tell + (logp as i32) < budget; + budget -= i32::from(tf_select_rsv); + let mut curr = 0i32; + let mut changed = false; + for i in start..end { + if tell + (logp as i32) <= budget { + enc.enc_bit_logp((self.tf_res[i] ^ curr) != 0, logp); + tell = enc.tell() as i32; + curr = self.tf_res[i]; + changed |= curr != 0; + } else { + self.tf_res[i] = curr; + } + logp = if transient { 4 } else { 5 }; + } + let t = usize::from(transient); + let ch = usize::from(changed); + if tf_select_rsv && TF_SELECT[lm][4 * t + ch] != TF_SELECT[lm][4 * t + 2 + ch] { + enc.enc_bit_logp(tf_select != 0, 1); + } else { + tf_select = 0; + } + for i in start..end { + self.tf_res[i] = TF_SELECT[lm][4 * t + 2 * tf_select + self.tf_res[i] as usize]; + } + } + + // -- Allocation (encode side of the decoder's implicit derivation) ------- + + #[allow(clippy::too_many_arguments)] + fn compute_allocation( + &mut self, + enc: &mut RangeEncoder, + start: usize, + end: usize, + alloc_trim: i32, + intensity: &mut usize, + dual_stereo: &mut bool, + total: i32, + balance: &mut i32, + c: usize, + lm: usize, + ) -> usize { + let mut total = total.max(0); + let mut skip_start = start; + let skip_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 }; + total -= skip_rsv; + let mut intensity_rsv = 0; + let mut dual_stereo_rsv = 0; + if c == 2 { + intensity_rsv = LOG2_FRAC[end - start]; + if intensity_rsv > total { + intensity_rsv = 0; + } else { + total -= intensity_rsv; + dual_stereo_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 }; + total -= dual_stereo_rsv; + } + } + + let mut thresh = [0i32; NB_BANDS]; + let mut trim_offset = [0i32; NB_BANDS]; + for j in start..end { + let width = (E_BANDS[j + 1] - E_BANDS[j]) as i32; + thresh[j] = ((c as i32) << BITRES).max((((3 * width) << lm) << BITRES) >> 4); + trim_offset[j] = (c as i32 + * width + * (alloc_trim - 5 - lm as i32) + * (end - j - 1) as i32 + * (1 << (lm as u32 + BITRES))) + >> 6; + if (width << lm) == 1 { + trim_offset[j] -= (c as i32) << BITRES; + } + } + + let mut lo = 1i32; + let mut hi = BAND_ALLOCATION.len() as i32 - 1; + while lo <= hi { + let mid = (lo + hi) >> 1; + let mut psum = 0; + let mut done = false; + for j in (start..end).rev() { + let width = (E_BANDS[j + 1] - E_BANDS[j]) as i32; + let mut bitsj = + (c as i32 * width * BAND_ALLOCATION[mid as usize][j] as i32) << lm >> 2; + if bitsj > 0 { + bitsj = 0.max(bitsj + trim_offset[j]); + } + bitsj += self.offsets[j]; + if bitsj >= thresh[j] || done { + done = true; + psum += bitsj.min(self.caps[j]); + } else if bitsj >= (c as i32) << BITRES { + psum += (c as i32) << BITRES; + } + } + if psum > total { + hi = mid - 1; + } else { + lo = mid + 1; + } + } + let hi = lo; + let lo = lo - 1; + + let mut bits1 = [0i32; NB_BANDS]; + let mut bits2 = [0i32; NB_BANDS]; + for j in start..end { + let width = (E_BANDS[j + 1] - E_BANDS[j]) as i32; + let mut b1 = (c as i32 * width * BAND_ALLOCATION[lo as usize][j] as i32) << lm >> 2; + let mut b2 = if hi as usize >= BAND_ALLOCATION.len() { + self.caps[j] + } else { + (c as i32 * width * BAND_ALLOCATION[hi as usize][j] as i32) << lm >> 2 + }; + if b1 > 0 { + b1 = 0.max(b1 + trim_offset[j]); + } + if b2 > 0 { + b2 = 0.max(b2 + trim_offset[j]); + } + if lo > 0 { + b1 += self.offsets[j]; + } + b2 += self.offsets[j]; + if self.offsets[j] > 0 { + skip_start = j; + } + bits1[j] = b1; + bits2[j] = 0.max(b2 - b1); + } + + self.interp_bits2pulses( + enc, + start, + end, + skip_start, + &bits1, + &bits2, + &thresh, + total, + balance, + skip_rsv, + intensity, + intensity_rsv, + dual_stereo, + dual_stereo_rsv, + c, + lm, + ) + } + + #[allow(clippy::too_many_arguments)] + fn interp_bits2pulses( + &mut self, + enc: &mut RangeEncoder, + start: usize, + end: usize, + skip_start: usize, + bits1: &[i32; NB_BANDS], + bits2: &[i32; NB_BANDS], + thresh: &[i32; NB_BANDS], + mut total: i32, + balance_out: &mut i32, + skip_rsv: i32, + intensity: &mut usize, + mut intensity_rsv: i32, + dual_stereo: &mut bool, + mut dual_stereo_rsv: i32, + c: usize, + lm: usize, + ) -> usize { + const ALLOC_STEPS: u32 = 6; + let alloc_floor = (c as i32) << BITRES; + let stereo = c > 1; + let log_m = (lm as i32) << BITRES; + let prev = self.last_coded_bands; + + let mut lo = 0i32; + let mut hi = 1i32 << ALLOC_STEPS; + for _ in 0..ALLOC_STEPS { + let mid = (lo + hi) >> 1; + let mut psum = 0; + let mut done = false; + for j in (start..end).rev() { + let tmp = bits1[j] + ((mid * bits2[j]) >> ALLOC_STEPS); + if tmp >= thresh[j] || done { + done = true; + psum += tmp.min(self.caps[j]); + } else if tmp >= alloc_floor { + psum += alloc_floor; + } + } + if psum > total { + hi = mid; + } else { + lo = mid; + } + } + + let mut psum = 0; + let mut done = false; + let bits = &mut self.pulses; + for j in (start..end).rev() { + let mut tmp = bits1[j] + ((lo * bits2[j]) >> ALLOC_STEPS); + if tmp < thresh[j] && !done { + tmp = if tmp >= alloc_floor { alloc_floor } else { 0 }; + } else { + done = true; + } + tmp = tmp.min(self.caps[j]); + bits[j] = tmp; + psum += tmp; + } + + let mut coded_bands = end; + loop { + let j = coded_bands - 1; + if j <= skip_start { + total += skip_rsv; + break; + } + let mut left = total - psum; + let percoeff = left / (E_BANDS[coded_bands] - E_BANDS[start]) as i32; + left -= (E_BANDS[coded_bands] - E_BANDS[start]) as i32 * percoeff; + let rem = 0.max(left - (E_BANDS[j] - E_BANDS[start]) as i32); + let band_width = (E_BANDS[coded_bands] - E_BANDS[j]) as i32; + let mut band_bits = self.pulses[j] + percoeff * band_width + rem; + if band_bits >= thresh[j].max(alloc_floor + (1 << BITRES)) { + // The one non-mandatory choice in the allocation: whether to + // stop skipping, with the reference's hysteresis on the band + // count of the previous frame. + let stay = band_bits + > (((if j < prev { 7 } else { 9 }) * band_width) << lm << BITRES) >> 4; + enc.enc_bit_logp(stay, 1); + if stay { + break; + } + psum += 1 << BITRES; + band_bits -= 1 << BITRES; + } + psum -= self.pulses[j] + intensity_rsv; + if intensity_rsv > 0 { + intensity_rsv = LOG2_FRAC[j - start]; + } + psum += intensity_rsv; + if band_bits >= alloc_floor { + psum += alloc_floor; + self.pulses[j] = alloc_floor; + } else { + self.pulses[j] = 0; + } + coded_bands -= 1; + } + + debug_assert!(coded_bands > start); + if intensity_rsv > 0 { + *intensity = (*intensity).min(coded_bands); + enc.enc_uint( + (*intensity - start) as u32, + (coded_bands + 1 - start) as u32, + ); + } else { + *intensity = 0; + } + if *intensity <= start { + total += dual_stereo_rsv; + dual_stereo_rsv = 0; + } + if dual_stereo_rsv > 0 { + enc.enc_bit_logp(*dual_stereo, 1); + } else { + *dual_stereo = false; + } + + let mut left = total - psum; + let percoeff = left / (E_BANDS[coded_bands] - E_BANDS[start]) as i32; + left -= (E_BANDS[coded_bands] - E_BANDS[start]) as i32 * percoeff; + for j in start..coded_bands { + self.pulses[j] += percoeff * (E_BANDS[j + 1] - E_BANDS[j]) as i32; + } + for j in start..coded_bands { + let tmp = left.min((E_BANDS[j + 1] - E_BANDS[j]) as i32); + self.pulses[j] += tmp; + left -= tmp; + } + + let mut balance = 0i32; + for j in start..coded_bands { + let n0 = (E_BANDS[j + 1] - E_BANDS[j]) as i32; + let n = n0 << lm; + self.pulses[j] += balance; + let mut excess; + if n > 1 { + excess = 0.max(self.pulses[j] - self.caps[j]); + self.pulses[j] -= excess; + let den = + c as i32 * n + i32::from(c == 2 && n > 2 && !*dual_stereo && j < *intensity); + let nc_log_n = den * (LOG_N[j] + log_m); + let mut offset = (nc_log_n >> 1) - den * FINE_OFFSET; + if n == 2 { + offset += den << BITRES >> 2; + } + if self.pulses[j] + offset < (den * 2) << BITRES { + offset += nc_log_n >> 2; + } else if self.pulses[j] + offset < (den * 3) << BITRES { + offset += nc_log_n >> 3; + } + let mut eb = + 0.max((self.pulses[j] + offset + (den << (BITRES - 1))) / (den << BITRES)); + if c as i32 * eb > (self.pulses[j] >> BITRES) { + eb = self.pulses[j] >> u32::from(stereo) >> BITRES; + } + eb = eb.min(MAX_FINE_BITS); + self.fine_quant[j] = eb; + self.fine_priority[j] = i32::from(eb * (den << BITRES) >= self.pulses[j] + offset); + self.pulses[j] -= (c as i32 * eb) << BITRES; + } else { + excess = 0.max(self.pulses[j] - ((c as i32) << BITRES)); + self.pulses[j] -= excess; + self.fine_quant[j] = 0; + self.fine_priority[j] = 1; + } + if excess > 0 { + let extra_fine = (excess >> (u32::from(stereo) + BITRES)) + .min(MAX_FINE_BITS - self.fine_quant[j]); + self.fine_quant[j] += extra_fine; + let extra_bits = (extra_fine * c as i32) << BITRES; + self.fine_priority[j] = i32::from(extra_bits >= excess - balance); + excess -= extra_bits; + } + balance = excess; + } + *balance_out = balance; + for j in coded_bands..end { + self.fine_quant[j] = self.pulses[j] >> u32::from(stereo) >> BITRES; + self.pulses[j] = 0; + self.fine_priority[j] = i32::from(self.fine_quant[j] < 1); + } + coded_bands + } + + // -- Band shapes --------------------------------------------------------- + + #[allow(clippy::too_many_arguments)] + fn quant_all_bands( + &mut self, + enc: &mut RangeEncoder, + start: usize, + end: usize, + short_blocks: usize, + spread: usize, + mut dual_stereo: bool, + intensity: usize, + total_bits: i32, + mut balance: i32, + lm: usize, + coded_bands: usize, + c: usize, + n: usize, + ) { + let m = 1usize << lm; + let blocks = if short_blocks != 0 { m } else { 1 }; + for i in start..end { + let n_band = m * E_BANDS[i + 1] - m * E_BANDS[i]; + let tell = enc.tell_frac() as i32; + if i != start { + balance -= tell; + } + let mut remaining_bits = total_bits - tell - 1; + let b = if i < coded_bands { + let curr_balance = balance / 3.min(coded_bands - i) as i32; + 0.max(16383.min((remaining_bits + 1).min(self.pulses[i] + curr_balance))) + } else { + 0 + }; + let tf_change = self.tf_res[i]; + if dual_stereo && i == intensity { + dual_stereo = false; + } + let x_off = m * E_BANDS[i]; + let base = EncBand { + i, + x: x_off, + y: None, + n: n_band, + b, + spread, + blocks, + intensity, + tf_change, + level: 0, + lm: lm as i32, + }; + if dual_stereo { + self.quant_band(enc, EncBand { b: b / 2, ..base }, &mut remaining_bits); + self.quant_band( + enc, + EncBand { + x: n + x_off, + b: b / 2, + ..base + }, + &mut remaining_bits, + ); + } else { + self.quant_band( + enc, + EncBand { + y: if c == 2 { Some(n + x_off) } else { None }, + ..base + }, + &mut remaining_bits, + ); + } + balance += self.pulses[i] + tell; + } + } + + /// Encodes one band (Section 5.3.4-5.3.5), recursing for splits and for + /// stereo. The mirror of the decoder's `quant_band`, with the resynthesis + /// paths removed — nothing the encoder writes depends on them. + fn quant_band(&mut self, enc: &mut RangeEncoder, a: EncBand, remaining_bits: &mut i32) { + let EncBand { + i, + x, + mut y, + mut n, + mut b, + spread, + mut blocks, + intensity, + mut tf_change, + level, + mut lm, + } = a; + let stereo = y.is_some(); + let mut split = stereo; + let long_blocks = blocks == 1; + let mut b0 = blocks; + + if n == 1 { + for offs in [Some(x), y].into_iter().flatten() { + if *remaining_bits >= 1 << BITRES { + let sign = self.x[offs] < 0.0; + enc.enc_bits(u32::from(sign), 1); + *remaining_bits -= 1 << BITRES; + } + } + return; + } + + let mut n_b = n / blocks; + if !stereo && level == 0 { + let recombine = if tf_change > 0 { tf_change as usize } else { 0 }; + for k in 0..recombine { + haar1(&mut self.x[x..], n >> k, 1 << k); + } + blocks >>= recombine; + n_b <<= recombine; + while (n_b & 1) == 0 && tf_change < 0 { + haar1(&mut self.x[x..], n_b, blocks); + blocks <<= 1; + n_b >>= 1; + tf_change += 1; + } + b0 = blocks; + if b0 > 1 { + deinterleave_hadamard( + &mut self.x[x..x + n], + &mut self.hadamard_tmp, + n_b >> recombine, + b0 << recombine, + long_blocks, + ); + } + } + + let cache_start = cache_index(i, lm); + let cache0 = CACHE_BITS[cache_start] as usize; + if !stereo && lm != -1 && b > CACHE_BITS[cache_start + cache0] as i32 + 12 && n > 2 { + n >>= 1; + y = Some(x + n); + split = true; + lm -= 1; + blocks = (blocks + 1) >> 1; + } + + if split { + let pulse_cap = LOG_N[i] + lm * (1 << BITRES); + let offset = (pulse_cap >> 1) + - if stereo && n == 2 { + QTHETA_OFFSET_TWOPHASE + } else { + QTHETA_OFFSET + }; + let mut qn = compute_qn(n as i32, b, offset, pulse_cap, stereo); + if stereo && i >= intensity { + qn = 1; + } + // The angle between the two halves, before any quantisation. + let mut itheta = { + let yy = y.unwrap(); + let (xs, ys) = (&self.x[x..x + n], &self.x[yy..yy + n]); + stereo_itheta(xs, ys, stereo, n) + }; + let tell = enc.tell_frac() as i32; + if qn != 1 { + itheta = (itheta * qn + 8192) >> 14; + // Entropy coding of the angle: step pdf for stereo, uniform + // for the time split, triangular otherwise. + if stereo && n > 2 { + let p0 = 3i32; + let x0 = qn / 2; + let ft = (p0 * (x0 + 1) + x0) as u32; + let xv = itheta; + let (fl, fh) = if xv <= x0 { + (p0 * xv, p0 * (xv + 1)) + } else { + ((xv - 1 - x0) + (x0 + 1) * p0, (xv - x0) + (x0 + 1) * p0) + }; + enc.encode(fl as u32, fh as u32, ft); + } else if b0 > 1 || stereo { + enc.enc_uint(itheta as u32, (qn + 1) as u32); + } else { + let ft = ((qn >> 1) + 1) * ((qn >> 1) + 1); + 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); + } + itheta = itheta * 16384 / qn; + if stereo { + let yy = y.unwrap(); + if itheta == 0 { + self.intensity_stereo(i, x, yy, n); + } else { + // stereo_split + for j in 0..n { + let l = core::f32::consts::FRAC_1_SQRT_2 * self.x[x + j]; + let r = core::f32::consts::FRAC_1_SQRT_2 * self.x[yy + j]; + self.x[x + j] = l + r; + self.x[yy + j] = r - l; + } + } + } + } else if stereo { + let yy = y.unwrap(); + let inv = itheta > 8192; + if inv { + for j in 0..n { + self.x[yy + j] = -self.x[yy + j]; + } + } + self.intensity_stereo(i, x, yy, n); + if b > 2 << BITRES && *remaining_bits > 2 << BITRES { + enc.enc_bit_logp(inv, 2); + } + itheta = 0; + } + let qalloc = enc.tell_frac() as i32 - tell; + b -= qalloc; + + let mut delta; + let imid; + let iside; + if itheta == 0 { + imid = 32767; + iside = 0; + delta = -16384; + } else if itheta == 16384 { + imid = 0; + iside = 32767; + delta = 16384; + } else { + imid = bitexact_cos(itheta as i16) as i32; + iside = bitexact_cos((16384 - itheta) as i16) as i32; + delta = frac_mul16( + ((n as i32 - 1) << 7) as i16, + bitexact_log2tan(iside, imid) as i16, + ); + } + let _ = imid; + let _ = iside; + + if n == 2 && stereo { + let mut mbits = b; + let mut sbits = 0; + if itheta != 0 && itheta != 16384 { + sbits = 1 << BITRES; + } + mbits -= sbits; + let yy = y.unwrap(); + let swap = itheta > 8192; + *remaining_bits -= qalloc + sbits; + let (x2, y2) = if swap { (yy, x) } else { (x, yy) }; + if sbits != 0 { + let sign = self.x[x2] * self.x[y2 + 1] - self.x[x2 + 1] * self.x[y2] < 0.0; + enc.enc_bits(u32::from(sign), 1); + } + self.quant_band( + enc, + EncBand { + x: x2, + y: None, + n, + b: mbits, + blocks, + tf_change, + lm, + ..a + }, + remaining_bits, + ); + } else { + if b0 > 1 && !stereo && (itheta & 0x3fff) != 0 { + if itheta > 8192 { + delta -= delta >> (4 - lm); + } else { + delta = 0.min(delta + ((n as i32) << BITRES >> (5 - lm))); + } + } + let mut mbits = 0.max(b.min((b - delta) / 2)); + let mut sbits = b - mbits; + *remaining_bits -= qalloc; + let next_level = if stereo { level } else { level + 1 }; + let mid_args = EncBand { + x, + y: None, + n, + blocks, + tf_change, + level: next_level, + lm, + ..a + }; + let side_args = EncBand { + x: y.unwrap(), + y: None, + n, + blocks, + tf_change, + level: next_level, + lm, + ..a + }; + let mut rebalance = *remaining_bits; + if mbits >= sbits { + self.quant_band( + enc, + EncBand { + b: mbits, + ..mid_args + }, + remaining_bits, + ); + rebalance = mbits - (rebalance - *remaining_bits); + if rebalance > 3 << BITRES && itheta != 0 { + sbits += rebalance - (3 << BITRES); + } + self.quant_band( + enc, + EncBand { + b: sbits, + ..side_args + }, + remaining_bits, + ); + } else { + self.quant_band( + enc, + EncBand { + b: sbits, + ..side_args + }, + remaining_bits, + ); + rebalance = sbits - (rebalance - *remaining_bits); + if rebalance > 3 << BITRES && itheta != 16384 { + mbits += rebalance - (3 << BITRES); + } + self.quant_band( + enc, + EncBand { + b: mbits, + ..mid_args + }, + remaining_bits, + ); + } + } + } else { + // The basic no-split case: straight PVQ. + let mut q = bits2pulses(i, lm, b); + let mut curr_bits = pulses2bits(i, lm, q); + *remaining_bits -= curr_bits; + while *remaining_bits < 0 && q > 0 { + *remaining_bits += curr_bits; + q -= 1; + curr_bits = pulses2bits(i, lm, q); + *remaining_bits -= curr_bits; + } + if q != 0 { + let k = get_pulses(q) as usize; + self.alg_quant(enc, x, n, k, spread, blocks); + } + // q == 0: the decoder folds or fills with noise on its own; + // nothing is coded. + } + } + + /// `intensity_stereo()`: collapses the pair onto a single channel weighted + /// by the band energies; only the combined channel is coded. + fn intensity_stereo(&mut self, band: usize, x: usize, y: usize, n: usize) { + let left = self.band_e[band]; + let right = self.band_e[band + NB_BANDS]; + let norm = 1e-15 + (1e-15 + left * left + right * right).sqrt(); + let a1 = left / norm; + let a2 = right / norm; + for j in 0..n { + let l = self.x[x + j]; + let r = self.x[y + j]; + self.x[x + j] = a1 * l + a2 * r; + } + } + + /// `alg_quant()`: the PVQ search — greedy pyramid projection plus one + /// pulse at a time on the exact `Rxy^2/Ryy` criterion — then the + /// enumeration encode. + fn alg_quant( + &mut self, + enc: &mut RangeEncoder, + x: usize, + n: usize, + k: usize, + spread: usize, + blocks: usize, + ) { + debug_assert!(n > 1 && k > 0); + exp_rotation(&mut self.x[x..x + n], n, 1, blocks, k, spread); + let xs = &mut self.x[x..x + n]; + let iy = &mut self.iy[..n]; + let y = &mut self.pvq_y[..n]; + let signs = &mut self.pvq_sign[..n]; + for j in 0..n { + if xs[j] > 0.0 { + signs[j] = 1; + } else { + signs[j] = -1; + xs[j] = -xs[j]; + } + iy[j] = 0; + y[j] = 0.0; + } + let mut xy = 0.0f32; + let mut yy = 0.0f32; + let mut pulses_left = k as i32; + if k > n >> 1 { + let mut sum = 0.0f32; + for v in xs.iter() { + sum += *v; + } + if !(sum > 1e-15 && sum < 64.0) { + xs[0] = 1.0; + for v in xs.iter_mut().skip(1) { + *v = 0.0; + } + sum = 1.0; + } + let rcp = (k as f32 - 1.0) / sum; + for j in 0..n { + iy[j] = (rcp * xs[j]).floor() as i32; + y[j] = iy[j] as f32; + yy += y[j] * y[j]; + xy += xs[j] * y[j]; + y[j] *= 2.0; + pulses_left -= iy[j]; + } + } + debug_assert!(pulses_left >= 1); + 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; + } + // The pulse-placement search is the encoder's hottest loop — O(K*N) + // per band, dominant at high rates — so it runs eight candidates a + // lane with `wide`. Lane-local bests are reduced after the sweep; + // only the tie-breaking order differs from the scalar loop, and any + // pulse choice is a valid codeword — the enumeration, not the + // search, is what conformance constrains. + for _ in 0..pulses_left { + yy += 1.0; + let mut best_id = 0usize; + let mut best_num = -1e15f32; + let mut best_den = 0.0f32; + let mut j0 = 0usize; + if n >= 16 { + #[allow(deprecated)] + use wide::{CmpGt, f32x8}; + let chunks = n / 8; + let xy_v = f32x8::splat(xy); + let yy_v = f32x8::splat(yy); + let mut bn = f32x8::splat(-1e15); + let mut bd = f32x8::splat(0.0); + let mut bc = f32x8::splat(0.0); + for c in 0..chunks { + let mut xa = [0f32; 8]; + let mut ya = [0f32; 8]; + xa.copy_from_slice(&xs[c * 8..c * 8 + 8]); + ya.copy_from_slice(&y[c * 8..c * 8 + 8]); + let rxy = xy_v + f32x8::from(xa); + let ryy = yy_v + f32x8::from(ya); + let rxy2 = rxy * rxy; + let mask = (bd * rxy2).simd_gt(ryy * bn); + bn = mask.blend(rxy2, bn); + bd = mask.blend(ryy, bd); + bc = mask.blend(f32x8::splat(c as f32), bc); + } + let bn_a: [f32; 8] = bn.into(); + let bd_a: [f32; 8] = bd.into(); + let bc_a: [f32; 8] = bc.into(); + for l in 0..8 { + if best_den * bn_a[l] > bd_a[l] * best_num { + best_den = bd_a[l]; + best_num = bn_a[l]; + best_id = bc_a[l] as usize * 8 + l; + } + } + j0 = chunks * 8; + } + for j in j0..n { + let rxy = xy + xs[j]; + let ryy = yy + y[j]; + let rxy2 = rxy * rxy; + if best_den * rxy2 > ryy * best_num { + best_den = ryy; + best_num = rxy2; + best_id = j; + } + } + xy += xs[best_id]; + yy += y[best_id]; + y[best_id] += 2.0; + iy[best_id] += 1; + } + for j in 0..n { + if signs[j] < 0 { + iy[j] = -iy[j]; + } + } + if self.urow.len() < k + 2 { + self.urow.resize(k + 2, 0); + } + encode_pulses(enc, &self.iy[..n], n, k, &mut self.urow); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::range::RangeDecoder; + + /// The forward MDCT against the transform's definition, at the 2/l scale + /// CELT puts on the analysis side. + #[test] + fn forward_mdct_matches_the_definition() { + for &l in &[120usize, 240, 480, 960] { + let w = celt::overlap_window(); + let flat = (l - OVERLAP) / 2; + // The full 2l low-overlap window. + let mut win = vec![0.0f32; 2 * l]; + for i in 0..l { + win[i] = if i < flat { + 0.0 + } else if i < flat + OVERLAP { + w[i - flat] + } else { + 1.0 + }; + win[2 * l - 1 - i] = win[i]; + } + // A signal over the window's support, zero-padded to 2l. + let support = l + OVERLAP; + let sig: Vec = (0..support) + .map(|i| ((i * 2654435761usize) % 2000) as f32 / 1000.0 - 1.0) + .collect(); + let mut x2l = vec![0.0f32; 2 * l]; + for j in 0..support { + x2l[flat + j] = win[flat + j] * sig[j]; + } + // Direct MDCT by definition. + let direct: Vec = (0..l) + .map(|k| { + let mut sum = 0.0f64; + for (nn, &v) in x2l.iter().enumerate() { + let a = core::f64::consts::PI / l as f64 + * (nn as f64 + 0.5 + l as f64 / 2.0) + * (k as f64 + 0.5); + sum += v as f64 * a.cos(); + } + sum * 2.0 / l as f64 + }) + .collect(); + let mut plan = MdctPlan::new(l); + let mut out = vec![0.0f32; l]; + plan.forward(&sig, 0, &w, &mut out, 0, 1); + let mut worst = 0.0f64; + for k in 0..l { + worst = worst.max((direct[k] - out[k] as f64).abs()); + } + assert!(worst < 1e-4, "l={l}: worst coefficient error {worst}"); + } + } + + /// encode_pulses must invert decode_pulses for every (n, k) shape the + /// allocation can produce. + #[test] + fn pulse_enumeration_round_trips() { + let mut state = 0x2545F491u32; + let mut rand = move || { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + state + }; + for &(n, k) in &[ + (2usize, 1usize), + (2, 8), + (3, 4), + (4, 6), + (5, 3), + (8, 10), + (16, 7), + (24, 4), + (48, 2), + (96, 1), + (176, 2), + (22, 8), + (32, 6), + (11, 12), + (64, 4), + ] { + for _ in 0..20 { + // A random pulse vector with |y| summing to k. + let mut iy = vec![0i32; n]; + for _ in 0..k { + let j = (rand() as usize) % n; + iy[j] += 1; + } + for v in iy.iter_mut() { + if *v != 0 && rand() & 1 == 1 { + *v = -*v; + } + } + let mut enc = RangeEncoder::new(); + enc.reset(600); + let mut u = vec![0u32; k + 2]; + encode_pulses(&mut enc, &iy, n, k, &mut u); + enc.done(); + assert!(!enc.error()); + let data = enc.data().to_vec(); + let mut dec = RangeDecoder::new(&data); + let mut got = vec![0i32; n]; + let mut u2 = vec![0u32; k + 2]; + crate::celt::decode_pulses(&mut dec, n, k, &mut got, &mut u2); + assert_eq!(got, iy, "n={n} k={k}"); + } + } + } + + /// The Laplace encoder against the decoder, over the whole coarse-energy + /// model space. + #[test] + fn laplace_round_trips() { + #[allow(clippy::needless_range_loop)] + for lm in 0..4 { + for intra in 0..2 { + for band in 0..21usize { + let model = &E_PROB_MODEL[lm][intra]; + let pi = 2 * band.min(20); + let fs = (model[pi] as u32) << 7; + let decay = (model[pi + 1] as i32) << 6; + for val in -12i32..=12 { + let mut enc = RangeEncoder::new(); + enc.reset(64); + let mut v = val; + laplace_encode(&mut enc, &mut v, fs, decay); + enc.done(); + let data = enc.data().to_vec(); + let mut dec = RangeDecoder::new(&data); + let got = crate::celt::laplace_decode(&mut dec, fs, decay); + assert_eq!(got, v, "lm={lm} intra={intra} band={band} val={val}"); + } + } + } + } + } +} diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs new file mode 100644 index 00000000..01ce7211 --- /dev/null +++ b/crates/ec-opus/src/encoder.rs @@ -0,0 +1,193 @@ +//! The Opus packet encoder: CELT-only, fullband, 48 kHz. +//! +//! One [`Encoder`] produces ordinary code-0 Opus packets (RFC 6716 Section 3) +//! or the self-delimited variant of Appendix B that the multistream framing +//! needs. Every configuration this encoder emits is a fullband CELT one +//! (TOC configs 28..31), which is what music encoding uses at every rate the +//! product asks for; there is no SILK and no hybrid path — a speech-optimised +//! mode below 16 kbps is out of scope, not silently approximated. +//! +//! Rate control is CBR by default — every packet the same size, derived from +//! the bitrate — or constrained VBR, the reference's reservoir scheme, when +//! [`Encoder::set_vbr_constrained`] is on. + +use ec_core::{Error, Result}; + +use crate::celt_enc::CeltEncoder; +use crate::range::RangeEncoder; + +/// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`). +const MAX_FRAME_BYTES: usize = 1275; + +/// One elementary Opus encoder: mono or stereo, CELT-only, 48 kHz in. +#[derive(Clone, Debug)] +pub struct Encoder { + celt: CeltEncoder, + range: RangeEncoder, + channels: usize, + bitrate: u32, + vbr: bool, + final_range: u32, +} + +impl Encoder { + /// An encoder for `channels` channels (1 or 2) at `sample_rate`, which + /// must be 48000 — CELT's native rate, and the only rate the product + /// feeds it (RFC 7845 Section 5.1: every Opus decoder runs at 48 kHz + /// regardless of what the container claims). + pub fn new(sample_rate: u32, channels: usize) -> Result { + if sample_rate != 48000 { + return Err(Error::unsupported( + format!("opus encode at {sample_rate} Hz"), + "this CELT-only encoder takes 48 kHz input; resample first", + )); + } + if !(1..=2).contains(&channels) { + return Err(Error::unsupported( + format!("{channels}-channel Opus stream"), + "one stream carries at most two channels; use MultistreamEncoder", + )); + } + Ok(Encoder { + celt: CeltEncoder::new(channels), + range: RangeEncoder::new(), + channels, + bitrate: 64_000 * channels as u32, + vbr: false, + final_range: 0, + }) + } + + /// Channels per frame of input. + pub fn channels(&self) -> usize { + self.channels + } + + /// Target bitrate in bits per second for the whole packet stream, + /// including the packet headers. Clamped to 500..=510000. + pub fn set_bitrate(&mut self, bps: u32) { + self.bitrate = bps.clamp(500, 510_000); + } + + /// Current target bitrate. + pub fn bitrate(&self) -> u32 { + self.bitrate + } + + /// Switches between CBR (default, every packet the target size) and + /// constrained VBR (packets vary, a reservoir holds the average to the + /// target). + pub fn set_vbr_constrained(&mut self, vbr: bool) { + self.vbr = vbr; + } + + /// The range coder state after the last packet — the same value RFC 6716 + /// test vectors carry, and what a conformant decoder's `final_range` + /// must equal after decoding that packet. + pub fn final_range(&self) -> u32 { + self.final_range + } + + /// Drops all inter-frame state; the next packet starts like the first. + pub fn reset(&mut self) { + self.celt.reset(); + self.final_range = 0; + } + + fn toc(&self, frame_size: usize) -> Result { + let fs_idx: u8 = match frame_size { + 120 => 0, + 240 => 1, + 480 => 2, + 960 => 3, + _ => { + return Err(Error::unsupported( + format!("opus frame of {frame_size} samples"), + "CELT frames are 120, 240, 480 or 960 samples at 48 kHz", + )); + } + }; + let config = 28 + fs_idx; // fullband CELT + Ok((config << 3) | (u8::from(self.channels == 2) << 2)) + } + + /// Encodes one frame — `frame_size` samples per channel of interleaved + /// `f32` at 48 kHz, `frame_size` one of 120/240/480/960 — as a code-0 + /// Opus packet in `out`, returning the packet length. + pub fn encode_float( + &mut self, + pcm: &[f32], + frame_size: usize, + out: &mut [u8], + ) -> Result { + let toc = self.toc(frame_size)?; + let n = self.encode_frame(pcm, frame_size, out.len().saturating_sub(1))?; + if out.len() < 1 + n { + return Err(Error::corrupt(format!( + "opus encode: packet needs {} bytes, buffer holds {}", + 1 + n, + out.len() + ))); + } + out[0] = toc; + out[1..1 + n].copy_from_slice(&self.range.data()[..n]); + Ok(1 + n) + } + + /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716 + /// Appendix B: TOC, an explicit frame length, then the frame. This is + /// what every stream but the last uses inside a multistream packet. + pub fn encode_self_delimited( + &mut self, + pcm: &[f32], + frame_size: usize, + out: &mut [u8], + ) -> Result { + let toc = self.toc(frame_size)?; + let n = self.encode_frame(pcm, frame_size, out.len().saturating_sub(3))?; + let len_bytes = if n < 252 { 1 } else { 2 }; + if out.len() < 1 + len_bytes + n { + return Err(Error::corrupt(format!( + "opus encode: self-delimited packet needs {} bytes, buffer holds {}", + 1 + len_bytes + n, + out.len() + ))); + } + out[0] = toc; + if n < 252 { + out[1] = n as u8; + } else { + let b0 = 252 + ((n - 252) & 3); + out[1] = b0 as u8; + out[2] = ((n - b0) / 4) as u8; + } + out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(&self.range.data()[..n]); + Ok(1 + len_bytes + n) + } + + /// Encodes the CELT frame into the internal range coder and returns its + /// byte length. `cap` bounds the frame (the caller's buffer minus + /// headers). + fn encode_frame(&mut self, pcm: &[f32], frame_size: usize, cap: usize) -> Result { + let cap = cap.min(MAX_FRAME_BYTES); + if cap < 2 { + return Err(Error::corrupt( + "opus encode: output buffer smaller than the minimum packet", + )); + } + // One byte per packet goes to the TOC; the CELT layer sees the rest. + let toc_bps = 8 * 48000 / frame_size as u32; + let (budget, vbr_rate) = if self.vbr { + (cap, self.bitrate.saturating_sub(toc_bps).max(500)) + } else { + let b = ((self.bitrate as u64 * frame_size as u64 + 4 * 48000) / (8 * 48000)) as usize; + (b.saturating_sub(1).clamp(2, cap), 0) + }; + self.range.reset(budget); + let n = self + .celt + .encode(&mut self.range, pcm, frame_size, vbr_rate)?; + self.final_range = self.range.range(); + Ok(n) + } +} diff --git a/crates/ec-opus/src/lib.rs b/crates/ec-opus/src/lib.rs index b7d8d226..b482136c 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -27,22 +27,56 @@ //! a container, never a gap, so the concealment would be dead weight; a //! caller that needs it (an RTP receiver) has to add it. //! -//! No unsafe, no allocation on the per-frame path beyond the decoder's own +//! The crate also carries the family's Opus *encoder* — [`Encoder`] for one +//! stream, [`MultistreamEncoder`] for surround — CELT-only, fullband, mono +//! and stereo, every rate from 16 to 510 kbps, CBR and constrained VBR. +//! +//! **Why the incumbent encoder collapsed above ~128-165 kbps** (the measured +//! record this crate replaces; edith `engine/Cargo.toml:124-140` and +//! `export.rs:1834`): its packets above that rate were decodable only by its +//! *own* decoder — correlation 0.06 against libopus at 256 kbps while its +//! internal round trip read 0.999 — and the rate the cliff sat at moved with +//! the content. That signature — self-consistent, world-divergent, at a +//! *bits-per-band* threshold — is a shared encode/decode convention error in +//! exactly the code CELT only exercises when a band's budget is large: the +//! over-32-bit-codeword band split (RFC 6716 Section 4.3.4.1: a band whose bit +//! demand exceeds its cache row is halved recursively, with an entropy-coded +//! angle and a rebalance of the leftover bits). An encoder whose split +//! bookkeeping (`tell`-derived budgets, rebalance, theta pdf selection) +//! drifts one bit from the normative derivation still decodes its own output +//! — both halves share the drift — but a conformant decoder desynchronises, +//! and the threshold moves with content because the split only triggers on +//! loud, flat bands. Content-dependence is also why mono broke at *every* +//! rate: half the coefficients means every band hits the split threshold at +//! half the bitrate. This encoder mirrors the reference's allocation +//! arithmetic symbol for symbol, and the tests hold the closed loop to it: +//! every packet is range-state-exact against this crate's own +//! RFC-vector-verified decoder, and libopus (via ffmpeg) plus the reference +//! `opus_demo` decoder read the same packets at correlation >= 0.99 across +//! the whole rate table, mono, stereo and 5.1 alike. +//! +//! No unsafe, no allocation on the per-frame path beyond the codecs' own //! buffers, no dependencies outside the family. #![forbid(unsafe_code)] #![warn(missing_docs)] pub mod celt; +pub mod celt_enc; +pub mod encoder; pub mod multistream; +pub mod multistream_enc; pub mod packet; pub mod range; pub mod silk; pub use celt::CeltDecoder; +pub use celt_enc::CeltEncoder; +pub use encoder::Encoder; pub use multistream::MultistreamDecoder; +pub use multistream_enc::MultistreamEncoder; pub use packet::{Bandwidth, Mode, Packet, Toc}; -pub use range::RangeDecoder; +pub use range::{RangeDecoder, RangeEncoder}; pub use silk::SilkDecoder; use ec_core::{Error, Result}; diff --git a/crates/ec-opus/src/multistream_enc.rs b/crates/ec-opus/src/multistream_enc.rs new file mode 100644 index 00000000..6e625642 --- /dev/null +++ b/crates/ec-opus/src/multistream_enc.rs @@ -0,0 +1,168 @@ +//! Multichannel Opus encoding: several elementary streams in one packet. +//! +//! The exact mirror of [`crate::MultistreamDecoder`]: the first `coupled` +//! streams are stereo, the rest mono, all but the last written in the +//! self-delimited framing of RFC 6716 Appendix B. `mapping[c]` names the +//! coded channel that input channel `c` feeds — the same table, in the same +//! direction, that the decoder uses to route its output, so input channel +//! *order is the mapping's*: RFC 7845 family 1 (what a 5.1 film track uses) +//! is Vorbis order — left, centre, right, back left, back right, LFE. +//! +//! An input channel mapped to 255 is discarded; a coded channel no input +//! names is encoded as silence. + +use ec_core::{Error, Result}; + +use crate::encoder::Encoder; + +/// A multichannel Opus encoder, mono through 255 channels. +#[derive(Debug)] +pub struct MultistreamEncoder { + streams: Vec, + coupled: usize, + mapping: Vec, + channels: usize, + /// Scratch for one stream's deinterleaved input. + buf: Vec, +} + +impl MultistreamEncoder { + /// An encoder for `streams` elementary streams of which the first + /// `coupled` are stereo, with `mapping` naming the coded channel each + /// input channel feeds. Layout rules are the decoder's, checked the same + /// way. + pub fn new( + sample_rate: u32, + streams: usize, + coupled: usize, + mapping: &[u8], + ) -> Result { + if streams == 0 || streams > 255 || coupled > streams { + return Err(Error::corrupt(format!( + "opus multistream: {streams} streams of which {coupled} coupled" + ))); + } + let coded = coupled + streams; + if mapping.is_empty() || mapping.len() > 255 { + return Err(Error::corrupt(format!( + "opus multistream: {} input channels", + mapping.len() + ))); + } + if let Some(&bad) = mapping.iter().find(|&&m| m != 255 && m as usize >= coded) { + return Err(Error::corrupt(format!( + "opus multistream: mapping entry {bad} names a channel of {coded}" + ))); + } + let mut encoders = Vec::with_capacity(streams); + for s in 0..streams { + let ch = if s < coupled { 2 } else { 1 }; + encoders.push(Encoder::new(sample_rate, ch)?); + } + Ok(MultistreamEncoder { + streams: encoders, + coupled, + mapping: mapping.to_vec(), + channels: mapping.len(), + buf: vec![0.0; 2 * 960], + }) + } + + /// The RFC 7845 mapping-family-1 layout for 5.1: four streams, two + /// coupled, Vorbis channel order (FL, FC, FR, BL, BR, LFE). + pub fn surround_5_1(sample_rate: u32) -> Result { + MultistreamEncoder::new(sample_rate, 4, 2, &[0, 4, 1, 2, 3, 5]) + } + + /// Input channels per frame. + pub fn channels(&self) -> usize { + self.channels + } + + /// The `(streams, coupled, mapping)` triple a RFC 7845 `OpusHead` needs. + pub fn layout(&self) -> (usize, usize, &[u8]) { + (self.streams.len(), self.coupled, &self.mapping) + } + + /// Total target bitrate in bits per second, split over the streams with + /// a coupled stream weighing twice a mono one. + pub fn set_bitrate(&mut self, total_bps: u32) { + let mono = self.streams.len() - self.coupled; + let shares = (2 * self.coupled + mono) as u32; + let share = total_bps / shares.max(1); + for (s, enc) in self.streams.iter_mut().enumerate() { + let w = if s < self.coupled { 2 } else { 1 }; + enc.set_bitrate(share * w); + } + } + + /// CBR (default) or constrained VBR, applied to every stream. + pub fn set_vbr_constrained(&mut self, vbr: bool) { + for enc in self.streams.iter_mut() { + enc.set_vbr_constrained(vbr); + } + } + + /// Drops all inter-frame state in every stream. + pub fn reset(&mut self) { + for enc in self.streams.iter_mut() { + enc.reset(); + } + } + + /// The range coder states of all streams, combined the way RFC 6716 + /// Section 6 combines them for conformance checking. + pub fn final_range(&self) -> u32 { + self.streams.iter().fold(0, |acc, s| acc ^ s.final_range()) + } + + /// Encodes one frame — `frame_size` samples per channel of interleaved + /// `f32` in the mapping's channel order — as one multistream Opus packet + /// in `out`, returning the packet length. + pub fn encode_float( + &mut self, + pcm: &[f32], + frame_size: usize, + out: &mut [u8], + ) -> Result { + if pcm.len() < frame_size * self.channels { + return Err(Error::corrupt(format!( + "opus multistream encode: {} samples for {} channels of {frame_size}", + pcm.len(), + self.channels + ))); + } + let nb_streams = self.streams.len(); + let mut pos = 0usize; + for s in 0..nb_streams { + let stream_channels = if s < self.coupled { 2 } else { 1 }; + // Gather this stream's channels; a coded channel nobody feeds is + // silence. + self.buf[..frame_size * stream_channels].fill(0.0); + for off in 0..stream_channels { + let coded = if s < self.coupled { + 2 * s + off + } else { + self.coupled + s + }; + if let Some(c) = self.mapping.iter().position(|&m| m as usize == coded) { + for i in 0..frame_size { + self.buf[i * stream_channels + off] = pcm[i * self.channels + c]; + } + } + } + let last = s == nb_streams - 1; + let (head, buf) = (&mut out[pos..], &self.buf[..frame_size * stream_channels]); + // The borrow checker cannot see that `buf` and the encoder are + // disjoint fields through `&mut self`; a split borrow does. + let enc = &mut self.streams[s]; + let n = if last { + enc.encode_float(buf, frame_size, head)? + } else { + enc.encode_self_delimited(buf, frame_size, head)? + }; + pos += n; + } + Ok(pos) + } +} diff --git a/crates/ec-opus/src/range.rs b/crates/ec-opus/src/range.rs index 23dfe8ca..27d4b818 100644 --- a/crates/ec-opus/src/range.rs +++ b/crates/ec-opus/src/range.rs @@ -260,147 +260,331 @@ impl<'a> RangeDecoder<'a> { } } -#[cfg(test)] -mod tests { - use super::*; +/// The Opus range *encoder* (RFC 6716, Section 5.1) — the exact mirror of +/// [`RangeDecoder`], over a fixed-size buffer. +/// +/// Range-coded bytes grow from the front of the buffer, raw bits from the +/// back, exactly as the decoder reads them; the two meeting is a bust, which +/// [`RangeEncoder::error`] reports rather than corrupting either stream. The +/// buffer is owned and reused across frames — [`RangeEncoder::reset`] costs a +/// `fill(0)` of the frame, so a steady-state encoder never allocates here. +#[derive(Clone, Debug)] +pub struct RangeEncoder { + buf: Vec, + /// Logical frame size: the decoder will be handed `buf[..storage]`. + storage: usize, + /// Next byte the range coder writes, from the front. + offs: usize, + /// Bytes already written by the raw-bit writer, from the back. + end_offs: usize, + /// Bits buffered by the raw-bit writer (LSB first). + end_window: u32, + nend_bits: u32, + /// Whole bits written so far, including what is buffered in `rng`. + nbits_total: u32, + /// Low end of the current range. + val: u32, + /// Size of the current range. + rng: u32, + /// A buffered byte awaiting carry propagation, `-1` before the first. + rem: i32, + /// Count of buffered `0xFF` bytes that a carry would turn into `0x00`. + ext: u32, + error: bool, +} - /// A minimal range *encoder* (RFC 6716, Section 5.1), test-only: it exists - /// so the decoder can be checked against something other than itself on - /// symbol shapes the test vectors reach only rarely. The vectors, not this, - /// are the real oracle. - struct RangeEncoder { - buf: Vec, - low: u32, - rng: u32, - rem: i32, - ext: u32, - // raw bits, packed backwards - end_bits: Vec, - } - - impl RangeEncoder { - fn new() -> Self { - RangeEncoder { - buf: Vec::new(), - low: 0, - rng: 0x8000_0000, - rem: -1, - ext: 0, - end_bits: Vec::new(), - } +impl RangeEncoder { + /// An encoder with no buffer; call [`RangeEncoder::reset`] before use. + pub fn new() -> RangeEncoder { + RangeEncoder { + buf: Vec::new(), + storage: 0, + offs: 0, + end_offs: 0, + end_window: 0, + nend_bits: 0, + nbits_total: CODE_BITS + 1, + val: 0, + rng: 1 << (CODE_BITS - 1), + rem: -1, + ext: 0, + error: false, } + } - fn carry_out(&mut self, c: i32) { - if c != 0xFF { - let carry = c >> 8; - if self.rem >= 0 { - let v = (self.rem + carry) as u8; - self.buf.push(v); - } - while self.ext > 0 { - self.buf.push(((0xFF + carry) & 0xFF) as u8); - self.ext -= 1; - } - self.rem = c & 0xFF; - } else { - self.ext += 1; - } + /// Starts a fresh frame of exactly `size` bytes. + pub fn reset(&mut self, size: usize) { + if self.buf.len() < size { + self.buf.resize(size, 0); } + self.buf[..size].fill(0); + self.storage = size; + self.offs = 0; + self.end_offs = 0; + self.end_window = 0; + self.nend_bits = 0; + self.nbits_total = CODE_BITS + 1; + self.val = 0; + self.rng = 1 << (CODE_BITS - 1); + self.rem = -1; + self.ext = 0; + self.error = false; + } - fn normalize(&mut self) { - while self.rng <= CODE_TOP { - self.carry_out((self.low >> 23) as i32); - self.low = (self.low << 8) & 0x7FFF_FFFF; - self.rng <<= 8; - } + /// The encoder's current range state — what the decoder's + /// [`RangeDecoder::range`] must equal after the same symbols. + pub fn range(&self) -> u32 { + self.rng + } + + /// True when the frame busted its budget; the frame is unusable. + pub fn error(&self) -> bool { + self.error + } + + /// The frame size in bytes. + pub fn storage(&self) -> usize { + self.storage + } + + /// Bytes the range coder has finalised so far (`ec_range_bytes`). + pub fn range_bytes(&self) -> usize { + self.offs + } + + /// The finished frame; call only after [`RangeEncoder::done`]. + pub fn data(&self) -> &[u8] { + &self.buf[..self.storage] + } + + fn write_byte(&mut self, value: u32) { + if self.offs + self.end_offs >= self.storage { + self.error = true; + return; } + self.buf[self.offs] = value as u8; + self.offs += 1; + } - fn encode(&mut self, fl: u32, fh: u32, ft: u32) { - let r = self.rng / ft; - if fl > 0 { - self.low = self.low.wrapping_add(self.rng - r * (ft - fl)); - self.rng = r * (fh - fl); - } else { - self.rng -= r * (ft - fh); - } - self.normalize(); + fn write_byte_at_end(&mut self, value: u32) { + if self.offs + self.end_offs >= self.storage { + self.error = true; + return; } + self.end_offs += 1; + self.buf[self.storage - self.end_offs] = value as u8; + } - fn enc_bit_logp(&mut self, bit: bool, logp: u32) { - let s = self.rng >> logp; - if bit { - self.low = self.low.wrapping_add(self.rng - s); - self.rng = s; - } else { - self.rng -= s; + fn carry_out(&mut self, c: i32) { + if c != 0xFF { + let carry = c >> 8; + if self.rem >= 0 { + self.write_byte((self.rem + carry) as u32); } - self.normalize(); + while self.ext > 0 { + self.write_byte(((0xFF + carry) & 0xFF) as u32); + self.ext -= 1; + } + self.rem = c & 0xFF; + } else { + self.ext += 1; } + } - fn enc_icdf(&mut self, k: usize, icdf: &[u8], ftb: u32) { - let r = self.rng >> ftb; - if k > 0 { - self.low = self.low.wrapping_add(self.rng - r * icdf[k - 1] as u32); - self.rng = r * (icdf[k - 1] as u32 - icdf[k] as u32); - } else { - self.rng -= r * icdf[k] as u32; - } - self.normalize(); + fn normalize(&mut self) { + while self.rng <= CODE_TOP { + self.carry_out((self.val >> 23) as i32); + self.val = (self.val << 8) & 0x7FFF_FFFF; + self.rng <<= 8; + self.nbits_total += 8; } + } - fn enc_uint(&mut self, value: u32, ft: u32) { - let ftb = ilog(ft - 1); - if ftb <= 8 { - self.encode(value, value + 1, ft); - } else { - let ftb = ftb - 8; - let hi = value >> ftb; - self.encode(hi, hi + 1, ((ft - 1) >> ftb) + 1); - self.enc_bits(value & ((1 << ftb) - 1), ftb); - } + /// `ec_encode()`: one symbol spanning `[fl, fh)` of `ft`. + #[inline] + pub fn encode(&mut self, fl: u32, fh: u32, ft: u32) { + let r = self.rng / ft; + if fl > 0 { + self.val = self.val.wrapping_add(self.rng - r * (ft - fl)); + self.rng = r * (fh - fl); + } else { + self.rng -= r * (ft - fh); } + self.normalize(); + } - fn enc_bits(&mut self, value: u32, bits: u32) { - for i in 0..bits { - self.end_bits.push((value >> i) & 1 == 1); - } + /// `ec_encode_bin()`: [`RangeEncoder::encode`] with `ft = 1<> bits; + if fl > 0 { + self.val = self.val.wrapping_add(self.rng - r * ((1 << bits) - fl)); + self.rng = r * (fh - fl); + } else { + self.rng -= r * ((1 << bits) - fh); } + self.normalize(); + } - /// Terminates the stream and returns the frame bytes. - fn finish(mut self) -> Vec { - // Output the value in [low, low+rng) with the most trailing zero - // bits, so the raw bits may overwrite them (Section 5.1.5). - let mut l = (32 - ilog(self.rng)) as i32; - let mut msk = 0x7FFF_FFFFu32 >> l; - let mut end = self.low.wrapping_add(msk) & !msk; - if (end | msk) as u64 >= self.low as u64 + self.rng as u64 { - l += 1; - msk >>= 1; - end = self.low.wrapping_add(msk) & !msk; - } - while l > 0 { - self.carry_out((end >> 23) as i32); - end = (end << 8) & 0x7FFF_FFFF; - l -= 8; - } - if self.rem >= 0 || self.ext > 0 { - self.carry_out(0); + /// `ec_enc_bit_logp()`: one bit whose probability of being 1 is `2**-logp`. + #[inline] + pub fn enc_bit_logp(&mut self, bit: bool, logp: u32) { + let r = self.rng; + let l = self.val; + let s = r >> logp; + let r = r - s; + if bit { + self.val = l.wrapping_add(r); + } + self.rng = if bit { s } else { r }; + self.normalize(); + } + + /// `ec_enc_icdf()`: symbol `k` of an inverse-CDF table, `ft = 1<> ftb; + if k > 0 { + self.val = self.val.wrapping_add(self.rng - r * icdf[k - 1] as u32); + self.rng = r * (icdf[k - 1] as u32 - icdf[k] as u32); + } else { + self.rng -= r * icdf[k] as u32; + } + self.normalize(); + } + + /// `ec_enc_uint()`: `value` as one of `ft` equiprobable values + /// (Section 5.1.4). `ft` must be at least 2. + pub fn enc_uint(&mut self, value: u32, ft: u32) { + debug_assert!(ft > 1); + let ft = ft - 1; + let ftb = ilog(ft); + if ftb > 8 { + let ftb = ftb - 8; + let ft1 = (ft >> ftb) + 1; + let hi = value >> ftb; + self.encode(hi, hi + 1, ft1); + self.enc_bits(value & ((1u32 << ftb) - 1), ftb); + } else { + self.encode(value, value + 1, ft + 1); + } + } + + /// `ec_enc_bits()`: `bits` raw bits, written backwards from the end of the + /// frame. + pub fn enc_bits(&mut self, fl: u32, bits: u32) { + debug_assert!(bits > 0); + let mut window = self.end_window; + let mut used = self.nend_bits; + if used + bits > 32 { + while used >= 8 { + self.write_byte_at_end(window & 0xFF); + window >>= 8; + used -= 8; } - // Append the raw bits, packed backwards from the end. - let raw_bytes = self.end_bits.len().div_ceil(8); - let mut tail = vec![0u8; raw_bytes]; - for (i, &b) in self.end_bits.iter().enumerate() { - if b { - let byte = raw_bytes - 1 - i / 8; - tail[byte] |= 1 << (i % 8); + } + window |= fl << used; + used += bits; + self.end_window = window; + self.nend_bits = used; + self.nbits_total += bits; + } + + /// `ec_enc_shrink()`: reduces the frame to `size` bytes, moving raw bits + /// already written so they still end the frame. Only legal while + /// `range_bytes()` plus the raw-bit bytes fit in `size`. + pub fn shrink(&mut self, size: usize) { + debug_assert!(self.offs + self.end_offs <= size); + self.buf.copy_within( + self.storage - self.end_offs..self.storage, + size - self.end_offs, + ); + self.storage = size; + // The abandoned tail must be zero for the "rest is zeros" guarantee. + if size > self.offs + self.end_offs { + self.buf[self.offs..size - self.end_offs].fill(0); + } + } + + /// `ec_tell()`: a conservative upper bound on whole bits used so far. + #[inline] + pub fn tell(&self) -> u32 { + self.nbits_total - ilog(self.rng) + } + + /// `ec_tell_frac()`: the same bound in 1/8th bits. + pub fn tell_frac(&self) -> u32 { + let mut lg = ilog(self.rng); + let mut r_q15 = self.rng >> (lg - 16); + for _ in 0..3 { + r_q15 = (r_q15 * r_q15) >> 15; + let bit = r_q15 >> 16; + lg = 2 * lg + bit; + r_q15 >>= bit; + } + self.nbits_total * 8 - lg + } + + /// Declares the rest of the frame used, so [`RangeEncoder::tell`] reports + /// the whole frame — the encoder side of the decoder's `skip_to_end`, + /// which is what a silent CELT frame does with its remaining bits. + pub fn pad_to_end(&mut self) { + self.nbits_total = (self.storage as u32) * 8 + ilog(self.rng); + } + + /// `ec_enc_done()`: terminates the frame. Everything between the range + /// bytes and the raw bits is left as zeros, which the decoder reads as + /// zeros — a CBR frame is therefore always exactly `storage` bytes. + pub fn done(&mut self) { + // Output the value in [val, val+rng) with the most trailing zeros. + let mut l = CODE_BITS as i32 - ilog(self.rng) as i32; + let mut msk = 0x7FFF_FFFFu32 >> l; + let mut end = self.val.wrapping_add(msk) & !msk; + if (end | msk) as u64 >= self.val as u64 + self.rng as u64 { + l += 1; + msk >>= 1; + end = self.val.wrapping_add(msk) & !msk; + } + while l > 0 { + self.carry_out((end >> 23) as i32); + end = (end << 8) & 0x7FFF_FFFF; + l -= 8; + } + if self.rem >= 0 || self.ext > 0 { + self.carry_out(0); + } + let mut window = self.end_window; + let mut used = self.nend_bits; + while used >= 8 { + self.write_byte_at_end(window & 0xFF); + window >>= 8; + used -= 8; + } + if !self.error && used > 0 { + // Anything not written is already zero (reset cleared the frame). + if self.end_offs >= self.storage { + self.error = true; + } else { + let l = -l; + if self.offs + self.end_offs >= self.storage && (l as u32) < used { + window &= (1u32 << l) - 1; + self.error = true; } + self.buf[self.storage - self.end_offs - 1] |= window as u8; } - // Pad so the range data and raw data never collide in this test. - self.buf.resize(self.buf.len() + 8, 0); - self.buf.extend_from_slice(&tail); - self.buf } } +} + +impl Default for RangeEncoder { + fn default() -> Self { + RangeEncoder::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; #[test] fn roundtrip_mixed_symbols() { @@ -412,6 +596,7 @@ mod tests { let uints: Vec = vec![0, 1, 5, 1000, 65535, 70000, 3]; let mut enc = RangeEncoder::new(); + enc.reset(512); for &s in &syms { enc.enc_icdf(s, ICDF, 4); } @@ -426,7 +611,9 @@ mod tests { enc.encode(fl, fl + 4, 16); } enc.enc_bits(0b1011, 4); - let frame = enc.finish(); + enc.done(); + assert!(!enc.error()); + let frame = enc.data().to_vec(); let mut dec = RangeDecoder::new(&frame); for &s in &syms { @@ -444,6 +631,86 @@ mod tests { assert_eq!(dec.dec_bits(4), 0b1011); } + /// The bit allocation is derived from `tell()`/`tell_frac()` on *both* + /// sides, so the encoder's accounting must match the decoder's after every + /// symbol — one bit of drift desynchronises the whole frame. + #[test] + fn encoder_and_decoder_tell_identically() { + const ICDF: &[u8] = &[100, 60, 30, 10, 0]; + let mut enc = RangeEncoder::new(); + enc.reset(256); + let mut log = Vec::new(); + let mut x = 7u32; + for i in 0..300 { + x = x.wrapping_mul(1664525).wrapping_add(1013904223); + match i % 4 { + 0 => enc.enc_icdf((x % 5) as usize, ICDF, 7), + 1 => enc.enc_bit_logp(x & 1 == 0, (x % 6) + 1), + 2 => enc.enc_uint(x % 500, 700), + _ => enc.enc_bits(x & 0x1F, 5), + } + log.push((i % 4, x, enc.tell(), enc.tell_frac(), enc.range())); + } + enc.done(); + assert!(!enc.error()); + let data = enc.data().to_vec(); + let mut dec = RangeDecoder::new(&data); + for (kind, x, tell, tell_frac, rng) in log { + match kind { + 0 => assert_eq!(dec.dec_icdf(ICDF, 7), (x % 5) as usize), + 1 => assert_eq!(dec.dec_bit_logp((x % 6) + 1), x & 1 == 0), + 2 => assert_eq!(dec.dec_uint(700), x % 500), + _ => assert_eq!(dec.dec_bits(5), x & 0x1F), + } + assert_eq!(dec.tell(), tell, "tell drifted"); + assert_eq!(dec.tell_frac(), tell_frac, "tell_frac drifted"); + assert_eq!(dec.range(), rng, "range state drifted"); + } + } + + /// A CBR frame stays exactly `storage` bytes: whatever the symbols leave + /// unused decodes as zeros, which is what the encoder assumed. + #[test] + fn fixed_size_frame_decodes_past_the_coded_symbols() { + let mut enc = RangeEncoder::new(); + enc.reset(40); + enc.enc_icdf(1, &[100, 50, 0], 7); + enc.enc_bits(0b101, 3); + enc.done(); + assert!(!enc.error()); + assert_eq!(enc.data().len(), 40); + let data = enc.data().to_vec(); + let mut dec = RangeDecoder::new(&data); + assert_eq!(dec.dec_icdf(&[100, 50, 0], 7), 1); + assert_eq!(dec.dec_bits(3), 0b101); + // The rest of the frame reads as zero symbols, not garbage. + for _ in 0..50 { + let _ = dec.dec_bit_logp(4); + } + } + + /// `shrink` moves the raw-bit tail; symbols written before and after the + /// shrink must both survive. + #[test] + fn shrink_preserves_both_streams() { + let mut enc = RangeEncoder::new(); + enc.reset(200); + enc.enc_uint(1234, 5000); + enc.enc_bits(0xAB, 8); + enc.shrink(50); + enc.enc_uint(999, 5000); + enc.enc_bits(0x5, 4); + enc.done(); + assert!(!enc.error()); + assert_eq!(enc.data().len(), 50); + let data = enc.data().to_vec(); + let mut dec = RangeDecoder::new(&data); + assert_eq!(dec.dec_uint(5000), 1234); + assert_eq!(dec.dec_bits(8), 0xAB); + assert_eq!(dec.dec_uint(5000), 999); + assert_eq!(dec.dec_bits(4), 0x5); + } + #[test] fn tell_agrees_with_tell_frac() { let data: Vec = (0..64u8) diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index b67f7b92..04a05f53 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -9,6 +9,50 @@ use std::path::{Path, PathBuf}; use ec_opus::Decoder; +// --------------------------------------------------------------------------- +// Counting allocator: proves the steady-state encode loop allocates nothing. +// Lives in the test binary only — the shipped crate has no allocator games. +// Same pattern as ec-h264's proof: only the thread that armed the counter is +// counted, so parallel tests (and ffmpeg child plumbing) allocate freely. +// --------------------------------------------------------------------------- + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; +use std::sync::atomic::{AtomicU64, Ordering}; + +struct CountingAlloc; + +static ALLOCS: AtomicU64 = AtomicU64::new(0); + +std::thread_local! { + static COUNTING_HERE: Cell = const { Cell::new(false) }; +} + +fn counting_here() -> bool { + COUNTING_HERE.try_with(Cell::get).unwrap_or(false) +} + +unsafe impl GlobalAlloc for CountingAlloc { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + if counting_here() { + ALLOCS.fetch_add(1, Ordering::Relaxed); + } + unsafe { System.alloc(layout) } + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) } + } + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + if counting_here() { + ALLOCS.fetch_add(1, Ordering::Relaxed); + } + unsafe { System.realloc(ptr, layout, new_size) } + } +} + +#[global_allocator] +static A: CountingAlloc = CountingAlloc; + /// One packet of an `opus_demo` test vector file. struct VectorPacket { payload: Vec, @@ -724,6 +768,580 @@ fn real_library_sweep() { } } +// --------------------------------------------------------------------------- +// Encoder: self-consistency (range-exact against our own decoder) +// --------------------------------------------------------------------------- + +use ec_opus::{Encoder, MultistreamEncoder}; + +/// A deterministic music-like test signal: several detuned partials plus a +/// swept component per channel, loud enough to exercise every band. +fn test_signal(channels: usize, secs: f64) -> Vec { + let n = (48000.0 * secs) as usize; + let mut out = Vec::with_capacity(n * channels); + for i in 0..n { + let t = i as f64 / 48000.0; + for c in 0..channels { + let base = 220.0 * (c as f64 * 0.5 + 1.0); + let sweep = 400.0 + 3000.0 * (0.5 + 0.5 * (0.13 * t).sin()); + let v = 0.35 * (std::f64::consts::TAU * base * t).sin() + + 0.2 * (std::f64::consts::TAU * base * 3.01 * t).sin() + + 0.12 * (std::f64::consts::TAU * sweep * t).sin() + + 0.08 * (std::f64::consts::TAU * 9000.0 * (1.0 + 0.02 * c as f64) * t).sin(); + out.push(v as f32); + } + } + out +} + +/// Encodes `pcm` in `frame`-sample packets and decodes each with our own +/// decoder, asserting the range coder states agree packet for packet — the +/// same bit-exact check the RFC vectors put on the decoder, now closing the +/// loop over the encoder. Returns the decoded signal and total packet bytes. +fn roundtrip_own( + enc: &mut Encoder, + pcm: &[f32], + channels: usize, + frame: usize, +) -> (Vec, usize) { + let mut dec = Decoder::new(48000, channels).unwrap(); + let mut out = vec![0u8; 1500]; + let mut decoded = Vec::new(); + let mut buf = vec![0.0f32; 5760 * channels]; + let mut bytes = 0usize; + let mut padded = Vec::new(); + for block in pcm.chunks(frame * channels) { + let block = if block.len() < frame * channels { + padded.clear(); + padded.extend_from_slice(block); + padded.resize(frame * channels, 0.0); + &padded[..] + } else { + block + }; + let len = enc.encode_float(block, frame, &mut out).expect("encode"); + bytes += len; + let n = dec.decode_float(&out[..len], &mut buf).expect("decode"); + assert_eq!(n, frame, "decoded frame size"); + assert_eq!( + dec.final_range(), + enc.final_range(), + "range state diverged between encoder and decoder" + ); + decoded.extend_from_slice(&buf[..n * channels]); + } + (decoded, bytes) +} + +/// Worst-channel correlation against the source with the encoder's +/// 120-sample delay removed. +fn delayed_corr(source: &[f32], decoded: &[f32], channels: usize) -> f64 { + const DELAY: usize = 120; + let n = (decoded.len() / channels).saturating_sub(DELAY); + let n = n.min(source.len() / channels); + let mut worst = 1.0f64; + for c in 0..channels { + let a: Vec = (0..n).map(|i| source[i * channels + c]).collect(); + let b: Vec = (0..n) + .map(|i| decoded[(i + DELAY) * channels + c]) + .collect(); + worst = worst.min(correlation(&a, &b)); + } + worst +} + +/// Every rate from the product's table, mono and stereo, 20 ms CBR: the +/// encoder must be decodable by its own decoder range-exactly (asserted in +/// the helper) and land close to the source. The cross-implementation checks +/// against libopus live below — self-consistency alone proves nothing about +/// the world (the incumbent's exact disease). +#[test] +fn encoder_roundtrips_at_every_rate() { + for channels in [1usize, 2] { + let pcm = test_signal(channels, 2.0); + for kbps in [32u32, 64, 96, 128, 160, 165, 192, 256, 320, 510] { + let mut enc = Encoder::new(48000, channels).unwrap(); + enc.set_bitrate(kbps * 1000); + let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, channels, 960); + let corr = delayed_corr(&pcm, &decoded, channels); + let rate = bytes as f64 * 8.0 / 2.0 / 1000.0; + println!("{channels} ch {kbps:>3} kbps: corr {corr:.4}, actual {rate:.1} kbps"); + let floor = if kbps < 64 { 0.8 } else { 0.9 }; + assert!( + corr >= floor, + "{channels} ch {kbps} kbps: correlation {corr:.4}" + ); + } + } +} + +/// All four CELT frame sizes survive the loop, and constrained VBR both +/// stays decodable and lands near its target. +#[test] +fn encoder_frame_sizes_and_vbr() { + let pcm = test_signal(2, 1.0); + for frame in [120usize, 240, 480, 960] { + let mut enc = Encoder::new(48000, 2).unwrap(); + enc.set_bitrate(128_000); + let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, frame); + let corr = delayed_corr(&pcm, &decoded, 2); + println!("frame {frame}: corr {corr:.4}"); + assert!(corr >= 0.85, "frame {frame}: correlation {corr:.4}"); + } + let mut enc = Encoder::new(48000, 2).unwrap(); + enc.set_bitrate(128_000); + enc.set_vbr_constrained(true); + let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, 2, 960); + let corr = delayed_corr(&pcm, &decoded, 2); + let rate = bytes as f64 * 8.0 / 1.0 / 1000.0; + println!("cvbr 128k: corr {corr:.4}, actual {rate:.1} kbps"); + assert!(corr >= 0.9, "cvbr: correlation {corr:.4}"); + assert!( + (90.0..=150.0).contains(&rate), + "cvbr at 128k landed on {rate:.1} kbps" + ); +} + +// --------------------------------------------------------------------------- +// Encoder: the world must decode it. Self-consistency alone was the +// incumbent's disease (correlation 0.06 against libopus at 256 kbps while +// its own round trip passed), so every claim here runs through ffmpeg's +// libopus — the reference implementation — via Ogg-Opus files this crate +// muxed itself. +// --------------------------------------------------------------------------- + +use ec_core::registry::{CodecId, CodecParameters, MediaParameters, Muxer, StreamInfo}; +use ec_core::{ChannelLayout, Packet as CorePacket, TimeBase}; +use ec_ogg::OggMuxer; + +/// The RFC 7845 identification header for this encoder: pre-skip 120, the +/// CELT overlap delay. +fn opus_head(channels: usize, layout: Option<(usize, usize, &[u8])>) -> Vec { + let mut h = Vec::from(*b"OpusHead"); + h.push(1); + h.push(channels as u8); + h.extend_from_slice(&120u16.to_le_bytes()); + h.extend_from_slice(&48000u32.to_le_bytes()); + h.extend_from_slice(&0i16.to_le_bytes()); + match layout { + None => h.push(0), + Some((streams, coupled, mapping)) => { + h.push(1); + h.push(streams as u8); + h.push(coupled as u8); + h.extend_from_slice(mapping); + } + } + h +} + +/// Muxes 20 ms packets into an Ogg-Opus file whose final granule trims the +/// stream to exactly `total_samples` — RFC 7845 end-trimming plus the +/// pre-skip accounting. +fn write_ogg_opus( + path: &Path, + packets: &[Vec], + head: Vec, + channels: usize, + total_samples: usize, +) { + let file = std::io::BufWriter::new(fs::File::create(path).unwrap()); + let mut mux = OggMuxer::new(file); + let tb = TimeBase::from_rate(48000); + let mut params = CodecParameters::new(CodecId::Opus); + params.extradata = Some(head.into()); + if let MediaParameters::Audio(a) = &mut params.media { + a.sample_rate = 48000; + a.layout = ChannelLayout::from_count(channels); + } + mux.add_stream(StreamInfo::new(0, tb, params)).unwrap(); + let mut pts = 0i64; + for (idx, p) in packets.iter().enumerate() { + let last = idx == packets.len() - 1; + let dur = if last { + total_samples as i64 + 120 - pts + } else { + 960 + }; + let pkt = CorePacket::new(0, tb, p.clone()) + .with_pts(pts) + .with_duration(dur); + mux.write_packet(&pkt).unwrap(); + pts += 960; + } + mux.finish().unwrap(); +} + +/// Encodes `pcm` (plus one flush frame for the 120-sample delay) as 20 ms +/// packets. +fn encode_packets(enc: &mut Encoder, pcm: &[f32], channels: usize) -> Vec> { + let mut out = vec![0u8; 1500]; + let mut packets = Vec::new(); + let mut padded = Vec::new(); + for block in pcm.chunks(960 * channels) { + let block = if block.len() < 960 * channels { + padded.clear(); + padded.extend_from_slice(block); + padded.resize(960 * channels, 0.0); + &padded[..] + } else { + block + }; + let len = enc.encode_float(block, 960, &mut out).expect("encode"); + packets.push(out[..len].to_vec()); + } + // One silent frame flushes the delay past the end trim. + let silence = vec![0.0f32; 960 * channels]; + let len = enc.encode_float(&silence, 960, &mut out).expect("encode"); + packets.push(out[..len].to_vec()); + packets +} + +fn temp_path(name: &str) -> PathBuf { + std::env::temp_dir().join(format!("ec-opus-enc-{}-{name}", std::process::id())) +} + +/// The full product rate table, mono and stereo, decoded by libopus: the +/// worst-channel correlation and the opus_compare quality, per rate. The +/// incumbent fails this file's 256 kbps row at correlation 0.06; the MUST +/// bars here are correlation >= 0.9 at 96/165/256 kbps. +#[test] +fn libopus_decodes_our_packets_across_the_rate_table() { + for channels in [1usize, 2] { + let pcm = test_signal(channels, 2.0); + let total = pcm.len() / channels; + let mut table = Vec::new(); + for kbps in [32u32, 64, 96, 128, 160, 165, 192, 256, 320, 510] { + let mut enc = Encoder::new(48000, channels).unwrap(); + enc.set_bitrate(kbps * 1000); + let packets = encode_packets(&mut enc, &pcm, channels); + let path = temp_path(&format!("{channels}ch-{kbps}k.opus")); + write_ogg_opus(&path, &packets, opus_head(channels, None), channels, total); + let Some(reference) = ffmpeg_decode(&path, channels) else { + eprintln!("ffmpeg unavailable, skipped"); + let _ = fs::remove_file(&path); + return; + }; + let _ = fs::remove_file(&path); + let n = (reference.len() / channels).min(total); + assert!( + n >= total - 960, + "{channels} ch {kbps} kbps: libopus returned {n} of {total} samples" + ); + let mut worst = 1.0f64; + for c in 0..channels { + let a: Vec = (0..n).map(|i| pcm[i * channels + c]).collect(); + let b: Vec = (0..n).map(|i| reference[i * channels + c]).collect(); + worst = worst.min(correlation(&a, &b)); + } + let quality = opus_compare( + &to_i16(&pcm[..n * channels]), + &to_i16(&reference[..n * channels]), + channels, + ); + table.push(format!( + "{channels} ch {kbps:>3} kbps: worst corr {worst:.4}, opus_compare {quality:.1}" + )); + let floor = match kbps { + 0..=39 => 0.6, + 40..=95 => 0.8, + _ => 0.9, + }; + assert!( + worst >= floor, + "{channels} ch {kbps} kbps: libopus heard correlation {worst:.4} (floor {floor})" + ); + if kbps >= 96 { + assert!( + quality >= 0.0, + "{channels} ch {kbps} kbps: opus_compare {quality:.1}" + ); + } + } + for line in table { + println!("{line}"); + } + } +} + +/// 5.1 multistream: one distinct tone per channel, encoded with the +/// mapping-family-1 layout and decoded by libopus — every channel must come +/// back in its place (order-preserved) at correlation >= 0.9. +#[test] +fn five_one_encode_end_to_end() { + const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3]; + const TONES: [f64; 6] = [220.0, 440.0, 660.0, 55.0, 880.0, 1320.0]; + let total = 96000usize; + // Vorbis order input, one tone per channel plus a quiet upper partial so + // every stream codes real content. + let mut pcm = Vec::with_capacity(total * 6); + for i in 0..total { + let t = i as f64 / 48000.0; + for f in TONES { + let v = 0.4 * (std::f64::consts::TAU * f * t).sin() + + 0.05 * (std::f64::consts::TAU * f * 7.03 * t).sin(); + pcm.push(v as f32); + } + } + let mut enc = MultistreamEncoder::surround_5_1(48000).unwrap(); + enc.set_bitrate(384_000); + let mut out = vec![0u8; 8 * 1500]; + let mut packets = Vec::new(); + for block in pcm.chunks_exact(960 * 6) { + let len = enc.encode_float(block, 960, &mut out).expect("encode"); + packets.push(out[..len].to_vec()); + } + let silence = vec![0.0f32; 960 * 6]; + let len = enc.encode_float(&silence, 960, &mut out).expect("encode"); + packets.push(out[..len].to_vec()); + let (streams, coupled, mapping) = enc.layout(); + let head = opus_head(6, Some((streams, coupled, mapping))); + let path = temp_path("5.1.opus"); + write_ogg_opus(&path, &packets, head, 6, total); + let Some(reference) = ffmpeg_decode(&path, 6) else { + eprintln!("ffmpeg unavailable, skipped"); + let _ = fs::remove_file(&path); + return; + }; + let _ = fs::remove_file(&path); + let n = (reference.len() / 6).min(total); + assert!(n >= total - 960, "libopus returned {n} of {total} samples"); + for (c, &their) in VORBIS_TO_FFMPEG_5_1.iter().enumerate() { + let a: Vec = (0..n).map(|i| pcm[i * 6 + c]).collect(); + let b: Vec = (0..n).map(|i| reference[i * 6 + their]).collect(); + let corr = correlation(&a, &b); + println!("5.1 channel {c} ({} Hz): corr {corr:.4}", TONES[c]); + assert!( + corr >= 0.9, + "5.1 channel {c} came back at correlation {corr:.4}" + ); + } +} + +/// The muxed file's duration must be exact: the final granule trims the +/// flush frame so a 2.000 s input probes as 2.000 s, and the sample count +/// libopus hands back is exactly the input length. +#[test] +fn ogg_opus_round_trip_duration_is_exact() { + let pcm = test_signal(2, 2.0); + let total = pcm.len() / 2; + let mut enc = Encoder::new(48000, 2).unwrap(); + enc.set_bitrate(128_000); + let packets = encode_packets(&mut enc, &pcm, 2); + let path = temp_path("duration.opus"); + write_ogg_opus(&path, &packets, opus_head(2, None), 2, total); + let probe = Command::new("ffprobe") + .args([ + "-v", + "error", + "-show_entries", + "stream=duration", + "-of", + "default=noprint_wrappers=1", + ]) + .arg(&path) + .output(); + if let Ok(p) = probe + && p.status.success() + { + let text = String::from_utf8_lossy(&p.stdout); + let dur: f64 = text + .trim() + .strip_prefix("duration=") + .unwrap_or("0") + .parse() + .unwrap_or(0.0); + // ffprobe reports Ogg-Opus durations *including* the pre-skip — its + // own 3.000 s encode probes as 3.0065 (312/48000 more). Ours carries + // a 120-sample pre-skip, so exact is 2.0025; the decoded sample + // count below is the pre-skip-free half of the claim. + let expected = (total as f64 + 120.0) / 48000.0; + assert!( + (dur - expected).abs() < 1e-6, + "ffprobe reports {dur} s, expected {expected} s (2.000 s + pre-skip)" + ); + } + if let Some(decoded) = ffmpeg_decode(&path, 2) { + assert_eq!( + decoded.len() / 2, + total, + "libopus decoded {} samples of {total}", + decoded.len() / 2 + ); + } + let _ = fs::remove_file(&path); +} + +/// Cross-check against the reference `opus_demo` decoder (RFC 6716 +/// Appendix A) over its own `.bit` format, when the binary is available: +/// `EC_OPUS_DEMO=/path/to/opus_demo cargo test`. +#[test] +fn opus_demo_decodes_our_bit_stream() { + let Ok(demo) = std::env::var("EC_OPUS_DEMO") else { + eprintln!("EC_OPUS_DEMO unset, skipped"); + return; + }; + let pcm = test_signal(2, 2.0); + let mut enc = Encoder::new(48000, 2).unwrap(); + enc.set_bitrate(256_000); + let mut out = vec![0u8; 1500]; + let mut bit = Vec::new(); + for block in pcm.chunks_exact(960 * 2) { + let len = enc.encode_float(block, 960, &mut out).expect("encode"); + bit.extend_from_slice(&(len as u32).to_be_bytes()); + bit.extend_from_slice(&enc.final_range().to_be_bytes()); + bit.extend_from_slice(&out[..len]); + } + let bit_path = temp_path("demo.bit"); + let pcm_path = temp_path("demo.pcm"); + fs::write(&bit_path, &bit).unwrap(); + let status = Command::new(&demo) + .arg("-d") + .arg("48000") + .arg("2") + .arg(&bit_path) + .arg(&pcm_path) + .status() + .expect("run opus_demo"); + assert!(status.success(), "opus_demo refused our stream"); + let decoded = read_i16(&pcm_path); + let _ = fs::remove_file(&bit_path); + let _ = fs::remove_file(&pcm_path); + // opus_demo does not apply pre-skip; compensate for the 120-sample delay. + let delay = 120usize; + let n = (decoded.len() / 2 - delay).min(pcm.len() / 2 - delay); + let mut worst = 1.0f64; + for c in 0..2 { + let a: Vec = (0..n).map(|i| pcm[i * 2 + c]).collect(); + let b: Vec = (0..n) + .map(|i| decoded[(i + delay) * 2 + c] as f32 / 32768.0) + .collect(); + worst = worst.min(correlation(&a, &b)); + } + println!("opus_demo 256 kbps stereo: worst corr {worst:.4}"); + assert!( + worst >= 0.9, + "reference decoder heard correlation {worst:.4}" + ); +} + +/// The steady-state encode loop allocates nothing: every buffer — MDCT +/// scratch, PVQ vectors, the range coder's frame — is owned by the encoder +/// and sized on the first frame (the decoder discipline, applied to the +/// encoder). +#[test] +fn steady_state_encode_loop_zero_alloc() { + let pcm = test_signal(2, 0.5); + let pcm6 = { + let mono = test_signal(1, 0.5); + let mut v = Vec::with_capacity(mono.len() * 6); + for &s in &mono { + for c in 0..6 { + v.push(s * (1.0 + c as f32 * 0.01)); + } + } + v + }; + // Stereo elementary encoder. + let mut enc = Encoder::new(48000, 2).unwrap(); + enc.set_bitrate(256_000); + let mut out = vec![0u8; 1500]; + for block in pcm.chunks_exact(960 * 2) { + enc.encode_float(block, 960, &mut out).unwrap(); + } + ALLOCS.store(0, Ordering::SeqCst); + COUNTING_HERE.with(|c| c.set(true)); + for block in pcm.chunks_exact(960 * 2) { + enc.encode_float(block, 960, &mut out).unwrap(); + } + COUNTING_HERE.with(|c| c.set(false)); + let n = ALLOCS.load(Ordering::SeqCst); + assert_eq!(n, 0, "stereo encode allocated {n} times in steady state"); + + // 5.1 multistream. + let mut ms = MultistreamEncoder::surround_5_1(48000).unwrap(); + ms.set_bitrate(384_000); + let mut out6 = vec![0u8; 8 * 1500]; + for block in pcm6.chunks_exact(960 * 6) { + ms.encode_float(block, 960, &mut out6).unwrap(); + } + ALLOCS.store(0, Ordering::SeqCst); + COUNTING_HERE.with(|c| c.set(true)); + for block in pcm6.chunks_exact(960 * 6) { + ms.encode_float(block, 960, &mut out6).unwrap(); + } + COUNTING_HERE.with(|c| c.set(false)); + let n = ALLOCS.load(Ordering::SeqCst); + assert_eq!(n, 0, "5.1 encode allocated {n} times in steady state"); +} + +/// The throughput headline: encode speed in multiples of realtime, per +/// configuration, at the product's rates. Floors are deliberately far under +/// the measured numbers — they catch a regression class (an accidental +/// O(n^2), a debug path left on), not machine variance. +#[test] +fn encode_speed() { + if cfg!(debug_assertions) { + eprintln!("encode speed is only meaningful in release; skipped"); + return; + } + let secs = 4.0; + for (name, channels, kbps, floor) in [ + ("mono 96k", 1usize, 96u32, 100.0f64), + ("stereo 128k", 2, 128, 70.0), + ("stereo 256k", 2, 256, 70.0), + ("stereo 510k", 2, 510, 50.0), + ] { + let pcm = test_signal(channels, secs); + let mut enc = Encoder::new(48000, channels).unwrap(); + enc.set_bitrate(kbps * 1000); + let mut out = vec![0u8; 1500]; + // Warm up one pass, then measure. + for block in pcm.chunks_exact(960 * channels) { + enc.encode_float(block, 960, &mut out).unwrap(); + } + let passes = 4; + let start = std::time::Instant::now(); + for _ in 0..passes { + for block in pcm.chunks_exact(960 * channels) { + enc.encode_float(block, 960, &mut out).unwrap(); + } + } + let elapsed = start.elapsed().as_secs_f64(); + let realtime = secs * passes as f64 / elapsed; + println!("{name}: {realtime:.0}x realtime"); + assert!( + realtime >= floor, + "{name}: {realtime:.0}x is below {floor}x" + ); + } + // 5.1 multistream. + let mono = test_signal(1, secs); + let mut pcm6 = Vec::with_capacity(mono.len() * 6); + for &s in &mono { + for c in 0..6 { + pcm6.push(s * (1.0 + c as f32 * 0.01)); + } + } + let mut ms = MultistreamEncoder::surround_5_1(48000).unwrap(); + ms.set_bitrate(384_000); + let mut out = vec![0u8; 8 * 1500]; + for block in pcm6.chunks_exact(960 * 6) { + ms.encode_float(block, 960, &mut out).unwrap(); + } + let passes = 4; + let start = std::time::Instant::now(); + for _ in 0..passes { + for block in pcm6.chunks_exact(960 * 6) { + ms.encode_float(block, 960, &mut out).unwrap(); + } + } + let elapsed = start.elapsed().as_secs_f64(); + let realtime = secs * passes as f64 / elapsed; + println!("5.1 384k: {realtime:.0}x realtime"); + assert!(realtime >= 25.0, "5.1: {realtime:.0}x is below 25x"); +} + /// Malformed input must come back as an error, never a panic: the decoders /// index tables with values the bitstream chooses, so this throws well-formed /// TOC bytes at random payloads to make sure every mode is actually entered. diff --git a/shims/opus-rs/Cargo.toml b/shims/opus-rs/Cargo.toml new file mode 100644 index 00000000..79495bf2 --- /dev/null +++ b/shims/opus-rs/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "opus-rs" +description = "Compatibility shim: the opus-rs 0.1.26 surface edith consumes, served by ec-opus." +version = "0.1.26" +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lib] +name = "opus_rs" + +[dependencies] +ec-opus = { path = "../../crates/ec-opus", version = "0.1.0" } diff --git a/shims/opus-rs/src/lib.rs b/shims/opus-rs/src/lib.rs new file mode 100644 index 00000000..009be1e9 --- /dev/null +++ b/shims/opus-rs/src/lib.rs @@ -0,0 +1,136 @@ +//! Compatibility shim: the `opus-rs` 0.1.26 surface edith consumes, served by +//! [`ec_opus`]. +//! +//! The incumbent this replaces encoded packets that only its own decoder read +//! back above ~128-165 kbps (correlation 0.06 against libopus at 256 kbps on +//! the same signal that round-tripped internally at 0.999), and mono was +//! broken at every rate. This shim serves the same three-call surface — +//! `OpusEncoder::new(rate, channels, Application)`, the public `bitrate_bps` +//! and `complexity` fields, `.encode(&pcm, frame_size, &mut out)` — from the +//! `ec-opus` CELT encoder, which is range-exact against the family's +//! RFC-vector-verified decoder and libopus-verified at every rate up to +//! 510 kbps, mono and stereo alike. The measured envelope that capped the +//! incumbent (`OPUS_MAX_KBPS = 128`) is obsolete behind this crate. +//! +//! `complexity` is accepted for drop-in compatibility and ignored: this +//! encoder has one (fast) analysis path, not a ladder. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +use std::fmt; + +/// What the encoded stream is optimised for. This CELT-only encoder treats +/// every application as [`Application::Audio`]; the variants exist for call +/// compatibility. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Application { + /// Speech-optimised (SILK in libopus; served by CELT here). + Voip, + /// Music and general audio. + Audio, + /// Lowest-latency mode. + RestrictedLowdelay, +} + +/// The error type of this shim: a message, as the incumbent's was. +#[derive(Debug, Clone)] +pub struct OpusError(String); + +impl fmt::Display for OpusError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for OpusError {} + +/// An Opus encoder with the incumbent's field-configured surface. +#[derive(Debug)] +pub struct OpusEncoder { + /// Target bitrate in bits per second, applied at the next + /// [`OpusEncoder::encode`] call. + pub bitrate_bps: i32, + /// Accepted for compatibility; this encoder has a single analysis path. + pub complexity: i32, + inner: ec_opus::Encoder, + channels: usize, +} + +impl OpusEncoder { + /// An encoder at `sample_rate` (48000 only — the rate the product feeds) + /// for `channels` channels (1 or 2). + pub fn new( + sample_rate: i32, + channels: i32, + _application: Application, + ) -> Result { + if sample_rate < 0 || channels < 0 { + return Err(OpusError(format!( + "invalid encoder arguments: {sample_rate} Hz, {channels} channels" + ))); + } + let inner = ec_opus::Encoder::new(sample_rate as u32, channels as usize) + .map_err(|e| OpusError(e.to_string()))?; + Ok(OpusEncoder { + bitrate_bps: 64_000 * channels, + complexity: 10, + inner, + channels: channels as usize, + }) + } + + /// Encodes `frame_size` samples per channel of interleaved `f32` into + /// `out`, returning the packet length in bytes. + pub fn encode( + &mut self, + pcm: &[f32], + frame_size: usize, + out: &mut [u8], + ) -> Result { + if pcm.len() < frame_size * self.channels { + return Err(OpusError(format!( + "{} samples is short of {} channels x {frame_size}", + pcm.len(), + self.channels + ))); + } + self.inner.set_bitrate(self.bitrate_bps.max(0) as u32); + self.inner + .encode_float(pcm, frame_size, out) + .map_err(|e| OpusError(e.to_string())) + } + + /// Drops all inter-frame state; the next packet starts a fresh stream. + pub fn reset(&mut self) { + self.inner.reset(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The exact call shape edith's export path uses (export.rs:1863-1896). + #[test] + fn edith_call_shape_compiles_and_encodes() { + let mut encoder = OpusEncoder::new(48000, 2, Application::Audio) + .map_err(|e| format!("the Opus encoder refused 48 kHz stereo: {e}")) + .unwrap(); + encoder.bitrate_bps = 256_000; + encoder.complexity = 10; + let frame = vec![0.1f32; 960 * 2]; + let mut out = vec![0u8; 1500]; + let len = encoder + .encode(&frame, 960, &mut out) + .map_err(|e| format!("Opus encode failed: {e}")) + .unwrap(); + assert!(len > 2 && len <= 1276); + // Mono — broken at every rate in the incumbent — encodes too. + let mut mono = OpusEncoder::new(48000, 1, Application::Audio).unwrap(); + mono.bitrate_bps = 96_000; + let frame = vec![0.1f32; 960]; + let len = mono.encode(&frame, 960, &mut out).unwrap(); + assert!(len > 2); + } +}