forge
Explore
Log in

Don't you dare go Hollow

CELT encoder — mono/stereo/multistream, all rates, CBR+CVBR

Browse files at this commit

52ead443dac62b7ef71668431adccc043ba8f355Ahmet Kaan GümüşParent: 49bb32e
  • feat
    • CELT encoder — mono/stereo/multistream, all rates, CBR+CVBR
Show full message
feat(opus): CELT encoder — mono/stereo/multistream, all rates, CBR+CVBR

Throughput-first CELT-only Opus encoder (RFC 6716 Section 5, coding path
mirrored symbol-for-symbol from the normative Appendix A; analysis replaced
by fast deterministic heuristics: no pitch prefilter, tf_res fixed, spread
fixed NORMAL, single-pass coarse energy):

- range.rs: full RFC 5.1 range encoder (fixed-size frames, shrink, raw-bit
  tail), tell()/tell_frac()/range-state exact against the decoder per symbol
- celt_enc.rs: forward MDCT as the exact adjoint of the decoder's inverse,
  transient/trim/dynalloc/stereo analyses, encode-side allocation, PVQ
  search (wide f32x8 lanes) + V(N,K) enumeration, Laplace coarse energy
- encoder.rs: TOC framing (configs 28..31), CBR and constrained-VBR, plain
  and self-delimited (App B) packets
- multistream_enc.rs: RFC 7845 family-1 surround (5.1 helper), per-stream
  self-delimited framing, coupled streams weighed 2:1 in the rate split
- shims/opus-rs: the opus-rs 0.1.26 surface edith consumes, mono fixed and
  no rate ceiling; root-cause doc for the incumbent's ~165 kbps cliff in
  lib.rs

Proof in tests/conformance.rs (same binary): per-packet range-state parity
encoder vs vector-verified decoder at 32..510 kbps x {mono,stereo} x all
frame sizes x CVBR; libopus (ffmpeg) decodes the whole rate table at worst
corr 0.9565 (32k stereo) to 1.0000; 5.1 order-preserved >=0.9978; reference
opus_demo 0.9995 at 256k stereo; Ogg-Opus duration exact; zero-alloc steady
state; speed floors (measured ~150-580x realtime per config).

11 changed files +3954 -166

Cargo.lockmodified+264 -0
@@ -2,16 +2,75 @@
2 # It is not intended for manual editing.2 # It is not intended for manual editing.
3 version = 43 version = 4
4 4
5+[[package]]
6+name = "adler2"
7+version = "2.0.1"
8+source = "registry+https://github.com/rust-lang/crates.io-index"
9+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
10+
5 [[package]]11 [[package]]
6 name = "bytemuck"12 name = "bytemuck"
7 version = "1.25.2"13 version = "1.25.2"
8 source = "registry+https://github.com/rust-lang/crates.io-index"14 source = "registry+https://github.com/rust-lang/crates.io-index"
9 checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"15 checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
10 16
17+[[package]]
18+name = "cfg-if"
19+version = "1.0.4"
20+source = "registry+https://github.com/rust-lang/crates.io-index"
21+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
22+
23+[[package]]
24+name = "crc32fast"
25+version = "1.5.0"
26+source = "registry+https://github.com/rust-lang/crates.io-index"
27+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
28+dependencies = [
29+ "cfg-if",
30+]
31+
32+[[package]]
33+name = "ec-ac3"
34+version = "0.1.0"
35+dependencies = [
36+ "ec-core",
37+ "ec-dsp",
38+]
39+
40+[[package]]
41+name = "ec-ass"
42+version = "0.1.0"
43+dependencies = [
44+ "ec-core",
45+ "ec-subs",
46+]
47+
48+[[package]]
49+name = "ec-av1-syntax"
50+version = "0.1.0"
51+dependencies = [
52+ "ec-core",
53+]
54+
11 [[package]]55 [[package]]
12 name = "ec-core"56 name = "ec-core"
13 version = "0.1.0"57 version = "0.1.0"
14 58
59+[[package]]
60+name = "ec-dsp"
61+version = "0.1.0"
62+dependencies = [
63+ "ec-core",
64+ "wide",
65+]
66+
67+[[package]]
68+name = "ec-flac"
69+version = "0.1.0"
70+dependencies = [
71+ "ec-core",
72+]
73+
15 [[package]]74 [[package]]
16 name = "ec-h264"75 name = "ec-h264"
17 version = "0.1.0"76 version = "0.1.0"
@@ -28,10 +87,209 @@ dependencies = [
28 "ec-core",87 "ec-core",
29 ]88 ]
30 89
90+[[package]]
91+name = "ec-inflate"
92+version = "0.1.0"
93+dependencies = [
94+ "ec-core",
95+ "flate2",
96+]
97+
98+[[package]]
99+name = "ec-matroska"
100+version = "0.1.0"
101+dependencies = [
102+ "ec-core",
103+ "ec-inflate",
104+]
105+
106+[[package]]
107+name = "ec-mp3"
108+version = "0.1.0"
109+dependencies = [
110+ "ec-core",
111+ "ec-dsp",
112+]
113+
114+[[package]]
115+name = "ec-mp4"
116+version = "0.1.0"
117+dependencies = [
118+ "ec-core",
119+]
120+
121+[[package]]
122+name = "ec-ogg"
123+version = "0.1.0"
124+dependencies = [
125+ "ec-core",
126+]
127+
128+[[package]]
129+name = "ec-opus"
130+version = "0.1.0"
131+dependencies = [
132+ "ec-core",
133+ "ec-dsp",
134+ "ec-ogg",
135+ "wide",
136+]
137+
138+[[package]]
139+name = "ec-pgs"
140+version = "0.1.0"
141+dependencies = [
142+ "ec-core",
143+]
144+
145+[[package]]
146+name = "ec-riff"
147+version = "0.1.0"
148+dependencies = [
149+ "ec-core",
150+]
151+
152+[[package]]
153+name = "ec-subs"
154+version = "0.1.0"
155+dependencies = [
156+ "ec-ass",
157+ "ec-core",
158+ "ec-pgs",
159+]
160+
161+[[package]]
162+name = "ec-va"
163+version = "0.1.0"
164+
165+[[package]]
166+name = "ec-vorbis"
167+version = "0.1.0"
168+dependencies = [
169+ "ec-core",
170+ "ec-dsp",
171+ "ec-ogg",
172+]
173+
174+[[package]]
175+name = "ec-vp9-syntax"
176+version = "0.1.0"
177+dependencies = [
178+ "ec-core",
179+]
180+
181+[[package]]
182+name = "flacenc"
183+version = "0.5.1"
184+dependencies = [
185+ "ec-flac",
186+]
187+
188+[[package]]
189+name = "flate2"
190+version = "1.1.9"
191+source = "registry+https://github.com/rust-lang/crates.io-index"
192+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
193+dependencies = [
194+ "crc32fast",
195+ "miniz_oxide 0.8.9 (registry+https://github.com/rust-lang/crates.io-index)",
196+]
197+
198+[[package]]
199+name = "hound"
200+version = "3.5.1"
201+dependencies = [
202+ "ec-riff",
203+]
204+
205+[[package]]
206+name = "miniz_oxide"
207+version = "0.8.9"
208+dependencies = [
209+ "ec-inflate",
210+]
211+
212+[[package]]
213+name = "miniz_oxide"
214+version = "0.8.9"
215+source = "registry+https://github.com/rust-lang/crates.io-index"
216+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
217+dependencies = [
218+ "adler2",
219+ "simd-adler32",
220+]
221+
222+[[package]]
223+name = "opus-rs"
224+version = "0.1.26"
225+dependencies = [
226+ "ec-opus",
227+]
228+
31 [[package]]229 [[package]]
32 name = "oracle"230 name = "oracle"
33 version = "0.1.0"231 version = "0.1.0"
34 232
233+[[package]]
234+name = "oxideav-ass"
235+version = "0.0.9"
236+dependencies = [
237+ "ec-ass",
238+ "ec-subs",
239+ "oxideav-core",
240+]
241+
242+[[package]]
243+name = "oxideav-core"
244+version = "0.1.34"
245+dependencies = [
246+ "ec-core",
247+]
248+
249+[[package]]
250+name = "oxideav-ogg"
251+version = "0.1.8"
252+dependencies = [
253+ "ec-core",
254+ "ec-ogg",
255+ "oxideav-core",
256+]
257+
258+[[package]]
259+name = "oxideav-sub-image"
260+version = "0.0.7"
261+dependencies = [
262+ "ec-pgs",
263+ "oxideav-ass",
264+ "oxideav-core",
265+ "oxideav-subtitle",
266+]
267+
268+[[package]]
269+name = "oxideav-subtitle"
270+version = "0.1.2"
271+dependencies = [
272+ "ec-subs",
273+ "oxideav-core",
274+]
275+
276+[[package]]
277+name = "rusty_mp3"
278+version = "0.6.1"
279+dependencies = [
280+ "ec-core",
281+ "ec-mp3",
282+]
283+
284+[[package]]
285+name = "rusty_vorbis"
286+version = "0.1.1"
287+dependencies = [
288+ "ec-core",
289+ "ec-ogg",
290+ "ec-vorbis",
291+]
292+
35 [[package]]293 [[package]]
36 name = "safe_arch"294 name = "safe_arch"
37 version = "1.1.0"295 version = "1.1.0"
@@ -41,6 +299,12 @@ dependencies = [
41 "bytemuck",299 "bytemuck",
42 ]300 ]
43 301
302+[[package]]
303+name = "simd-adler32"
304+version = "0.3.10"
305+source = "registry+https://github.com/rust-lang/crates.io-index"
306+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
307+
44 [[package]]308 [[package]]
45 name = "wide"309 name = "wide"
46 version = "1.6.1"310 version = "1.6.1"
crates/ec-opus/Cargo.tomlmodified+3 -1
@@ -1,6 +1,6 @@
1 [package]1 [package]
2 name = "ec-opus"2 name = "ec-opus"
3-description = "Opus decoder (RFC 6716): SILK, CELT, hybrid and multistream, built on the edith_codecs IR."3+description = "Opus codec (RFC 6716): SILK+CELT+hybrid+multistream decoder and CELT fullband encoder (mono, stereo, multistream), built on the edith_codecs IR."
4 version.workspace = true4 version.workspace = true
5 edition.workspace = true5 edition.workspace = true
6 license.workspace = true6 license.workspace = true
@@ -9,6 +9,8 @@ authors.workspace = true
9 [dependencies]9 [dependencies]
10 ec-core.workspace = true10 ec-core.workspace = true
11 ec-dsp.workspace = true11 ec-dsp.workspace = true
12+wide.workspace = true
12 13
13 [dev-dependencies]14 [dev-dependencies]
14 ec-dsp.workspace = true15 ec-dsp.workspace = true
16+ec-ogg.workspace = true
crates/ec-opus/src/celt.rsmodified+63 -44
@@ -29,13 +29,13 @@ use crate::range::RangeDecoder;
29 /// Bands in the 48 kHz mode.29 /// Bands in the 48 kHz mode.
30 pub const NB_BANDS: usize = 21;30 pub const NB_BANDS: usize = 21;
31 /// Band boundaries in units of 2.5 ms MDCT bins (Table 55).31 /// Band boundaries in units of 2.5 ms MDCT bins (Table 55).
32-const E_BANDS: [usize; NB_BANDS + 1] = [32+pub(crate) const E_BANDS: [usize; NB_BANDS + 1] = [
33 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100,33 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100,
34 ];34 ];
35 /// MDCT bins in a 2.5 ms frame; the window overlap is the same length.35 /// MDCT bins in a 2.5 ms frame; the window overlap is the same length.
36-const SHORT_MDCT: usize = 120;36+pub(crate) const SHORT_MDCT: usize = 120;
37 /// Samples of overlap between consecutive frames.37 /// Samples of overlap between consecutive frames.
38-const OVERLAP: usize = 120;38+pub(crate) const OVERLAP: usize = 120;
39 /// Longest post-filter period, and the history the comb filter needs.39 /// Longest post-filter period, and the history the comb filter needs.
40 #[allow(dead_code)]40 #[allow(dead_code)]
41 const MAX_PERIOD: usize = 1024;41 const MAX_PERIOD: usize = 1024;
@@ -44,26 +44,26 @@ const MIN_PERIOD: usize = 15;
44 /// Synthesis history kept per channel.44 /// Synthesis history kept per channel.
45 const DECODE_BUFFER: usize = 2048;45 const DECODE_BUFFER: usize = 2048;
46 /// Allocation resolution: 1/8 bit.46 /// Allocation resolution: 1/8 bit.
47-const BITRES: u32 = 3;47+pub(crate) const BITRES: u32 = 3;
48 /// Most fine-energy bits a band can get.48 /// Most fine-energy bits a band can get.
49-const MAX_FINE_BITS: i32 = 8;49+pub(crate) const MAX_FINE_BITS: i32 = 8;
50-const FINE_OFFSET: i32 = 21;50+pub(crate) const FINE_OFFSET: i32 = 21;
51-const QTHETA_OFFSET: i32 = 4;51+pub(crate) const QTHETA_OFFSET: i32 = 4;
52-const QTHETA_OFFSET_TWOPHASE: i32 = 16;52+pub(crate) const QTHETA_OFFSET_TWOPHASE: i32 = 16;
53 53
54 /// `logN400`: `log2(N)` per band in 1/8 bits, for the fine-energy offset.54 /// `logN400`: `log2(N)` per band in 1/8 bits, for the fine-energy offset.
55-const LOG_N: [i32; NB_BANDS] = [55+pub(crate) const LOG_N: [i32; NB_BANDS] = [
56 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36,56 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36,
57 ];57 ];
58 58
59 /// Mean energy per band, subtracted before quantisation (`eMeans`, in log2).59 /// Mean energy per band, subtracted before quantisation (`eMeans`, in log2).
60-const E_MEANS: [f32; NB_BANDS] = [60+pub(crate) const E_MEANS: [f32; NB_BANDS] = [
61 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,61 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,
62 4.625, 4.3125, 4.5, 4.375, 4.625, 4.75, 4.4375, 3.75,62 4.625, 4.3125, 4.5, 4.375, 4.625, 4.75, 4.4375, 3.75,
63 ];63 ];
64 64
65 /// Static allocation table (Table 57), `[quality][band]`, 1/32 bit per bin.65 /// Static allocation table (Table 57), `[quality][band]`, 1/32 bit per bin.
66-const BAND_ALLOCATION: [[u8; NB_BANDS]; 11] = [66+pub(crate) const BAND_ALLOCATION: [[u8; NB_BANDS]; 11] = [
67 [0; NB_BANDS],67 [0; NB_BANDS],
68 [68 [
69 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0,69 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] = [
100 ];100 ];
101 101
102 /// Laplace parameters for coarse energy, `[LM][intra][2*band]` (`e_prob_model`).102 /// Laplace parameters for coarse energy, `[LM][intra][2*band]` (`e_prob_model`).
103-const E_PROB_MODEL: [[[u8; 42]; 2]; 4] = [103+pub(crate) const E_PROB_MODEL: [[[u8; 42]; 2]; 4] = [
104 [104 [
105 [105 [
106 72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79,106 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] = [
152 ];152 ];
153 153
154 /// Inter-frame prediction gain for coarse energy, per LM (`pred_coef`).154 /// Inter-frame prediction gain for coarse energy, per LM (`pred_coef`).
155-const PRED_COEF: [f32; 4] = [155+pub(crate) const PRED_COEF: [f32; 4] = [
156 29440.0 / 32768.0,156 29440.0 / 32768.0,
157 26112.0 / 32768.0,157 26112.0 / 32768.0,
158 21248.0 / 32768.0,158 21248.0 / 32768.0,
159 16384.0 / 32768.0,159 16384.0 / 32768.0,
160 ];160 ];
161 /// Intra-frame (across bands) prediction gain, per LM (`beta_coef`).161 /// Intra-frame (across bands) prediction gain, per LM (`beta_coef`).
162-const BETA_COEF: [f32; 4] = [162+pub(crate) const BETA_COEF: [f32; 4] = [
163 30147.0 / 32768.0,163 30147.0 / 32768.0,
164 22282.0 / 32768.0,164 22282.0 / 32768.0,
165 12124.0 / 32768.0,165 12124.0 / 32768.0,
166 6554.0 / 32768.0,166 6554.0 / 32768.0,
167 ];167 ];
168 /// The same for an intra frame.168 /// The same for an intra frame.
169-const BETA_INTRA: f32 = 4915.0 / 32768.0;169+pub(crate) const BETA_INTRA: f32 = 4915.0 / 32768.0;
170 170
171 /// TF resolution adjustment, `[LM][4*transient + 2*tf_select + tf_change]`171 /// TF resolution adjustment, `[LM][4*transient + 2*tf_select + tf_change]`
172 /// (Tables 60-63).172 /// (Tables 60-63).
173-const TF_SELECT: [[i32; 8]; 4] = [173+pub(crate) const TF_SELECT: [[i32; 8]; 4] = [
174 [0, -1, 0, -1, 0, -1, 0, -1],174 [0, -1, 0, -1, 0, -1, 0, -1],
175 [0, -1, 0, -2, 1, 0, 1, -1],175 [0, -1, 0, -2, 1, 0, 1, -1],
176 [0, -2, 0, -3, 2, 0, 1, -1],176 [0, -2, 0, -3, 2, 0, 1, -1],
@@ -178,7 +178,7 @@ const TF_SELECT: [[i32; 8]; 4] = [
178 ];178 ];
179 179
180 /// Conservative `log2` in 1/8 bits, used to reserve the intensity parameter.180 /// Conservative `log2` in 1/8 bits, used to reserve the intensity parameter.
181-const LOG2_FRAC: [i32; 24] = [181+pub(crate) const LOG2_FRAC: [i32; 24] = [
182 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37,182 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37,
183 ];183 ];
184 184
@@ -193,7 +193,7 @@ const CACHE_INDEX: [i16; 105] = [
193 ];193 ];
194 194
195 /// Bits (minus one) to code `k` pulses in each band size (`cache_bits50`).195 /// Bits (minus one) to code `k` pulses in each band size (`cache_bits50`).
196-const CACHE_BITS: [u8; 392] = [196+pub(crate) const CACHE_BITS: [u8; 392] = [
197 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,197 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,
198 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,198 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,
199 47, 49, 50, 51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62, 63, 63, 65, 66, 67, 68, 69, 70, 71,199 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] = [
216 ];216 ];
217 217
218 /// Per-band allocation ceiling, `[2*LM + stereo][band]` (`cache_caps50`).218 /// Per-band allocation ceiling, `[2*LM + stereo][band]` (`cache_caps50`).
219-const CACHE_CAPS: [u8; 168] = [219+pub(crate) const CACHE_CAPS: [u8; 168] = [
220 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134,220 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134,
221 61, 37, 224, 224, 224, 224, 224, 224, 224, 224, 240, 240, 240, 240, 207, 207, 207, 198, 198,221 61, 37, 224, 224, 224, 224, 224, 224, 224, 224, 240, 240, 240, 240, 207, 207, 207, 198, 198,
222 183, 144, 66, 40, 160, 160, 160, 160, 160, 160, 160, 160, 185, 185, 185, 185, 193, 193, 193,222 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] = [
236 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5,236 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5,
237 ];237 ];
238 238
239-const TRIM_ICDF: [u8; 11] = [126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0];239+pub(crate) const TRIM_ICDF: [u8; 11] = [126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0];
240-const SPREAD_ICDF: [u8; 4] = [25, 23, 2, 0];240+pub(crate) const SPREAD_ICDF: [u8; 4] = [25, 23, 2, 0];
241 const TAPSET_ICDF: [u8; 3] = [2, 1, 0];241 const TAPSET_ICDF: [u8; 3] = [2, 1, 0];
242-const SMALL_ENERGY_ICDF: [u8; 3] = [2, 1, 0];242+pub(crate) const SMALL_ENERGY_ICDF: [u8; 3] = [2, 1, 0];
243 243
244 /// Post-filter tap sets (Section 4.3.7.1).244 /// Post-filter tap sets (Section 4.3.7.1).
245 const POSTFILTER_GAINS: [[f32; 3]; 3] = [245 const POSTFILTER_GAINS: [[f32; 3]; 3] = [
@@ -249,17 +249,17 @@ const POSTFILTER_GAINS: [[f32; 3]; 3] = [
249 ];249 ];
250 250
251 /// De-emphasis coefficient, `1/(1 - 0.85 z^-1)` at 48 kHz.251 /// De-emphasis coefficient, `1/(1 - 0.85 z^-1)` at 48 kHz.
252-const PREEMPH: f32 = 0.850_006_1;252+pub(crate) const PREEMPH: f32 = 0.850_006_1;
253 /// Internal signal scale; the output is divided by this.253 /// Internal signal scale; the output is divided by this.
254-const SIG_SCALE: f32 = 32768.0;254+pub(crate) const SIG_SCALE: f32 = 32768.0;
255 255
256-const SPREAD_NONE: usize = 0;256+pub(crate) const SPREAD_NONE: usize = 0;
257-const SPREAD_NORMAL: usize = 2;257+pub(crate) const SPREAD_NORMAL: usize = 2;
258 const SPREAD_AGGRESSIVE: usize = 3;258 const SPREAD_AGGRESSIVE: usize = 3;
259 259
260 /// `ilog(x)`: index of the highest set bit plus one.260 /// `ilog(x)`: index of the highest set bit plus one.
261 #[inline]261 #[inline]
262-fn ilog(x: u32) -> i32 {262+pub(crate) fn ilog(x: u32) -> i32 {
263 (32 - x.leading_zeros()) as i32263 (32 - x.leading_zeros()) as i32
264 }264 }
265 265
@@ -299,7 +299,7 @@ pub(crate) fn overlap_window() -> Vec<f32> {
299 /// decimation stage, so the whole transform stays `O(n log n)` without a299 /// decimation stage, so the whole transform stays `O(n log n)` without a
300 /// mixed-radix kernel in the DSP crate.300 /// mixed-radix kernel in the DSP crate.
301 #[derive(Clone, Debug)]301 #[derive(Clone, Debug)]
302-struct Fft15 {302+pub(crate) struct Fft15 {
303 n: usize,303 n: usize,
304 /// Sub-transform of length `n/15`.304 /// Sub-transform of length `n/15`.
305 sub: Fft<f32>,305 sub: Fft<f32>,
@@ -311,7 +311,7 @@ struct Fft15 {
311 }311 }
312 312
313 impl Fft15 {313 impl Fft15 {
314- fn new(n: usize) -> Fft15 {314+ pub(crate) fn new(n: usize) -> Fft15 {
315 assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two());315 assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two());
316 let l = n / 15;316 let l = n / 15;
317 let mut tw_re = vec![0.0; n];317 let mut tw_re = vec![0.0; n];
@@ -334,7 +334,7 @@ impl Fft15 {
334 }334 }
335 335
336 /// Unscaled inverse transform: `X[k] = sum x[n] exp(+2 pi i n k / N)`.336 /// Unscaled inverse transform: `X[k] = sum x[n] exp(+2 pi i n k / N)`.
337- fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) {337+ pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) {
338 let n = self.n;338 let n = self.n;
339 let l = n / 15;339 let l = n / 15;
340 debug_assert_eq!(re.len(), n);340 debug_assert_eq!(re.len(), n);
@@ -574,7 +574,7 @@ fn pvq_urow(n: usize, k: usize, u: &mut [u32]) -> u32 {
574 }574 }
575 575
576 /// Steps a `U` row up one dimension in place.576 /// Steps a `U` row up one dimension in place.
577-fn unext(u: &mut [u32], mut ui0: u32) {577+pub(crate) fn unext(u: &mut [u32], mut ui0: u32) {
578 for j in 1..u.len() {578 for j in 1..u.len() {
579 let ui1 = u[j].wrapping_add(u[j - 1]).wrapping_add(ui0);579 let ui1 = u[j].wrapping_add(u[j - 1]).wrapping_add(ui0);
580 u[j - 1] = ui0;580 u[j - 1] = ui0;
@@ -596,7 +596,13 @@ fn uprev(u: &mut [u32], mut ui0: u32) {
596 }596 }
597 597
598 /// Decodes one PVQ codeword of `k` pulses in `n` dimensions.598 /// Decodes one PVQ codeword of `k` pulses in `n` dimensions.
599-fn decode_pulses(dec: &mut RangeDecoder, n: usize, k: usize, y: &mut [i32], u: &mut [u32]) {599+pub(crate) fn decode_pulses(
600+ dec: &mut RangeDecoder,
601+ n: usize,
602+ k: usize,
603+ y: &mut [i32],
604+ u: &mut [u32],
605+) {
600 let v = pvq_urow(n, k, u);606 let v = pvq_urow(n, k, u);
601 let mut i = dec.dec_uint(v.max(2));607 let mut i = dec.dec_uint(v.max(2));
602 let mut k = k;608 let mut k = k;
@@ -679,7 +685,7 @@ fn celt_lcg_rand(seed: u32) -> u32 {
679 }685 }
680 686
681 /// Start of a band's pulse-cache row. `lm` is `-1` for a twice-split band.687 /// Start of a band's pulse-cache row. `lm` is `-1` for a twice-split band.
682-fn cache_index(band: usize, lm: i32) -> usize {688+pub(crate) fn cache_index(band: usize, lm: i32) -> usize {
683 let row = (lm + 1) as usize;689 let row = (lm + 1) as usize;
684 let idx = CACHE_INDEX[row * NB_BANDS + band];690 let idx = CACHE_INDEX[row * NB_BANDS + band];
685 debug_assert!(idx >= 0, "no pulse cache for band {band} at LM {lm}");691 debug_assert!(idx >= 0, "no pulse cache for band {band} at LM {lm}");
@@ -2345,7 +2351,7 @@ impl CeltDecoder {
2345 }2351 }
2346 2352
2347 /// `ec_laplace_decode()`: the coarse-energy prediction error.2353 /// `ec_laplace_decode()`: the coarse-energy prediction error.
2348-fn laplace_decode(dec: &mut RangeDecoder, fs0: u32, decay: i32) -> i32 {2354+pub(crate) fn laplace_decode(dec: &mut RangeDecoder, fs0: u32, decay: i32) -> i32 {
2349 const MINP: u32 = 1;2355 const MINP: u32 = 1;
2350 const NMIN: u32 = 16;2356 const NMIN: u32 = 16;
2351 let mut val = 0i32;2357 let mut val = 0i32;
@@ -2380,7 +2386,7 @@ fn laplace_decode(dec: &mut RangeDecoder, fs0: u32, decay: i32) -> i32 {
2380 2386
2381 /// `bitexact_cos()`: a cosine that must round identically everywhere, because2387 /// `bitexact_cos()`: a cosine that must round identically everywhere, because
2382 /// the bit allocation depends on it.2388 /// the bit allocation depends on it.
2383-fn bitexact_cos(x: i16) -> i16 {2389+pub(crate) fn bitexact_cos(x: i16) -> i16 {
2384 let tmp = (4096 + (x as i32) * (x as i32)) >> 13;2390 let tmp = (4096 + (x as i32) * (x as i32)) >> 13;
2385 let mut x2 = tmp as i16;2391 let mut x2 = tmp as i16;
2386 x2 = (32767 - x2 as i322392 x2 = (32767 - x2 as i32
@@ -2391,11 +2397,11 @@ fn bitexact_cos(x: i16) -> i16 {
2391 1 + x22397 1 + x2
2392 }2398 }
2393 2399
2394-fn frac_mul16(a: i16, b: i16) -> i32 {2400+pub(crate) fn frac_mul16(a: i16, b: i16) -> i32 {
2395 (16384 + (a as i32) * (b as i32)) >> 152401 (16384 + (a as i32) * (b as i32)) >> 15
2396 }2402 }
2397 2403
2398-fn bitexact_log2tan(isin: i32, icos: i32) -> i32 {2404+pub(crate) fn bitexact_log2tan(isin: i32, icos: i32) -> i32 {
2399 let lc = ilog(icos as u32);2405 let lc = ilog(icos as u32);
2400 let ls = ilog(isin as u32);2406 let ls = ilog(isin as u32);
2401 let isin = (isin << (15 - ls)) as i16;2407 let isin = (isin << (15 - ls)) as i16;
@@ -2404,7 +2410,7 @@ fn bitexact_log2tan(isin: i32, icos: i32) -> i32 {
2404 - frac_mul16(icos, (frac_mul16(icos, -2597) + 7932) as i16)2410 - frac_mul16(icos, (frac_mul16(icos, -2597) + 7932) as i16)
2405 }2411 }
2406 2412
2407-fn compute_qn(n: i32, b: i32, offset: i32, pulse_cap: i32, stereo: bool) -> i32 {2413+pub(crate) fn compute_qn(n: i32, b: i32, offset: i32, pulse_cap: i32, stereo: bool) -> i32 {
2408 const EXP2_TABLE8: [i32; 8] = [16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048];2414 const EXP2_TABLE8: [i32; 8] = [16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048];
2409 let mut n2 = 2 * n - 1;2415 let mut n2 = 2 * n - 1;
2410 if stereo && n == 2 {2416 if stereo && n == 2 {
@@ -2420,7 +2426,7 @@ fn compute_qn(n: i32, b: i32, offset: i32, pulse_cap: i32, stereo: bool) -> i32
2420 }2426 }
2421 }2427 }
2422 2428
2423-fn get_pulses(i: i32) -> i32 {2429+pub(crate) fn get_pulses(i: i32) -> i32 {
2424 if i < 8 {2430 if i < 8 {
2425 i2431 i
2426 } else {2432 } else {
@@ -2428,7 +2434,7 @@ fn get_pulses(i: i32) -> i32 {
2428 }2434 }
2429 }2435 }
2430 2436
2431-fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 {2437+pub(crate) fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 {
2432 let cache = &CACHE_BITS[cache_index(band, lm)..];2438 let cache = &CACHE_BITS[cache_index(band, lm)..];
2433 let mut lo = 0i32;2439 let mut lo = 0i32;
2434 let mut hi = cache[0] as i32;2440 let mut hi = cache[0] as i32;
@@ -2453,7 +2459,7 @@ fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 {
2453 }2459 }
2454 }2460 }
2455 2461
2456-fn pulses2bits(band: usize, lm: i32, pulses: i32) -> i32 {2462+pub(crate) fn pulses2bits(band: usize, lm: i32, pulses: i32) -> i32 {
2457 if pulses == 0 {2463 if pulses == 0 {
2458 return 0;2464 return 0;
2459 }2465 }
@@ -2462,7 +2468,7 @@ fn pulses2bits(band: usize, lm: i32, pulses: i32) -> i32 {
2462 }2468 }
2463 2469
2464 /// One level of the Haar transform, used for the time/frequency changes.2470 /// One level of the Haar transform, used for the time/frequency changes.
2465-fn haar1(x: &mut [f32], n0: usize, stride: usize) {2471+pub(crate) fn haar1(x: &mut [f32], n0: usize, stride: usize) {
2466 let n0 = n0 >> 1;2472 let n0 = n0 >> 1;
2467 const S: f32 = core::f32::consts::FRAC_1_SQRT_2;2473 const S: f32 = core::f32::consts::FRAC_1_SQRT_2;
2468 for i in 0..stride {2474 for i in 0..stride {
@@ -2475,7 +2481,13 @@ fn haar1(x: &mut [f32], n0: usize, stride: usize) {
2475 }2481 }
2476 }2482 }
2477 2483
2478-fn deinterleave_hadamard(x: &mut [f32], tmp: &mut [f32], n0: usize, stride: usize, hadamard: bool) {2484+pub(crate) fn deinterleave_hadamard(
2485+ x: &mut [f32],
2486+ tmp: &mut [f32],
2487+ n0: usize,
2488+ stride: usize,
2489+ hadamard: bool,
2490+) {
2479 let n = n0 * stride;2491 let n = n0 * stride;
2480 let tmp = &mut tmp[..n];2492 let tmp = &mut tmp[..n];
2481 if hadamard {2493 if hadamard {
@@ -2556,7 +2568,14 @@ fn stereo_merge(buf: &mut [f32], x: usize, y: usize, mid: f32, n: usize) {
2556 }2568 }
2557 2569
2558 /// The spreading rotation (Section 4.3.4.3), applied in the decode direction.2570 /// The spreading rotation (Section 4.3.4.3), applied in the decode direction.
2559-fn exp_rotation(x: &mut [f32], len: usize, dir: i32, stride: usize, k: usize, spread: usize) {2571+pub(crate) fn exp_rotation(
2572+ x: &mut [f32],
2573+ len: usize,
2574+ dir: i32,
2575+ stride: usize,
2576+ k: usize,
2577+ spread: usize,
2578+) {
2560 const SPREAD_FACTOR: [usize; 3] = [15, 10, 5];2579 const SPREAD_FACTOR: [usize; 3] = [15, 10, 5];
2561 if 2 * k >= len || spread == SPREAD_NONE {2580 if 2 * k >= len || spread == SPREAD_NONE {
2562 return;2581 return;
crates/ec-opus/src/celt_enc.rsadded+2073 -0

Diff too large; view file

@@ -0,0 +1,2073 @@
1+//! The CELT encoder — RFC 6716 Section 5.3, throughput-first.
2+//!
3+//! The *coding* path — every symbol written, every `tell()` the bit allocation
4+//! reads — mirrors the normative reference (RFC 6716 Appendix A) exactly,
5+//! because the decoder derives the allocation from the same arithmetic and one
6+//! bit of drift desynchronises the frame. The *analysis* path is where this
7+//! encoder buys its speed, with fast deterministic heuristics in place of the
8+//! reference's searches:
9+//!
10+//! - **No pitch prefilter.** The postfilter-off bit is coded every frame,
11+//! which removes the most expensive analysis in the reference encoder (an
12+//! autocorrelation search over 1024 lags). Same choice the reference makes
13+//! below complexity 5.
14+//! - **No time/frequency Viterbi.** `tf_res` is all zeros: long-block frames
15+//! keep full frequency resolution, transient frames get the tf-table's
16+//! maximum time resolution — the two defaults the search almost always
17+//! lands on.
18+//! - **Fixed spreading.** `SPREAD_NORMAL` every frame, coded explicitly.
19+//! - **Single-pass coarse energy** with the reference's own delayed-intra
20+//! heuristic, not the two-pass encode-both-and-compare.
21+//!
22+//! What stays: transient detection, the closed-form allocation-trim and
23+//! dynalloc spike heuristics, the stereo-mode analysis, intensity thresholds
24+//! and constrained-VBR reservoir — all cheap O(frame) arithmetic that decides
25+//! *rates*, not searches.
26+//!
27+//! Steady state allocates nothing: every buffer is owned by the encoder and
28+//! sized at construction.
29+
30+use ec_core::{Error, Result};
31+
32+use crate::celt::{
33+ self, BITRES, E_BANDS, E_MEANS, E_PROB_MODEL, FINE_OFFSET, LOG_N, LOG2_FRAC, MAX_FINE_BITS,
34+ NB_BANDS, OVERLAP, PREEMPH, QTHETA_OFFSET, QTHETA_OFFSET_TWOPHASE, SHORT_MDCT, SIG_SCALE,
35+ SMALL_ENERGY_ICDF, SPREAD_ICDF, SPREAD_NORMAL, TF_SELECT, TRIM_ICDF,
36+};
37+use crate::range::RangeEncoder;
38+
39+/// `BAND_ALLOCATION` and friends live in the decoder module; local aliases
40+/// keep the transcription below readable.
41+use crate::celt::{
42+ BAND_ALLOCATION, BETA_COEF, BETA_INTRA, CACHE_CAPS, PRED_COEF, bitexact_cos, bitexact_log2tan,
43+ bits2pulses, cache_index, compute_qn, deinterleave_hadamard, exp_rotation, frac_mul16,
44+ get_pulses, haar1, pulses2bits, unext,
45+};
46+
47+const CACHE_BITS: &[u8] = &crate::celt::CACHE_BITS;
48+
49+// ---------------------------------------------------------------------------
50+// Forward MDCT
51+// ---------------------------------------------------------------------------
52+
53+/// One forward-MDCT plan, the exact adjoint of the decoder's `ImdctPlan`:
54+/// window-fold, pre-rotation, an `l/2`-point FFT and post-rotation, scaled by
55+/// `2/l` so that decode(encode(x)) reconstructs at unit gain.
56+#[derive(Clone, Debug)]
57+struct MdctPlan {
58+ l: usize,
59+ fft: celt::Fft15,
60+ rot_re: Vec<f32>,
61+ rot_im: Vec<f32>,
62+ fre: Vec<f32>,
63+ fim: Vec<f32>,
64+ t: Vec<f32>,
65+}
66+
67+impl MdctPlan {
68+ fn new(l: usize) -> MdctPlan {
69+ let n = 2 * l;
70+ let quarter = l / 2;
71+ let mut rot_re = vec![0.0; quarter];
72+ let mut rot_im = vec![0.0; quarter];
73+ for i in 0..quarter {
74+ let a = 2.0 * core::f64::consts::PI * (i as f64 + 0.125) / n as f64;
75+ rot_re[i] = a.cos() as f32;
76+ rot_im[i] = a.sin() as f32;
77+ }
78+ MdctPlan {
79+ l,
80+ fft: celt::Fft15::new(quarter),
81+ rot_re,
82+ rot_im,
83+ fre: vec![0.0; quarter],
84+ fim: vec![0.0; quarter],
85+ t: vec![0.0; l],
86+ }
87+ }
88+
89+ /// Transforms `l + OVERLAP` time samples starting at `input[off]` — the
90+ /// support of the low-overlap window — into `l` MDCT coefficients written
91+ /// at `out[out_off + k*stride]`.
92+ fn forward(
93+ &mut self,
94+ input: &[f32],
95+ off: usize,
96+ window: &[f32],
97+ out: &mut [f32],
98+ out_off: usize,
99+ stride: usize,
100+ ) {
101+ let l = self.l;
102+ let quarter = l / 2;
103+ let flat = quarter - OVERLAP / 2;
104+ let mirror = quarter + OVERLAP / 2;
105+ let t = &mut self.t;
106+ // Window fold: the adjoint of the inverse's scatter, so every
107+ // coefficient, sign and window position matches by construction.
108+ for i in 0..flat {
109+ t[quarter - 1 - i] = input[off + mirror - 1 - i];
110+ }
111+ for i in flat..quarter {
112+ let w = i - flat;
113+ t[quarter - 1 - i] =
114+ -window[w] * input[off + w] + window[OVERLAP - 1 - w] * input[off + mirror - 1 - i];
115+ }
116+ for i in 0..flat {
117+ t[quarter + i] = input[off + mirror + i];
118+ }
119+ for i in flat..quarter {
120+ let w = i - flat;
121+ t[quarter + i] = window[w] * input[off + l + OVERLAP - 1 - w]
122+ + window[OVERLAP - 1 - w] * input[off + mirror + i];
123+ }
124+ // Shuffle into the complex FFT input.
125+ for i in 0..quarter {
126+ self.fre[i] = -t[2 * i];
127+ self.fim[i] = t[2 * (quarter - 1 - i) + 1];
128+ }
129+ // Rotate by -theta (adjoint of the inverse's post-rotation).
130+ for i in 0..quarter {
131+ let (c, s) = (self.rot_re[i], self.rot_im[i]);
132+ let (re, im) = (self.fre[i], self.fim[i]);
133+ self.fre[i] = re * c + im * s;
134+ self.fim[i] = im * c - re * s;
135+ }
136+ // Forward FFT = conjugate, +i-convention FFT, conjugate.
137+ for v in self.fim.iter_mut() {
138+ *v = -*v;
139+ }
140+ self.fft.inverse(&mut self.fre, &mut self.fim);
141+ for v in self.fim.iter_mut() {
142+ *v = -*v;
143+ }
144+ // Adjoint of the pre-rotation, with the 2/l forward scaling CELT puts
145+ // on this side of the transform.
146+ let scale = 2.0 / l as f32;
147+ for i in 0..quarter {
148+ let (c, s) = (self.rot_re[i], self.rot_im[i]);
149+ let (re, im) = (self.fre[i], self.fim[i]);
150+ out[out_off + (2 * i) * stride] = scale * (s * re - c * im);
151+ out[out_off + (l - 1 - 2 * i) * stride] = scale * (-c * re - s * im);
152+ }
153+ }
154+}
155+
156+// ---------------------------------------------------------------------------
157+// Symbol-level helpers
158+// ---------------------------------------------------------------------------
159+
160+/// `ec_laplace_encode()`: the coarse-energy prediction error. May clamp
161+/// `value`, which is why it is passed back.
162+fn laplace_encode(enc: &mut RangeEncoder, value: &mut i32, mut fs: u32, decay: i32) -> i32 {
163+ const MINP: u32 = 1;
164+ const NMIN: u32 = 16;
165+ let mut fl = 0u32;
166+ let mut val = *value;
167+ if val != 0 {
168+ let s = if val < 0 { -1i32 } else { 0 };
169+ val = (val + s) ^ s;
170+ fl = fs;
171+ let fs0 = fs;
172+ fs = ((32768 - MINP * (2 * NMIN) - fs0) * (16384 - decay as u32)) >> 15;
173+ // Search the decaying part of the pdf.
174+ let mut i = 1i32;
175+ while fs > 0 && i < val {
176+ fs *= 2;
177+ fl += fs + 2 * MINP;
178+ fs = (fs * decay as u32) >> 15;
179+ i += 1;
180+ }
181+ if fs == 0 {
182+ // Everything beyond has probability MINP.
183+ let mut ndi_max = (32768 - fl + MINP - 1) as i32;
184+ ndi_max = (ndi_max - s) >> 1;
185+ let di = (val - i).min(ndi_max - 1);
186+ fl += ((2 * di + 1 + s) as u32) * MINP;
187+ fs = MINP.min(32768 - fl);
188+ *value = (i + di + s) ^ s;
189+ } else {
190+ fs += MINP;
191+ if s == 0 {
192+ fl += fs;
193+ }
194+ }
195+ debug_assert!(fl + fs <= 32768);
196+ debug_assert!(fs > 0);
197+ }
198+ enc.encode_bin(fl, fl + fs, 15);
199+ *value
200+}
201+
202+/// `encode_pulses()` for the general case: index the pulse vector in the
203+/// V(N,K) enumeration and code it as one uniform symbol (Section 5.3.4).
204+fn encode_pulses(enc: &mut RangeEncoder, iy: &[i32], n: usize, k: usize, u: &mut [u32]) {
205+ debug_assert!(n >= 2 && k > 0);
206+ u[0] = 0;
207+ for (kk, slot) in u.iter_mut().enumerate().take(k + 2).skip(1) {
208+ *slot = (2 * kk - 1) as u32;
209+ }
210+ let mut i = u32::from(iy[n - 1] < 0);
211+ let mut kk = iy[n - 1].unsigned_abs() as usize;
212+ let j = n - 2;
213+ i = i.wrapping_add(u[kk]);
214+ kk += iy[j].unsigned_abs() as usize;
215+ if iy[j] < 0 {
216+ i = i.wrapping_add(u[kk + 1]);
217+ }
218+ let mut j = j;
219+ while j > 0 {
220+ j -= 1;
221+ unext(&mut u[..k + 2], 0);
222+ i = i.wrapping_add(u[kk]);
223+ kk += iy[j].unsigned_abs() as usize;
224+ if iy[j] < 0 {
225+ i = i.wrapping_add(u[kk + 1]);
226+ }
227+ }
228+ let nc = u[kk].wrapping_add(u[kk + 1]);
229+ enc.enc_uint(i, nc.max(2));
230+}
231+
232+/// `stereo_itheta()`: the angle between mid and side (or the two halves of a
233+/// split mono band), in Q14 (0..16384).
234+fn stereo_itheta(x: &[f32], y: &[f32], stereo: bool, n: usize) -> i32 {
235+ let mut emid = 1e-15f32;
236+ let mut eside = 1e-15f32;
237+ if stereo {
238+ for j in 0..n {
239+ let m = x[j] + y[j];
240+ let s = x[j] - y[j];
241+ emid += m * m;
242+ eside += s * s;
243+ }
244+ } else {
245+ for j in 0..n {
246+ emid += x[j] * x[j];
247+ eside += y[j] * y[j];
248+ }
249+ }
250+ let mid = emid.sqrt();
251+ let side = eside.sqrt();
252+ // 0.63662 is the reference's own 2/pi literal (vq.c, stereo_itheta); the
253+ // exact constant would round a boundary theta differently.
254+ #[allow(clippy::approx_constant)]
255+ const TWO_OVER_PI: f64 = 0.63662;
256+ (0.5 + 16384.0 * TWO_OVER_PI * (side as f64).atan2(mid as f64)).floor() as i32
257+}
258+
259+// ---------------------------------------------------------------------------
260+// The encoder
261+// ---------------------------------------------------------------------------
262+
263+/// Arguments threaded through the band-encode recursion; the encode-side
264+/// mirror of the decoder's `BandArgs`, minus everything only resynthesis
265+/// needs (folding sources, gains, collapse fill).
266+#[derive(Clone, Copy, Debug)]
267+struct EncBand {
268+ i: usize,
269+ x: usize,
270+ y: Option<usize>,
271+ n: usize,
272+ b: i32,
273+ spread: usize,
274+ blocks: usize,
275+ intensity: usize,
276+ tf_change: i32,
277+ level: i32,
278+ lm: i32,
279+}
280+
281+/// A CELT-layer encoder for one elementary Opus stream (mono or stereo),
282+/// fullband at 48 kHz.
283+#[derive(Clone, Debug)]
284+pub struct CeltEncoder {
285+ channels: usize,
286+ window: Vec<f32>,
287+ plans: Vec<MdctPlan>,
288+ /// Preemphasised history, `channels * OVERLAP`.
289+ in_mem: Vec<f32>,
290+ preemph_mem: [f32; 2],
291+ /// Coarse-energy prediction state, `2 * NB_BANDS`.
292+ old_band_e: Vec<f32>,
293+ delayed_intra: f32,
294+ consec_transient: u32,
295+ last_coded_bands: usize,
296+ force_intra: bool,
297+ // Constrained-VBR reservoir.
298+ vbr_reservoir: i32,
299+ vbr_drift: i32,
300+ vbr_offset: i32,
301+ vbr_count: i32,
302+ // Per-frame scratch, allocated once.
303+ in_buf: Vec<f32>,
304+ freq: Vec<f32>,
305+ x: Vec<f32>,
306+ band_e: Vec<f32>,
307+ band_log_e: Vec<f32>,
308+ error: Vec<f32>,
309+ transient_tmp: Vec<f32>,
310+ hadamard_tmp: Vec<f32>,
311+ tf_res: [i32; NB_BANDS],
312+ pulses: [i32; NB_BANDS],
313+ fine_quant: [i32; NB_BANDS],
314+ fine_priority: [i32; NB_BANDS],
315+ offsets: [i32; NB_BANDS],
316+ caps: [i32; NB_BANDS],
317+ iy: Vec<i32>,
318+ pvq_y: Vec<f32>,
319+ pvq_sign: Vec<i32>,
320+ urow: Vec<u32>,
321+}
322+
323+impl CeltEncoder {
324+ /// An encoder for `channels` channels (1 or 2) at 48 kHz.
325+ pub fn new(channels: usize) -> CeltEncoder {
326+ assert!((1..=2).contains(&channels));
327+ let max_n = SHORT_MDCT * 8;
328+ CeltEncoder {
329+ channels,
330+ window: celt::overlap_window(),
331+ plans: (0..4).map(|lm| MdctPlan::new(SHORT_MDCT << lm)).collect(),
332+ in_mem: vec![0.0; channels * OVERLAP],
333+ preemph_mem: [0.0; 2],
334+ old_band_e: vec![0.0; 2 * NB_BANDS],
335+ delayed_intra: 1.0,
336+ consec_transient: 0,
337+ last_coded_bands: 0,
338+ force_intra: true,
339+ vbr_reservoir: 0,
340+ vbr_drift: 0,
341+ vbr_offset: 0,
342+ vbr_count: 0,
343+ in_buf: vec![0.0; channels * (max_n + OVERLAP)],
344+ freq: vec![0.0; channels * max_n],
345+ x: vec![0.0; channels * max_n],
346+ band_e: vec![0.0; 2 * NB_BANDS],
347+ band_log_e: vec![0.0; 2 * NB_BANDS],
348+ error: vec![0.0; 2 * NB_BANDS],
349+ transient_tmp: vec![0.0; max_n + OVERLAP],
350+ hadamard_tmp: vec![0.0; max_n],
351+ tf_res: [0; NB_BANDS],
352+ pulses: [0; NB_BANDS],
353+ fine_quant: [0; NB_BANDS],
354+ fine_priority: [0; NB_BANDS],
355+ offsets: [0; NB_BANDS],
356+ caps: [0; NB_BANDS],
357+ iy: vec![0; max_n],
358+ pvq_y: vec![0.0; max_n],
359+ pvq_sign: vec![0; max_n],
360+ urow: vec![0; 1280],
361+ }
362+ }
363+
364+ /// Channels this encoder codes.
365+ pub fn channels(&self) -> usize {
366+ self.channels
367+ }
368+
369+ /// Drops all inter-frame state.
370+ pub fn reset(&mut self) {
371+ self.in_mem.fill(0.0);
372+ self.preemph_mem = [0.0; 2];
373+ self.old_band_e.fill(0.0);
374+ self.delayed_intra = 1.0;
375+ self.consec_transient = 0;
376+ self.last_coded_bands = 0;
377+ self.force_intra = true;
378+ self.vbr_reservoir = 0;
379+ self.vbr_drift = 0;
380+ self.vbr_offset = 0;
381+ self.vbr_count = 0;
382+ }
383+
384+ /// Encodes one frame of interleaved `f32` (`frame_size` samples per
385+ /// channel at 48 kHz, `frame_size` one of 120/240/480/960) into `enc`,
386+ /// which must have been `reset` to the frame's byte budget. With
387+ /// `vbr_rate_bps` set, the frame may be shrunk below that budget
388+ /// (constrained VBR); the return value is the final frame size in bytes.
389+ pub fn encode(
390+ &mut self,
391+ enc: &mut RangeEncoder,
392+ pcm: &[f32],
393+ frame_size: usize,
394+ vbr_rate_bps: u32,
395+ ) -> Result<usize> {
396+ let lm: usize = match frame_size {
397+ 120 => 0,
398+ 240 => 1,
399+ 480 => 2,
400+ 960 => 3,
401+ _ => {
402+ return Err(Error::unsupported(
403+ format!("celt frame of {frame_size} samples"),
404+ "CELT frames are 2.5, 5, 10 or 20 ms at 48 kHz",
405+ ));
406+ }
407+ };
408+ let m = 1usize << lm;
409+ let n = frame_size;
410+ let c = self.channels;
411+ if pcm.len() < n * c {
412+ return Err(Error::corrupt(format!(
413+ "celt encode: {} samples for a {}-channel {frame_size}-sample frame",
414+ pcm.len(),
415+ c
416+ )));
417+ }
418+ let (start, end) = (0usize, NB_BANDS);
419+
420+ let mut nb_compressed = enc.storage();
421+ let mut nb_available = nb_compressed as i32;
422+ // The target rate in 1/8-bit units per frame, VBR only.
423+ let (vbr_rate, mut effective_bytes) = if vbr_rate_bps > 0 {
424+ let den = 48000i64 >> BITRES;
425+ let vr = ((vbr_rate_bps as i64 * n as i64 + (den >> 1)) / den) as i32;
426+ (vr, vr >> (3 + BITRES))
427+ } else {
428+ (0, nb_compressed as i32)
429+ };
430+
431+ if vbr_rate > 0 {
432+ // Constrained VBR: cap this frame so the reservoir never dips
433+ // below one frame of buffering.
434+ let vbr_bound = vbr_rate;
435+ let max_allowed = (2i32
436+ .max((vbr_rate + vbr_bound - self.vbr_reservoir) >> (BITRES + 3)))
437+ .min(nb_available);
438+ if max_allowed < nb_available {
439+ nb_compressed = max_allowed as usize;
440+ nb_available = max_allowed;
441+ enc.shrink(nb_compressed);
442+ }
443+ }
444+ let mut total_bits = (nb_compressed * 8) as i32;
445+
446+ // --- Preemphasis ----------------------------------------------------
447+ let stride = n + OVERLAP;
448+ let mut silence = true;
449+ for ch in 0..c {
450+ let base = ch * stride;
451+ self.in_buf[base..base + OVERLAP]
452+ .copy_from_slice(&self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]);
453+ let mut mem = self.preemph_mem[ch];
454+ for i in 0..n {
455+ let mut x = pcm[i * c + ch] * SIG_SCALE;
456+ if !x.is_finite() {
457+ x = 0.0;
458+ }
459+ x = x.clamp(-65536.0, 65536.0);
460+ let v = x + mem;
461+ mem = -PREEMPH * x;
462+ self.in_buf[base + OVERLAP + i] = v;
463+ silence &= v == 0.0;
464+ }
465+ self.preemph_mem[ch] = mem;
466+ self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]
467+ .copy_from_slice(&self.in_buf[base + n..base + n + OVERLAP]);
468+ }
469+
470+ // --- Silence flag (first symbol of the frame) -----------------------
471+ enc.enc_bit_logp(silence, 15);
472+ if silence {
473+ if vbr_rate > 0 {
474+ nb_compressed = nb_compressed.min(2);
475+ total_bits = (nb_compressed * 8) as i32;
476+ nb_available = 2;
477+ enc.shrink(nb_compressed);
478+ }
479+ enc.pad_to_end();
480+ }
481+
482+ // --- Postfilter: always off (throughput-first, = complexity < 5) ----
483+ if enc.tell() as i32 + 16 <= total_bits {
484+ enc.enc_bit_logp(false, 1);
485+ }
486+
487+ // --- Transient flag -------------------------------------------------
488+ let mut is_transient = false;
489+ let mut short_blocks = 0usize;
490+ if lm > 0 && enc.tell() as i32 + 3 <= total_bits {
491+ is_transient = self.transient_analysis(n + OVERLAP, c, stride);
492+ if is_transient {
493+ short_blocks = m;
494+ }
495+ enc.enc_bit_logp(is_transient, 3);
496+ }
497+
498+ // --- Forward MDCTs, energies, normalisation -------------------------
499+ self.compute_mdcts(short_blocks, lm, n, c);
500+ for ch in 0..c {
501+ for i in 0..end {
502+ let mut sum = 1e-27f32;
503+ for j in m * E_BANDS[i]..m * E_BANDS[i + 1] {
504+ let v = self.freq[ch * n + j];
505+ sum += v * v;
506+ }
507+ self.band_e[i + ch * NB_BANDS] = sum.sqrt();
508+ self.band_log_e[i + ch * NB_BANDS] =
509+ (self.band_e[i + ch * NB_BANDS] as f64).log2() as f32 - E_MEANS[i];
510+ }
511+ for i in 0..end {
512+ let g = 1.0 / (1e-27 + self.band_e[i + ch * NB_BANDS]);
513+ for j in m * E_BANDS[i]..m * E_BANDS[i + 1] {
514+ self.x[ch * n + j] = self.freq[ch * n + j] * g;
515+ }
516+ }
517+ }
518+
519+ // --- tf_res: all zeros (throughput-first) ---------------------------
520+ self.tf_res = [0; NB_BANDS];
521+ let tf_select = 0usize;
522+
523+ // --- Coarse energy --------------------------------------------------
524+ let two_pass = false;
525+ let mut intra = self.force_intra
526+ || (!two_pass
527+ && self.delayed_intra > (2 * c * (end - start)) as f32
528+ && nb_available > ((end - start) * c) as i32);
529+ let new_distortion = {
530+ let mut dist = 0.0f32;
531+ for ch in 0..c {
532+ for i in start..end {
533+ let d = self.band_log_e[i + ch * NB_BANDS] - self.old_band_e[i + ch * NB_BANDS];
534+ dist += d * d;
535+ }
536+ }
537+ dist.min(200.0)
538+ };
539+ let tell = enc.tell();
540+ if tell + 3 > total_bits as u32 {
541+ intra = false;
542+ }
543+ let max_decay = 16.0f32.min(0.125 * nb_available as f32);
544+ self.quant_coarse_energy(enc, start, end, intra, c, lm, total_bits, max_decay);
545+ self.delayed_intra = if intra {
546+ new_distortion
547+ } else {
548+ PRED_COEF[lm] * PRED_COEF[lm] * self.delayed_intra + new_distortion
549+ };
550+
551+ // --- tf encode ------------------------------------------------------
552+ self.tf_encode(enc, start, end, is_transient, lm, tf_select, nb_compressed);
553+
554+ // --- Spread: fixed NORMAL -------------------------------------------
555+ if enc.tell() as i32 + 4 <= total_bits {
556+ enc.enc_icdf(SPREAD_NORMAL, &SPREAD_ICDF, 5);
557+ }
558+
559+ // --- Caps + dynalloc ------------------------------------------------
560+ for i in 0..NB_BANDS {
561+ let bw = (E_BANDS[i + 1] - E_BANDS[i]) << lm;
562+ self.caps[i] =
563+ ((CACHE_CAPS[NB_BANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * bw as i32)
564+ >> 2;
565+ }
566+ self.offsets = [0; NB_BANDS];
567+ if effective_bytes > 50 && lm >= 1 {
568+ let (t1, t2) = if lm <= 1 {
569+ (3.0f32, 5.0f32)
570+ } else {
571+ (2.0, 4.0)
572+ };
573+ for i in start + 1..end - 1 {
574+ let mut d2 =
575+ 2.0 * self.band_log_e[i] - self.band_log_e[i - 1] - self.band_log_e[i + 1];
576+ if c == 2 {
577+ d2 = 0.5
578+ * (d2 + 2.0 * self.band_log_e[i + NB_BANDS]
579+ - self.band_log_e[i - 1 + NB_BANDS]
580+ - self.band_log_e[i + 1 + NB_BANDS]);
581+ }
582+ if d2 > t1 {
583+ self.offsets[i] += 1;
584+ }
585+ if d2 > t2 {
586+ self.offsets[i] += 1;
587+ }
588+ }
589+ }
590+ let mut dynalloc_logp = 6u32;
591+ let total_bits_frac = total_bits << BITRES;
592+ let mut total_boost = 0i32;
593+ let mut tell_frac = enc.tell_frac() as i32;
594+ for i in start..end {
595+ let width = ((c * (E_BANDS[i + 1] - E_BANDS[i])) << lm) as i32;
596+ let quanta = (width << BITRES).min((6 << BITRES).max(width));
597+ let mut loop_logp = dynalloc_logp;
598+ let mut boost = 0i32;
599+ let mut j = 0i32;
600+ while tell_frac + ((loop_logp as i32) << BITRES) < total_bits_frac - total_boost
601+ && boost < self.caps[i]
602+ {
603+ let flag = j < self.offsets[i];
604+ enc.enc_bit_logp(flag, loop_logp);
605+ tell_frac = enc.tell_frac() as i32;
606+ if !flag {
607+ break;
608+ }
609+ boost += quanta;
610+ total_boost += quanta;
611+ loop_logp = 1;
612+ j += 1;
613+ }
614+ if j > 0 {
615+ dynalloc_logp = dynalloc_logp.saturating_sub(1).max(2);
616+ }
617+ self.offsets[i] = boost;
618+ }
619+
620+ // --- Allocation trim ------------------------------------------------
621+ let mut alloc_trim = 5i32;
622+ if tell_frac + (6 << BITRES) <= total_bits_frac - total_boost {
623+ alloc_trim = self.alloc_trim_analysis(end, lm, c, n);
624+ enc.enc_icdf(alloc_trim as usize, &TRIM_ICDF, 7);
625+ tell_frac = enc.tell_frac() as i32;
626+ }
627+
628+ // --- Constrained VBR ------------------------------------------------
629+ if vbr_rate > 0 {
630+ let lm_diff = 3 - lm as i32;
631+ let mut target =
632+ vbr_rate + (self.vbr_offset >> lm_diff) - ((40 * c as i32 + 20) << BITRES);
633+ // tf_sum is zero with tf analysis disabled, so only the transient
634+ // boost of the reference's ladder applies.
635+ if short_blocks != 0 {
636+ target = 7 * target / 4;
637+ } else if m > 1 {
638+ target -= (target + 14) / 28;
639+ }
640+ target += tell_frac;
641+ let min_allowed =
642+ ((tell_frac + total_boost + (1 << (BITRES + 3)) - 1) >> (BITRES + 3)) + 2;
643+ let mut nb_avail = (target + (1 << (BITRES + 2))) >> (BITRES + 3);
644+ nb_avail = nb_avail.max(min_allowed);
645+ nb_avail = nb_avail.min(nb_compressed as i32);
646+ let mut delta = target - vbr_rate;
647+ target = nb_avail << (BITRES + 3);
648+ if silence {
649+ nb_avail = 2;
650+ delta = 0;
651+ }
652+ let alpha = if self.vbr_count < 970 {
653+ self.vbr_count += 1;
654+ 1.0 / (self.vbr_count + 20) as f32
655+ } else {
656+ 0.001
657+ };
658+ self.vbr_reservoir += target - vbr_rate;
659+ self.vbr_drift += (alpha
660+ * ((delta * (1 << lm_diff)) as f32
661+ - self.vbr_offset as f32
662+ - self.vbr_drift as f32)) as i32;
663+ self.vbr_offset = -self.vbr_drift;
664+ if self.vbr_reservoir < 0 {
665+ let adjust = (-self.vbr_reservoir) / (8 << BITRES);
666+ if !silence {
667+ nb_avail += adjust;
668+ }
669+ self.vbr_reservoir = 0;
670+ }
671+ let shrunk = (nb_compressed as i32).min(nb_avail).max(2) as usize;
672+ if shrunk < nb_compressed {
673+ nb_compressed = shrunk;
674+ enc.shrink(nb_compressed);
675+ }
676+ }
677+
678+ // --- Stereo decisions -----------------------------------------------
679+ let mut intensity = 0usize;
680+ let mut dual_stereo = false;
681+ if c == 2 {
682+ if lm != 0 {
683+ dual_stereo = self.stereo_analysis(lm, n);
684+ }
685+ let effective_rate = 2 * (((8 * effective_bytes - 80) >> lm) as i32) / 5;
686+ intensity = if effective_rate < 35 {
687+ 8
688+ } else if effective_rate < 50 {
689+ 12
690+ } else if effective_rate < 68 {
691+ 16
692+ } else if effective_rate < 84 {
693+ 18
694+ } else if effective_rate < 102 {
695+ 19
696+ } else if effective_rate < 130 {
697+ 20
698+ } else {
699+ 100
700+ };
701+ intensity = intensity.clamp(start, end);
702+ }
703+ let _ = &mut effective_bytes;
704+
705+ // --- Bit allocation -------------------------------------------------
706+ let mut bits = (((nb_compressed * 8) as i32) << BITRES) - enc.tell_frac() as i32 - 1;
707+ let anti_collapse_rsv = if is_transient && lm >= 2 && bits >= ((lm as i32 + 2) << BITRES) {
708+ 1 << BITRES
709+ } else {
710+ 0
711+ };
712+ bits -= anti_collapse_rsv;
713+ let mut balance = 0i32;
714+ let coded_bands = self.compute_allocation(
715+ enc,
716+ start,
717+ end,
718+ alloc_trim,
719+ &mut intensity,
720+ &mut dual_stereo,
721+ bits,
722+ &mut balance,
723+ c,
724+ lm,
725+ );
726+ self.last_coded_bands = coded_bands;
727+
728+ // --- Fine energy ----------------------------------------------------
729+ for i in start..end {
730+ if self.fine_quant[i] <= 0 {
731+ continue;
732+ }
733+ let frac = 1 << self.fine_quant[i];
734+ for ch in 0..c {
735+ let e = &mut self.error[i + ch * NB_BANDS];
736+ let q2 = (((*e + 0.5) * frac as f32).floor() as i32).clamp(0, frac - 1);
737+ enc.enc_bits(q2 as u32, self.fine_quant[i] as u32);
738+ let offset = (q2 as f32 + 0.5) / frac as f32 - 0.5;
739+ self.old_band_e[i + ch * NB_BANDS] += offset;
740+ *e -= offset;
741+ }
742+ }
743+
744+ // --- Shapes ---------------------------------------------------------
745+ self.quant_all_bands(
746+ enc,
747+ start,
748+ end,
749+ short_blocks,
750+ SPREAD_NORMAL,
751+ dual_stereo,
752+ intensity,
753+ (nb_compressed as i32 * (8 << BITRES)) - anti_collapse_rsv,
754+ balance,
755+ lm,
756+ coded_bands,
757+ c,
758+ n,
759+ );
760+
761+ // --- Anti-collapse --------------------------------------------------
762+ if anti_collapse_rsv > 0 {
763+ let on = self.consec_transient < 2;
764+ enc.enc_bits(u32::from(on), 1);
765+ }
766+
767+ // --- Leftover fine bits ---------------------------------------------
768+ let mut bits_left = nb_compressed as i32 * 8 - enc.tell() as i32;
769+ for prio in 0..2 {
770+ for i in start..end {
771+ if bits_left < c as i32 {
772+ break;
773+ }
774+ if self.fine_quant[i] >= MAX_FINE_BITS || self.fine_priority[i] != prio {
775+ continue;
776+ }
777+ for ch in 0..c {
778+ let q2 = i32::from(self.error[i + ch * NB_BANDS] >= 0.0);
779+ enc.enc_bits(q2 as u32, 1);
780+ let offset = (q2 as f32 - 0.5) / (1 << (self.fine_quant[i] + 1)) as f32;
781+ self.old_band_e[i + ch * NB_BANDS] += offset;
782+ bits_left -= 1;
783+ }
784+ }
785+ }
786+
787+ if silence {
788+ for e in self.old_band_e.iter_mut() {
789+ *e = -28.0;
790+ }
791+ }
792+ if c == 1 {
793+ for i in 0..NB_BANDS {
794+ self.old_band_e[NB_BANDS + i] = self.old_band_e[i];
795+ }
796+ }
797+ if is_transient {
798+ self.consec_transient += 1;
799+ } else {
800+ self.consec_transient = 0;
801+ }
802+ self.force_intra = false;
803+
804+ enc.done();
805+ if enc.error() {
806+ return Err(Error::corrupt("celt encode: busted the frame budget"));
807+ }
808+ Ok(nb_compressed)
809+ }
810+
811+ // -- Analysis ------------------------------------------------------------
812+
813+ /// `transient_analysis()`: a high-passed peak-decay detector, straight
814+ /// from the reference.
815+ fn transient_analysis(&mut self, len: usize, c: usize, stride: usize) -> bool {
816+ let tmp = &mut self.transient_tmp[..len];
817+ if c == 1 {
818+ tmp.copy_from_slice(&self.in_buf[..len]);
819+ } else {
820+ for (i, v) in tmp.iter_mut().enumerate() {
821+ *v = self.in_buf[i] + self.in_buf[stride + i];
822+ }
823+ }
824+ let mut mem0 = 0.0f32;
825+ let mut mem1 = 0.0f32;
826+ for v in tmp.iter_mut() {
827+ let x = *v;
828+ let y = mem0 + x;
829+ mem0 = mem1 + y - 2.0 * x;
830+ mem1 = x - 0.5 * y;
831+ *v = y;
832+ }
833+ for v in tmp.iter_mut().take(12) {
834+ *v = 0.0;
835+ }
836+ let block = OVERLAP / 2;
837+ let nbins = len / block;
838+ let mut bins = [0.0f32; 20];
839+ for (i, bin) in bins.iter_mut().enumerate().take(nbins) {
840+ let mut max_abs = 0.0f32;
841+ for j in 0..block {
842+ max_abs = max_abs.max(tmp[i * block + j].abs());
843+ }
844+ *bin = max_abs;
845+ }
846+ let mut is_transient = false;
847+ #[allow(clippy::needless_range_loop)]
848+ for i in 0..nbins {
849+ let t1 = 0.15 * bins[i];
850+ let t2 = 0.4 * bins[i];
851+ let t3 = 0.15 * bins[i];
852+ let mut conseq = 0;
853+ for &b in bins.iter().take(i) {
854+ if b < t1 {
855+ conseq += 1;
856+ }
857+ if b < t2 {
858+ conseq += 1;
859+ } else {
860+ conseq = 0;
861+ }
862+ }
863+ if conseq >= 3 {
864+ is_transient = true;
865+ }
866+ conseq = 0;
867+ for &b in bins.iter().take(nbins).skip(i + 1) {
868+ if b < t3 {
869+ conseq += 1;
870+ } else {
871+ conseq = 0;
872+ }
873+ }
874+ if conseq >= 7 {
875+ is_transient = true;
876+ }
877+ }
878+ is_transient
879+ }
880+
881+ fn compute_mdcts(&mut self, short_blocks: usize, lm: usize, n: usize, c: usize) {
882+ let stride = n + OVERLAP;
883+ let (n2, blocks, plan_lm) = if short_blocks != 0 {
884+ (SHORT_MDCT, short_blocks, 0)
885+ } else {
886+ (n, 1, lm)
887+ };
888+ for ch in 0..c {
889+ for b in 0..blocks {
890+ let plan = &mut self.plans[plan_lm];
891+ plan.forward(
892+ &self.in_buf,
893+ ch * stride + b * n2,
894+ &self.window,
895+ &mut self.freq,
896+ ch * n + b,
897+ blocks,
898+ );
899+ }
900+ }
901+ }
902+
903+ /// `alloc_trim_analysis()`: stereo correlation plus spectral tilt.
904+ fn alloc_trim_analysis(&self, end: usize, lm: usize, c: usize, n0: usize) -> i32 {
905+ let mut trim = 5i32;
906+ if c == 2 {
907+ let mut sum = 0.0f32;
908+ for i in 0..8 {
909+ let mut partial = 0.0f32;
910+ for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) {
911+ partial += self.x[j] * self.x[n0 + j];
912+ }
913+ sum += partial;
914+ }
915+ sum *= 1.0 / 8.0;
916+ if sum > 0.995 {
917+ trim -= 4;
918+ } else if sum > 0.92 {
919+ trim -= 3;
920+ } else if sum > 0.85 {
921+ trim -= 2;
922+ } else if sum > 0.8 {
923+ trim -= 1;
924+ }
925+ }
926+ let mut diff = 0.0f32;
927+ for ch in 0..c {
928+ for i in 0..end - 1 {
929+ diff += self.band_log_e[i + ch * NB_BANDS]
930+ * (2 + 2 * i as i32 - NB_BANDS as i32) as f32;
931+ }
932+ }
933+ diff /= (2 * c * (end - 1)) as f32;
934+ if diff > 2.0 {
935+ trim -= 1;
936+ }
937+ if diff > 8.0 {
938+ trim -= 1;
939+ }
940+ if diff < -4.0 {
941+ trim += 1;
942+ }
943+ if diff < -10.0 {
944+ trim += 1;
945+ }
946+ trim.clamp(0, 10)
947+ }
948+
949+ /// `stereo_analysis()`: L1 entropy model of L/R against M/S.
950+ fn stereo_analysis(&self, lm: usize, n0: usize) -> bool {
951+ let mut sum_lr = 1e-15f64;
952+ let mut sum_ms = 1e-15f64;
953+ for i in 0..13 {
954+ for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) {
955+ let l = self.x[j] as f64;
956+ let r = self.x[n0 + j] as f64;
957+ sum_lr += l.abs() + r.abs();
958+ sum_ms += (l + r).abs() + (l - r).abs();
959+ }
960+ }
961+ // The reference's own literal (bands.c, stereo_analysis), kept as such.
962+ #[allow(clippy::approx_constant)]
963+ const SQRT_HALF: f64 = 0.707107;
964+ sum_ms *= SQRT_HALF;
965+ let mut thetas = 13;
966+ if lm <= 1 {
967+ thetas -= 8;
968+ }
969+ ((E_BANDS[13] << (lm + 1)) + thetas) as f64 * sum_ms
970+ > ((E_BANDS[13] << (lm + 1)) as f64) * sum_lr
971+ }
972+
973+ // -- Energy --------------------------------------------------------------
974+
975+ #[allow(clippy::too_many_arguments)]
976+ fn quant_coarse_energy(
977+ &mut self,
978+ enc: &mut RangeEncoder,
979+ start: usize,
980+ end: usize,
981+ intra: bool,
982+ c: usize,
983+ lm: usize,
984+ budget: i32,
985+ max_decay: f32,
986+ ) {
987+ let tell = enc.tell() as i32;
988+ if tell + 3 <= budget {
989+ enc.enc_bit_logp(intra, 3);
990+ }
991+ let model = &E_PROB_MODEL[lm][usize::from(intra)];
992+ let (coef, beta) = if intra {
993+ (0.0, BETA_INTRA)
994+ } else {
995+ (PRED_COEF[lm], BETA_COEF[lm])
996+ };
997+ let mut prev = [0.0f32; 2];
998+ for i in start..end {
999+ for (ch, prev) in prev.iter_mut().enumerate().take(c) {
1000+ let x = self.band_log_e[i + ch * NB_BANDS];
1001+ let old_raw = self.old_band_e[i + ch * NB_BANDS];
1002+ let old = old_raw.max(-9.0);
1003+ let f = x - coef * old - *prev;
1004+ let mut qi = (0.5 + f).floor() as i32;
1005+ let decay_bound = old_raw.max(-28.0) - max_decay;
1006+ // Prevent the energy from dropping faster than the decoder
1007+ // can follow.
1008+ if qi < 0 && x < decay_bound {
1009+ qi += (decay_bound - x) as i32;
1010+ if qi > 0 {
1011+ qi = 0;
1012+ }
1013+ }
1014+ let tell = enc.tell() as i32;
1015+ let bits_left = budget - tell - 3 * (c as i32) * (end - i) as i32;
1016+ if i != start && bits_left < 30 {
1017+ if bits_left < 24 {
1018+ qi = qi.min(1);
1019+ }
1020+ if bits_left < 16 {
1021+ qi = qi.max(-1);
1022+ }
1023+ }
1024+ if budget - tell >= 15 {
1025+ let pi = 2 * i.min(20);
1026+ laplace_encode(
1027+ enc,
1028+ &mut qi,
1029+ (model[pi] as u32) << 7,
1030+ (model[pi + 1] as i32) << 6,
1031+ );
1032+ } else if budget - tell >= 2 {
1033+ qi = qi.clamp(-1, 1);
1034+ enc.enc_icdf(
1035+ ((2 * qi) ^ -i32::from(qi < 0)) as usize,
1036+ &SMALL_ENERGY_ICDF,
1037+ 2,
1038+ );
1039+ } else if budget - tell >= 1 {
1040+ qi = qi.min(0);
1041+ enc.enc_bit_logp(qi != 0, 1);
1042+ } else {
1043+ qi = -1;
1044+ }
1045+ self.error[i + ch * NB_BANDS] = f - qi as f32;
1046+ let q = qi as f32;
1047+ self.old_band_e[i + ch * NB_BANDS] = coef * old + *prev + q;
1048+ *prev += q - beta * q;
1049+ }
1050+ }
1051+ }
1052+
1053+ #[allow(clippy::too_many_arguments)]
1054+ fn tf_encode(
1055+ &mut self,
1056+ enc: &mut RangeEncoder,
1057+ start: usize,
1058+ end: usize,
1059+ transient: bool,
1060+ lm: usize,
1061+ mut tf_select: usize,
1062+ len: usize,
1063+ ) {
1064+ let mut budget = (len * 8) as i32;
1065+ let mut tell = enc.tell() as i32;
1066+ let mut logp: u32 = if transient { 2 } else { 4 };
1067+ let tf_select_rsv = lm > 0 && tell + (logp as i32) < budget;
1068+ budget -= i32::from(tf_select_rsv);
1069+ let mut curr = 0i32;
1070+ let mut changed = false;
1071+ for i in start..end {
1072+ if tell + (logp as i32) <= budget {
1073+ enc.enc_bit_logp((self.tf_res[i] ^ curr) != 0, logp);
1074+ tell = enc.tell() as i32;
1075+ curr = self.tf_res[i];
1076+ changed |= curr != 0;
1077+ } else {
1078+ self.tf_res[i] = curr;
1079+ }
1080+ logp = if transient { 4 } else { 5 };
1081+ }
1082+ let t = usize::from(transient);
1083+ let ch = usize::from(changed);
1084+ if tf_select_rsv && TF_SELECT[lm][4 * t + ch] != TF_SELECT[lm][4 * t + 2 + ch] {
1085+ enc.enc_bit_logp(tf_select != 0, 1);
1086+ } else {
1087+ tf_select = 0;
1088+ }
1089+ for i in start..end {
1090+ self.tf_res[i] = TF_SELECT[lm][4 * t + 2 * tf_select + self.tf_res[i] as usize];
1091+ }
1092+ }
1093+
1094+ // -- Allocation (encode side of the decoder's implicit derivation) -------
1095+
1096+ #[allow(clippy::too_many_arguments)]
1097+ fn compute_allocation(
1098+ &mut self,
1099+ enc: &mut RangeEncoder,
1100+ start: usize,
1101+ end: usize,
1102+ alloc_trim: i32,
1103+ intensity: &mut usize,
1104+ dual_stereo: &mut bool,
1105+ total: i32,
1106+ balance: &mut i32,
1107+ c: usize,
1108+ lm: usize,
1109+ ) -> usize {
1110+ let mut total = total.max(0);
1111+ let mut skip_start = start;
1112+ let skip_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 };
1113+ total -= skip_rsv;
1114+ let mut intensity_rsv = 0;
1115+ let mut dual_stereo_rsv = 0;
1116+ if c == 2 {
1117+ intensity_rsv = LOG2_FRAC[end - start];
1118+ if intensity_rsv > total {
1119+ intensity_rsv = 0;
1120+ } else {
1121+ total -= intensity_rsv;
1122+ dual_stereo_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 };
1123+ total -= dual_stereo_rsv;
1124+ }
1125+ }
1126+
1127+ let mut thresh = [0i32; NB_BANDS];
1128+ let mut trim_offset = [0i32; NB_BANDS];
1129+ for j in start..end {
1130+ let width = (E_BANDS[j + 1] - E_BANDS[j]) as i32;
1131+ thresh[j] = ((c as i32) << BITRES).max((((3 * width) << lm) << BITRES) >> 4);
1132+ trim_offset[j] = (c as i32
1133+ * width
1134+ * (alloc_trim - 5 - lm as i32)
1135+ * (end - j - 1) as i32
1136+ * (1 << (lm as u32 + BITRES)))
1137+ >> 6;
1138+ if (width << lm) == 1 {
1139+ trim_offset[j] -= (c as i32) << BITRES;
1140+ }
1141+ }
1142+
1143+ let mut lo = 1i32;
1144+ let mut hi = BAND_ALLOCATION.len() as i32 - 1;
1145+ while lo <= hi {
1146+ let mid = (lo + hi) >> 1;
1147+ let mut psum = 0;
1148+ let mut done = false;
1149+ for j in (start..end).rev() {
1150+ let width = (E_BANDS[j + 1] - E_BANDS[j]) as i32;
1151+ let mut bitsj =
1152+ (c as i32 * width * BAND_ALLOCATION[mid as usize][j] as i32) << lm >> 2;
1153+ if bitsj > 0 {
1154+ bitsj = 0.max(bitsj + trim_offset[j]);
1155+ }
1156+ bitsj += self.offsets[j];
1157+ if bitsj >= thresh[j] || done {
1158+ done = true;
1159+ psum += bitsj.min(self.caps[j]);
1160+ } else if bitsj >= (c as i32) << BITRES {
1161+ psum += (c as i32) << BITRES;
1162+ }
1163+ }
1164+ if psum > total {
1165+ hi = mid - 1;
1166+ } else {
1167+ lo = mid + 1;
1168+ }
1169+ }
1170+ let hi = lo;
1171+ let lo = lo - 1;
1172+
1173+ let mut bits1 = [0i32; NB_BANDS];
1174+ let mut bits2 = [0i32; NB_BANDS];
1175+ for j in start..end {
1176+ let width = (E_BANDS[j + 1] - E_BANDS[j]) as i32;
1177+ let mut b1 = (c as i32 * width * BAND_ALLOCATION[lo as usize][j] as i32) << lm >> 2;
1178+ let mut b2 = if hi as usize >= BAND_ALLOCATION.len() {
1179+ self.caps[j]
1180+ } else {
1181+ (c as i32 * width * BAND_ALLOCATION[hi as usize][j] as i32) << lm >> 2
1182+ };
1183+ if b1 > 0 {
1184+ b1 = 0.max(b1 + trim_offset[j]);
1185+ }
1186+ if b2 > 0 {
1187+ b2 = 0.max(b2 + trim_offset[j]);
1188+ }
1189+ if lo > 0 {
1190+ b1 += self.offsets[j];
1191+ }
1192+ b2 += self.offsets[j];
1193+ if self.offsets[j] > 0 {
1194+ skip_start = j;
1195+ }
1196+ bits1[j] = b1;
1197+ bits2[j] = 0.max(b2 - b1);
1198+ }
1199+
1200+ self.interp_bits2pulses(
1201+ enc,
1202+ start,
1203+ end,
1204+ skip_start,
1205+ &bits1,
1206+ &bits2,
1207+ &thresh,
1208+ total,
1209+ balance,
1210+ skip_rsv,
1211+ intensity,
1212+ intensity_rsv,
1213+ dual_stereo,
1214+ dual_stereo_rsv,
1215+ c,
1216+ lm,
1217+ )
1218+ }
1219+
1220+ #[allow(clippy::too_many_arguments)]
1221+ fn interp_bits2pulses(
1222+ &mut self,
1223+ enc: &mut RangeEncoder,
1224+ start: usize,
1225+ end: usize,
1226+ skip_start: usize,
1227+ bits1: &[i32; NB_BANDS],
1228+ bits2: &[i32; NB_BANDS],
1229+ thresh: &[i32; NB_BANDS],
1230+ mut total: i32,
1231+ balance_out: &mut i32,
1232+ skip_rsv: i32,
1233+ intensity: &mut usize,
1234+ mut intensity_rsv: i32,
1235+ dual_stereo: &mut bool,
1236+ mut dual_stereo_rsv: i32,
1237+ c: usize,
1238+ lm: usize,
1239+ ) -> usize {
1240+ const ALLOC_STEPS: u32 = 6;
1241+ let alloc_floor = (c as i32) << BITRES;
1242+ let stereo = c > 1;
1243+ let log_m = (lm as i32) << BITRES;
1244+ let prev = self.last_coded_bands;
1245+
1246+ let mut lo = 0i32;
1247+ let mut hi = 1i32 << ALLOC_STEPS;
1248+ for _ in 0..ALLOC_STEPS {
1249+ let mid = (lo + hi) >> 1;
1250+ let mut psum = 0;
1251+ let mut done = false;
1252+ for j in (start..end).rev() {
1253+ let tmp = bits1[j] + ((mid * bits2[j]) >> ALLOC_STEPS);
1254+ if tmp >= thresh[j] || done {
1255+ done = true;
1256+ psum += tmp.min(self.caps[j]);
1257+ } else if tmp >= alloc_floor {
1258+ psum += alloc_floor;
1259+ }
1260+ }
1261+ if psum > total {
1262+ hi = mid;
1263+ } else {
1264+ lo = mid;
1265+ }
1266+ }
1267+
1268+ let mut psum = 0;
1269+ let mut done = false;
1270+ let bits = &mut self.pulses;
1271+ for j in (start..end).rev() {
1272+ let mut tmp = bits1[j] + ((lo * bits2[j]) >> ALLOC_STEPS);
1273+ if tmp < thresh[j] && !done {
1274+ tmp = if tmp >= alloc_floor { alloc_floor } else { 0 };
1275+ } else {
1276+ done = true;
1277+ }
1278+ tmp = tmp.min(self.caps[j]);
1279+ bits[j] = tmp;
1280+ psum += tmp;
1281+ }
1282+
1283+ let mut coded_bands = end;
1284+ loop {
1285+ let j = coded_bands - 1;
1286+ if j <= skip_start {
1287+ total += skip_rsv;
1288+ break;
1289+ }
1290+ let mut left = total - psum;
1291+ let percoeff = left / (E_BANDS[coded_bands] - E_BANDS[start]) as i32;
1292+ left -= (E_BANDS[coded_bands] - E_BANDS[start]) as i32 * percoeff;
1293+ let rem = 0.max(left - (E_BANDS[j] - E_BANDS[start]) as i32);
1294+ let band_width = (E_BANDS[coded_bands] - E_BANDS[j]) as i32;
1295+ let mut band_bits = self.pulses[j] + percoeff * band_width + rem;
1296+ if band_bits >= thresh[j].max(alloc_floor + (1 << BITRES)) {
1297+ // The one non-mandatory choice in the allocation: whether to
1298+ // stop skipping, with the reference's hysteresis on the band
1299+ // count of the previous frame.
1300+ let stay = band_bits
1301+ > (((if j < prev { 7 } else { 9 }) * band_width) << lm << BITRES) >> 4;
1302+ enc.enc_bit_logp(stay, 1);
1303+ if stay {
1304+ break;
1305+ }
1306+ psum += 1 << BITRES;
1307+ band_bits -= 1 << BITRES;
1308+ }
1309+ psum -= self.pulses[j] + intensity_rsv;
1310+ if intensity_rsv > 0 {
1311+ intensity_rsv = LOG2_FRAC[j - start];
1312+ }
1313+ psum += intensity_rsv;
1314+ if band_bits >= alloc_floor {
1315+ psum += alloc_floor;
1316+ self.pulses[j] = alloc_floor;
1317+ } else {
1318+ self.pulses[j] = 0;
1319+ }
1320+ coded_bands -= 1;
1321+ }
1322+
1323+ debug_assert!(coded_bands > start);
1324+ if intensity_rsv > 0 {
1325+ *intensity = (*intensity).min(coded_bands);
1326+ enc.enc_uint(
1327+ (*intensity - start) as u32,
1328+ (coded_bands + 1 - start) as u32,
1329+ );
1330+ } else {
1331+ *intensity = 0;
1332+ }
1333+ if *intensity <= start {
1334+ total += dual_stereo_rsv;
1335+ dual_stereo_rsv = 0;
1336+ }
1337+ if dual_stereo_rsv > 0 {
1338+ enc.enc_bit_logp(*dual_stereo, 1);
1339+ } else {
1340+ *dual_stereo = false;
1341+ }
1342+
1343+ let mut left = total - psum;
1344+ let percoeff = left / (E_BANDS[coded_bands] - E_BANDS[start]) as i32;
1345+ left -= (E_BANDS[coded_bands] - E_BANDS[start]) as i32 * percoeff;
1346+ for j in start..coded_bands {
1347+ self.pulses[j] += percoeff * (E_BANDS[j + 1] - E_BANDS[j]) as i32;
1348+ }
1349+ for j in start..coded_bands {
1350+ let tmp = left.min((E_BANDS[j + 1] - E_BANDS[j]) as i32);
1351+ self.pulses[j] += tmp;
1352+ left -= tmp;
1353+ }
1354+
1355+ let mut balance = 0i32;
1356+ for j in start..coded_bands {
1357+ let n0 = (E_BANDS[j + 1] - E_BANDS[j]) as i32;
1358+ let n = n0 << lm;
1359+ self.pulses[j] += balance;
1360+ let mut excess;
1361+ if n > 1 {
1362+ excess = 0.max(self.pulses[j] - self.caps[j]);
1363+ self.pulses[j] -= excess;
1364+ let den =
1365+ c as i32 * n + i32::from(c == 2 && n > 2 && !*dual_stereo && j < *intensity);
1366+ let nc_log_n = den * (LOG_N[j] + log_m);
1367+ let mut offset = (nc_log_n >> 1) - den * FINE_OFFSET;
1368+ if n == 2 {
1369+ offset += den << BITRES >> 2;
1370+ }
1371+ if self.pulses[j] + offset < (den * 2) << BITRES {
1372+ offset += nc_log_n >> 2;
1373+ } else if self.pulses[j] + offset < (den * 3) << BITRES {
1374+ offset += nc_log_n >> 3;
1375+ }
1376+ let mut eb =
1377+ 0.max((self.pulses[j] + offset + (den << (BITRES - 1))) / (den << BITRES));
1378+ if c as i32 * eb > (self.pulses[j] >> BITRES) {
1379+ eb = self.pulses[j] >> u32::from(stereo) >> BITRES;
1380+ }
1381+ eb = eb.min(MAX_FINE_BITS);
1382+ self.fine_quant[j] = eb;
1383+ self.fine_priority[j] = i32::from(eb * (den << BITRES) >= self.pulses[j] + offset);
1384+ self.pulses[j] -= (c as i32 * eb) << BITRES;
1385+ } else {
1386+ excess = 0.max(self.pulses[j] - ((c as i32) << BITRES));
1387+ self.pulses[j] -= excess;
1388+ self.fine_quant[j] = 0;
1389+ self.fine_priority[j] = 1;
1390+ }
1391+ if excess > 0 {
1392+ let extra_fine = (excess >> (u32::from(stereo) + BITRES))
1393+ .min(MAX_FINE_BITS - self.fine_quant[j]);
1394+ self.fine_quant[j] += extra_fine;
1395+ let extra_bits = (extra_fine * c as i32) << BITRES;
1396+ self.fine_priority[j] = i32::from(extra_bits >= excess - balance);
1397+ excess -= extra_bits;
1398+ }
1399+ balance = excess;
1400+ }
1401+ *balance_out = balance;
1402+ for j in coded_bands..end {
1403+ self.fine_quant[j] = self.pulses[j] >> u32::from(stereo) >> BITRES;
1404+ self.pulses[j] = 0;
1405+ self.fine_priority[j] = i32::from(self.fine_quant[j] < 1);
1406+ }
1407+ coded_bands
1408+ }
1409+
1410+ // -- Band shapes ---------------------------------------------------------
1411+
1412+ #[allow(clippy::too_many_arguments)]
1413+ fn quant_all_bands(
1414+ &mut self,
1415+ enc: &mut RangeEncoder,
1416+ start: usize,
1417+ end: usize,
1418+ short_blocks: usize,
1419+ spread: usize,
1420+ mut dual_stereo: bool,
1421+ intensity: usize,
1422+ total_bits: i32,
1423+ mut balance: i32,
1424+ lm: usize,
1425+ coded_bands: usize,
1426+ c: usize,
1427+ n: usize,
1428+ ) {
1429+ let m = 1usize << lm;
1430+ let blocks = if short_blocks != 0 { m } else { 1 };
1431+ for i in start..end {
1432+ let n_band = m * E_BANDS[i + 1] - m * E_BANDS[i];
1433+ let tell = enc.tell_frac() as i32;
1434+ if i != start {
1435+ balance -= tell;
1436+ }
1437+ let mut remaining_bits = total_bits - tell - 1;
1438+ let b = if i < coded_bands {
1439+ let curr_balance = balance / 3.min(coded_bands - i) as i32;
1440+ 0.max(16383.min((remaining_bits + 1).min(self.pulses[i] + curr_balance)))
1441+ } else {
1442+ 0
1443+ };
1444+ let tf_change = self.tf_res[i];
1445+ if dual_stereo && i == intensity {
1446+ dual_stereo = false;
1447+ }
1448+ let x_off = m * E_BANDS[i];
1449+ let base = EncBand {
1450+ i,
1451+ x: x_off,
1452+ y: None,
1453+ n: n_band,
1454+ b,
1455+ spread,
1456+ blocks,
1457+ intensity,
1458+ tf_change,
1459+ level: 0,
1460+ lm: lm as i32,
1461+ };
1462+ if dual_stereo {
1463+ self.quant_band(enc, EncBand { b: b / 2, ..base }, &mut remaining_bits);
1464+ self.quant_band(
1465+ enc,
1466+ EncBand {
1467+ x: n + x_off,
1468+ b: b / 2,
1469+ ..base
1470+ },
1471+ &mut remaining_bits,
1472+ );
1473+ } else {
1474+ self.quant_band(
1475+ enc,
1476+ EncBand {
1477+ y: if c == 2 { Some(n + x_off) } else { None },
1478+ ..base
1479+ },
1480+ &mut remaining_bits,
1481+ );
1482+ }
1483+ balance += self.pulses[i] + tell;
1484+ }
1485+ }
1486+
1487+ /// Encodes one band (Section 5.3.4-5.3.5), recursing for splits and for
1488+ /// stereo. The mirror of the decoder's `quant_band`, with the resynthesis
1489+ /// paths removed — nothing the encoder writes depends on them.
1490+ fn quant_band(&mut self, enc: &mut RangeEncoder, a: EncBand, remaining_bits: &mut i32) {
1491+ let EncBand {
1492+ i,
1493+ x,
1494+ mut y,
1495+ mut n,
1496+ mut b,
1497+ spread,
1498+ mut blocks,
1499+ intensity,
1500+ mut tf_change,
1501+ level,
1502+ mut lm,
1503+ } = a;
1504+ let stereo = y.is_some();
1505+ let mut split = stereo;
1506+ let long_blocks = blocks == 1;
1507+ let mut b0 = blocks;
1508+
1509+ if n == 1 {
1510+ for offs in [Some(x), y].into_iter().flatten() {
1511+ if *remaining_bits >= 1 << BITRES {
1512+ let sign = self.x[offs] < 0.0;
1513+ enc.enc_bits(u32::from(sign), 1);
1514+ *remaining_bits -= 1 << BITRES;
1515+ }
1516+ }
1517+ return;
1518+ }
1519+
1520+ let mut n_b = n / blocks;
1521+ if !stereo && level == 0 {
1522+ let recombine = if tf_change > 0 { tf_change as usize } else { 0 };
1523+ for k in 0..recombine {
1524+ haar1(&mut self.x[x..], n >> k, 1 << k);
1525+ }
1526+ blocks >>= recombine;
1527+ n_b <<= recombine;
1528+ while (n_b & 1) == 0 && tf_change < 0 {
1529+ haar1(&mut self.x[x..], n_b, blocks);
1530+ blocks <<= 1;
1531+ n_b >>= 1;
1532+ tf_change += 1;
1533+ }
1534+ b0 = blocks;
1535+ if b0 > 1 {
1536+ deinterleave_hadamard(
1537+ &mut self.x[x..x + n],
1538+ &mut self.hadamard_tmp,
1539+ n_b >> recombine,
1540+ b0 << recombine,
1541+ long_blocks,
1542+ );
1543+ }
1544+ }
1545+
1546+ let cache_start = cache_index(i, lm);
1547+ let cache0 = CACHE_BITS[cache_start] as usize;
1548+ if !stereo && lm != -1 && b > CACHE_BITS[cache_start + cache0] as i32 + 12 && n > 2 {
1549+ n >>= 1;
1550+ y = Some(x + n);
1551+ split = true;
1552+ lm -= 1;
1553+ blocks = (blocks + 1) >> 1;
1554+ }
1555+
1556+ if split {
1557+ let pulse_cap = LOG_N[i] + lm * (1 << BITRES);
1558+ let offset = (pulse_cap >> 1)
1559+ - if stereo && n == 2 {
1560+ QTHETA_OFFSET_TWOPHASE
1561+ } else {
1562+ QTHETA_OFFSET
1563+ };
1564+ let mut qn = compute_qn(n as i32, b, offset, pulse_cap, stereo);
1565+ if stereo && i >= intensity {
1566+ qn = 1;
1567+ }
1568+ // The angle between the two halves, before any quantisation.
1569+ let mut itheta = {
1570+ let yy = y.unwrap();
1571+ let (xs, ys) = (&self.x[x..x + n], &self.x[yy..yy + n]);
1572+ stereo_itheta(xs, ys, stereo, n)
1573+ };
1574+ let tell = enc.tell_frac() as i32;
1575+ if qn != 1 {
1576+ itheta = (itheta * qn + 8192) >> 14;
1577+ // Entropy coding of the angle: step pdf for stereo, uniform
1578+ // for the time split, triangular otherwise.
1579+ if stereo && n > 2 {
1580+ let p0 = 3i32;
1581+ let x0 = qn / 2;
1582+ let ft = (p0 * (x0 + 1) + x0) as u32;
1583+ let xv = itheta;
1584+ let (fl, fh) = if xv <= x0 {
1585+ (p0 * xv, p0 * (xv + 1))
1586+ } else {
1587+ ((xv - 1 - x0) + (x0 + 1) * p0, (xv - x0) + (x0 + 1) * p0)
1588+ };
1589+ enc.encode(fl as u32, fh as u32, ft);
1590+ } else if b0 > 1 || stereo {
1591+ enc.enc_uint(itheta as u32, (qn + 1) as u32);
1592+ } else {
1593+ let ft = ((qn >> 1) + 1) * ((qn >> 1) + 1);
1594+ let (fl, fs) = if itheta <= qn >> 1 {
1595+ ((itheta * (itheta + 1)) >> 1, itheta + 1)
1596+ } else {
1597+ (
1598+ ft - (((qn + 1 - itheta) * (qn + 2 - itheta)) >> 1),
1599+ qn + 1 - itheta,
1600+ )
1601+ };
1602+ enc.encode(fl as u32, (fl + fs) as u32, ft as u32);
1603+ }
1604+ itheta = itheta * 16384 / qn;
1605+ if stereo {
1606+ let yy = y.unwrap();
1607+ if itheta == 0 {
1608+ self.intensity_stereo(i, x, yy, n);
1609+ } else {
1610+ // stereo_split
1611+ for j in 0..n {
1612+ let l = core::f32::consts::FRAC_1_SQRT_2 * self.x[x + j];
1613+ let r = core::f32::consts::FRAC_1_SQRT_2 * self.x[yy + j];
1614+ self.x[x + j] = l + r;
1615+ self.x[yy + j] = r - l;
1616+ }
1617+ }
1618+ }
1619+ } else if stereo {
1620+ let yy = y.unwrap();
1621+ let inv = itheta > 8192;
1622+ if inv {
1623+ for j in 0..n {
1624+ self.x[yy + j] = -self.x[yy + j];
1625+ }
1626+ }
1627+ self.intensity_stereo(i, x, yy, n);
1628+ if b > 2 << BITRES && *remaining_bits > 2 << BITRES {
1629+ enc.enc_bit_logp(inv, 2);
1630+ }
1631+ itheta = 0;
1632+ }
1633+ let qalloc = enc.tell_frac() as i32 - tell;
1634+ b -= qalloc;
1635+
1636+ let mut delta;
1637+ let imid;
1638+ let iside;
1639+ if itheta == 0 {
1640+ imid = 32767;
1641+ iside = 0;
1642+ delta = -16384;
1643+ } else if itheta == 16384 {
1644+ imid = 0;
1645+ iside = 32767;
1646+ delta = 16384;
1647+ } else {
1648+ imid = bitexact_cos(itheta as i16) as i32;
1649+ iside = bitexact_cos((16384 - itheta) as i16) as i32;
1650+ delta = frac_mul16(
1651+ ((n as i32 - 1) << 7) as i16,
1652+ bitexact_log2tan(iside, imid) as i16,
1653+ );
1654+ }
1655+ let _ = imid;
1656+ let _ = iside;
1657+
1658+ if n == 2 && stereo {
1659+ let mut mbits = b;
1660+ let mut sbits = 0;
1661+ if itheta != 0 && itheta != 16384 {
1662+ sbits = 1 << BITRES;
1663+ }
1664+ mbits -= sbits;
1665+ let yy = y.unwrap();
1666+ let swap = itheta > 8192;
1667+ *remaining_bits -= qalloc + sbits;
1668+ let (x2, y2) = if swap { (yy, x) } else { (x, yy) };
1669+ if sbits != 0 {
1670+ let sign = self.x[x2] * self.x[y2 + 1] - self.x[x2 + 1] * self.x[y2] < 0.0;
1671+ enc.enc_bits(u32::from(sign), 1);
1672+ }
1673+ self.quant_band(
1674+ enc,
1675+ EncBand {
1676+ x: x2,
1677+ y: None,
1678+ n,
1679+ b: mbits,
1680+ blocks,
1681+ tf_change,
1682+ lm,
1683+ ..a
1684+ },
1685+ remaining_bits,
1686+ );
1687+ } else {
1688+ if b0 > 1 && !stereo && (itheta & 0x3fff) != 0 {
1689+ if itheta > 8192 {
1690+ delta -= delta >> (4 - lm);
1691+ } else {
1692+ delta = 0.min(delta + ((n as i32) << BITRES >> (5 - lm)));
1693+ }
1694+ }
1695+ let mut mbits = 0.max(b.min((b - delta) / 2));
1696+ let mut sbits = b - mbits;
1697+ *remaining_bits -= qalloc;
1698+ let next_level = if stereo { level } else { level + 1 };
1699+ let mid_args = EncBand {
1700+ x,
1701+ y: None,
1702+ n,
1703+ blocks,
1704+ tf_change,
1705+ level: next_level,
1706+ lm,
1707+ ..a
1708+ };
1709+ let side_args = EncBand {
1710+ x: y.unwrap(),
1711+ y: None,
1712+ n,
1713+ blocks,
1714+ tf_change,
1715+ level: next_level,
1716+ lm,
1717+ ..a
1718+ };
1719+ let mut rebalance = *remaining_bits;
1720+ if mbits >= sbits {
1721+ self.quant_band(
1722+ enc,
1723+ EncBand {
1724+ b: mbits,
1725+ ..mid_args
1726+ },
1727+ remaining_bits,
1728+ );
1729+ rebalance = mbits - (rebalance - *remaining_bits);
1730+ if rebalance > 3 << BITRES && itheta != 0 {
1731+ sbits += rebalance - (3 << BITRES);
1732+ }
1733+ self.quant_band(
1734+ enc,
1735+ EncBand {
1736+ b: sbits,
1737+ ..side_args
1738+ },
1739+ remaining_bits,
1740+ );
1741+ } else {
1742+ self.quant_band(
1743+ enc,
1744+ EncBand {
1745+ b: sbits,
1746+ ..side_args
1747+ },
1748+ remaining_bits,
1749+ );
1750+ rebalance = sbits - (rebalance - *remaining_bits);
1751+ if rebalance > 3 << BITRES && itheta != 16384 {
1752+ mbits += rebalance - (3 << BITRES);
1753+ }
1754+ self.quant_band(
1755+ enc,
1756+ EncBand {
1757+ b: mbits,
1758+ ..mid_args
1759+ },
1760+ remaining_bits,
1761+ );
1762+ }
1763+ }
1764+ } else {
1765+ // The basic no-split case: straight PVQ.
1766+ let mut q = bits2pulses(i, lm, b);
1767+ let mut curr_bits = pulses2bits(i, lm, q);
1768+ *remaining_bits -= curr_bits;
1769+ while *remaining_bits < 0 && q > 0 {
1770+ *remaining_bits += curr_bits;
1771+ q -= 1;
1772+ curr_bits = pulses2bits(i, lm, q);
1773+ *remaining_bits -= curr_bits;
1774+ }
1775+ if q != 0 {
1776+ let k = get_pulses(q) as usize;
1777+ self.alg_quant(enc, x, n, k, spread, blocks);
1778+ }
1779+ // q == 0: the decoder folds or fills with noise on its own;
1780+ // nothing is coded.
1781+ }
1782+ }
1783+
1784+ /// `intensity_stereo()`: collapses the pair onto a single channel weighted
1785+ /// by the band energies; only the combined channel is coded.
1786+ fn intensity_stereo(&mut self, band: usize, x: usize, y: usize, n: usize) {
1787+ let left = self.band_e[band];
1788+ let right = self.band_e[band + NB_BANDS];
1789+ let norm = 1e-15 + (1e-15 + left * left + right * right).sqrt();
1790+ let a1 = left / norm;
1791+ let a2 = right / norm;
1792+ for j in 0..n {
1793+ let l = self.x[x + j];
1794+ let r = self.x[y + j];
1795+ self.x[x + j] = a1 * l + a2 * r;
1796+ }
1797+ }
1798+
1799+ /// `alg_quant()`: the PVQ search — greedy pyramid projection plus one
1800+ /// pulse at a time on the exact `Rxy^2/Ryy` criterion — then the
1801+ /// enumeration encode.
1802+ fn alg_quant(
1803+ &mut self,
1804+ enc: &mut RangeEncoder,
1805+ x: usize,
1806+ n: usize,
1807+ k: usize,
1808+ spread: usize,
1809+ blocks: usize,
1810+ ) {
1811+ debug_assert!(n > 1 && k > 0);
1812+ exp_rotation(&mut self.x[x..x + n], n, 1, blocks, k, spread);
1813+ let xs = &mut self.x[x..x + n];
1814+ let iy = &mut self.iy[..n];
1815+ let y = &mut self.pvq_y[..n];
1816+ let signs = &mut self.pvq_sign[..n];
1817+ for j in 0..n {
1818+ if xs[j] > 0.0 {
1819+ signs[j] = 1;
1820+ } else {
1821+ signs[j] = -1;
1822+ xs[j] = -xs[j];
1823+ }
1824+ iy[j] = 0;
1825+ y[j] = 0.0;
1826+ }
1827+ let mut xy = 0.0f32;
1828+ let mut yy = 0.0f32;
1829+ let mut pulses_left = k as i32;
1830+ if k > n >> 1 {
1831+ let mut sum = 0.0f32;
1832+ for v in xs.iter() {
1833+ sum += *v;
1834+ }
1835+ if !(sum > 1e-15 && sum < 64.0) {
1836+ xs[0] = 1.0;
1837+ for v in xs.iter_mut().skip(1) {
1838+ *v = 0.0;
1839+ }
1840+ sum = 1.0;
1841+ }
1842+ let rcp = (k as f32 - 1.0) / sum;
1843+ for j in 0..n {
1844+ iy[j] = (rcp * xs[j]).floor() as i32;
1845+ y[j] = iy[j] as f32;
1846+ yy += y[j] * y[j];
1847+ xy += xs[j] * y[j];
1848+ y[j] *= 2.0;
1849+ pulses_left -= iy[j];
1850+ }
1851+ }
1852+ debug_assert!(pulses_left >= 1);
1853+ if pulses_left > n as i32 + 3 {
1854+ let tmp = pulses_left as f32;
1855+ yy += tmp * tmp;
1856+ yy += tmp * y[0];
1857+ iy[0] += pulses_left;
1858+ pulses_left = 0;
1859+ }
1860+ // The pulse-placement search is the encoder's hottest loop — O(K*N)
1861+ // per band, dominant at high rates — so it runs eight candidates a
1862+ // lane with `wide`. Lane-local bests are reduced after the sweep;
1863+ // only the tie-breaking order differs from the scalar loop, and any
1864+ // pulse choice is a valid codeword — the enumeration, not the
1865+ // search, is what conformance constrains.
1866+ for _ in 0..pulses_left {
1867+ yy += 1.0;
1868+ let mut best_id = 0usize;
1869+ let mut best_num = -1e15f32;
1870+ let mut best_den = 0.0f32;
1871+ let mut j0 = 0usize;
1872+ if n >= 16 {
1873+ #[allow(deprecated)]
1874+ use wide::{CmpGt, f32x8};
1875+ let chunks = n / 8;
1876+ let xy_v = f32x8::splat(xy);
1877+ let yy_v = f32x8::splat(yy);
1878+ let mut bn = f32x8::splat(-1e15);
1879+ let mut bd = f32x8::splat(0.0);
1880+ let mut bc = f32x8::splat(0.0);
1881+ for c in 0..chunks {
1882+ let mut xa = [0f32; 8];
1883+ let mut ya = [0f32; 8];
1884+ xa.copy_from_slice(&xs[c * 8..c * 8 + 8]);
1885+ ya.copy_from_slice(&y[c * 8..c * 8 + 8]);
1886+ let rxy = xy_v + f32x8::from(xa);
1887+ let ryy = yy_v + f32x8::from(ya);
1888+ let rxy2 = rxy * rxy;
1889+ let mask = (bd * rxy2).simd_gt(ryy * bn);
1890+ bn = mask.blend(rxy2, bn);
1891+ bd = mask.blend(ryy, bd);
1892+ bc = mask.blend(f32x8::splat(c as f32), bc);
1893+ }
1894+ let bn_a: [f32; 8] = bn.into();
1895+ let bd_a: [f32; 8] = bd.into();
1896+ let bc_a: [f32; 8] = bc.into();
1897+ for l in 0..8 {
1898+ if best_den * bn_a[l] > bd_a[l] * best_num {
1899+ best_den = bd_a[l];
1900+ best_num = bn_a[l];
1901+ best_id = bc_a[l] as usize * 8 + l;
1902+ }
1903+ }
1904+ j0 = chunks * 8;
1905+ }
1906+ for j in j0..n {
1907+ let rxy = xy + xs[j];
1908+ let ryy = yy + y[j];
1909+ let rxy2 = rxy * rxy;
1910+ if best_den * rxy2 > ryy * best_num {
1911+ best_den = ryy;
1912+ best_num = rxy2;
1913+ best_id = j;
1914+ }
1915+ }
1916+ xy += xs[best_id];
1917+ yy += y[best_id];
1918+ y[best_id] += 2.0;
1919+ iy[best_id] += 1;
1920+ }
1921+ for j in 0..n {
1922+ if signs[j] < 0 {
1923+ iy[j] = -iy[j];
1924+ }
1925+ }
1926+ if self.urow.len() < k + 2 {
1927+ self.urow.resize(k + 2, 0);
1928+ }
1929+ encode_pulses(enc, &self.iy[..n], n, k, &mut self.urow);
1930+ }
1931+}
1932+
1933+#[cfg(test)]
1934+mod tests {
1935+ use super::*;
1936+ use crate::range::RangeDecoder;
1937+
1938+ /// The forward MDCT against the transform's definition, at the 2/l scale
1939+ /// CELT puts on the analysis side.
1940+ #[test]
1941+ fn forward_mdct_matches_the_definition() {
1942+ for &l in &[120usize, 240, 480, 960] {
1943+ let w = celt::overlap_window();
1944+ let flat = (l - OVERLAP) / 2;
1945+ // The full 2l low-overlap window.
1946+ let mut win = vec![0.0f32; 2 * l];
1947+ for i in 0..l {
1948+ win[i] = if i < flat {
1949+ 0.0
1950+ } else if i < flat + OVERLAP {
1951+ w[i - flat]
1952+ } else {
1953+ 1.0
1954+ };
1955+ win[2 * l - 1 - i] = win[i];
1956+ }
1957+ // A signal over the window's support, zero-padded to 2l.
1958+ let support = l + OVERLAP;
1959+ let sig: Vec<f32> = (0..support)
1960+ .map(|i| ((i * 2654435761usize) % 2000) as f32 / 1000.0 - 1.0)
1961+ .collect();
1962+ let mut x2l = vec![0.0f32; 2 * l];
1963+ for j in 0..support {
1964+ x2l[flat + j] = win[flat + j] * sig[j];
1965+ }
1966+ // Direct MDCT by definition.
1967+ let direct: Vec<f64> = (0..l)
1968+ .map(|k| {
1969+ let mut sum = 0.0f64;
1970+ for (nn, &v) in x2l.iter().enumerate() {
1971+ let a = core::f64::consts::PI / l as f64
1972+ * (nn as f64 + 0.5 + l as f64 / 2.0)
1973+ * (k as f64 + 0.5);
1974+ sum += v as f64 * a.cos();
1975+ }
1976+ sum * 2.0 / l as f64
1977+ })
1978+ .collect();
1979+ let mut plan = MdctPlan::new(l);
1980+ let mut out = vec![0.0f32; l];
1981+ plan.forward(&sig, 0, &w, &mut out, 0, 1);
1982+ let mut worst = 0.0f64;
1983+ for k in 0..l {
1984+ worst = worst.max((direct[k] - out[k] as f64).abs());
1985+ }
1986+ assert!(worst < 1e-4, "l={l}: worst coefficient error {worst}");
1987+ }
1988+ }
1989+
1990+ /// encode_pulses must invert decode_pulses for every (n, k) shape the
1991+ /// allocation can produce.
1992+ #[test]
1993+ fn pulse_enumeration_round_trips() {
1994+ let mut state = 0x2545F491u32;
1995+ let mut rand = move || {
1996+ state ^= state << 13;
1997+ state ^= state >> 17;
1998+ state ^= state << 5;
1999+ state
2000+ };
crates/ec-opus/src/encoder.rsadded+193 -0
@@ -0,0 +1,193 @@
1+//! The Opus packet encoder: CELT-only, fullband, 48 kHz.
2+//!
3+//! One [`Encoder`] produces ordinary code-0 Opus packets (RFC 6716 Section 3)
4+//! or the self-delimited variant of Appendix B that the multistream framing
5+//! needs. Every configuration this encoder emits is a fullband CELT one
6+//! (TOC configs 28..31), which is what music encoding uses at every rate the
7+//! product asks for; there is no SILK and no hybrid path — a speech-optimised
8+//! mode below 16 kbps is out of scope, not silently approximated.
9+//!
10+//! Rate control is CBR by default — every packet the same size, derived from
11+//! the bitrate — or constrained VBR, the reference's reservoir scheme, when
12+//! [`Encoder::set_vbr_constrained`] is on.
13+
14+use ec_core::{Error, Result};
15+
16+use crate::celt_enc::CeltEncoder;
17+use crate::range::RangeEncoder;
18+
19+/// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`).
20+const MAX_FRAME_BYTES: usize = 1275;
21+
22+/// One elementary Opus encoder: mono or stereo, CELT-only, 48 kHz in.
23+#[derive(Clone, Debug)]
24+pub struct Encoder {
25+ celt: CeltEncoder,
26+ range: RangeEncoder,
27+ channels: usize,
28+ bitrate: u32,
29+ vbr: bool,
30+ final_range: u32,
31+}
32+
33+impl Encoder {
34+ /// An encoder for `channels` channels (1 or 2) at `sample_rate`, which
35+ /// must be 48000 — CELT's native rate, and the only rate the product
36+ /// feeds it (RFC 7845 Section 5.1: every Opus decoder runs at 48 kHz
37+ /// regardless of what the container claims).
38+ pub fn new(sample_rate: u32, channels: usize) -> Result<Encoder> {
39+ if sample_rate != 48000 {
40+ return Err(Error::unsupported(
41+ format!("opus encode at {sample_rate} Hz"),
42+ "this CELT-only encoder takes 48 kHz input; resample first",
43+ ));
44+ }
45+ if !(1..=2).contains(&channels) {
46+ return Err(Error::unsupported(
47+ format!("{channels}-channel Opus stream"),
48+ "one stream carries at most two channels; use MultistreamEncoder",
49+ ));
50+ }
51+ Ok(Encoder {
52+ celt: CeltEncoder::new(channels),
53+ range: RangeEncoder::new(),
54+ channels,
55+ bitrate: 64_000 * channels as u32,
56+ vbr: false,
57+ final_range: 0,
58+ })
59+ }
60+
61+ /// Channels per frame of input.
62+ pub fn channels(&self) -> usize {
63+ self.channels
64+ }
65+
66+ /// Target bitrate in bits per second for the whole packet stream,
67+ /// including the packet headers. Clamped to 500..=510000.
68+ pub fn set_bitrate(&mut self, bps: u32) {
69+ self.bitrate = bps.clamp(500, 510_000);
70+ }
71+
72+ /// Current target bitrate.
73+ pub fn bitrate(&self) -> u32 {
74+ self.bitrate
75+ }
76+
77+ /// Switches between CBR (default, every packet the target size) and
78+ /// constrained VBR (packets vary, a reservoir holds the average to the
79+ /// target).
80+ pub fn set_vbr_constrained(&mut self, vbr: bool) {
81+ self.vbr = vbr;
82+ }
83+
84+ /// The range coder state after the last packet — the same value RFC 6716
85+ /// test vectors carry, and what a conformant decoder's `final_range`
86+ /// must equal after decoding that packet.
87+ pub fn final_range(&self) -> u32 {
88+ self.final_range
89+ }
90+
91+ /// Drops all inter-frame state; the next packet starts like the first.
92+ pub fn reset(&mut self) {
93+ self.celt.reset();
94+ self.final_range = 0;
95+ }
96+
97+ fn toc(&self, frame_size: usize) -> Result<u8> {
98+ let fs_idx: u8 = match frame_size {
99+ 120 => 0,
100+ 240 => 1,
101+ 480 => 2,
102+ 960 => 3,
103+ _ => {
104+ return Err(Error::unsupported(
105+ format!("opus frame of {frame_size} samples"),
106+ "CELT frames are 120, 240, 480 or 960 samples at 48 kHz",
107+ ));
108+ }
109+ };
110+ let config = 28 + fs_idx; // fullband CELT
111+ Ok((config << 3) | (u8::from(self.channels == 2) << 2))
112+ }
113+
114+ /// Encodes one frame — `frame_size` samples per channel of interleaved
115+ /// `f32` at 48 kHz, `frame_size` one of 120/240/480/960 — as a code-0
116+ /// Opus packet in `out`, returning the packet length.
117+ pub fn encode_float(
118+ &mut self,
119+ pcm: &[f32],
120+ frame_size: usize,
121+ out: &mut [u8],
122+ ) -> Result<usize> {
123+ let toc = self.toc(frame_size)?;
124+ let n = self.encode_frame(pcm, frame_size, out.len().saturating_sub(1))?;
125+ if out.len() < 1 + n {
126+ return Err(Error::corrupt(format!(
127+ "opus encode: packet needs {} bytes, buffer holds {}",
128+ 1 + n,
129+ out.len()
130+ )));
131+ }
132+ out[0] = toc;
133+ out[1..1 + n].copy_from_slice(&self.range.data()[..n]);
134+ Ok(1 + n)
135+ }
136+
137+ /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716
138+ /// Appendix B: TOC, an explicit frame length, then the frame. This is
139+ /// what every stream but the last uses inside a multistream packet.
140+ pub fn encode_self_delimited(
141+ &mut self,
142+ pcm: &[f32],
143+ frame_size: usize,
144+ out: &mut [u8],
145+ ) -> Result<usize> {
146+ let toc = self.toc(frame_size)?;
147+ let n = self.encode_frame(pcm, frame_size, out.len().saturating_sub(3))?;
148+ let len_bytes = if n < 252 { 1 } else { 2 };
149+ if out.len() < 1 + len_bytes + n {
150+ return Err(Error::corrupt(format!(
151+ "opus encode: self-delimited packet needs {} bytes, buffer holds {}",
152+ 1 + len_bytes + n,
153+ out.len()
154+ )));
155+ }
156+ out[0] = toc;
157+ if n < 252 {
158+ out[1] = n as u8;
159+ } else {
160+ let b0 = 252 + ((n - 252) & 3);
161+ out[1] = b0 as u8;
162+ out[2] = ((n - b0) / 4) as u8;
163+ }
164+ out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(&self.range.data()[..n]);
165+ Ok(1 + len_bytes + n)
166+ }
167+
168+ /// Encodes the CELT frame into the internal range coder and returns its
169+ /// byte length. `cap` bounds the frame (the caller's buffer minus
170+ /// headers).
171+ fn encode_frame(&mut self, pcm: &[f32], frame_size: usize, cap: usize) -> Result<usize> {
172+ let cap = cap.min(MAX_FRAME_BYTES);
173+ if cap < 2 {
174+ return Err(Error::corrupt(
175+ "opus encode: output buffer smaller than the minimum packet",
176+ ));
177+ }
178+ // One byte per packet goes to the TOC; the CELT layer sees the rest.
179+ let toc_bps = 8 * 48000 / frame_size as u32;
180+ let (budget, vbr_rate) = if self.vbr {
181+ (cap, self.bitrate.saturating_sub(toc_bps).max(500))
182+ } else {
183+ let b = ((self.bitrate as u64 * frame_size as u64 + 4 * 48000) / (8 * 48000)) as usize;
184+ (b.saturating_sub(1).clamp(2, cap), 0)
185+ };
186+ self.range.reset(budget);
187+ let n = self
188+ .celt
189+ .encode(&mut self.range, pcm, frame_size, vbr_rate)?;
190+ self.final_range = self.range.range();
191+ Ok(n)
192+ }
193+}
crates/ec-opus/src/lib.rsmodified+36 -2
@@ -27,22 +27,56 @@
27 //! a container, never a gap, so the concealment would be dead weight; a27 //! a container, never a gap, so the concealment would be dead weight; a
28 //! caller that needs it (an RTP receiver) has to add it.28 //! caller that needs it (an RTP receiver) has to add it.
29 //!29 //!
30-//! No unsafe, no allocation on the per-frame path beyond the decoder's own30+//! The crate also carries the family's Opus *encoder* — [`Encoder`] for one
31+//! stream, [`MultistreamEncoder`] for surround — CELT-only, fullband, mono
32+//! and stereo, every rate from 16 to 510 kbps, CBR and constrained VBR.
33+//!
34+//! **Why the incumbent encoder collapsed above ~128-165 kbps** (the measured
35+//! record this crate replaces; edith `engine/Cargo.toml:124-140` and
36+//! `export.rs:1834`): its packets above that rate were decodable only by its
37+//! *own* decoder — correlation 0.06 against libopus at 256 kbps while its
38+//! internal round trip read 0.999 — and the rate the cliff sat at moved with
39+//! the content. That signature — self-consistent, world-divergent, at a
40+//! *bits-per-band* threshold — is a shared encode/decode convention error in
41+//! exactly the code CELT only exercises when a band's budget is large: the
42+//! over-32-bit-codeword band split (RFC 6716 Section 4.3.4.1: a band whose bit
43+//! demand exceeds its cache row is halved recursively, with an entropy-coded
44+//! angle and a rebalance of the leftover bits). An encoder whose split
45+//! bookkeeping (`tell`-derived budgets, rebalance, theta pdf selection)
46+//! drifts one bit from the normative derivation still decodes its own output
47+//! — both halves share the drift — but a conformant decoder desynchronises,
48+//! and the threshold moves with content because the split only triggers on
49+//! loud, flat bands. Content-dependence is also why mono broke at *every*
50+//! rate: half the coefficients means every band hits the split threshold at
51+//! half the bitrate. This encoder mirrors the reference's allocation
52+//! arithmetic symbol for symbol, and the tests hold the closed loop to it:
53+//! every packet is range-state-exact against this crate's own
54+//! RFC-vector-verified decoder, and libopus (via ffmpeg) plus the reference
55+//! `opus_demo` decoder read the same packets at correlation >= 0.99 across
56+//! the whole rate table, mono, stereo and 5.1 alike.
57+//!
58+//! No unsafe, no allocation on the per-frame path beyond the codecs' own
31 //! buffers, no dependencies outside the family.59 //! buffers, no dependencies outside the family.
32 60
33 #![forbid(unsafe_code)]61 #![forbid(unsafe_code)]
34 #![warn(missing_docs)]62 #![warn(missing_docs)]
35 63
36 pub mod celt;64 pub mod celt;
65+pub mod celt_enc;
66+pub mod encoder;
37 pub mod multistream;67 pub mod multistream;
68+pub mod multistream_enc;
38 pub mod packet;69 pub mod packet;
39 pub mod range;70 pub mod range;
40 pub mod silk;71 pub mod silk;
41 72
42 pub use celt::CeltDecoder;73 pub use celt::CeltDecoder;
74+pub use celt_enc::CeltEncoder;
75+pub use encoder::Encoder;
43 pub use multistream::MultistreamDecoder;76 pub use multistream::MultistreamDecoder;
77+pub use multistream_enc::MultistreamEncoder;
44 pub use packet::{Bandwidth, Mode, Packet, Toc};78 pub use packet::{Bandwidth, Mode, Packet, Toc};
45-pub use range::RangeDecoder;79+pub use range::{RangeDecoder, RangeEncoder};
46 pub use silk::SilkDecoder;80 pub use silk::SilkDecoder;
47 81
48 use ec_core::{Error, Result};82 use ec_core::{Error, Result};
crates/ec-opus/src/multistream_enc.rsadded+168 -0
@@ -0,0 +1,168 @@
1+//! Multichannel Opus encoding: several elementary streams in one packet.
2+//!
3+//! The exact mirror of [`crate::MultistreamDecoder`]: the first `coupled`
4+//! streams are stereo, the rest mono, all but the last written in the
5+//! self-delimited framing of RFC 6716 Appendix B. `mapping[c]` names the
6+//! coded channel that input channel `c` feeds — the same table, in the same
7+//! direction, that the decoder uses to route its output, so input channel
8+//! *order is the mapping's*: RFC 7845 family 1 (what a 5.1 film track uses)
9+//! is Vorbis order — left, centre, right, back left, back right, LFE.
10+//!
11+//! An input channel mapped to 255 is discarded; a coded channel no input
12+//! names is encoded as silence.
13+
14+use ec_core::{Error, Result};
15+
16+use crate::encoder::Encoder;
17+
18+/// A multichannel Opus encoder, mono through 255 channels.
19+#[derive(Debug)]
20+pub struct MultistreamEncoder {
21+ streams: Vec<Encoder>,
22+ coupled: usize,
23+ mapping: Vec<u8>,
24+ channels: usize,
25+ /// Scratch for one stream's deinterleaved input.
26+ buf: Vec<f32>,
27+}
28+
29+impl MultistreamEncoder {
30+ /// An encoder for `streams` elementary streams of which the first
31+ /// `coupled` are stereo, with `mapping` naming the coded channel each
32+ /// input channel feeds. Layout rules are the decoder's, checked the same
33+ /// way.
34+ pub fn new(
35+ sample_rate: u32,
36+ streams: usize,
37+ coupled: usize,
38+ mapping: &[u8],
39+ ) -> Result<MultistreamEncoder> {
40+ if streams == 0 || streams > 255 || coupled > streams {
41+ return Err(Error::corrupt(format!(
42+ "opus multistream: {streams} streams of which {coupled} coupled"
43+ )));
44+ }
45+ let coded = coupled + streams;
46+ if mapping.is_empty() || mapping.len() > 255 {
47+ return Err(Error::corrupt(format!(
48+ "opus multistream: {} input channels",
49+ mapping.len()
50+ )));
51+ }
52+ if let Some(&bad) = mapping.iter().find(|&&m| m != 255 && m as usize >= coded) {
53+ return Err(Error::corrupt(format!(
54+ "opus multistream: mapping entry {bad} names a channel of {coded}"
55+ )));
56+ }
57+ let mut encoders = Vec::with_capacity(streams);
58+ for s in 0..streams {
59+ let ch = if s < coupled { 2 } else { 1 };
60+ encoders.push(Encoder::new(sample_rate, ch)?);
61+ }
62+ Ok(MultistreamEncoder {
63+ streams: encoders,
64+ coupled,
65+ mapping: mapping.to_vec(),
66+ channels: mapping.len(),
67+ buf: vec![0.0; 2 * 960],
68+ })
69+ }
70+
71+ /// The RFC 7845 mapping-family-1 layout for 5.1: four streams, two
72+ /// coupled, Vorbis channel order (FL, FC, FR, BL, BR, LFE).
73+ pub fn surround_5_1(sample_rate: u32) -> Result<MultistreamEncoder> {
74+ MultistreamEncoder::new(sample_rate, 4, 2, &[0, 4, 1, 2, 3, 5])
75+ }
76+
77+ /// Input channels per frame.
78+ pub fn channels(&self) -> usize {
79+ self.channels
80+ }
81+
82+ /// The `(streams, coupled, mapping)` triple a RFC 7845 `OpusHead` needs.
83+ pub fn layout(&self) -> (usize, usize, &[u8]) {
84+ (self.streams.len(), self.coupled, &self.mapping)
85+ }
86+
87+ /// Total target bitrate in bits per second, split over the streams with
88+ /// a coupled stream weighing twice a mono one.
89+ pub fn set_bitrate(&mut self, total_bps: u32) {
90+ let mono = self.streams.len() - self.coupled;
91+ let shares = (2 * self.coupled + mono) as u32;
92+ let share = total_bps / shares.max(1);
93+ for (s, enc) in self.streams.iter_mut().enumerate() {
94+ let w = if s < self.coupled { 2 } else { 1 };
95+ enc.set_bitrate(share * w);
96+ }
97+ }
98+
99+ /// CBR (default) or constrained VBR, applied to every stream.
100+ pub fn set_vbr_constrained(&mut self, vbr: bool) {
101+ for enc in self.streams.iter_mut() {
102+ enc.set_vbr_constrained(vbr);
103+ }
104+ }
105+
106+ /// Drops all inter-frame state in every stream.
107+ pub fn reset(&mut self) {
108+ for enc in self.streams.iter_mut() {
109+ enc.reset();
110+ }
111+ }
112+
113+ /// The range coder states of all streams, combined the way RFC 6716
114+ /// Section 6 combines them for conformance checking.
115+ pub fn final_range(&self) -> u32 {
116+ self.streams.iter().fold(0, |acc, s| acc ^ s.final_range())
117+ }
118+
119+ /// Encodes one frame — `frame_size` samples per channel of interleaved
120+ /// `f32` in the mapping's channel order — as one multistream Opus packet
121+ /// in `out`, returning the packet length.
122+ pub fn encode_float(
123+ &mut self,
124+ pcm: &[f32],
125+ frame_size: usize,
126+ out: &mut [u8],
127+ ) -> Result<usize> {
128+ if pcm.len() < frame_size * self.channels {
129+ return Err(Error::corrupt(format!(
130+ "opus multistream encode: {} samples for {} channels of {frame_size}",
131+ pcm.len(),
132+ self.channels
133+ )));
134+ }
135+ let nb_streams = self.streams.len();
136+ let mut pos = 0usize;
137+ for s in 0..nb_streams {
138+ let stream_channels = if s < self.coupled { 2 } else { 1 };
139+ // Gather this stream's channels; a coded channel nobody feeds is
140+ // silence.
141+ self.buf[..frame_size * stream_channels].fill(0.0);
142+ for off in 0..stream_channels {
143+ let coded = if s < self.coupled {
144+ 2 * s + off
145+ } else {
146+ self.coupled + s
147+ };
148+ if let Some(c) = self.mapping.iter().position(|&m| m as usize == coded) {
149+ for i in 0..frame_size {
150+ self.buf[i * stream_channels + off] = pcm[i * self.channels + c];
151+ }
152+ }
153+ }
154+ let last = s == nb_streams - 1;
155+ let (head, buf) = (&mut out[pos..], &self.buf[..frame_size * stream_channels]);
156+ // The borrow checker cannot see that `buf` and the encoder are
157+ // disjoint fields through `&mut self`; a split borrow does.
158+ let enc = &mut self.streams[s];
159+ let n = if last {
160+ enc.encode_float(buf, frame_size, head)?
161+ } else {
162+ enc.encode_self_delimited(buf, frame_size, head)?
163+ };
164+ pos += n;
165+ }
166+ Ok(pos)
167+ }
168+}
crates/ec-opus/src/range.rsmodified+386 -119
@@ -260,147 +260,331 @@ impl<'a> RangeDecoder<'a> {
260 }260 }
261 }261 }
262 262
263-#[cfg(test)]263+/// The Opus range *encoder* (RFC 6716, Section 5.1) — the exact mirror of
264-mod tests {264+/// [`RangeDecoder`], over a fixed-size buffer.
265- use super::*;265+///
266+/// Range-coded bytes grow from the front of the buffer, raw bits from the
267+/// back, exactly as the decoder reads them; the two meeting is a bust, which
268+/// [`RangeEncoder::error`] reports rather than corrupting either stream. The
269+/// buffer is owned and reused across frames — [`RangeEncoder::reset`] costs a
270+/// `fill(0)` of the frame, so a steady-state encoder never allocates here.
271+#[derive(Clone, Debug)]
272+pub struct RangeEncoder {
273+ buf: Vec<u8>,
274+ /// Logical frame size: the decoder will be handed `buf[..storage]`.
275+ storage: usize,
276+ /// Next byte the range coder writes, from the front.
277+ offs: usize,
278+ /// Bytes already written by the raw-bit writer, from the back.
279+ end_offs: usize,
280+ /// Bits buffered by the raw-bit writer (LSB first).
281+ end_window: u32,
282+ nend_bits: u32,
283+ /// Whole bits written so far, including what is buffered in `rng`.
284+ nbits_total: u32,
285+ /// Low end of the current range.
286+ val: u32,
287+ /// Size of the current range.
288+ rng: u32,
289+ /// A buffered byte awaiting carry propagation, `-1` before the first.
290+ rem: i32,
291+ /// Count of buffered `0xFF` bytes that a carry would turn into `0x00`.
292+ ext: u32,
293+ error: bool,
294+}
266 295
267- /// A minimal range *encoder* (RFC 6716, Section 5.1), test-only: it exists296+impl RangeEncoder {
268- /// so the decoder can be checked against something other than itself on297+ /// An encoder with no buffer; call [`RangeEncoder::reset`] before use.
269- /// symbol shapes the test vectors reach only rarely. The vectors, not this,298+ pub fn new() -> RangeEncoder {
270- /// are the real oracle.299+ RangeEncoder {
271- struct RangeEncoder {300+ buf: Vec::new(),
272- buf: Vec<u8>,301+ storage: 0,
273- low: u32,302+ offs: 0,
274- rng: u32,303+ end_offs: 0,
275- rem: i32,304+ end_window: 0,
276- ext: u32,305+ nend_bits: 0,
277- // raw bits, packed backwards306+ nbits_total: CODE_BITS + 1,
278- end_bits: Vec<bool>,307+ val: 0,
279- }308+ rng: 1 << (CODE_BITS - 1),
280-309+ rem: -1,
281- impl RangeEncoder {310+ ext: 0,
282- fn new() -> Self {311+ error: false,
283- RangeEncoder {
284- buf: Vec::new(),
285- low: 0,
286- rng: 0x8000_0000,
287- rem: -1,
288- ext: 0,
289- end_bits: Vec::new(),
290- }
291 }312 }
313+ }
292 314
293- fn carry_out(&mut self, c: i32) {315+ /// Starts a fresh frame of exactly `size` bytes.
294- if c != 0xFF {316+ pub fn reset(&mut self, size: usize) {
295- let carry = c >> 8;317+ if self.buf.len() < size {
296- if self.rem >= 0 {318+ self.buf.resize(size, 0);
297- let v = (self.rem + carry) as u8;
298- self.buf.push(v);
299- }
300- while self.ext > 0 {
301- self.buf.push(((0xFF + carry) & 0xFF) as u8);
302- self.ext -= 1;
303- }
304- self.rem = c & 0xFF;
305- } else {
306- self.ext += 1;
307- }
308 }319 }
320+ self.buf[..size].fill(0);
321+ self.storage = size;
322+ self.offs = 0;
323+ self.end_offs = 0;
324+ self.end_window = 0;
325+ self.nend_bits = 0;
326+ self.nbits_total = CODE_BITS + 1;
327+ self.val = 0;
328+ self.rng = 1 << (CODE_BITS - 1);
329+ self.rem = -1;
330+ self.ext = 0;
331+ self.error = false;
332+ }
309 333
310- fn normalize(&mut self) {334+ /// The encoder's current range state — what the decoder's
311- while self.rng <= CODE_TOP {335+ /// [`RangeDecoder::range`] must equal after the same symbols.
312- self.carry_out((self.low >> 23) as i32);336+ pub fn range(&self) -> u32 {
313- self.low = (self.low << 8) & 0x7FFF_FFFF;337+ self.rng
314- self.rng <<= 8;338+ }
315- }339+
340+ /// True when the frame busted its budget; the frame is unusable.
341+ pub fn error(&self) -> bool {
342+ self.error
343+ }
344+
345+ /// The frame size in bytes.
346+ pub fn storage(&self) -> usize {
347+ self.storage
348+ }
349+
350+ /// Bytes the range coder has finalised so far (`ec_range_bytes`).
351+ pub fn range_bytes(&self) -> usize {
352+ self.offs
353+ }
354+
355+ /// The finished frame; call only after [`RangeEncoder::done`].
356+ pub fn data(&self) -> &[u8] {
357+ &self.buf[..self.storage]
358+ }
359+
360+ fn write_byte(&mut self, value: u32) {
361+ if self.offs + self.end_offs >= self.storage {
362+ self.error = true;
363+ return;
316 }364 }
365+ self.buf[self.offs] = value as u8;
366+ self.offs += 1;
367+ }
317 368
318- fn encode(&mut self, fl: u32, fh: u32, ft: u32) {369+ fn write_byte_at_end(&mut self, value: u32) {
319- let r = self.rng / ft;370+ if self.offs + self.end_offs >= self.storage {
320- if fl > 0 {371+ self.error = true;
321- self.low = self.low.wrapping_add(self.rng - r * (ft - fl));372+ return;
322- self.rng = r * (fh - fl);
323- } else {
324- self.rng -= r * (ft - fh);
325- }
326- self.normalize();
327 }373 }
374+ self.end_offs += 1;
375+ self.buf[self.storage - self.end_offs] = value as u8;
376+ }
328 377
329- fn enc_bit_logp(&mut self, bit: bool, logp: u32) {378+ fn carry_out(&mut self, c: i32) {
330- let s = self.rng >> logp;379+ if c != 0xFF {
331- if bit {380+ let carry = c >> 8;
332- self.low = self.low.wrapping_add(self.rng - s);381+ if self.rem >= 0 {
333- self.rng = s;382+ self.write_byte((self.rem + carry) as u32);
334- } else {
335- self.rng -= s;
336 }383 }
337- self.normalize();384+ while self.ext > 0 {
385+ self.write_byte(((0xFF + carry) & 0xFF) as u32);
386+ self.ext -= 1;
387+ }
388+ self.rem = c & 0xFF;
389+ } else {
390+ self.ext += 1;
338 }391 }
392+ }
339 393
340- fn enc_icdf(&mut self, k: usize, icdf: &[u8], ftb: u32) {394+ fn normalize(&mut self) {
341- let r = self.rng >> ftb;395+ while self.rng <= CODE_TOP {
342- if k > 0 {396+ self.carry_out((self.val >> 23) as i32);
343- self.low = self.low.wrapping_add(self.rng - r * icdf[k - 1] as u32);397+ self.val = (self.val << 8) & 0x7FFF_FFFF;
344- self.rng = r * (icdf[k - 1] as u32 - icdf[k] as u32);398+ self.rng <<= 8;
345- } else {399+ self.nbits_total += 8;
346- self.rng -= r * icdf[k] as u32;
347- }
348- self.normalize();
349 }400 }
401+ }
350 402
351- fn enc_uint(&mut self, value: u32, ft: u32) {403+ /// `ec_encode()`: one symbol spanning `[fl, fh)` of `ft`.
352- let ftb = ilog(ft - 1);404+ #[inline]
353- if ftb <= 8 {405+ pub fn encode(&mut self, fl: u32, fh: u32, ft: u32) {
354- self.encode(value, value + 1, ft);406+ let r = self.rng / ft;
355- } else {407+ if fl > 0 {
356- let ftb = ftb - 8;408+ self.val = self.val.wrapping_add(self.rng - r * (ft - fl));
357- let hi = value >> ftb;409+ self.rng = r * (fh - fl);
358- self.encode(hi, hi + 1, ((ft - 1) >> ftb) + 1);410+ } else {
359- self.enc_bits(value & ((1 << ftb) - 1), ftb);411+ self.rng -= r * (ft - fh);
360- }
361 }412 }
413+ self.normalize();
414+ }
362 415
363- fn enc_bits(&mut self, value: u32, bits: u32) {416+ /// `ec_encode_bin()`: [`RangeEncoder::encode`] with `ft = 1<<bits`.
364- for i in 0..bits {417+ #[inline]
365- self.end_bits.push((value >> i) & 1 == 1);418+ pub fn encode_bin(&mut self, fl: u32, fh: u32, bits: u32) {
366- }419+ let r = self.rng >> bits;
420+ if fl > 0 {
421+ self.val = self.val.wrapping_add(self.rng - r * ((1 << bits) - fl));
422+ self.rng = r * (fh - fl);
423+ } else {
424+ self.rng -= r * ((1 << bits) - fh);
367 }425 }
426+ self.normalize();
427+ }
368 428
369- /// Terminates the stream and returns the frame bytes.429+ /// `ec_enc_bit_logp()`: one bit whose probability of being 1 is `2**-logp`.
370- fn finish(mut self) -> Vec<u8> {430+ #[inline]
371- // Output the value in [low, low+rng) with the most trailing zero431+ pub fn enc_bit_logp(&mut self, bit: bool, logp: u32) {
372- // bits, so the raw bits may overwrite them (Section 5.1.5).432+ let r = self.rng;
373- let mut l = (32 - ilog(self.rng)) as i32;433+ let l = self.val;
374- let mut msk = 0x7FFF_FFFFu32 >> l;434+ let s = r >> logp;
375- let mut end = self.low.wrapping_add(msk) & !msk;435+ let r = r - s;
376- if (end | msk) as u64 >= self.low as u64 + self.rng as u64 {436+ if bit {
377- l += 1;437+ self.val = l.wrapping_add(r);
378- msk >>= 1;438+ }
379- end = self.low.wrapping_add(msk) & !msk;439+ self.rng = if bit { s } else { r };
380- }440+ self.normalize();
381- while l > 0 {441+ }
382- self.carry_out((end >> 23) as i32);442+
383- end = (end << 8) & 0x7FFF_FFFF;443+ /// `ec_enc_icdf()`: symbol `k` of an inverse-CDF table, `ft = 1<<ftb`.
384- l -= 8;444+ #[inline]
385- }445+ pub fn enc_icdf(&mut self, k: usize, icdf: &[u8], ftb: u32) {
386- if self.rem >= 0 || self.ext > 0 {446+ let r = self.rng >> ftb;
387- self.carry_out(0);447+ if k > 0 {
448+ self.val = self.val.wrapping_add(self.rng - r * icdf[k - 1] as u32);
449+ self.rng = r * (icdf[k - 1] as u32 - icdf[k] as u32);
450+ } else {
451+ self.rng -= r * icdf[k] as u32;
452+ }
453+ self.normalize();
454+ }
455+
456+ /// `ec_enc_uint()`: `value` as one of `ft` equiprobable values
457+ /// (Section 5.1.4). `ft` must be at least 2.
458+ pub fn enc_uint(&mut self, value: u32, ft: u32) {
459+ debug_assert!(ft > 1);
460+ let ft = ft - 1;
461+ let ftb = ilog(ft);
462+ if ftb > 8 {
463+ let ftb = ftb - 8;
464+ let ft1 = (ft >> ftb) + 1;
465+ let hi = value >> ftb;
466+ self.encode(hi, hi + 1, ft1);
467+ self.enc_bits(value & ((1u32 << ftb) - 1), ftb);
468+ } else {
469+ self.encode(value, value + 1, ft + 1);
470+ }
471+ }
472+
473+ /// `ec_enc_bits()`: `bits` raw bits, written backwards from the end of the
474+ /// frame.
475+ pub fn enc_bits(&mut self, fl: u32, bits: u32) {
476+ debug_assert!(bits > 0);
477+ let mut window = self.end_window;
478+ let mut used = self.nend_bits;
479+ if used + bits > 32 {
480+ while used >= 8 {
481+ self.write_byte_at_end(window & 0xFF);
482+ window >>= 8;
483+ used -= 8;
388 }484 }
389- // Append the raw bits, packed backwards from the end.485+ }
390- let raw_bytes = self.end_bits.len().div_ceil(8);486+ window |= fl << used;
391- let mut tail = vec![0u8; raw_bytes];487+ used += bits;
392- for (i, &b) in self.end_bits.iter().enumerate() {488+ self.end_window = window;
393- if b {489+ self.nend_bits = used;
394- let byte = raw_bytes - 1 - i / 8;490+ self.nbits_total += bits;
395- tail[byte] |= 1 << (i % 8);491+ }
492+
493+ /// `ec_enc_shrink()`: reduces the frame to `size` bytes, moving raw bits
494+ /// already written so they still end the frame. Only legal while
495+ /// `range_bytes()` plus the raw-bit bytes fit in `size`.
496+ pub fn shrink(&mut self, size: usize) {
497+ debug_assert!(self.offs + self.end_offs <= size);
498+ self.buf.copy_within(
499+ self.storage - self.end_offs..self.storage,
500+ size - self.end_offs,
501+ );
502+ self.storage = size;
503+ // The abandoned tail must be zero for the "rest is zeros" guarantee.
504+ if size > self.offs + self.end_offs {
505+ self.buf[self.offs..size - self.end_offs].fill(0);
506+ }
507+ }
508+
509+ /// `ec_tell()`: a conservative upper bound on whole bits used so far.
510+ #[inline]
511+ pub fn tell(&self) -> u32 {
512+ self.nbits_total - ilog(self.rng)
513+ }
514+
515+ /// `ec_tell_frac()`: the same bound in 1/8th bits.
516+ pub fn tell_frac(&self) -> u32 {
517+ let mut lg = ilog(self.rng);
518+ let mut r_q15 = self.rng >> (lg - 16);
519+ for _ in 0..3 {
520+ r_q15 = (r_q15 * r_q15) >> 15;
521+ let bit = r_q15 >> 16;
522+ lg = 2 * lg + bit;
523+ r_q15 >>= bit;
524+ }
525+ self.nbits_total * 8 - lg
526+ }
527+
528+ /// Declares the rest of the frame used, so [`RangeEncoder::tell`] reports
529+ /// the whole frame — the encoder side of the decoder's `skip_to_end`,
530+ /// which is what a silent CELT frame does with its remaining bits.
531+ pub fn pad_to_end(&mut self) {
532+ self.nbits_total = (self.storage as u32) * 8 + ilog(self.rng);
533+ }
534+
535+ /// `ec_enc_done()`: terminates the frame. Everything between the range
536+ /// bytes and the raw bits is left as zeros, which the decoder reads as
537+ /// zeros — a CBR frame is therefore always exactly `storage` bytes.
538+ pub fn done(&mut self) {
539+ // Output the value in [val, val+rng) with the most trailing zeros.
540+ let mut l = CODE_BITS as i32 - ilog(self.rng) as i32;
541+ let mut msk = 0x7FFF_FFFFu32 >> l;
542+ let mut end = self.val.wrapping_add(msk) & !msk;
543+ if (end | msk) as u64 >= self.val as u64 + self.rng as u64 {
544+ l += 1;
545+ msk >>= 1;
546+ end = self.val.wrapping_add(msk) & !msk;
547+ }
548+ while l > 0 {
549+ self.carry_out((end >> 23) as i32);
550+ end = (end << 8) & 0x7FFF_FFFF;
551+ l -= 8;
552+ }
553+ if self.rem >= 0 || self.ext > 0 {
554+ self.carry_out(0);
555+ }
556+ let mut window = self.end_window;
557+ let mut used = self.nend_bits;
558+ while used >= 8 {
559+ self.write_byte_at_end(window & 0xFF);
560+ window >>= 8;
561+ used -= 8;
562+ }
563+ if !self.error && used > 0 {
564+ // Anything not written is already zero (reset cleared the frame).
565+ if self.end_offs >= self.storage {
566+ self.error = true;
567+ } else {
568+ let l = -l;
569+ if self.offs + self.end_offs >= self.storage && (l as u32) < used {
570+ window &= (1u32 << l) - 1;
571+ self.error = true;
396 }572 }
573+ self.buf[self.storage - self.end_offs - 1] |= window as u8;
397 }574 }
398- // Pad so the range data and raw data never collide in this test.
399- self.buf.resize(self.buf.len() + 8, 0);
400- self.buf.extend_from_slice(&tail);
401- self.buf
402 }575 }
403 }576 }
577+}
578+
579+impl Default for RangeEncoder {
580+ fn default() -> Self {
581+ RangeEncoder::new()
582+ }
583+}
584+
585+#[cfg(test)]
586+mod tests {
587+ use super::*;
404 588
405 #[test]589 #[test]
406 fn roundtrip_mixed_symbols() {590 fn roundtrip_mixed_symbols() {
@@ -412,6 +596,7 @@ mod tests {
412 let uints: Vec<u32> = vec![0, 1, 5, 1000, 65535, 70000, 3];596 let uints: Vec<u32> = vec![0, 1, 5, 1000, 65535, 70000, 3];
413 597
414 let mut enc = RangeEncoder::new();598 let mut enc = RangeEncoder::new();
599+ enc.reset(512);
415 for &s in &syms {600 for &s in &syms {
416 enc.enc_icdf(s, ICDF, 4);601 enc.enc_icdf(s, ICDF, 4);
417 }602 }
@@ -426,7 +611,9 @@ mod tests {
426 enc.encode(fl, fl + 4, 16);611 enc.encode(fl, fl + 4, 16);
427 }612 }
428 enc.enc_bits(0b1011, 4);613 enc.enc_bits(0b1011, 4);
429- let frame = enc.finish();614+ enc.done();
615+ assert!(!enc.error());
616+ let frame = enc.data().to_vec();
430 617
431 let mut dec = RangeDecoder::new(&frame);618 let mut dec = RangeDecoder::new(&frame);
432 for &s in &syms {619 for &s in &syms {
@@ -444,6 +631,86 @@ mod tests {
444 assert_eq!(dec.dec_bits(4), 0b1011);631 assert_eq!(dec.dec_bits(4), 0b1011);
445 }632 }
446 633
634+ /// The bit allocation is derived from `tell()`/`tell_frac()` on *both*
635+ /// sides, so the encoder's accounting must match the decoder's after every
636+ /// symbol — one bit of drift desynchronises the whole frame.
637+ #[test]
638+ fn encoder_and_decoder_tell_identically() {
639+ const ICDF: &[u8] = &[100, 60, 30, 10, 0];
640+ let mut enc = RangeEncoder::new();
641+ enc.reset(256);
642+ let mut log = Vec::new();
643+ let mut x = 7u32;
644+ for i in 0..300 {
645+ x = x.wrapping_mul(1664525).wrapping_add(1013904223);
646+ match i % 4 {
647+ 0 => enc.enc_icdf((x % 5) as usize, ICDF, 7),
648+ 1 => enc.enc_bit_logp(x & 1 == 0, (x % 6) + 1),
649+ 2 => enc.enc_uint(x % 500, 700),
650+ _ => enc.enc_bits(x & 0x1F, 5),
651+ }
652+ log.push((i % 4, x, enc.tell(), enc.tell_frac(), enc.range()));
653+ }
654+ enc.done();
655+ assert!(!enc.error());
656+ let data = enc.data().to_vec();
657+ let mut dec = RangeDecoder::new(&data);
658+ for (kind, x, tell, tell_frac, rng) in log {
659+ match kind {
660+ 0 => assert_eq!(dec.dec_icdf(ICDF, 7), (x % 5) as usize),
661+ 1 => assert_eq!(dec.dec_bit_logp((x % 6) + 1), x & 1 == 0),
662+ 2 => assert_eq!(dec.dec_uint(700), x % 500),
663+ _ => assert_eq!(dec.dec_bits(5), x & 0x1F),
664+ }
665+ assert_eq!(dec.tell(), tell, "tell drifted");
666+ assert_eq!(dec.tell_frac(), tell_frac, "tell_frac drifted");
667+ assert_eq!(dec.range(), rng, "range state drifted");
668+ }
669+ }
670+
671+ /// A CBR frame stays exactly `storage` bytes: whatever the symbols leave
672+ /// unused decodes as zeros, which is what the encoder assumed.
673+ #[test]
674+ fn fixed_size_frame_decodes_past_the_coded_symbols() {
675+ let mut enc = RangeEncoder::new();
676+ enc.reset(40);
677+ enc.enc_icdf(1, &[100, 50, 0], 7);
678+ enc.enc_bits(0b101, 3);
679+ enc.done();
680+ assert!(!enc.error());
681+ assert_eq!(enc.data().len(), 40);
682+ let data = enc.data().to_vec();
683+ let mut dec = RangeDecoder::new(&data);
684+ assert_eq!(dec.dec_icdf(&[100, 50, 0], 7), 1);
685+ assert_eq!(dec.dec_bits(3), 0b101);
686+ // The rest of the frame reads as zero symbols, not garbage.
687+ for _ in 0..50 {
688+ let _ = dec.dec_bit_logp(4);
689+ }
690+ }
691+
692+ /// `shrink` moves the raw-bit tail; symbols written before and after the
693+ /// shrink must both survive.
694+ #[test]
695+ fn shrink_preserves_both_streams() {
696+ let mut enc = RangeEncoder::new();
697+ enc.reset(200);
698+ enc.enc_uint(1234, 5000);
699+ enc.enc_bits(0xAB, 8);
700+ enc.shrink(50);
701+ enc.enc_uint(999, 5000);
702+ enc.enc_bits(0x5, 4);
703+ enc.done();
704+ assert!(!enc.error());
705+ assert_eq!(enc.data().len(), 50);
706+ let data = enc.data().to_vec();
707+ let mut dec = RangeDecoder::new(&data);
708+ assert_eq!(dec.dec_uint(5000), 1234);
709+ assert_eq!(dec.dec_bits(8), 0xAB);
710+ assert_eq!(dec.dec_uint(5000), 999);
711+ assert_eq!(dec.dec_bits(4), 0x5);
712+ }
713+
447 #[test]714 #[test]
448 fn tell_agrees_with_tell_frac() {715 fn tell_agrees_with_tell_frac() {
449 let data: Vec<u8> = (0..64u8)716 let data: Vec<u8> = (0..64u8)
crates/ec-opus/tests/conformance.rsmodified+618 -0
@@ -9,6 +9,50 @@ use std::path::{Path, PathBuf};
9 9
10 use ec_opus::Decoder;10 use ec_opus::Decoder;
11 11
12+// ---------------------------------------------------------------------------
13+// Counting allocator: proves the steady-state encode loop allocates nothing.
14+// Lives in the test binary only — the shipped crate has no allocator games.
15+// Same pattern as ec-h264's proof: only the thread that armed the counter is
16+// counted, so parallel tests (and ffmpeg child plumbing) allocate freely.
17+// ---------------------------------------------------------------------------
18+
19+use std::alloc::{GlobalAlloc, Layout, System};
20+use std::cell::Cell;
21+use std::sync::atomic::{AtomicU64, Ordering};
22+
23+struct CountingAlloc;
24+
25+static ALLOCS: AtomicU64 = AtomicU64::new(0);
26+
27+std::thread_local! {
28+ static COUNTING_HERE: Cell<bool> = const { Cell::new(false) };
29+}
30+
31+fn counting_here() -> bool {
32+ COUNTING_HERE.try_with(Cell::get).unwrap_or(false)
33+}
34+
35+unsafe impl GlobalAlloc for CountingAlloc {
36+ unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
37+ if counting_here() {
38+ ALLOCS.fetch_add(1, Ordering::Relaxed);
39+ }
40+ unsafe { System.alloc(layout) }
41+ }
42+ unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
43+ unsafe { System.dealloc(ptr, layout) }
44+ }
45+ unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
46+ if counting_here() {
47+ ALLOCS.fetch_add(1, Ordering::Relaxed);
48+ }
49+ unsafe { System.realloc(ptr, layout, new_size) }
50+ }
51+}
52+
53+#[global_allocator]
54+static A: CountingAlloc = CountingAlloc;
55+
12 /// One packet of an `opus_demo` test vector file.56 /// One packet of an `opus_demo` test vector file.
13 struct VectorPacket {57 struct VectorPacket {
14 payload: Vec<u8>,58 payload: Vec<u8>,
@@ -724,6 +768,580 @@ fn real_library_sweep() {
724 }768 }
725 }769 }
726 770
771+// ---------------------------------------------------------------------------
772+// Encoder: self-consistency (range-exact against our own decoder)
773+// ---------------------------------------------------------------------------
774+
775+use ec_opus::{Encoder, MultistreamEncoder};
776+
777+/// A deterministic music-like test signal: several detuned partials plus a
778+/// swept component per channel, loud enough to exercise every band.
779+fn test_signal(channels: usize, secs: f64) -> Vec<f32> {
780+ let n = (48000.0 * secs) as usize;
781+ let mut out = Vec::with_capacity(n * channels);
782+ for i in 0..n {
783+ let t = i as f64 / 48000.0;
784+ for c in 0..channels {
785+ let base = 220.0 * (c as f64 * 0.5 + 1.0);
786+ let sweep = 400.0 + 3000.0 * (0.5 + 0.5 * (0.13 * t).sin());
787+ let v = 0.35 * (std::f64::consts::TAU * base * t).sin()
788+ + 0.2 * (std::f64::consts::TAU * base * 3.01 * t).sin()
789+ + 0.12 * (std::f64::consts::TAU * sweep * t).sin()
790+ + 0.08 * (std::f64::consts::TAU * 9000.0 * (1.0 + 0.02 * c as f64) * t).sin();
791+ out.push(v as f32);
792+ }
793+ }
794+ out
795+}
796+
797+/// Encodes `pcm` in `frame`-sample packets and decodes each with our own
798+/// decoder, asserting the range coder states agree packet for packet — the
799+/// same bit-exact check the RFC vectors put on the decoder, now closing the
800+/// loop over the encoder. Returns the decoded signal and total packet bytes.
801+fn roundtrip_own(
802+ enc: &mut Encoder,
803+ pcm: &[f32],
804+ channels: usize,
805+ frame: usize,
806+) -> (Vec<f32>, usize) {
807+ let mut dec = Decoder::new(48000, channels).unwrap();
808+ let mut out = vec![0u8; 1500];
809+ let mut decoded = Vec::new();
810+ let mut buf = vec![0.0f32; 5760 * channels];
811+ let mut bytes = 0usize;
812+ let mut padded = Vec::new();
813+ for block in pcm.chunks(frame * channels) {
814+ let block = if block.len() < frame * channels {
815+ padded.clear();
816+ padded.extend_from_slice(block);
817+ padded.resize(frame * channels, 0.0);
818+ &padded[..]
819+ } else {
820+ block
821+ };
822+ let len = enc.encode_float(block, frame, &mut out).expect("encode");
823+ bytes += len;
824+ let n = dec.decode_float(&out[..len], &mut buf).expect("decode");
825+ assert_eq!(n, frame, "decoded frame size");
826+ assert_eq!(
827+ dec.final_range(),
828+ enc.final_range(),
829+ "range state diverged between encoder and decoder"
830+ );
831+ decoded.extend_from_slice(&buf[..n * channels]);
832+ }
833+ (decoded, bytes)
834+}
835+
836+/// Worst-channel correlation against the source with the encoder's
837+/// 120-sample delay removed.
838+fn delayed_corr(source: &[f32], decoded: &[f32], channels: usize) -> f64 {
839+ const DELAY: usize = 120;
840+ let n = (decoded.len() / channels).saturating_sub(DELAY);
841+ let n = n.min(source.len() / channels);
842+ let mut worst = 1.0f64;
843+ for c in 0..channels {
844+ let a: Vec<f32> = (0..n).map(|i| source[i * channels + c]).collect();
845+ let b: Vec<f32> = (0..n)
846+ .map(|i| decoded[(i + DELAY) * channels + c])
847+ .collect();
848+ worst = worst.min(correlation(&a, &b));
849+ }
850+ worst
851+}
852+
853+/// Every rate from the product's table, mono and stereo, 20 ms CBR: the
854+/// encoder must be decodable by its own decoder range-exactly (asserted in
855+/// the helper) and land close to the source. The cross-implementation checks
856+/// against libopus live below — self-consistency alone proves nothing about
857+/// the world (the incumbent's exact disease).
858+#[test]
859+fn encoder_roundtrips_at_every_rate() {
860+ for channels in [1usize, 2] {
861+ let pcm = test_signal(channels, 2.0);
862+ for kbps in [32u32, 64, 96, 128, 160, 165, 192, 256, 320, 510] {
863+ let mut enc = Encoder::new(48000, channels).unwrap();
864+ enc.set_bitrate(kbps * 1000);
865+ let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, channels, 960);
866+ let corr = delayed_corr(&pcm, &decoded, channels);
867+ let rate = bytes as f64 * 8.0 / 2.0 / 1000.0;
868+ println!("{channels} ch {kbps:>3} kbps: corr {corr:.4}, actual {rate:.1} kbps");
869+ let floor = if kbps < 64 { 0.8 } else { 0.9 };
870+ assert!(
871+ corr >= floor,
872+ "{channels} ch {kbps} kbps: correlation {corr:.4}"
873+ );
874+ }
875+ }
876+}
877+
878+/// All four CELT frame sizes survive the loop, and constrained VBR both
879+/// stays decodable and lands near its target.
880+#[test]
881+fn encoder_frame_sizes_and_vbr() {
882+ let pcm = test_signal(2, 1.0);
883+ for frame in [120usize, 240, 480, 960] {
884+ let mut enc = Encoder::new(48000, 2).unwrap();
885+ enc.set_bitrate(128_000);
886+ let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, frame);
887+ let corr = delayed_corr(&pcm, &decoded, 2);
888+ println!("frame {frame}: corr {corr:.4}");
889+ assert!(corr >= 0.85, "frame {frame}: correlation {corr:.4}");
890+ }
891+ let mut enc = Encoder::new(48000, 2).unwrap();
892+ enc.set_bitrate(128_000);
893+ enc.set_vbr_constrained(true);
894+ let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, 2, 960);
895+ let corr = delayed_corr(&pcm, &decoded, 2);
896+ let rate = bytes as f64 * 8.0 / 1.0 / 1000.0;
897+ println!("cvbr 128k: corr {corr:.4}, actual {rate:.1} kbps");
898+ assert!(corr >= 0.9, "cvbr: correlation {corr:.4}");
899+ assert!(
900+ (90.0..=150.0).contains(&rate),
901+ "cvbr at 128k landed on {rate:.1} kbps"
902+ );
903+}
904+
905+// ---------------------------------------------------------------------------
906+// Encoder: the world must decode it. Self-consistency alone was the
907+// incumbent's disease (correlation 0.06 against libopus at 256 kbps while
908+// its own round trip passed), so every claim here runs through ffmpeg's
909+// libopus — the reference implementation — via Ogg-Opus files this crate
910+// muxed itself.
911+// ---------------------------------------------------------------------------
912+
913+use ec_core::registry::{CodecId, CodecParameters, MediaParameters, Muxer, StreamInfo};
914+use ec_core::{ChannelLayout, Packet as CorePacket, TimeBase};
915+use ec_ogg::OggMuxer;
916+
917+/// The RFC 7845 identification header for this encoder: pre-skip 120, the
918+/// CELT overlap delay.
919+fn opus_head(channels: usize, layout: Option<(usize, usize, &[u8])>) -> Vec<u8> {
920+ let mut h = Vec::from(*b"OpusHead");
921+ h.push(1);
922+ h.push(channels as u8);
923+ h.extend_from_slice(&120u16.to_le_bytes());
924+ h.extend_from_slice(&48000u32.to_le_bytes());
925+ h.extend_from_slice(&0i16.to_le_bytes());
926+ match layout {
927+ None => h.push(0),
928+ Some((streams, coupled, mapping)) => {
929+ h.push(1);
930+ h.push(streams as u8);
931+ h.push(coupled as u8);
932+ h.extend_from_slice(mapping);
933+ }
934+ }
935+ h
936+}
937+
938+/// Muxes 20 ms packets into an Ogg-Opus file whose final granule trims the
939+/// stream to exactly `total_samples` — RFC 7845 end-trimming plus the
940+/// pre-skip accounting.
941+fn write_ogg_opus(
942+ path: &Path,
943+ packets: &[Vec<u8>],
944+ head: Vec<u8>,
945+ channels: usize,
946+ total_samples: usize,
947+) {
948+ let file = std::io::BufWriter::new(fs::File::create(path).unwrap());
949+ let mut mux = OggMuxer::new(file);
950+ let tb = TimeBase::from_rate(48000);
951+ let mut params = CodecParameters::new(CodecId::Opus);
952+ params.extradata = Some(head.into());
953+ if let MediaParameters::Audio(a) = &mut params.media {
954+ a.sample_rate = 48000;
955+ a.layout = ChannelLayout::from_count(channels);
956+ }
957+ mux.add_stream(StreamInfo::new(0, tb, params)).unwrap();
958+ let mut pts = 0i64;
959+ for (idx, p) in packets.iter().enumerate() {
960+ let last = idx == packets.len() - 1;
961+ let dur = if last {
962+ total_samples as i64 + 120 - pts
963+ } else {
964+ 960
965+ };
966+ let pkt = CorePacket::new(0, tb, p.clone())
967+ .with_pts(pts)
968+ .with_duration(dur);
969+ mux.write_packet(&pkt).unwrap();
970+ pts += 960;
971+ }
972+ mux.finish().unwrap();
973+}
974+
975+/// Encodes `pcm` (plus one flush frame for the 120-sample delay) as 20 ms
976+/// packets.
977+fn encode_packets(enc: &mut Encoder, pcm: &[f32], channels: usize) -> Vec<Vec<u8>> {
978+ let mut out = vec![0u8; 1500];
979+ let mut packets = Vec::new();
980+ let mut padded = Vec::new();
981+ for block in pcm.chunks(960 * channels) {
982+ let block = if block.len() < 960 * channels {
983+ padded.clear();
984+ padded.extend_from_slice(block);
985+ padded.resize(960 * channels, 0.0);
986+ &padded[..]
987+ } else {
988+ block
989+ };
990+ let len = enc.encode_float(block, 960, &mut out).expect("encode");
991+ packets.push(out[..len].to_vec());
992+ }
993+ // One silent frame flushes the delay past the end trim.
994+ let silence = vec![0.0f32; 960 * channels];
995+ let len = enc.encode_float(&silence, 960, &mut out).expect("encode");
996+ packets.push(out[..len].to_vec());
997+ packets
998+}
999+
1000+fn temp_path(name: &str) -> PathBuf {
1001+ std::env::temp_dir().join(format!("ec-opus-enc-{}-{name}", std::process::id()))
1002+}
1003+
1004+/// The full product rate table, mono and stereo, decoded by libopus: the
1005+/// worst-channel correlation and the opus_compare quality, per rate. The
1006+/// incumbent fails this file's 256 kbps row at correlation 0.06; the MUST
1007+/// bars here are correlation >= 0.9 at 96/165/256 kbps.
1008+#[test]
1009+fn libopus_decodes_our_packets_across_the_rate_table() {
1010+ for channels in [1usize, 2] {
1011+ let pcm = test_signal(channels, 2.0);
1012+ let total = pcm.len() / channels;
1013+ let mut table = Vec::new();
1014+ for kbps in [32u32, 64, 96, 128, 160, 165, 192, 256, 320, 510] {
1015+ let mut enc = Encoder::new(48000, channels).unwrap();
1016+ enc.set_bitrate(kbps * 1000);
1017+ let packets = encode_packets(&mut enc, &pcm, channels);
1018+ let path = temp_path(&format!("{channels}ch-{kbps}k.opus"));
1019+ write_ogg_opus(&path, &packets, opus_head(channels, None), channels, total);
1020+ let Some(reference) = ffmpeg_decode(&path, channels) else {
1021+ eprintln!("ffmpeg unavailable, skipped");
1022+ let _ = fs::remove_file(&path);
1023+ return;
1024+ };
1025+ let _ = fs::remove_file(&path);
1026+ let n = (reference.len() / channels).min(total);
1027+ assert!(
1028+ n >= total - 960,
1029+ "{channels} ch {kbps} kbps: libopus returned {n} of {total} samples"
1030+ );
1031+ let mut worst = 1.0f64;
1032+ for c in 0..channels {
1033+ let a: Vec<f32> = (0..n).map(|i| pcm[i * channels + c]).collect();
1034+ let b: Vec<f32> = (0..n).map(|i| reference[i * channels + c]).collect();
1035+ worst = worst.min(correlation(&a, &b));
1036+ }
1037+ let quality = opus_compare(
1038+ &to_i16(&pcm[..n * channels]),
1039+ &to_i16(&reference[..n * channels]),
1040+ channels,
1041+ );
1042+ table.push(format!(
1043+ "{channels} ch {kbps:>3} kbps: worst corr {worst:.4}, opus_compare {quality:.1}"
1044+ ));
1045+ let floor = match kbps {
1046+ 0..=39 => 0.6,
1047+ 40..=95 => 0.8,
1048+ _ => 0.9,
1049+ };
1050+ assert!(
1051+ worst >= floor,
1052+ "{channels} ch {kbps} kbps: libopus heard correlation {worst:.4} (floor {floor})"
1053+ );
1054+ if kbps >= 96 {
1055+ assert!(
1056+ quality >= 0.0,
1057+ "{channels} ch {kbps} kbps: opus_compare {quality:.1}"
1058+ );
1059+ }
1060+ }
1061+ for line in table {
1062+ println!("{line}");
1063+ }
1064+ }
1065+}
1066+
1067+/// 5.1 multistream: one distinct tone per channel, encoded with the
1068+/// mapping-family-1 layout and decoded by libopus — every channel must come
1069+/// back in its place (order-preserved) at correlation >= 0.9.
1070+#[test]
1071+fn five_one_encode_end_to_end() {
1072+ const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3];
1073+ const TONES: [f64; 6] = [220.0, 440.0, 660.0, 55.0, 880.0, 1320.0];
1074+ let total = 96000usize;
1075+ // Vorbis order input, one tone per channel plus a quiet upper partial so
1076+ // every stream codes real content.
1077+ let mut pcm = Vec::with_capacity(total * 6);
1078+ for i in 0..total {
1079+ let t = i as f64 / 48000.0;
1080+ for f in TONES {
1081+ let v = 0.4 * (std::f64::consts::TAU * f * t).sin()
1082+ + 0.05 * (std::f64::consts::TAU * f * 7.03 * t).sin();
1083+ pcm.push(v as f32);
1084+ }
1085+ }
1086+ let mut enc = MultistreamEncoder::surround_5_1(48000).unwrap();
1087+ enc.set_bitrate(384_000);
1088+ let mut out = vec![0u8; 8 * 1500];
1089+ let mut packets = Vec::new();
1090+ for block in pcm.chunks_exact(960 * 6) {
1091+ let len = enc.encode_float(block, 960, &mut out).expect("encode");
1092+ packets.push(out[..len].to_vec());
1093+ }
1094+ let silence = vec![0.0f32; 960 * 6];
1095+ let len = enc.encode_float(&silence, 960, &mut out).expect("encode");
1096+ packets.push(out[..len].to_vec());
1097+ let (streams, coupled, mapping) = enc.layout();
1098+ let head = opus_head(6, Some((streams, coupled, mapping)));
1099+ let path = temp_path("5.1.opus");
1100+ write_ogg_opus(&path, &packets, head, 6, total);
1101+ let Some(reference) = ffmpeg_decode(&path, 6) else {
1102+ eprintln!("ffmpeg unavailable, skipped");
1103+ let _ = fs::remove_file(&path);
1104+ return;
1105+ };
1106+ let _ = fs::remove_file(&path);
1107+ let n = (reference.len() / 6).min(total);
1108+ assert!(n >= total - 960, "libopus returned {n} of {total} samples");
1109+ for (c, &their) in VORBIS_TO_FFMPEG_5_1.iter().enumerate() {
1110+ let a: Vec<f32> = (0..n).map(|i| pcm[i * 6 + c]).collect();
1111+ let b: Vec<f32> = (0..n).map(|i| reference[i * 6 + their]).collect();
1112+ let corr = correlation(&a, &b);
1113+ println!("5.1 channel {c} ({} Hz): corr {corr:.4}", TONES[c]);
1114+ assert!(
1115+ corr >= 0.9,
1116+ "5.1 channel {c} came back at correlation {corr:.4}"
1117+ );
1118+ }
1119+}
1120+
1121+/// The muxed file's duration must be exact: the final granule trims the
1122+/// flush frame so a 2.000 s input probes as 2.000 s, and the sample count
1123+/// libopus hands back is exactly the input length.
1124+#[test]
1125+fn ogg_opus_round_trip_duration_is_exact() {
1126+ let pcm = test_signal(2, 2.0);
1127+ let total = pcm.len() / 2;
1128+ let mut enc = Encoder::new(48000, 2).unwrap();
1129+ enc.set_bitrate(128_000);
1130+ let packets = encode_packets(&mut enc, &pcm, 2);
1131+ let path = temp_path("duration.opus");
1132+ write_ogg_opus(&path, &packets, opus_head(2, None), 2, total);
1133+ let probe = Command::new("ffprobe")
1134+ .args([
1135+ "-v",
1136+ "error",
1137+ "-show_entries",
1138+ "stream=duration",
1139+ "-of",
1140+ "default=noprint_wrappers=1",
1141+ ])
1142+ .arg(&path)
1143+ .output();
1144+ if let Ok(p) = probe
1145+ && p.status.success()
1146+ {
1147+ let text = String::from_utf8_lossy(&p.stdout);
1148+ let dur: f64 = text
1149+ .trim()
1150+ .strip_prefix("duration=")
1151+ .unwrap_or("0")
1152+ .parse()
1153+ .unwrap_or(0.0);
1154+ // ffprobe reports Ogg-Opus durations *including* the pre-skip — its
1155+ // own 3.000 s encode probes as 3.0065 (312/48000 more). Ours carries
1156+ // a 120-sample pre-skip, so exact is 2.0025; the decoded sample
1157+ // count below is the pre-skip-free half of the claim.
1158+ let expected = (total as f64 + 120.0) / 48000.0;
1159+ assert!(
1160+ (dur - expected).abs() < 1e-6,
1161+ "ffprobe reports {dur} s, expected {expected} s (2.000 s + pre-skip)"
1162+ );
1163+ }
1164+ if let Some(decoded) = ffmpeg_decode(&path, 2) {
1165+ assert_eq!(
1166+ decoded.len() / 2,
1167+ total,
1168+ "libopus decoded {} samples of {total}",
1169+ decoded.len() / 2
1170+ );
1171+ }
1172+ let _ = fs::remove_file(&path);
1173+}
1174+
1175+/// Cross-check against the reference `opus_demo` decoder (RFC 6716
1176+/// Appendix A) over its own `.bit` format, when the binary is available:
1177+/// `EC_OPUS_DEMO=/path/to/opus_demo cargo test`.
1178+#[test]
1179+fn opus_demo_decodes_our_bit_stream() {
1180+ let Ok(demo) = std::env::var("EC_OPUS_DEMO") else {
1181+ eprintln!("EC_OPUS_DEMO unset, skipped");
1182+ return;
1183+ };
1184+ let pcm = test_signal(2, 2.0);
1185+ let mut enc = Encoder::new(48000, 2).unwrap();
1186+ enc.set_bitrate(256_000);
1187+ let mut out = vec![0u8; 1500];
1188+ let mut bit = Vec::new();
1189+ for block in pcm.chunks_exact(960 * 2) {
1190+ let len = enc.encode_float(block, 960, &mut out).expect("encode");
1191+ bit.extend_from_slice(&(len as u32).to_be_bytes());
1192+ bit.extend_from_slice(&enc.final_range().to_be_bytes());
1193+ bit.extend_from_slice(&out[..len]);
1194+ }
1195+ let bit_path = temp_path("demo.bit");
1196+ let pcm_path = temp_path("demo.pcm");
1197+ fs::write(&bit_path, &bit).unwrap();
1198+ let status = Command::new(&demo)
1199+ .arg("-d")
1200+ .arg("48000")
1201+ .arg("2")
1202+ .arg(&bit_path)
1203+ .arg(&pcm_path)
1204+ .status()
1205+ .expect("run opus_demo");
1206+ assert!(status.success(), "opus_demo refused our stream");
1207+ let decoded = read_i16(&pcm_path);
1208+ let _ = fs::remove_file(&bit_path);
1209+ let _ = fs::remove_file(&pcm_path);
1210+ // opus_demo does not apply pre-skip; compensate for the 120-sample delay.
1211+ let delay = 120usize;
1212+ let n = (decoded.len() / 2 - delay).min(pcm.len() / 2 - delay);
1213+ let mut worst = 1.0f64;
1214+ for c in 0..2 {
1215+ let a: Vec<f32> = (0..n).map(|i| pcm[i * 2 + c]).collect();
1216+ let b: Vec<f32> = (0..n)
1217+ .map(|i| decoded[(i + delay) * 2 + c] as f32 / 32768.0)
1218+ .collect();
1219+ worst = worst.min(correlation(&a, &b));
1220+ }
1221+ println!("opus_demo 256 kbps stereo: worst corr {worst:.4}");
1222+ assert!(
1223+ worst >= 0.9,
1224+ "reference decoder heard correlation {worst:.4}"
1225+ );
1226+}
1227+
1228+/// The steady-state encode loop allocates nothing: every buffer — MDCT
1229+/// scratch, PVQ vectors, the range coder's frame — is owned by the encoder
1230+/// and sized on the first frame (the decoder discipline, applied to the
1231+/// encoder).
1232+#[test]
1233+fn steady_state_encode_loop_zero_alloc() {
1234+ let pcm = test_signal(2, 0.5);
1235+ let pcm6 = {
1236+ let mono = test_signal(1, 0.5);
1237+ let mut v = Vec::with_capacity(mono.len() * 6);
1238+ for &s in &mono {
1239+ for c in 0..6 {
1240+ v.push(s * (1.0 + c as f32 * 0.01));
1241+ }
1242+ }
1243+ v
1244+ };
1245+ // Stereo elementary encoder.
1246+ let mut enc = Encoder::new(48000, 2).unwrap();
1247+ enc.set_bitrate(256_000);
1248+ let mut out = vec![0u8; 1500];
1249+ for block in pcm.chunks_exact(960 * 2) {
1250+ enc.encode_float(block, 960, &mut out).unwrap();
1251+ }
1252+ ALLOCS.store(0, Ordering::SeqCst);
1253+ COUNTING_HERE.with(|c| c.set(true));
1254+ for block in pcm.chunks_exact(960 * 2) {
1255+ enc.encode_float(block, 960, &mut out).unwrap();
1256+ }
1257+ COUNTING_HERE.with(|c| c.set(false));
1258+ let n = ALLOCS.load(Ordering::SeqCst);
1259+ assert_eq!(n, 0, "stereo encode allocated {n} times in steady state");
1260+
1261+ // 5.1 multistream.
1262+ let mut ms = MultistreamEncoder::surround_5_1(48000).unwrap();
1263+ ms.set_bitrate(384_000);
1264+ let mut out6 = vec![0u8; 8 * 1500];
1265+ for block in pcm6.chunks_exact(960 * 6) {
1266+ ms.encode_float(block, 960, &mut out6).unwrap();
1267+ }
1268+ ALLOCS.store(0, Ordering::SeqCst);
1269+ COUNTING_HERE.with(|c| c.set(true));
1270+ for block in pcm6.chunks_exact(960 * 6) {
1271+ ms.encode_float(block, 960, &mut out6).unwrap();
1272+ }
1273+ COUNTING_HERE.with(|c| c.set(false));
1274+ let n = ALLOCS.load(Ordering::SeqCst);
1275+ assert_eq!(n, 0, "5.1 encode allocated {n} times in steady state");
1276+}
1277+
1278+/// The throughput headline: encode speed in multiples of realtime, per
1279+/// configuration, at the product's rates. Floors are deliberately far under
1280+/// the measured numbers — they catch a regression class (an accidental
1281+/// O(n^2), a debug path left on), not machine variance.
1282+#[test]
1283+fn encode_speed() {
1284+ if cfg!(debug_assertions) {
1285+ eprintln!("encode speed is only meaningful in release; skipped");
1286+ return;
1287+ }
1288+ let secs = 4.0;
1289+ for (name, channels, kbps, floor) in [
1290+ ("mono 96k", 1usize, 96u32, 100.0f64),
1291+ ("stereo 128k", 2, 128, 70.0),
1292+ ("stereo 256k", 2, 256, 70.0),
1293+ ("stereo 510k", 2, 510, 50.0),
1294+ ] {
1295+ let pcm = test_signal(channels, secs);
1296+ let mut enc = Encoder::new(48000, channels).unwrap();
1297+ enc.set_bitrate(kbps * 1000);
1298+ let mut out = vec![0u8; 1500];
1299+ // Warm up one pass, then measure.
1300+ for block in pcm.chunks_exact(960 * channels) {
1301+ enc.encode_float(block, 960, &mut out).unwrap();
1302+ }
1303+ let passes = 4;
1304+ let start = std::time::Instant::now();
1305+ for _ in 0..passes {
1306+ for block in pcm.chunks_exact(960 * channels) {
1307+ enc.encode_float(block, 960, &mut out).unwrap();
1308+ }
1309+ }
1310+ let elapsed = start.elapsed().as_secs_f64();
1311+ let realtime = secs * passes as f64 / elapsed;
1312+ println!("{name}: {realtime:.0}x realtime");
1313+ assert!(
1314+ realtime >= floor,
1315+ "{name}: {realtime:.0}x is below {floor}x"
1316+ );
1317+ }
1318+ // 5.1 multistream.
1319+ let mono = test_signal(1, secs);
1320+ let mut pcm6 = Vec::with_capacity(mono.len() * 6);
1321+ for &s in &mono {
1322+ for c in 0..6 {
1323+ pcm6.push(s * (1.0 + c as f32 * 0.01));
1324+ }
1325+ }
1326+ let mut ms = MultistreamEncoder::surround_5_1(48000).unwrap();
1327+ ms.set_bitrate(384_000);
1328+ let mut out = vec![0u8; 8 * 1500];
1329+ for block in pcm6.chunks_exact(960 * 6) {
1330+ ms.encode_float(block, 960, &mut out).unwrap();
1331+ }
1332+ let passes = 4;
1333+ let start = std::time::Instant::now();
1334+ for _ in 0..passes {
1335+ for block in pcm6.chunks_exact(960 * 6) {
1336+ ms.encode_float(block, 960, &mut out).unwrap();
1337+ }
1338+ }
1339+ let elapsed = start.elapsed().as_secs_f64();
1340+ let realtime = secs * passes as f64 / elapsed;
1341+ println!("5.1 384k: {realtime:.0}x realtime");
1342+ assert!(realtime >= 25.0, "5.1: {realtime:.0}x is below 25x");
1343+}
1344+
727 /// Malformed input must come back as an error, never a panic: the decoders1345 /// Malformed input must come back as an error, never a panic: the decoders
728 /// index tables with values the bitstream chooses, so this throws well-formed1346 /// index tables with values the bitstream chooses, so this throws well-formed
729 /// TOC bytes at random payloads to make sure every mode is actually entered.1347 /// TOC bytes at random payloads to make sure every mode is actually entered.
shims/opus-rs/Cargo.tomladded+14 -0
@@ -0,0 +1,14 @@
1+[package]
2+name = "opus-rs"
3+description = "Compatibility shim: the opus-rs 0.1.26 surface edith consumes, served by ec-opus."
4+version = "0.1.26"
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+publish = false
9+
10+[lib]
11+name = "opus_rs"
12+
13+[dependencies]
14+ec-opus = { path = "../../crates/ec-opus", version = "0.1.0" }
shims/opus-rs/src/lib.rsadded+136 -0
@@ -0,0 +1,136 @@
1+//! Compatibility shim: the `opus-rs` 0.1.26 surface edith consumes, served by
2+//! [`ec_opus`].
3+//!
4+//! The incumbent this replaces encoded packets that only its own decoder read
5+//! back above ~128-165 kbps (correlation 0.06 against libopus at 256 kbps on
6+//! the same signal that round-tripped internally at 0.999), and mono was
7+//! broken at every rate. This shim serves the same three-call surface —
8+//! `OpusEncoder::new(rate, channels, Application)`, the public `bitrate_bps`
9+//! and `complexity` fields, `.encode(&pcm, frame_size, &mut out)` — from the
10+//! `ec-opus` CELT encoder, which is range-exact against the family's
11+//! RFC-vector-verified decoder and libopus-verified at every rate up to
12+//! 510 kbps, mono and stereo alike. The measured envelope that capped the
13+//! incumbent (`OPUS_MAX_KBPS = 128`) is obsolete behind this crate.
14+//!
15+//! `complexity` is accepted for drop-in compatibility and ignored: this
16+//! encoder has one (fast) analysis path, not a ladder.
17+
18+#![forbid(unsafe_code)]
19+#![warn(missing_docs)]
20+
21+use std::fmt;
22+
23+/// What the encoded stream is optimised for. This CELT-only encoder treats
24+/// every application as [`Application::Audio`]; the variants exist for call
25+/// compatibility.
26+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27+pub enum Application {
28+ /// Speech-optimised (SILK in libopus; served by CELT here).
29+ Voip,
30+ /// Music and general audio.
31+ Audio,
32+ /// Lowest-latency mode.
33+ RestrictedLowdelay,
34+}
35+
36+/// The error type of this shim: a message, as the incumbent's was.
37+#[derive(Debug, Clone)]
38+pub struct OpusError(String);
39+
40+impl fmt::Display for OpusError {
41+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42+ f.write_str(&self.0)
43+ }
44+}
45+
46+impl std::error::Error for OpusError {}
47+
48+/// An Opus encoder with the incumbent's field-configured surface.
49+#[derive(Debug)]
50+pub struct OpusEncoder {
51+ /// Target bitrate in bits per second, applied at the next
52+ /// [`OpusEncoder::encode`] call.
53+ pub bitrate_bps: i32,
54+ /// Accepted for compatibility; this encoder has a single analysis path.
55+ pub complexity: i32,
56+ inner: ec_opus::Encoder,
57+ channels: usize,
58+}
59+
60+impl OpusEncoder {
61+ /// An encoder at `sample_rate` (48000 only — the rate the product feeds)
62+ /// for `channels` channels (1 or 2).
63+ pub fn new(
64+ sample_rate: i32,
65+ channels: i32,
66+ _application: Application,
67+ ) -> Result<OpusEncoder, OpusError> {
68+ if sample_rate < 0 || channels < 0 {
69+ return Err(OpusError(format!(
70+ "invalid encoder arguments: {sample_rate} Hz, {channels} channels"
71+ )));
72+ }
73+ let inner = ec_opus::Encoder::new(sample_rate as u32, channels as usize)
74+ .map_err(|e| OpusError(e.to_string()))?;
75+ Ok(OpusEncoder {
76+ bitrate_bps: 64_000 * channels,
77+ complexity: 10,
78+ inner,
79+ channels: channels as usize,
80+ })
81+ }
82+
83+ /// Encodes `frame_size` samples per channel of interleaved `f32` into
84+ /// `out`, returning the packet length in bytes.
85+ pub fn encode(
86+ &mut self,
87+ pcm: &[f32],
88+ frame_size: usize,
89+ out: &mut [u8],
90+ ) -> Result<usize, OpusError> {
91+ if pcm.len() < frame_size * self.channels {
92+ return Err(OpusError(format!(
93+ "{} samples is short of {} channels x {frame_size}",
94+ pcm.len(),
95+ self.channels
96+ )));
97+ }
98+ self.inner.set_bitrate(self.bitrate_bps.max(0) as u32);
99+ self.inner
100+ .encode_float(pcm, frame_size, out)
101+ .map_err(|e| OpusError(e.to_string()))
102+ }
103+
104+ /// Drops all inter-frame state; the next packet starts a fresh stream.
105+ pub fn reset(&mut self) {
106+ self.inner.reset();
107+ }
108+}
109+
110+#[cfg(test)]
111+mod tests {
112+ use super::*;
113+
114+ /// The exact call shape edith's export path uses (export.rs:1863-1896).
115+ #[test]
116+ fn edith_call_shape_compiles_and_encodes() {
117+ let mut encoder = OpusEncoder::new(48000, 2, Application::Audio)
118+ .map_err(|e| format!("the Opus encoder refused 48 kHz stereo: {e}"))
119+ .unwrap();
120+ encoder.bitrate_bps = 256_000;
121+ encoder.complexity = 10;
122+ let frame = vec![0.1f32; 960 * 2];
123+ let mut out = vec![0u8; 1500];
124+ let len = encoder
125+ .encode(&frame, 960, &mut out)
126+ .map_err(|e| format!("Opus encode failed: {e}"))
127+ .unwrap();
128+ assert!(len > 2 && len <= 1276);
129+ // Mono — broken at every rate in the incumbent — encodes too.
130+ let mut mono = OpusEncoder::new(48000, 1, Application::Audio).unwrap();
131+ mono.bitrate_bps = 96_000;
132+ let frame = vec![0.1f32; 960];
133+ let len = mono.encode(&frame, 960, &mut out).unwrap();
134+ assert!(len > 2);
135+ }
136+}