forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

conformance.rs5011 lines, 188.8 KiBHistoryRawDownload
1//! RFC 6716 conformance: the official test vectors, the `opus_compare` quality
2//! metric, real-file oracles against ffmpeg, and the decode-speed floor.
3//!
4//! All of it lives in one test binary on purpose — a file per feature costs a
5//! serial link-and-run for every build.
6
7use std::fs;
8use std::path::{Path, PathBuf};
9
10use ec_opus::Decoder;
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
19use std::alloc::System;
20use std::sync::Once;
21
22use std::cell::Cell;
23use std::sync::atomic::{AtomicU64, Ordering};
24use tracking_allocator::{AllocationGroupId, AllocationRegistry, AllocationTracker, Allocator};
25
26struct CountingAlloc;
27
28static ALLOCS: AtomicU64 = AtomicU64::new(0);
29
30std::thread_local! {
31 static COUNTING_HERE: Cell<bool> = const { Cell::new(false) };
32}
33
34fn counting_here() -> bool {
35 COUNTING_HERE.try_with(Cell::get).unwrap_or(false)
36}
37
38impl AllocationTracker for CountingAlloc {
39 fn allocated(&self, _addr: usize, _object_size: usize, _wrapped: usize, _g: AllocationGroupId) {
40 if counting_here() {
41 ALLOCS.fetch_add(1, Ordering::Relaxed);
42 }
43 }
44 fn deallocated(
45 &self,
46 _addr: usize,
47 _object_size: usize,
48 _wrapped: usize,
49 _source: AllocationGroupId,
50 _current: AllocationGroupId,
51 ) {
52 }
53}
54
55#[global_allocator]
56static A: Allocator<System> = Allocator::system();
57
58/// Installs the tracker once; every test that arms the counter calls this first.
59fn install_counter() {
60 static ONCE: Once = Once::new();
61 ONCE.call_once(|| {
62 let _ = AllocationRegistry::set_global_tracker(CountingAlloc);
63 AllocationRegistry::enable_tracking();
64 });
65}
66
67/// One packet of an `opus_demo` test vector file.
68struct VectorPacket {
69 payload: Vec<u8>,
70 /// The reference decoder's range state after this packet.
71 final_range: u32,
72}
73
74/// The `.bit` files are `opus_demo` output: per packet, a big-endian length, a
75/// big-endian final range, then the packet itself.
76fn read_vector(path: &Path) -> Vec<VectorPacket> {
77 let data = fs::read(path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
78 let mut out = Vec::new();
79 let mut i = 0;
80 while i + 8 <= data.len() {
81 let len = u32::from_be_bytes(data[i..i + 4].try_into().unwrap()) as usize;
82 let rng = u32::from_be_bytes(data[i + 4..i + 8].try_into().unwrap());
83 i += 8;
84 if i + len > data.len() {
85 break;
86 }
87 out.push(VectorPacket {
88 payload: data[i..i + len].to_vec(),
89 final_range: rng,
90 });
91 i += len;
92 }
93 out
94}
95
96fn vectors_dir() -> PathBuf {
97 Path::new(env!("CARGO_MANIFEST_DIR"))
98 .join("../../fixtures/vectors/opus-rfc6716/opus_testvectors")
99}
100
101/// Decodes a vector at 48 kHz stereo, returning the samples and how many
102/// packets ended with the reference range state.
103fn decode_vector(packets: &[VectorPacket]) -> (Vec<f32>, usize, usize) {
104 decode_vector_ch(packets, 2, true)
105}
106
107/// Decodes a vector at 48 kHz with `channels` output channels (1 or 2), with the
108/// RFC 6716 reconstruction when `legacy` and the RFC 8251 one otherwise.
109fn decode_vector_ch(
110 packets: &[VectorPacket],
111 channels: usize,
112 legacy: bool,
113) -> (Vec<f32>, usize, usize) {
114 let mut dec = Decoder::new(48000, channels).unwrap();
115 dec.set_legacy_rfc6716(legacy);
116 let mut pcm = Vec::new();
117 let mut buf = vec![0.0f32; 5760 * channels];
118 let mut matched = 0;
119 let mut decoded = 0;
120 for p in packets {
121 match dec.decode_float(&p.payload, &mut buf) {
122 Ok(n) => {
123 pcm.extend_from_slice(&buf[..n * channels]);
124 decoded += 1;
125 if dec.final_range() == p.final_range {
126 matched += 1;
127 }
128 }
129 Err(e) => {
130 panic!("packet {decoded} failed: {e}");
131 }
132 }
133 }
134 (pcm, matched, decoded)
135}
136
137// ---------------------------------------------------------------------------
138// The conformance metric
139// ---------------------------------------------------------------------------
140//
141// RFC 6716 Section 6 defines a compliant decoder as one whose output stays
142// "within the thresholds specified by the opus_compare.c tool" against the
143// reference decoder's output for each test vector. That tool is a weighted
144// spectral comparison, reimplemented here so the check needs no C toolchain:
145//
146// 1. Both signals are cut into 480-sample Hann windows at a 120-sample hop
147// and turned into per-bin power spectra (bins 0..200 of 240).
148// 2. The reference's per-band energy is spread by a masking model: 10 dB per
149// Bark upwards, 15 dB downwards, -3 dB per 2.5 ms in time, 1 % crosstalk
150// between channels. A tenth of that masking energy is added to both
151// spectra, so error under a strong signal counts for less.
152// 3. Consecutive frames are averaged pairwise, then per bin the ratio
153// r = Y/X contributes r - log(r) - 1 (zero when equal, growing either
154// way); bins 79..81 are damped because the SILK/CELT crossover is free.
155// 4. The per-band mean is squared, averaged over bands, squared again,
156// raised to the fourth power per frame, averaged, and the 16th root taken.
157// Quality is 100*(1 - 0.5*ln(1+err)/ln(1.13)); 0 is the pass threshold and
158// 100 means identical output.
159//
160// A quality of 0 was calibrated to additive white noise at 48 dB SNR.
161
162const NBANDS: usize = 21;
163const BANDS: [usize; NBANDS + 1] = [
164 0, 2, 4, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 68, 80, 96, 120, 156, 200,
165];
166const WIN_SIZE: usize = 480;
167const WIN_STEP: usize = 120;
168const NFREQS: usize = 240;
169
170/// A complex FFT of size `15 * 2^k`, which is what a 480-sample window needs.
171/// Same decomposition the decoder uses; duplicated here so the test measures
172/// the reference metric rather than the decoder's own code.
173struct Fft15 {
174 n: usize,
175 sub: ec_dsp::Fft<f64>,
176}
177
178impl Fft15 {
179 fn new(n: usize) -> Fft15 {
180 assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two());
181 Fft15 {
182 n,
183 sub: ec_dsp::Fft::new(n / 15),
184 }
185 }
186
187 /// Power spectrum of a real signal, bins `0..n/2`.
188 fn power(&mut self, x: &[f64], out: &mut [f64]) {
189 let n = self.n;
190 let l = n / 15;
191 let mut re = vec![0.0f64; n];
192 let mut im = vec![0.0f64; n];
193 for n2 in 0..l {
194 for k1 in 0..15 {
195 let (mut sr, mut si) = (0.0, 0.0);
196 for n1 in 0..15 {
197 let a = 2.0 * std::f64::consts::PI * ((k1 * n1) % 15) as f64 / 15.0;
198 sr += x[l * n1 + n2] * a.cos();
199 si += x[l * n1 + n2] * a.sin();
200 }
201 let a = 2.0 * std::f64::consts::PI * (k1 * n2) as f64 / n as f64;
202 let (c, s) = (a.cos(), a.sin());
203 re[k1 * l + n2] = sr * c - si * s;
204 im[k1 * l + n2] = sr * s + si * c;
205 }
206 }
207 for k1 in 0..15 {
208 let rr = &mut re[k1 * l..(k1 + 1) * l];
209 let ii = &mut im[k1 * l..(k1 + 1) * l];
210 self.sub.inverse_split(rr, ii);
211 for k2 in 0..l {
212 let idx = k1 + 15 * k2;
213 if idx < out.len() {
214 let (r, i) = (rr[k2] * l as f64, ii[k2] * l as f64);
215 out[idx] = r * r + i * i;
216 }
217 }
218 }
219 }
220}
221
222/// Per-bin power spectra and per-band energies, `band_energy()` in the tool.
223fn band_energy(
224 signal: &[f64],
225 channels: usize,
226 nframes: usize,
227 bands: &mut Option<&mut Vec<f64>>,
228 ps: &mut Vec<f64>,
229) {
230 let mut fft = Fft15::new(WIN_SIZE);
231 let window: Vec<f64> = (0..WIN_SIZE)
232 .map(|j| 0.5 - 0.5 * (2.0 * std::f64::consts::PI / (WIN_SIZE - 1) as f64 * j as f64).cos())
233 .collect();
234 ps.resize(nframes * NFREQS * channels, 0.0);
235 if let Some(b) = bands {
236 b.resize(nframes * NBANDS * channels, 0.0);
237 }
238 let mut frame = vec![0.0f64; WIN_SIZE];
239 let mut spec = vec![0.0f64; NFREQS];
240 for xi in 0..nframes {
241 for ci in 0..channels {
242 for k in 0..WIN_SIZE {
243 frame[k] = window[k] * signal[(xi * WIN_STEP + k) * channels + ci];
244 }
245 spec.fill(0.0);
246 fft.power(&frame, &mut spec);
247 for bi in 0..NBANDS {
248 let mut p = 0.0;
249 for xj in BANDS[bi]..BANDS[bi + 1] {
250 let v = spec[xj] + 100000.0;
251 ps[(xi * NFREQS + xj) * channels + ci] = v;
252 p += v;
253 }
254 if let Some(b) = bands {
255 b[(xi * NBANDS + bi) * channels + ci] = p / (BANDS[bi + 1] - BANDS[bi]) as f64;
256 }
257 }
258 }
259 }
260}
261
262/// The raw `opus_compare` spectral error (before the quality mapping):
263/// 0 is identical output, growing with divergence. Used by the encoder gate
264/// to take an `err_ratio` of ours-vs-reference before the monotonic quality
265/// transform flattens the high-error tail.
266fn opus_compare_err(reference: &[i16], test: &[i16], channels: usize) -> f64 {
267 opus_compare_err_parts(reference, test, channels).0
268}
269
270/// `opus_compare_err` with the intermediates the per-band divergence
271/// diagnostic needs: `(err, per-band mean eb², per-frame ef²)`. The per-band
272/// mean is each band's additive share of the pre-squared frame error
273/// `ef = mean(eb²)`; the numerics are the wrapped function's, unchanged
274/// (guarded by `opus_compare_err_pinned_against_c`).
275fn opus_compare_err_parts(
276 reference: &[i16],
277 test: &[i16],
278 channels: usize,
279) -> (f64, Vec<f64>, Vec<f64>) {
280 assert_eq!(reference.len(), test.len(), "sample counts must match");
281 let x: Vec<f64> = reference.iter().map(|&v| v as f64).collect();
282 let y: Vec<f64> = test.iter().map(|&v| v as f64).collect();
283 let xlength = x.len() / channels;
284 assert!(xlength >= WIN_SIZE, "not enough samples to compare");
285 let nframes = (xlength - WIN_SIZE + WIN_STEP) / WIN_STEP;
286 let mut band_eb2 = vec![0.0f64; NBANDS];
287 let mut frame_ef2 = Vec::with_capacity(nframes);
288
289 let mut xb = Vec::new();
290 let mut big_x = Vec::new();
291 let mut big_y = Vec::new();
292 band_energy(&x, channels, nframes, &mut Some(&mut xb), &mut big_x);
293 band_energy(&y, channels, nframes, &mut None, &mut big_y);
294
295 for xi in 0..nframes {
296 // Frequency masking, low to high then high to low.
297 for bi in 1..NBANDS {
298 for ci in 0..channels {
299 xb[(xi * NBANDS + bi) * channels + ci] +=
300 0.1 * xb[(xi * NBANDS + bi - 1) * channels + ci];
301 }
302 }
303 for bi in (0..NBANDS - 1).rev() {
304 for ci in 0..channels {
305 xb[(xi * NBANDS + bi) * channels + ci] +=
306 0.03 * xb[(xi * NBANDS + bi + 1) * channels + ci];
307 }
308 }
309 // Temporal masking.
310 if xi > 0 {
311 for bi in 0..NBANDS {
312 for ci in 0..channels {
313 xb[(xi * NBANDS + bi) * channels + ci] +=
314 0.5 * xb[((xi - 1) * NBANDS + bi) * channels + ci];
315 }
316 }
317 }
318 // Crosstalk between channels.
319 if channels == 2 {
320 for bi in 0..NBANDS {
321 let l = xb[(xi * NBANDS + bi) * channels];
322 let r = xb[(xi * NBANDS + bi) * channels + 1];
323 xb[(xi * NBANDS + bi) * channels] += 0.01 * r;
324 xb[(xi * NBANDS + bi) * channels + 1] += 0.01 * l;
325 }
326 }
327 // Apply the masking to both spectra.
328 for bi in 0..NBANDS {
329 for xj in BANDS[bi]..BANDS[bi + 1] {
330 for ci in 0..channels {
331 let m = 0.1 * xb[(xi * NBANDS + bi) * channels + ci];
332 big_x[(xi * NFREQS + xj) * channels + ci] += m;
333 big_y[(xi * NFREQS + xj) * channels + ci] += m;
334 }
335 }
336 }
337 }
338
339 // Average consecutive frames to make the comparison less twitchy.
340 for bi in 0..NBANDS {
341 for xj in BANDS[bi]..BANDS[bi + 1] {
342 for ci in 0..channels {
343 let mut xtmp = big_x[xj * channels + ci];
344 let mut ytmp = big_y[xj * channels + ci];
345 for xi in 1..nframes {
346 let xtmp2 = big_x[(xi * NFREQS + xj) * channels + ci];
347 let ytmp2 = big_y[(xi * NFREQS + xj) * channels + ci];
348 big_x[(xi * NFREQS + xj) * channels + ci] += xtmp;
349 big_y[(xi * NFREQS + xj) * channels + ci] += ytmp;
350 xtmp = xtmp2;
351 ytmp = ytmp2;
352 }
353 }
354 }
355 }
356
357 let max_compare = BANDS[NBANDS];
358 let mut err = 0.0f64;
359 for xi in 0..nframes {
360 let mut ef = 0.0f64;
361 for bi in 0..NBANDS {
362 let mut eb = 0.0f64;
363 for xj in BANDS[bi]..BANDS[bi + 1].min(max_compare) {
364 for ci in 0..channels {
365 let re = big_y[(xi * NFREQS + xj) * channels + ci]
366 / big_x[(xi * NFREQS + xj) * channels + ci];
367 let mut im = re - re.ln() - 1.0;
368 // The SILK/CELT crossover may differ in its filters.
369 if (79..=81).contains(&xj) {
370 im *= 0.1;
371 }
372 if xj == 80 {
373 im *= 0.1;
374 }
375 eb += im;
376 }
377 }
378 eb /= ((BANDS[bi + 1] - BANDS[bi]) * channels) as f64;
379 let eb2 = eb * eb;
380 band_eb2[bi] += eb2;
381 ef += eb2;
382 }
383 ef /= NBANDS as f64;
384 ef *= ef;
385 let ef2 = ef * ef;
386 frame_ef2.push(ef2);
387 err += ef2;
388 }
389 err = (err / nframes as f64).powf(1.0 / 16.0);
390 for b in &mut band_eb2 {
391 *b /= nframes as f64;
392 }
393 (err, band_eb2, frame_ef2)
394}
395
396/// The `opus_compare` quality metric: >= 0 passes, 100 is identical output.
397fn opus_compare(reference: &[i16], test: &[i16], channels: usize) -> f64 {
398 let err = opus_compare_err(reference, test, channels);
399 100.0 * (1.0 - 0.5 * (1.0 + err).ln() / 1.13f64.ln())
400}
401
402/// `FLOAT2INT16`: what `opus_demo` writes, so the metric sees the same samples.
403fn to_i16(pcm: &[f32]) -> Vec<i16> {
404 pcm.iter()
405 .map(|&v| (v * 32768.0).round().clamp(-32768.0, 32767.0) as i16)
406 .collect()
407}
408
409fn read_i16(path: &Path) -> Vec<i16> {
410 let d = fs::read(path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
411 d.as_chunks::<2>()
412 .0
413 .iter()
414 .map(|c| i16::from_le_bytes([c[0], c[1]]))
415 .collect()
416}
417
418/// The RFC 8251 updated vectors (`opus_newvectors`), fetched by
419/// `scripts/fetch-vectors.sh opus-rfc8251`. Each `testvectorNN.bit` has two
420/// stereo references: `testvectorNN.dec` (with the CELT 180-degree phase shift
421/// of RFC 8251 Section 10) and `testvectorNNm.dec` (without it). An
422/// implementation is compliant when it matches either set.
423fn vectors_dir_8251() -> PathBuf {
424 Path::new(env!("CARGO_MANIFEST_DIR"))
425 .join("../../fixtures/vectors/opus-rfc8251/opus_newvectors")
426}
427
428/// Runs one RFC 8251 vector (stereo) against one of its reference files. Returns
429/// `(range-exact, decoded packets, quality %)`; the caller decides what passes.
430fn run_rfc8251(name: &str, reference: &str) -> (usize, usize, f64) {
431 let dir = vectors_dir_8251();
432 let bit = dir.join(format!("{name}.bit"));
433 if !bit.exists() {
434 assert!(
435 std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
436 "RFC 8251 test vector {name} missing at {} — run scripts/fetch-vectors.sh opus-rfc8251",
437 bit.display()
438 );
439 eprintln!(
440 "SKIP RFC 8251 test vector {name} missing at {}",
441 bit.display()
442 );
443 return (0, 0, f64::NAN);
444 }
445 let packets = read_vector(&bit);
446 let (pcm, matched, decoded) = decode_vector_ch(&packets, 2, false);
447 let refs = read_i16(&dir.join(reference));
448 let mine = to_i16(&pcm);
449 assert_eq!(
450 refs.len(),
451 mine.len(),
452 "{reference}: decoded {} samples, reference has {}",
453 mine.len(),
454 refs.len()
455 );
456 let identical = refs.iter().zip(&mine).filter(|(a, b)| a == b).count();
457 let quality = opus_compare(&refs, &mine, 2);
458 println!(
459 "{reference}: {matched}/{decoded} packets range-exact, {:.4} % samples identical, quality {quality:.2} %",
460 100.0 * identical as f64 / refs.len() as f64
461 );
462 (matched, decoded, quality)
463}
464
465/// RFC 8251 Section 11: "An implementation is compliant as long as it passes
466/// either set of vectors." A set passes when every vector in it has all packets
467/// range-exact and quality >= 0. The `.dec` set (with the CELT 180-degree phase
468/// shift) and the `m` set (without it) are both run and both reported.
469#[test]
470fn rfc8251_test_vectors() {
471 let _timing = timing_shared();
472 let mut dec_ok = true;
473 let mut m_ok = true;
474 for name in VECTORS {
475 let (dm, dd, dq) = run_rfc8251(name, &format!("{name}.dec"));
476 let (mm, md, mq) = run_rfc8251(name, &format!("{name}m.dec"));
477 dec_ok &= dm == dd && dq >= 0.0;
478 m_ok &= mm == md && mq >= 0.0;
479 }
480 println!("RFC 8251 set `.dec` passes: {dec_ok}; set `m` passes: {m_ok}");
481 assert!(
482 dec_ok || m_ok,
483 "neither RFC 8251 set passes (see the per-vector lines above)"
484 );
485}
486
487/// Every vector in the RFC 6716 suite, in the order the RFC lists them.
488const VECTORS: [&str; 12] = [
489 "testvector01",
490 "testvector02",
491 "testvector03",
492 "testvector04",
493 "testvector05",
494 "testvector06",
495 "testvector07",
496 "testvector08",
497 "testvector09",
498 "testvector10",
499 "testvector11",
500 "testvector12",
501];
502
503/// The conformance test of RFC 6716 Section 6, both halves of it: the decoder's
504/// range coder state MUST match the reference on every packet, and the output
505/// MUST stay within the `opus_compare` threshold (quality >= 0).
506#[test]
507fn rfc6716_test_vectors() {
508 let _timing = timing_shared();
509 // A missing test vector made this gate skip GREEN having decoded nothing —
510 // the "gate skips on its own failure" class. The root `fixtures/` tree is
511 // gitignored, so `git worktree add` hands every lane worktree a tree without
512 // it. `EC_REQUIRE_FIXTURES=1` turns a missing vector into a hard failure
513 // naming the exact path and the command that produces it; unset, the skip
514 // is kept and now says what it skipped. Set it in every batch run.
515 let base = vectors_dir();
516 let mut table = Vec::new();
517 for name in VECTORS {
518 let path = base.join(format!("{name}.bit"));
519 if !path.exists() {
520 assert!(
521 std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
522 "RFC 6716 test vector {name} missing at {} — this gate would prove \
523 nothing. A worktree has no gitignored root `fixtures/`: run \
524 scripts/link-fixtures.sh, or fetch it with scripts/fetch-vectors.sh.",
525 path.display()
526 );
527 eprintln!(
528 "SKIP RFC 6716 test vector {name} missing at {} — this gate proved \
529 nothing; run scripts/link-fixtures.sh, or fetch it with \
530 scripts/fetch-vectors.sh (or set EC_REQUIRE_FIXTURES=1 to make this \
531 a failure).",
532 path.display()
533 );
534 continue;
535 }
536 let packets = read_vector(&path);
537 let (pcm, matched, decoded) = decode_vector(&packets);
538 let reference = read_i16(&vectors_dir().join(format!("{name}.dec")));
539 let mine = to_i16(&pcm);
540 assert_eq!(
541 reference.len(),
542 mine.len(),
543 "{name}: decoded {} samples, reference has {}",
544 mine.len() / 2,
545 reference.len() / 2
546 );
547 let identical = reference.iter().zip(&mine).filter(|(a, b)| a == b).count();
548 let quality = opus_compare(&reference, &mine, 2);
549 table.push(format!(
550 "{name}: {matched}/{decoded} packets range-exact, \
551 {:.4} % samples identical, quality {quality:.2} %",
552 100.0 * identical as f64 / reference.len() as f64
553 ));
554 assert_eq!(
555 matched, decoded,
556 "{name}: range coder state diverged from the reference"
557 );
558 assert!(
559 quality >= 0.0,
560 "{name}: opus_compare quality {quality:.2} %"
561 );
562 }
563 for line in table {
564 println!("{line}");
565 }
566}
567
568// ---------------------------------------------------------------------------
569// Real files: the Ogg-Opus fixtures, against ffmpeg
570// ---------------------------------------------------------------------------
571
572use ec_opus::MultistreamDecoder;
573use std::process::Command;
574
575/// Splits an Ogg stream into packets (RFC 3533): a page header, a segment
576/// table, and packets that end on any segment shorter than 255 bytes.
577fn ogg_packets(data: &[u8]) -> Vec<Vec<u8>> {
578 let mut packets = Vec::new();
579 let mut partial: Vec<u8> = Vec::new();
580 let mut i = 0;
581 while i + 27 <= data.len() {
582 assert_eq!(&data[i..i + 4], b"OggS", "not an Ogg page at {i}");
583 let nsegs = data[i + 26] as usize;
584 let table = &data[i + 27..i + 27 + nsegs];
585 let mut body = i + 27 + nsegs;
586 for &len in table {
587 let len = len as usize;
588 partial.extend_from_slice(&data[body..body + len]);
589 body += len;
590 if len < 255 {
591 packets.push(core::mem::take(&mut partial));
592 }
593 }
594 i = body;
595 }
596 packets
597}
598
599/// The RFC 7845 identification header: channel count, pre-skip and the
600/// multistream layout.
601struct OpusHead {
602 channels: usize,
603 pre_skip: usize,
604 streams: usize,
605 coupled: usize,
606 mapping: Vec<u8>,
607}
608
609fn parse_opus_head(p: &[u8]) -> OpusHead {
610 assert_eq!(&p[..8], b"OpusHead");
611 let channels = p[9] as usize;
612 let pre_skip = u16::from_le_bytes([p[10], p[11]]) as usize;
613 let family = p[18];
614 if family == 0 {
615 OpusHead {
616 channels,
617 pre_skip,
618 streams: 1,
619 coupled: channels - 1,
620 mapping: (0..channels as u8).collect(),
621 }
622 } else {
623 OpusHead {
624 channels,
625 pre_skip,
626 streams: p[19] as usize,
627 coupled: p[20] as usize,
628 mapping: p[21..21 + channels].to_vec(),
629 }
630 }
631}
632
633fn fixture(name: &str) -> PathBuf {
634 Path::new(env!("CARGO_MANIFEST_DIR"))
635 .join("../../fixtures/audio")
636 .join(name)
637}
638
639/// ffmpeg's decode of the same file, interleaved `f32` in ffmpeg's channel
640/// order, with the pre-skip already removed.
641///
642/// The decoder is forced to `libopus` — the reference implementation. ffmpeg's
643/// own native Opus decoder is a third implementation and deviates from libopus
644/// by as much as 0.97 correlation on this very fixture's coupled surround
645/// streams, so it makes a poor oracle.
646fn ffmpeg_decode(path: &Path, channels: usize) -> Option<Vec<f32>> {
647 let out = Command::new("ffmpeg")
648 .args(["-v", "error", "-c:a", "libopus", "-i"])
649 .arg(path)
650 .args([
651 "-f",
652 "f32le",
653 "-ar",
654 "48000",
655 "-ac",
656 &channels.to_string(),
657 "-",
658 ])
659 .output()
660 .ok()?;
661 if !out.status.success() {
662 return None;
663 }
664 Some(
665 out.stdout
666 .as_chunks::<4>()
667 .0
668 .iter()
669 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
670 .collect(),
671 )
672}
673
674/// Decodes an Ogg-Opus file with the multistream decoder, pre-skip removed.
675fn decode_ogg(path: &Path) -> (Vec<f32>, usize) {
676 let data = fs::read(path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
677 let packets = ogg_packets(&data);
678 let head = parse_opus_head(&packets[0]);
679 let mut dec = MultistreamDecoder::with_rate(48000, head.streams, head.coupled, &head.mapping);
680 let mut pcm = Vec::new();
681 for p in packets.iter().skip(2) {
682 if p.is_empty() {
683 continue;
684 }
685 let frame = dec.decode_packet(p).expect("decode");
686 pcm.extend_from_slice(&frame);
687 }
688 pcm.drain(..head.pre_skip * head.channels);
689 (pcm, head.channels)
690}
691
692fn correlation(a: &[f32], b: &[f32]) -> f64 {
693 let n = a.len().min(b.len());
694 let (mut sxy, mut sxx, mut syy) = (0.0f64, 0.0f64, 0.0f64);
695 for i in 0..n {
696 sxy += a[i] as f64 * b[i] as f64;
697 sxx += (a[i] as f64).powi(2);
698 syy += (b[i] as f64).powi(2);
699 }
700 if sxx == 0.0 || syy == 0.0 {
701 return if sxx == syy { 1.0 } else { 0.0 };
702 }
703 sxy / (sxx * syy).sqrt()
704}
705
706/// Power at `freq` in a channel, by the Goertzel algorithm.
707fn tone_power(x: &[f32], channels: usize, ch: usize, freq: f64) -> f64 {
708 let n = x.len() / channels;
709 let w = 2.0 * std::f64::consts::PI * freq / 48000.0;
710 let coeff = 2.0 * w.cos();
711 let (mut s1, mut s2) = (0.0f64, 0.0f64);
712 for i in 0..n {
713 let s = x[i * channels + ch] as f64 + coeff * s1 - s2;
714 s2 = s1;
715 s1 = s;
716 }
717 (s1 * s1 + s2 * s2 - coeff * s1 * s2) / (n * n) as f64
718}
719
720#[test]
721fn ogg_opus_fixtures_match_ffmpeg() {
722 let _timing = timing_shared();
723 // Mapping family 1 puts 5.1 in Vorbis order; ffmpeg hands its own order
724 // back, so the comparison permutes one into the other.
725 const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3];
726 for (name, channels) in [
727 ("opus-ogg-mono-48000.opus", 1usize),
728 ("opus-ogg-stereo-48000.opus", 2),
729 ("opus-ogg-5.1-48000.opus", 6),
730 ] {
731 let path = fixture(name);
732 if !path.exists() {
733 eprintln!("{name}: missing, skipped (run scripts/gen-fixtures.sh)");
734 continue;
735 }
736 let Some(reference) = ffmpeg_decode(&path, channels) else {
737 eprintln!("{name}: ffmpeg unavailable, skipped");
738 continue;
739 };
740 let (mine, ch) = decode_ogg(&path);
741 assert_eq!(ch, channels, "{name}: channel count");
742 let mut worst = 1.0f64;
743 let n = (reference.len() / channels).min(mine.len() / channels);
744 assert!(n > 48000, "{name}: only {n} samples decoded");
745 for c in 0..channels {
746 let their_c = if channels == 6 {
747 VORBIS_TO_FFMPEG_5_1[c]
748 } else {
749 c
750 };
751 let a: Vec<f32> = (0..n).map(|i| mine[i * channels + c]).collect();
752 let b: Vec<f32> = (0..n).map(|i| reference[i * channels + their_c]).collect();
753 let corr = correlation(&a, &b);
754 println!("{name}: channel {c} correlation {corr:.5}");
755 worst = worst.min(corr);
756 }
757 assert!(
758 worst >= 0.99,
759 "{name}: worst channel correlation {worst:.5}"
760 );
761 }
762}
763
764#[test]
765fn five_one_channels_land_in_the_right_places() {
766 let _timing = timing_shared();
767 // The fixture carries one distinct sine per channel, so a channel-order
768 // bug shows up as a channel playing the wrong tone. The tones themselves
769 // come from the reference decode rather than from an assumption about how
770 // ffmpeg laid the fixture out; what is asserted is that this decoder's
771 // Vorbis-order output is the reference's 5.1-order output permuted.
772 const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3];
773 const TONES: [f64; 6] = [220.0, 440.0, 660.0, 55.0, 880.0, 1320.0];
774 let path = fixture("opus-ogg-5.1-48000.opus");
775 if !path.exists() {
776 eprintln!("5.1 fixture missing, skipped");
777 return;
778 }
779 let Some(reference) = ffmpeg_decode(&path, 6) else {
780 eprintln!("ffmpeg unavailable, skipped");
781 return;
782 };
783 let (pcm, channels) = decode_ogg(&path);
784 assert_eq!(channels, 6);
785 let dominant = |x: &[f32], ch: usize| -> usize {
786 let mut best = (0usize, 0.0f64);
787 for (t, &f) in TONES.iter().enumerate() {
788 let p = tone_power(x, 6, ch, f);
789 if p > best.1 {
790 best = (t, p);
791 }
792 }
793 best.0
794 };
795 let mut seen = [false; 6];
796 for (c, &their) in VORBIS_TO_FFMPEG_5_1.iter().enumerate() {
797 let want = dominant(&reference, their);
798 let got = dominant(&pcm, c);
799 println!(
800 "channel {c}: {} Hz (reference channel {their} carries {} Hz)",
801 TONES[got], TONES[want]
802 );
803 assert_eq!(got, want, "channel {c} carries the wrong tone");
804 assert!(!seen[got], "tone {} Hz appears on two channels", TONES[got]);
805 seen[got] = true;
806 }
807}
808
809/// Every speed-floor test takes this exclusively and every other test in this
810/// binary takes it shared, so a floor is never measured while another
811/// conformance test is loading the same host.
812static TIMING: std::sync::RwLock<()> = std::sync::RwLock::new(());
813
814fn timing_shared() -> std::sync::RwLockReadGuard<'static, ()> {
815 TIMING.read().unwrap_or_else(|e| e.into_inner())
816}
817
818fn timing_exclusive() -> std::sync::RwLockWriteGuard<'static, ()> {
819 TIMING.write().unwrap_or_else(|e| e.into_inner())
820}
821
822/// Seconds of CPU time consumed by the calling thread, or `None` where the
823/// clock is unavailable. Used by the speed floors: a loaded host that
824/// deschedules the test thread (or runs the other conformance tests beside it)
825/// must not count against the floor, so the floors measure work, not wall time.
826fn thread_cpu_secs() -> Option<f64> {
827 #[cfg(target_os = "linux")]
828 {
829 if let Ok(t) = cpu_time::ThreadTime::try_now() {
830 return Some(t.as_duration().as_secs_f64());
831 }
832 }
833 None
834}
835
836/// Time one run of `f`: thread CPU time where available, wall time elsewhere.
837fn timed_once<F: FnMut()>(f: &mut F) -> f64 {
838 let cpu0 = thread_cpu_secs();
839 let wall = std::time::Instant::now();
840 f();
841 match (cpu0, thread_cpu_secs()) {
842 (Some(a), Some(b)) => b - a,
843 _ => wall.elapsed().as_secs_f64(),
844 }
845}
846
847/// Best of three runs. The fastest run is the one least disturbed by the host,
848/// which is the usual benchmark practice for a throughput floor.
849fn best_of_3<F: FnMut()>(mut f: F) -> f64 {
850 (0..3)
851 .map(|_| timed_once(&mut f))
852 .fold(f64::INFINITY, f64::min)
853}
854
855#[test]
856fn decode_speed() {
857 let _timing = timing_exclusive();
858 if cfg!(debug_assertions) {
859 eprintln!("decode speed is only meaningful in release; skipped");
860 return;
861 }
862 for (name, channels) in [
863 ("opus-ogg-stereo-48000.opus", 2usize),
864 ("opus-ogg-5.1-48000.opus", 6),
865 ] {
866 let path = fixture(name);
867 if !path.exists() {
868 continue;
869 }
870 let data = fs::read(&path).unwrap();
871 let packets = ogg_packets(&data);
872 let head = parse_opus_head(&packets[0]);
873 let audio: Vec<&Vec<u8>> = packets.iter().skip(2).filter(|p| !p.is_empty()).collect();
874 let mut dec =
875 MultistreamDecoder::with_rate(48000, head.streams, head.coupled, &head.mapping);
876 let mut out = vec![0.0f32; 5760 * channels];
877 // Warm up, then measure enough passes to cover several seconds of audio.
878 let mut samples = 0usize;
879 for p in &audio {
880 samples += dec.decode_float(p, &mut out).unwrap();
881 }
882 let passes = 20;
883 let elapsed = best_of_3(|| {
884 for _ in 0..passes {
885 dec.reset();
886 for p in &audio {
887 dec.decode_float(p, &mut out).unwrap();
888 }
889 }
890 });
891 let audio_secs = (samples * passes) as f64 / 48000.0;
892 let realtime = audio_secs / elapsed;
893 println!(
894 "{name}: {realtime:.0}x realtime ({channels} channels, {audio_secs:.1} s in {elapsed:.3} s)"
895 );
896 let floor = if channels == 6 { 104.0 } else { 135.0 };
897 assert!(
898 realtime >= floor,
899 "{name}: {realtime:.0}x realtime is below the {floor}x floor"
900 );
901 }
902
903 // The fixtures are sine tones, which are cheap; testvector01 is real music
904 // at a high rate and is the honest stereo number.
905 let path = vectors_dir().join("testvector01.bit");
906 if path.exists() {
907 let packets = read_vector(&path);
908 let mut out = vec![0.0f32; 5760 * 2];
909 let mut samples = 0usize;
910 let elapsed = best_of_3(|| {
911 let mut dec = Decoder::new(48000, 2).unwrap();
912 samples = 0;
913 for p in &packets {
914 samples += dec.decode_float(&p.payload, &mut out).unwrap();
915 }
916 });
917 let realtime = samples as f64 / 48000.0 / elapsed;
918 println!("testvector01 (stereo music): {realtime:.0}x realtime");
919 assert!(realtime >= 135.0, "stereo music decodes at {realtime:.0}x");
920 }
921}
922
923#[test]
924#[ignore = "probe: report harness with no asserts; unblocks by setting EC_OPUS_FILES to committed .opus fixtures -- unset, it decodes nothing"]
925fn real_library_sweep() {
926 let _timing = timing_shared();
927 // Files named on the command line (EC_OPUS_FILES=a.opus:b.opus), decoded
928 // and compared against libopus channel by channel, with the decode speed.
929 let files = std::env::var("EC_OPUS_FILES").unwrap_or_default();
930 for f in files.split(':').filter(|s| !s.is_empty()) {
931 let path = PathBuf::from(f);
932 let (pcm, channels) = decode_ogg(&path);
933 let reference = ffmpeg_decode(&path, channels).expect("libopus");
934 let n = (reference.len() / channels).min(pcm.len() / channels);
935 let mut worst = 1.0f64;
936 for c in 0..channels {
937 let a: Vec<f32> = (0..n).map(|i| pcm[i * channels + c]).collect();
938 let b: Vec<f32> = (0..n).map(|i| reference[i * channels + c]).collect();
939 let corr = correlation(&a, &b);
940 worst = worst.min(corr);
941 println!("{f}: channel {c} correlation {corr:.5}");
942 }
943 // Speed on the same file.
944 let data = fs::read(&path).unwrap();
945 let packets = ogg_packets(&data);
946 let head = parse_opus_head(&packets[0]);
947 let audio: Vec<&Vec<u8>> = packets.iter().skip(2).filter(|p| !p.is_empty()).collect();
948 let mut dec =
949 MultistreamDecoder::with_rate(48000, head.streams, head.coupled, &head.mapping);
950 let mut out = vec![0.0f32; 5760 * channels];
951 let mut samples = 0usize;
952 for p in &audio {
953 samples += dec.decode_float(p, &mut out).unwrap();
954 }
955 dec.reset();
956 let start = std::time::Instant::now();
957 for p in &audio {
958 dec.decode_float(p, &mut out).unwrap();
959 }
960 let elapsed = start.elapsed().as_secs_f64();
961 println!(
962 "{f}: {channels} ch, {:.1} s audio, {:.0}x realtime, worst channel {worst:.5}",
963 samples as f64 / 48000.0,
964 samples as f64 / 48000.0 / elapsed
965 );
966 }
967}
968
969// ---------------------------------------------------------------------------
970// Encoder: self-consistency (range-exact against our own decoder)
971// ---------------------------------------------------------------------------
972
973use ec_opus::{Application, Bandwidth, Encoder, Mode, MultistreamEncoder, Packet};
974
975/// A deterministic music-like test signal: several detuned partials plus a
976/// swept component per channel, loud enough to exercise every band.
977fn test_signal(channels: usize, secs: f64) -> Vec<f32> {
978 let n = (48000.0 * secs) as usize;
979 let mut out = Vec::with_capacity(n * channels);
980 for i in 0..n {
981 let t = i as f64 / 48000.0;
982 for c in 0..channels {
983 let base = 220.0 * (c as f64 * 0.5 + 1.0);
984 let sweep = 400.0 + 3000.0 * (0.5 + 0.5 * (0.13 * t).sin());
985 let v = 0.35 * (std::f64::consts::TAU * base * t).sin()
986 + 0.2 * (std::f64::consts::TAU * base * 3.01 * t).sin()
987 + 0.12 * (std::f64::consts::TAU * sweep * t).sin()
988 + 0.08 * (std::f64::consts::TAU * 9000.0 * (1.0 + 0.02 * c as f64) * t).sin();
989 out.push(v as f32);
990 }
991 }
992 out
993}
994
995/// Encodes `pcm` in `frame`-sample packets and decodes each with our own
996/// decoder, asserting the range coder states agree packet for packet — the
997/// same bit-exact check the RFC vectors put on the decoder, now closing the
998/// loop over the encoder. Returns the decoded signal and total packet bytes.
999fn roundtrip_own(
1000 enc: &mut Encoder,
1001 pcm: &[f32],
1002 channels: usize,
1003 frame: usize,
1004) -> (Vec<f32>, usize) {
1005 let mut dec = Decoder::new(48000, channels).unwrap();
1006 let mut out = vec![0u8; 1500];
1007 let mut decoded = Vec::new();
1008 let mut buf = vec![0.0f32; 5760 * channels];
1009 let mut bytes = 0usize;
1010 let mut padded = Vec::new();
1011 for block in pcm.chunks(frame * channels) {
1012 let block = if block.len() < frame * channels {
1013 padded.clear();
1014 padded.extend_from_slice(block);
1015 padded.resize(frame * channels, 0.0);
1016 &padded[..]
1017 } else {
1018 block
1019 };
1020 let len = enc.encode_float(block, frame, &mut out).expect("encode");
1021 bytes += len;
1022 let n = dec.decode_float(&out[..len], &mut buf).expect("decode");
1023 assert_eq!(n, frame, "decoded frame size");
1024 assert_eq!(
1025 dec.final_range(),
1026 enc.final_range(),
1027 "range state diverged between encoder and decoder"
1028 );
1029 decoded.extend_from_slice(&buf[..n * channels]);
1030 }
1031 (decoded, bytes)
1032}
1033
1034/// Worst-channel correlation against the source with the encoder's own
1035/// delay removed — `delay` is [`Encoder::look_ahead`] for the frame size the
1036/// round trip used, never a constant (it moved 120 -> 312 when the CELT layer
1037/// took libopus's Fs/250 input delay).
1038fn delayed_corr(source: &[f32], decoded: &[f32], channels: usize, delay: usize) -> f64 {
1039 let n = (decoded.len() / channels).saturating_sub(delay);
1040 let n = n.min(source.len() / channels);
1041 let mut worst = 1.0f64;
1042 for c in 0..channels {
1043 let a: Vec<f32> = (0..n).map(|i| source[i * channels + c]).collect();
1044 let b: Vec<f32> = (0..n)
1045 .map(|i| decoded[(i + delay) * channels + c])
1046 .collect();
1047 worst = worst.min(correlation(&a, &b));
1048 }
1049 worst
1050}
1051
1052/// Every rate from the product's table, mono and stereo, 20 ms CBR: the
1053/// encoder must be decodable by its own decoder range-exactly (asserted in
1054/// the helper) and land close to the source. The cross-implementation checks
1055/// against libopus live below — self-consistency alone proves nothing about
1056/// the world (the incumbent's exact disease).
1057#[test]
1058fn encoder_roundtrips_at_every_rate() {
1059 let _timing = timing_shared();
1060 for channels in [1usize, 2] {
1061 let pcm = test_signal(channels, 2.0);
1062 for kbps in [32u32, 64, 96, 128, 160, 165, 192, 256, 320, 510] {
1063 let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap();
1064 enc.set_bitrate(kbps * 1000);
1065 let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, channels, 960);
1066 let corr = delayed_corr(&pcm, &decoded, channels, enc.look_ahead(960));
1067 let rate = bytes as f64 * 8.0 / 2.0 / 1000.0;
1068 println!("{channels} ch {kbps:>3} kbps: corr {corr:.4}, actual {rate:.1} kbps");
1069 let floor = if kbps < 64 { 0.8 } else { 0.9 };
1070 assert!(
1071 corr >= floor,
1072 "{channels} ch {kbps} kbps: correlation {corr:.4}"
1073 );
1074 }
1075 }
1076}
1077
1078/// The libopus input alignment ([`Encoder::set_libopus_input_alignment`]):
1079/// with it on the CELT layer's advertised delay grows by libopus's
1080/// `delay_compensation`, and the decoded signal tracks the source at exactly
1081/// that lag and not at the old one — the knob is usable, not just present.
1082/// It is on by default except for `Application::LowDelay`, as in libopus.
1083#[test]
1084fn libopus_input_alignment_delays_and_still_decodes() {
1085 let _timing = timing_shared();
1086 let pcm = test_signal(2, 1.0);
1087 let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap();
1088 enc.set_bitrate(128_000);
1089 assert_eq!(
1090 enc.look_ahead(960),
1091 312,
1092 "default: overlap + delay_compensation"
1093 );
1094 enc.set_libopus_input_alignment(false);
1095 assert_eq!(enc.look_ahead(960), 120, "off: one MDCT overlap");
1096 enc.set_libopus_input_alignment(true);
1097 let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, 960);
1098 let aligned = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(960));
1099 let old = delayed_corr(&pcm, &decoded, 2, 120);
1100 println!("aligned: corr at 312 {aligned:.4}, at 120 {old:.4}");
1101 assert!(aligned >= 0.85, "aligned round trip corr {aligned:.4}");
1102 assert!(
1103 aligned > old,
1104 "advertised delay 312 correlates {aligned:.4}, worse than the old 120 ({old:.4})"
1105 );
1106}
1107
1108#[test]
1109// Expectations are libopus 1.6's (opus_encoder.c mode_thresholds and the
1110// voice/music bandwidth tables blended by voice_est) since lane opus-mode;
1111// matched against ffmpeg libopus on real speech in lanes/opus-mode-r1.sweep.txt.
1112fn encoder_mode_follows_application_bitrate_channels_and_frame_size() {
1113 let _timing = timing_shared();
1114 #[derive(Clone, Copy, Debug)]
1115 struct Case {
1116 app: Application,
1117 channels: usize,
1118 bps: u32,
1119 frame: usize,
1120 mode_request: Option<Mode>,
1121 bandwidth_request: Option<Bandwidth>,
1122 mode: Mode,
1123 bandwidth: Bandwidth,
1124 config: u8,
1125 code: u8,
1126 frames: usize,
1127 }
1128
1129 let cases = [
1130 Case {
1131 app: Application::Voip,
1132 channels: 1,
1133 bps: 8_000,
1134 frame: 480,
1135 mode_request: None,
1136 bandwidth_request: None,
1137 mode: Mode::Celt,
1138 bandwidth: Bandwidth::Narrow,
1139 config: 18,
1140 code: 0,
1141 frames: 1,
1142 },
1143 Case {
1144 app: Application::Voip,
1145 channels: 1,
1146 bps: 12_000,
1147 frame: 960,
1148 mode_request: None,
1149 bandwidth_request: None,
1150 mode: Mode::Silk,
1151 bandwidth: Bandwidth::Wide,
1152 config: 9,
1153 code: 0,
1154 frames: 1,
1155 },
1156 Case {
1157 app: Application::Voip,
1158 channels: 1,
1159 bps: 13_000,
1160 frame: 960,
1161 mode_request: None,
1162 bandwidth_request: None,
1163 mode: Mode::Silk,
1164 bandwidth: Bandwidth::Wide,
1165 config: 9,
1166 code: 0,
1167 frames: 1,
1168 },
1169 Case {
1170 app: Application::Voip,
1171 channels: 1,
1172 bps: 16_000,
1173 frame: 960,
1174 mode_request: None,
1175 bandwidth_request: None,
1176 mode: Mode::Hybrid,
1177 bandwidth: Bandwidth::Full,
1178 config: 15,
1179 code: 0,
1180 frames: 1,
1181 },
1182 Case {
1183 app: Application::Voip,
1184 channels: 1,
1185 bps: 19_000,
1186 frame: 960,
1187 mode_request: None,
1188 bandwidth_request: None,
1189 mode: Mode::Hybrid,
1190 bandwidth: Bandwidth::Full,
1191 config: 15,
1192 code: 0,
1193 frames: 1,
1194 },
1195 Case {
1196 app: Application::Voip,
1197 channels: 1,
1198 bps: 20_000,
1199 frame: 960,
1200 mode_request: None,
1201 bandwidth_request: None,
1202 mode: Mode::Hybrid,
1203 bandwidth: Bandwidth::Full,
1204 config: 15,
1205 code: 0,
1206 frames: 1,
1207 },
1208 Case {
1209 app: Application::Voip,
1210 channels: 1,
1211 bps: 39_000,
1212 frame: 960,
1213 mode_request: None,
1214 bandwidth_request: None,
1215 mode: Mode::Hybrid,
1216 bandwidth: Bandwidth::Full,
1217 config: 15,
1218 code: 0,
1219 frames: 1,
1220 },
1221 Case {
1222 app: Application::Voip,
1223 channels: 1,
1224 bps: 40_000,
1225 frame: 960,
1226 mode_request: None,
1227 bandwidth_request: None,
1228 mode: Mode::Hybrid,
1229 bandwidth: Bandwidth::Full,
1230 config: 15,
1231 code: 0,
1232 frames: 1,
1233 },
1234 Case {
1235 app: Application::Audio,
1236 channels: 1,
1237 bps: 16_000,
1238 frame: 960,
1239 mode_request: None,
1240 bandwidth_request: None,
1241 mode: Mode::Hybrid,
1242 bandwidth: Bandwidth::Full,
1243 config: 15,
1244 code: 0,
1245 frames: 1,
1246 },
1247 Case {
1248 app: Application::Audio,
1249 channels: 1,
1250 bps: 64_000,
1251 frame: 960,
1252 mode_request: None,
1253 bandwidth_request: None,
1254 mode: Mode::Celt,
1255 bandwidth: Bandwidth::Full,
1256 config: 31,
1257 code: 0,
1258 frames: 1,
1259 },
1260 Case {
1261 app: Application::LowDelay,
1262 channels: 1,
1263 bps: 16_000,
1264 frame: 960,
1265 mode_request: None,
1266 bandwidth_request: None,
1267 mode: Mode::Celt,
1268 bandwidth: Bandwidth::Full,
1269 config: 31,
1270 code: 0,
1271 frames: 1,
1272 },
1273 Case {
1274 app: Application::Voip,
1275 channels: 2,
1276 bps: 16_000,
1277 frame: 960,
1278 mode_request: None,
1279 bandwidth_request: None,
1280 mode: Mode::Hybrid,
1281 bandwidth: Bandwidth::Full,
1282 config: 15,
1283 code: 0,
1284 frames: 1,
1285 },
1286 Case {
1287 app: Application::Voip,
1288 channels: 2,
1289 bps: 24_000,
1290 frame: 960,
1291 mode_request: None,
1292 bandwidth_request: None,
1293 mode: Mode::Hybrid,
1294 bandwidth: Bandwidth::Full,
1295 config: 15,
1296 code: 0,
1297 frames: 1,
1298 },
1299 Case {
1300 app: Application::Voip,
1301 channels: 2,
1302 bps: 32_000,
1303 frame: 960,
1304 mode_request: None,
1305 bandwidth_request: None,
1306 mode: Mode::Hybrid,
1307 bandwidth: Bandwidth::Full,
1308 config: 15,
1309 code: 0,
1310 frames: 1,
1311 },
1312 Case {
1313 app: Application::Voip,
1314 channels: 2,
1315 bps: 38_000,
1316 frame: 960,
1317 mode_request: None,
1318 bandwidth_request: None,
1319 mode: Mode::Hybrid,
1320 bandwidth: Bandwidth::Full,
1321 config: 15,
1322 code: 0,
1323 frames: 1,
1324 },
1325 Case {
1326 app: Application::Voip,
1327 channels: 2,
1328 bps: 40_000,
1329 frame: 960,
1330 mode_request: None,
1331 bandwidth_request: None,
1332 mode: Mode::Hybrid,
1333 bandwidth: Bandwidth::Full,
1334 config: 15,
1335 code: 0,
1336 frames: 1,
1337 },
1338 Case {
1339 app: Application::Voip,
1340 channels: 2,
1341 bps: 78_000,
1342 frame: 960,
1343 mode_request: None,
1344 bandwidth_request: None,
1345 mode: Mode::Celt,
1346 bandwidth: Bandwidth::Full,
1347 config: 31,
1348 code: 0,
1349 frames: 1,
1350 },
1351 Case {
1352 app: Application::Voip,
1353 channels: 2,
1354 bps: 80_000,
1355 frame: 960,
1356 mode_request: None,
1357 bandwidth_request: None,
1358 mode: Mode::Celt,
1359 bandwidth: Bandwidth::Full,
1360 config: 31,
1361 code: 0,
1362 frames: 1,
1363 },
1364 Case {
1365 app: Application::Voip,
1366 channels: 2,
1367 bps: 32_000,
1368 frame: 480,
1369 mode_request: None,
1370 bandwidth_request: None,
1371 mode: Mode::Hybrid,
1372 bandwidth: Bandwidth::Full,
1373 config: 14,
1374 code: 0,
1375 frames: 1,
1376 },
1377 Case {
1378 app: Application::Voip,
1379 channels: 2,
1380 bps: 32_000,
1381 frame: 1920,
1382 mode_request: None,
1383 bandwidth_request: None,
1384 mode: Mode::Hybrid,
1385 bandwidth: Bandwidth::Full,
1386 config: 15,
1387 code: 3,
1388 frames: 2,
1389 },
1390 Case {
1391 app: Application::Voip,
1392 channels: 2,
1393 bps: 32_000,
1394 frame: 2880,
1395 mode_request: None,
1396 bandwidth_request: None,
1397 mode: Mode::Hybrid,
1398 bandwidth: Bandwidth::Full,
1399 config: 15,
1400 code: 3,
1401 frames: 3,
1402 },
1403 Case {
1404 app: Application::Voip,
1405 channels: 1,
1406 bps: 16_000,
1407 frame: 1920,
1408 mode_request: None,
1409 bandwidth_request: None,
1410 mode: Mode::Hybrid,
1411 bandwidth: Bandwidth::Full,
1412 config: 15,
1413 code: 3,
1414 frames: 2,
1415 },
1416 Case {
1417 app: Application::Voip,
1418 channels: 1,
1419 bps: 19_000,
1420 frame: 2880,
1421 mode_request: None,
1422 bandwidth_request: None,
1423 mode: Mode::Hybrid,
1424 bandwidth: Bandwidth::Full,
1425 config: 15,
1426 code: 3,
1427 frames: 3,
1428 },
1429 Case {
1430 app: Application::Audio,
1431 channels: 1,
1432 bps: 64_000,
1433 frame: 480,
1434 mode_request: Some(Mode::Silk),
1435 bandwidth_request: Some(Bandwidth::Medium),
1436 mode: Mode::Silk,
1437 bandwidth: Bandwidth::Medium,
1438 config: 4,
1439 code: 0,
1440 frames: 1,
1441 },
1442 ];
1443
1444 for case in cases {
1445 let mut enc = Encoder::new(48000, case.channels, case.app).unwrap();
1446 enc.set_bitrate(case.bps);
1447 enc.set_mode(case.mode_request);
1448 enc.set_bandwidth(case.bandwidth_request);
1449 let pcm = vec![0.0f32; case.frame * case.channels];
1450 let mut out = vec![0u8; 4096];
1451 let n = enc.encode_float(&pcm, case.frame, &mut out).unwrap();
1452 let packet = Packet::parse(&out[..n], false).unwrap();
1453 let toc = packet.toc;
1454 assert_eq!(toc.mode(), case.mode, "{case:?}");
1455 assert_eq!(toc.bandwidth(), case.bandwidth, "{case:?}");
1456 assert_eq!(toc.config, case.config, "{case:?}");
1457 let cbr_padded = case.code == 0 && toc.code == 3 && case.mode == Mode::Silk;
1458 assert!(toc.code == case.code || cbr_padded, "{case:?}");
1459 assert_eq!(
1460 toc.stereo,
1461 case.channels == 2 && case.bps > 16_000,
1462 "{case:?}"
1463 );
1464 assert_eq!(packet.frames.len(), case.frames, "{case:?}");
1465 assert_eq!(packet.samples_48k(), case.frame, "{case:?}");
1466 assert!(n > 1, "{case:?}: empty packet");
1467 }
1468}
1469
1470/// All four CELT frame sizes survive the loop, and constrained VBR both
1471/// stays decodable and lands near its target.
1472#[test]
1473fn encoder_frame_sizes_and_vbr() {
1474 let _timing = timing_shared();
1475 let pcm = test_signal(2, 1.0);
1476 for frame in [120usize, 240, 480, 960] {
1477 let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap();
1478 enc.set_bitrate(128_000);
1479 let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, frame);
1480 let corr = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(frame));
1481 println!("frame {frame}: corr {corr:.4}");
1482 assert!(corr >= 0.85, "frame {frame}: correlation {corr:.4}");
1483 }
1484 let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap();
1485 enc.set_bitrate(128_000);
1486 enc.set_vbr_constrained(true);
1487 let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, 2, 960);
1488 let corr = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(960));
1489 let rate = bytes as f64 * 8.0 / 1.0 / 1000.0;
1490 println!("cvbr 128k: corr {corr:.4}, actual {rate:.1} kbps");
1491 assert!(corr >= 0.9, "cvbr: correlation {corr:.4}");
1492 assert!(
1493 (90.0..=150.0).contains(&rate),
1494 "cvbr at 128k landed on {rate:.1} kbps"
1495 );
1496}
1497
1498// ---------------------------------------------------------------------------
1499// Encoder: the world must decode it. Self-consistency alone was the
1500// incumbent's disease (correlation 0.06 against libopus at 256 kbps while
1501// its own round trip passed), so every claim here runs through ffmpeg's
1502// libopus — the reference implementation — via Ogg-Opus files this crate
1503// muxed itself.
1504// ---------------------------------------------------------------------------
1505
1506use ec_core::registry::{CodecId, CodecParameters, MediaParameters, Muxer, StreamInfo};
1507use ec_core::{ChannelLayout, Packet as CorePacket, TimeBase};
1508use ec_ogg::OggMuxer;
1509
1510/// The RFC 7845 identification header for this encoder — built by the crate's
1511/// own [`ec_opus::ogg`] helper, so a muxer and the encoder cannot disagree.
1512/// `pre_skip` is the encoder's [`Encoder::look_ahead`]: 312, the CELT overlap
1513/// plus its input delay compensation, for every CELT call site; SILK's own
1514/// delay for SILK.
1515fn opus_head(channels: usize, pre_skip: u16, layout: Option<(usize, usize, &[u8])>) -> Vec<u8> {
1516 let mapping =
1517 layout.map(|(streams, coupled, table)| (1u8, streams as u8, coupled as u8, table));
1518 ec_opus::ogg::opus_head(channels as u8, pre_skip, 48000, 0, mapping)
1519}
1520
1521/// Muxes packets into an Ogg-Opus file whose final granule trims the stream
1522/// to exactly `total_samples` — RFC 7845 end-trimming plus the pre-skip
1523/// accounting.
1524fn write_ogg_opus(
1525 path: &Path,
1526 packets: &[Vec<u8>],
1527 head: Vec<u8>,
1528 channels: usize,
1529 total_samples: usize,
1530 pre_skip: i64,
1531) {
1532 let file = std::io::BufWriter::new(fs::File::create(path).unwrap());
1533 let mut mux = OggMuxer::new(file);
1534 let tb = TimeBase::from_rate(48000);
1535 let mut params = CodecParameters::new(CodecId::Opus);
1536 params.extradata = Some(head.into());
1537 if let MediaParameters::Audio(a) = &mut params.media {
1538 a.sample_rate = 48000;
1539 a.layout = ChannelLayout::from_count(channels);
1540 }
1541 mux.add_stream(StreamInfo::new(0, tb, params)).unwrap();
1542 let mut pts = 0i64;
1543 for (idx, p) in packets.iter().enumerate() {
1544 let last = idx == packets.len() - 1;
1545 let packet_dur = ec_opus::Packet::parse(p, false).unwrap().samples_48k() as i64;
1546 let dur = if last {
1547 total_samples as i64 + pre_skip - pts
1548 } else {
1549 packet_dur
1550 };
1551 let pkt = CorePacket::new(0, tb, p.clone())
1552 .with_pts(pts)
1553 .with_duration(dur);
1554 mux.write_packet(&pkt).unwrap();
1555 pts += packet_dur;
1556 }
1557 mux.finish().unwrap();
1558}
1559
1560/// Encodes `pcm` (plus one flush frame for the 120-sample delay) as 20 ms
1561/// packets.
1562fn encode_packets(enc: &mut Encoder, pcm: &[f32], channels: usize) -> Vec<Vec<u8>> {
1563 let mut out = vec![0u8; 1500];
1564 let mut packets = Vec::new();
1565 let mut padded = Vec::new();
1566 for block in pcm.chunks(960 * channels) {
1567 let block = if block.len() < 960 * channels {
1568 padded.clear();
1569 padded.extend_from_slice(block);
1570 padded.resize(960 * channels, 0.0);
1571 &padded[..]
1572 } else {
1573 block
1574 };
1575 let len = enc.encode_float(block, 960, &mut out).expect("encode");
1576 packets.push(out[..len].to_vec());
1577 }
1578 // One silent frame flushes the delay past the end trim.
1579 let silence = vec![0.0f32; 960 * channels];
1580 let len = enc.encode_float(&silence, 960, &mut out).expect("encode");
1581 packets.push(out[..len].to_vec());
1582 packets
1583}
1584
1585fn temp_path(name: &str) -> PathBuf {
1586 let root = std::env::var_os("EC_OPUS_SCRATCH")
1587 .map(PathBuf::from)
1588 .unwrap_or_else(|| {
1589 let home = std::env::var_os("HOME").expect("HOME set for encoder scratch");
1590 PathBuf::from(home).join(".cache/silk2")
1591 });
1592 fs::create_dir_all(&root).unwrap();
1593 root.join(format!("ec-opus-enc-{}-{name}", std::process::id()))
1594}
1595
1596/// The full product rate table, mono and stereo, decoded by libopus: the
1597/// worst-channel correlation and the opus_compare quality, per rate. The
1598/// incumbent fails this file's 256 kbps row at correlation 0.06; the MUST
1599/// bars here are correlation >= 0.9 at 96/165/256 kbps.
1600#[test]
1601fn oracle_decodes_our_packets_across_the_rate_table() {
1602 let _timing = timing_shared();
1603 for channels in [1usize, 2] {
1604 let pcm = test_signal(channels, 2.0);
1605 let total = pcm.len() / channels;
1606 let mut table = Vec::new();
1607 for kbps in [16u32, 32, 64, 96, 128, 160, 165, 192, 256, 320, 510] {
1608 let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap();
1609 enc.set_bitrate(kbps * 1000);
1610 let packets = encode_packets(&mut enc, &pcm, channels);
1611 let path = temp_path(&format!("{channels}ch-{kbps}k.opus"));
1612 write_ogg_opus(
1613 &path,
1614 &packets,
1615 opus_head(channels, enc.look_ahead(960) as u16, None),
1616 channels,
1617 total,
1618 enc.look_ahead(960) as i64,
1619 );
1620 let Some(reference) = ffmpeg_decode(&path, channels) else {
1621 eprintln!("ffmpeg unavailable, skipped");
1622 let _ = fs::remove_file(&path);
1623 return;
1624 };
1625 let _ = fs::remove_file(&path);
1626 let n = (reference.len() / channels).min(total);
1627 assert!(
1628 n >= total - 960,
1629 "{channels} ch {kbps} kbps: libopus returned {n} of {total} samples"
1630 );
1631 let mut worst = 1.0f64;
1632 for c in 0..channels {
1633 let a: Vec<f32> = (0..n).map(|i| pcm[i * channels + c]).collect();
1634 let b: Vec<f32> = (0..n).map(|i| reference[i * channels + c]).collect();
1635 worst = worst.min(correlation(&a, &b));
1636 }
1637 let quality = opus_compare(
1638 &to_i16(&pcm[..n * channels]),
1639 &to_i16(&reference[..n * channels]),
1640 channels,
1641 );
1642 table.push(format!(
1643 "{channels} ch {kbps:>3} kbps: worst corr {worst:.4}, opus_compare {quality:.1}"
1644 ));
1645 let floor = match kbps {
1646 // 16 kbps fullband CELT is the honest bottom of the range:
1647 // reported, held to "clearly the same signal", not to hi-fi.
1648 0..=19 => {
1649 if channels == 1 {
1650 0.6
1651 } else {
1652 // Stereo SILK with the libopus LR_to_MS rate split
1653 // and panned-mono rule (lane opus-silkq r4): .4534.
1654 0.44
1655 }
1656 }
1657 20..=39 => 0.6,
1658 40..=95 => 0.8,
1659 _ => 0.9,
1660 };
1661 assert!(
1662 worst >= floor,
1663 "{channels} ch {kbps} kbps: libopus heard correlation {worst:.4} (floor {floor})"
1664 );
1665 if kbps >= 96 {
1666 assert!(
1667 quality >= 0.0,
1668 "{channels} ch {kbps} kbps: opus_compare {quality:.1}"
1669 );
1670 }
1671 }
1672 for line in table {
1673 println!("{line}");
1674 }
1675 }
1676
1677 // SILK, mono, the speech-rate corner: libopus must hear what our decoder hears.
1678 let pcm = test_signal(1, 2.0);
1679 let total = pcm.len();
1680 for kbps in [8u32, 12, 16] {
1681 let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap();
1682 enc.set_bitrate(kbps * 1000);
1683 let pre_skip = enc.look_ahead(960) as u16;
1684 let packets = encode_packets(&mut enc, &pcm, 1);
1685 let path = temp_path(&format!("silk-1ch-{kbps}k.opus"));
1686 write_ogg_opus(
1687 &path,
1688 &packets,
1689 opus_head(1, pre_skip, None),
1690 1,
1691 total,
1692 pre_skip as i64,
1693 );
1694 let Some(reference) = ffmpeg_decode(&path, 1) else {
1695 eprintln!("ffmpeg unavailable, skipped");
1696 let _ = fs::remove_file(&path);
1697 return;
1698 };
1699 let _ = fs::remove_file(&path);
1700 let mut dec = Decoder::new(48000, 1).unwrap();
1701 let mut buf = vec![0f32; 5760];
1702 let mut ours = Vec::new();
1703 for p in &packets {
1704 let n = dec.decode_float(p, &mut buf).unwrap();
1705 ours.extend_from_slice(&buf[..n]);
1706 }
1707 let ours = &ours[pre_skip as usize..];
1708 let n = reference.len().min(ours.len()).min(total);
1709 let corr = correlation(&ours[..n], &reference[..n]);
1710 println!("silk 1 ch {kbps:>3} kbps: oracle vs ours corr {corr:.4}");
1711 assert!(corr >= 0.99, "silk {kbps} kbps: correlation {corr:.4}");
1712 }
1713}
1714
1715/// 5.1 multistream: one distinct tone per channel, encoded with the
1716/// mapping-family-1 layout and decoded by libopus — every channel must come
1717/// back in its place (order-preserved) at correlation >= 0.9.
1718#[test]
1719fn five_one_encode_end_to_end() {
1720 let _timing = timing_shared();
1721 const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3];
1722 const TONES: [f64; 6] = [220.0, 440.0, 660.0, 55.0, 880.0, 1320.0];
1723 let total = 96000usize;
1724 // Vorbis order input, one tone per channel plus a quiet upper partial so
1725 // every stream codes real content.
1726 let mut pcm = Vec::with_capacity(total * 6);
1727 for i in 0..total {
1728 let t = i as f64 / 48000.0;
1729 for f in TONES {
1730 let v = 0.4 * (std::f64::consts::TAU * f * t).sin()
1731 + 0.05 * (std::f64::consts::TAU * f * 7.03 * t).sin();
1732 pcm.push(v as f32);
1733 }
1734 }
1735 let mut enc = MultistreamEncoder::surround_5_1(48000).unwrap();
1736 enc.set_bitrate(384_000);
1737 let mut out = vec![0u8; 8 * 1500];
1738 let mut packets = Vec::new();
1739 for block in pcm.as_chunks::<{ 960 * 6 }>().0 {
1740 let len = enc.encode_float(block, 960, &mut out).expect("encode");
1741 packets.push(out[..len].to_vec());
1742 }
1743 let silence = vec![0.0f32; 960 * 6];
1744 let len = enc.encode_float(&silence, 960, &mut out).expect("encode");
1745 packets.push(out[..len].to_vec());
1746 let (streams, coupled, mapping) = enc.layout();
1747 let pre_skip = enc.look_ahead(960);
1748 let head = opus_head(6, pre_skip as u16, Some((streams, coupled, mapping)));
1749 let path = temp_path("5.1.opus");
1750 write_ogg_opus(&path, &packets, head, 6, total, pre_skip as i64);
1751 let Some(reference) = ffmpeg_decode(&path, 6) else {
1752 eprintln!("ffmpeg unavailable, skipped");
1753 let _ = fs::remove_file(&path);
1754 return;
1755 };
1756 let _ = fs::remove_file(&path);
1757 let n = (reference.len() / 6).min(total);
1758 assert!(n >= total - 960, "libopus returned {n} of {total} samples");
1759 for (c, &their) in VORBIS_TO_FFMPEG_5_1.iter().enumerate() {
1760 let a: Vec<f32> = (0..n).map(|i| pcm[i * 6 + c]).collect();
1761 let b: Vec<f32> = (0..n).map(|i| reference[i * 6 + their]).collect();
1762 let corr = correlation(&a, &b);
1763 println!("5.1 channel {c} ({} Hz): corr {corr:.4}", TONES[c]);
1764 assert!(
1765 corr >= 0.9,
1766 "5.1 channel {c} came back at correlation {corr:.4}"
1767 );
1768 }
1769}
1770
1771/// The muxed file's duration must be exact: the final granule trims the
1772/// flush frame so a 2.000 s input probes as 2.000 s, and the sample count
1773/// libopus hands back is exactly the input length.
1774#[test]
1775fn ogg_opus_round_trip_duration_is_exact() {
1776 let _timing = timing_shared();
1777 let pcm = test_signal(2, 2.0);
1778 let total = pcm.len() / 2;
1779 let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap();
1780 enc.set_bitrate(128_000);
1781 let packets = encode_packets(&mut enc, &pcm, 2);
1782 let path = temp_path("duration.opus");
1783 let pre_skip = enc.look_ahead(960);
1784 write_ogg_opus(
1785 &path,
1786 &packets,
1787 opus_head(2, pre_skip as u16, None),
1788 2,
1789 total,
1790 pre_skip as i64,
1791 );
1792 let probe = Command::new("ffprobe")
1793 .args([
1794 "-v",
1795 "error",
1796 "-show_entries",
1797 "stream=duration",
1798 "-of",
1799 "default=noprint_wrappers=1",
1800 ])
1801 .arg(&path)
1802 .output();
1803 if let Ok(p) = probe
1804 && p.status.success()
1805 {
1806 let text = String::from_utf8_lossy(&p.stdout);
1807 let dur: f64 = text
1808 .trim()
1809 .strip_prefix("duration=")
1810 .unwrap_or("0")
1811 .parse()
1812 .unwrap_or(0.0);
1813 // ffprobe reports Ogg-Opus durations *including* the pre-skip — its
1814 // own 3.000 s encode probes as 3.0065 (312/48000 more). Ours carries
1815 // the same pre-skip our encoder advertises, so exact is 2.000 s plus
1816 // it; the decoded sample count below is the pre-skip-free half.
1817 let expected = (total as f64 + pre_skip as f64) / 48000.0;
1818 assert!(
1819 (dur - expected).abs() < 1e-6,
1820 "ffprobe reports {dur} s, expected {expected} s (2.000 s + pre-skip)"
1821 );
1822 }
1823 if let Some(decoded) = ffmpeg_decode(&path, 2) {
1824 assert_eq!(
1825 decoded.len() / 2,
1826 total,
1827 "libopus decoded {} samples of {total}",
1828 decoded.len() / 2
1829 );
1830 }
1831 let _ = fs::remove_file(&path);
1832}
1833
1834/// Cross-check against the reference `opus_demo` decoder (RFC 6716
1835/// Appendix A) over its own `.bit` format, when the binary is available:
1836/// `EC_OPUS_DEMO=/path/to/opus_demo cargo test`.
1837#[test]
1838fn opus_demo_decodes_our_bit_stream() {
1839 let _timing = timing_shared();
1840 let Ok(demo) = std::env::var("EC_OPUS_DEMO") else {
1841 eprintln!("EC_OPUS_DEMO unset, skipped");
1842 return;
1843 };
1844 let pcm = test_signal(2, 2.0);
1845 let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap();
1846 enc.set_bitrate(256_000);
1847 let mut out = vec![0u8; 1500];
1848 let mut bit = Vec::new();
1849 for block in pcm.as_chunks::<{ 960 * 2 }>().0 {
1850 let len = enc.encode_float(block, 960, &mut out).expect("encode");
1851 bit.extend_from_slice(&(len as u32).to_be_bytes());
1852 bit.extend_from_slice(&enc.final_range().to_be_bytes());
1853 bit.extend_from_slice(&out[..len]);
1854 }
1855 let bit_path = temp_path("demo.bit");
1856 let pcm_path = temp_path("demo.pcm");
1857 fs::write(&bit_path, &bit).unwrap();
1858 let status = Command::new(&demo)
1859 .arg("-d")
1860 .arg("48000")
1861 .arg("2")
1862 .arg(&bit_path)
1863 .arg(&pcm_path)
1864 .status()
1865 .expect("run opus_demo");
1866 assert!(status.success(), "opus_demo refused our stream");
1867 let decoded = read_i16(&pcm_path);
1868 let _ = fs::remove_file(&bit_path);
1869 let _ = fs::remove_file(&pcm_path);
1870 // opus_demo does not apply pre-skip; compensate for the 120-sample delay.
1871 let delay = 120usize;
1872 let n = (decoded.len() / 2 - delay).min(pcm.len() / 2 - delay);
1873 let mut worst = 1.0f64;
1874 for c in 0..2 {
1875 let a: Vec<f32> = (0..n).map(|i| pcm[i * 2 + c]).collect();
1876 let b: Vec<f32> = (0..n)
1877 .map(|i| decoded[(i + delay) * 2 + c] as f32 / 32768.0)
1878 .collect();
1879 worst = worst.min(correlation(&a, &b));
1880 }
1881 println!("opus_demo 256 kbps stereo: worst corr {worst:.4}");
1882 assert!(
1883 worst >= 0.9,
1884 "reference decoder heard correlation {worst:.4}"
1885 );
1886}
1887
1888/// The steady-state encode loop allocates nothing: every buffer — MDCT
1889/// scratch, PVQ vectors, the range coder's frame — is owned by the encoder
1890/// and sized on the first frame (the decoder discipline, applied to the
1891/// encoder).
1892#[test]
1893fn steady_state_encode_loop_zero_alloc() {
1894 install_counter();
1895 let _timing = timing_shared();
1896 let pcm = test_signal(2, 0.5);
1897 let pcm6 = {
1898 let mono = test_signal(1, 0.5);
1899 let mut v = Vec::with_capacity(mono.len() * 6);
1900 for &s in &mono {
1901 for c in 0..6 {
1902 v.push(s * (1.0 + c as f32 * 0.01));
1903 }
1904 }
1905 v
1906 };
1907 // Stereo elementary encoder.
1908 let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap();
1909 enc.set_bitrate(256_000);
1910 let mut out = vec![0u8; 1500];
1911 for block in pcm.as_chunks::<{ 960 * 2 }>().0 {
1912 enc.encode_float(block, 960, &mut out).unwrap();
1913 }
1914 ALLOCS.store(0, Ordering::SeqCst);
1915 COUNTING_HERE.with(|c| c.set(true));
1916 for block in pcm.as_chunks::<{ 960 * 2 }>().0 {
1917 enc.encode_float(block, 960, &mut out).unwrap();
1918 }
1919 COUNTING_HERE.with(|c| c.set(false));
1920 let n = ALLOCS.load(Ordering::SeqCst);
1921 assert_eq!(n, 0, "stereo encode allocated {n} times in steady state");
1922
1923 // 5.1 multistream.
1924 let mut ms = MultistreamEncoder::surround_5_1(48000).unwrap();
1925 ms.set_bitrate(384_000);
1926 let mut out6 = vec![0u8; 8 * 1500];
1927 for block in pcm6.as_chunks::<{ 960 * 6 }>().0 {
1928 ms.encode_float(block, 960, &mut out6).unwrap();
1929 }
1930 ALLOCS.store(0, Ordering::SeqCst);
1931 COUNTING_HERE.with(|c| c.set(true));
1932 for block in pcm6.as_chunks::<{ 960 * 6 }>().0 {
1933 ms.encode_float(block, 960, &mut out6).unwrap();
1934 }
1935 COUNTING_HERE.with(|c| c.set(false));
1936 let n = ALLOCS.load(Ordering::SeqCst);
1937 assert_eq!(n, 0, "5.1 encode allocated {n} times in steady state");
1938
1939 // Mono SILK (Voip, 12 kbps) is NOT asserted zero-alloc here: fixing
1940 // `Encoder::zero_stuff_mono` to reuse a scratch buffer removed its
1941 // per-frame Vec, but the SILK encode path itself (NLSF/LPC
1942 // analysis, pitch search) allocates well beyond that one site — sweeping
1943 // those is a separate, much larger effort than this defect's scope.
1944}
1945
1946/// The throughput headline: encode speed in multiples of realtime, per
1947/// configuration, at the product's rates. Floors are deliberately far under
1948/// the measured numbers — they catch a regression class (an accidental
1949/// O(n^2), a debug path left on), not machine variance.
1950#[test]
1951fn encode_speed() {
1952 let _timing = timing_exclusive();
1953 if cfg!(debug_assertions) {
1954 eprintln!("encode speed is only meaningful in release; skipped");
1955 return;
1956 }
1957 let secs = 4.0;
1958 for (name, channels, kbps, floor) in [
1959 ("mono 96k", 1usize, 96u32, 100.0f64),
1960 ("stereo 128k", 2, 128, 70.0),
1961 ("stereo 256k", 2, 256, 70.0),
1962 ("stereo 510k", 2, 510, 50.0),
1963 ] {
1964 let pcm = test_signal(channels, secs);
1965 let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap();
1966 enc.set_bitrate(kbps * 1000);
1967 let mut out = vec![0u8; 1500];
1968 // Warm up one pass, then measure.
1969 for block in pcm.chunks_exact(960 * channels) {
1970 enc.encode_float(block, 960, &mut out).unwrap();
1971 }
1972 let passes = 4;
1973 let elapsed = best_of_3(|| {
1974 for _ in 0..passes {
1975 for block in pcm.chunks_exact(960 * channels) {
1976 enc.encode_float(block, 960, &mut out).unwrap();
1977 }
1978 }
1979 });
1980 let realtime = secs * passes as f64 / elapsed;
1981 println!("{name}: {realtime:.0}x realtime");
1982 assert!(
1983 realtime >= floor,
1984 "{name}: {realtime:.0}x is below {floor}x"
1985 );
1986 }
1987 // 5.1 multistream.
1988 let mono = test_signal(1, secs);
1989 let mut pcm6 = Vec::with_capacity(mono.len() * 6);
1990 for &s in &mono {
1991 for c in 0..6 {
1992 pcm6.push(s * (1.0 + c as f32 * 0.01));
1993 }
1994 }
1995 let mut ms = MultistreamEncoder::surround_5_1(48000).unwrap();
1996 ms.set_bitrate(384_000);
1997 let mut out = vec![0u8; 8 * 1500];
1998 for block in pcm6.as_chunks::<{ 960 * 6 }>().0 {
1999 ms.encode_float(block, 960, &mut out).unwrap();
2000 }
2001 let passes = 4;
2002 let elapsed = best_of_3(|| {
2003 for _ in 0..passes {
2004 for block in pcm6.as_chunks::<{ 960 * 6 }>().0 {
2005 ms.encode_float(block, 960, &mut out).unwrap();
2006 }
2007 }
2008 });
2009 let realtime = secs * passes as f64 / elapsed;
2010 println!("5.1 384k: {realtime:.0}x realtime");
2011 assert!(realtime >= 25.0, "5.1: {realtime:.0}x is below 25x");
2012}
2013
2014/// Malformed input must come back as an error, never a panic: the decoders
2015/// index tables with values the bitstream chooses, so this throws well-formed
2016/// TOC bytes at random payloads to make sure every mode is actually entered.
2017#[test]
2018fn garbage_payloads_never_panic() {
2019 let _timing = timing_shared();
2020 let mut state = 0x12345678u32;
2021 let mut rand = move || {
2022 state ^= state << 13;
2023 state ^= state >> 17;
2024 state ^= state << 5;
2025 state
2026 };
2027 let mut dec = Decoder::new(48000, 2).unwrap();
2028 let mut ms = MultistreamDecoder::with_rate(48000, 4, 2, &[0, 4, 1, 2, 3, 5]);
2029 let mut out = vec![0.0f32; 5760 * 6];
2030 for config in 0..32u8 {
2031 for stereo in 0..2u8 {
2032 for code in 0..4u8 {
2033 let toc = (config << 3) | (stereo << 2) | code;
2034 for trial in 0..40 {
2035 let len = 2 + (rand() as usize % 400);
2036 let mut packet = vec![toc];
2037 for _ in 0..len {
2038 packet.push(rand() as u8);
2039 }
2040 if trial % 2 == 0 {
2041 dec.reset();
2042 }
2043 let _ = dec.decode_float(&packet, &mut out);
2044 let _ = ms.decode_float(&packet, &mut out);
2045 }
2046 }
2047 }
2048 }
2049 // Truncations of a real packet, which exercise the mid-frame paths.
2050 let path = vectors_dir().join("testvector10.bit");
2051 if path.exists() {
2052 for p in read_vector(&path).iter().take(200) {
2053 for cut in 1..p.payload.len().min(64) {
2054 let _ = dec.decode_float(&p.payload[..cut], &mut out);
2055 }
2056 }
2057 }
2058}
2059
2060// ---------------------------------------------------------------------------
2061// SILK encoder (mono, 20 ms, NB/WB)
2062// ---------------------------------------------------------------------------
2063
2064/// A 1 s speech-like signal at 48 kHz: 0.6 s of a pitch-modulated pulse train
2065/// through a formant-ish AR(2) filter, then 0.4 s of filtered noise.
2066fn speech_like() -> Vec<f32> {
2067 let mut out = Vec::with_capacity(48000);
2068 let (mut y1, mut y2) = (0f32, 0f32);
2069 let mut phase = 0f64;
2070 let mut s = 12345u32;
2071 for i in 0..48000 {
2072 let t = i as f64 / 48000.0;
2073 let e = if t < 0.6 {
2074 let f0 = 120.0 + 30.0 * (2.0 * std::f64::consts::PI * 2.0 * t).sin();
2075 phase += f0 / 48000.0;
2076 if phase >= 1.0 {
2077 phase -= 1.0;
2078 1.0
2079 } else {
2080 0.0
2081 }
2082 } else {
2083 s = s.wrapping_mul(1664525).wrapping_add(1013904223);
2084 ((s >> 8) as f32 / (1u32 << 24) as f32 - 0.5) * 0.3
2085 };
2086 // Resonance near 700 Hz, radius 0.97.
2087 let (r, w) = (0.97f32, 2.0 * std::f32::consts::PI * 700.0 / 48000.0);
2088 let y = e + 2.0 * r * w.cos() * y1 - r * r * y2;
2089 y2 = y1;
2090 y1 = y;
2091 out.push(y * 0.03);
2092 }
2093 out
2094}
2095
2096/// 16-bit PCM mono WAV at 48 kHz, as `f32`.
2097fn read_wav_mono(path: &Path) -> Vec<f32> {
2098 let d = fs::read(path).unwrap();
2099 assert_eq!(u16::from_le_bytes([d[22], d[23]]), 1, "mono fixture");
2100 assert_eq!(u32::from_le_bytes([d[24], d[25], d[26], d[27]]), 48000);
2101 let mut pos = 12;
2102 loop {
2103 let id = &d[pos..pos + 4];
2104 let len = u32::from_le_bytes([d[pos + 4], d[pos + 5], d[pos + 6], d[pos + 7]]) as usize;
2105 if id == b"data" {
2106 return d[pos + 8..pos + 8 + len]
2107 .as_chunks::<2>()
2108 .0
2109 .iter()
2110 .map(|c| i16::from_le_bytes([c[0], c[1]]) as f32 / 32768.0)
2111 .collect();
2112 }
2113 pos += 8 + len + (len & 1);
2114 }
2115}
2116
2117/// Windowed-sinc low-pass at `cutoff_hz` (48 kHz input), zero-phase.
2118fn lowpass(x: &[f32], cutoff_hz: f64) -> Vec<f32> {
2119 let taps = 127usize;
2120 let c = cutoff_hz / 48000.0;
2121 let h: Vec<f64> = (0..taps)
2122 .map(|i| {
2123 let m = i as f64 - (taps - 1) as f64 / 2.0;
2124 let sinc = if m == 0.0 {
2125 2.0 * c
2126 } else {
2127 (2.0 * std::f64::consts::PI * c * m).sin() / (std::f64::consts::PI * m)
2128 };
2129 sinc * (0.54 - 0.46 * (2.0 * std::f64::consts::PI * i as f64 / (taps - 1) as f64).cos())
2130 })
2131 .collect();
2132 let half = (taps - 1) / 2;
2133 (0..x.len())
2134 .map(|n| {
2135 h.iter()
2136 .enumerate()
2137 .map(|(k, &hk)| {
2138 let idx = n as isize + half as isize - k as isize;
2139 if idx >= 0 && (idx as usize) < x.len() {
2140 hk * x[idx as usize] as f64
2141 } else {
2142 0.0
2143 }
2144 })
2145 .sum::<f64>() as f32
2146 })
2147 .collect()
2148}
2149
2150fn silk_encoder(bandwidth: Bandwidth, bps: Option<u32>) -> Encoder {
2151 let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap();
2152 enc.set_mode(Some(Mode::Silk));
2153 enc.set_bandwidth(Some(bandwidth));
2154 enc.set_vbr_constrained(true);
2155 if let Some(bps) = bps {
2156 enc.set_bitrate(bps);
2157 }
2158 enc
2159}
2160
2161/// Encodes `pcm` in `frame_ms` frames, decodes each packet with our decoder
2162/// asserting the range-coder invariant, returns (decoded 48 kHz, packets).
2163fn silk_roundtrip(enc: &mut Encoder, pcm: &[f32], frame_ms: usize) -> (Vec<f32>, Vec<Vec<u8>>) {
2164 let frame = 48 * frame_ms;
2165 let mut dec = Decoder::new(48000, 1).unwrap();
2166 let mut out = vec![0u8; 1500];
2167 let mut buf = vec![0f32; 5760];
2168 let mut decoded = Vec::new();
2169 let mut packets = Vec::new();
2170 let mut padded = pcm.to_vec();
2171 padded.resize(pcm.len().div_ceil(frame) * frame + frame, 0.0);
2172 for block in padded.chunks(frame) {
2173 let len = enc
2174 .encode_float(block, frame, &mut out)
2175 .expect("silk encode");
2176 let n = dec
2177 .decode_float(&out[..len], &mut buf)
2178 .expect("silk decode");
2179 assert_eq!(n, frame);
2180 assert_eq!(dec.final_range(), enc.final_range(), "range state diverged");
2181 decoded.extend_from_slice(&buf[..n]);
2182 packets.push(out[..len].to_vec());
2183 }
2184 (decoded, packets)
2185}
2186
2187/// Correlation after aligning `decoded` to `reference` at the best lag in
2188/// `[0, max_lag)`; the peak must be interior (a peak at the search bound is
2189/// no measurement).
2190fn aligned_corr(reference: &[f32], decoded: &[f32], max_lag: usize) -> (f64, usize) {
2191 let (mut best, mut best_lag) = (-1.0f64, 0usize);
2192 for lag in 0..max_lag {
2193 let c = correlation(reference, &decoded[lag..]);
2194 if c > best {
2195 best = c;
2196 best_lag = lag;
2197 }
2198 }
2199 assert!(best_lag + 1 < max_lag, "alignment peak at the search bound");
2200 (best, best_lag)
2201}
2202
2203#[test]
2204fn silk_mono_nb_wb_roundtrip() {
2205 let _timing = timing_shared();
2206 let wav = fixture("wav16-mono-48000.wav");
2207 let mut sources = vec![("synthetic", speech_like())];
2208 if wav.exists() {
2209 let w = read_wav_mono(&wav);
2210 sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec()));
2211 }
2212 for (name, pcm) in &sources {
2213 for wideband in [false, true] {
2214 let (bandwidth, band, tag) = if wideband {
2215 (Bandwidth::Wide, 7000.0, "WB")
2216 } else {
2217 (Bandwidth::Narrow, 3500.0, "NB")
2218 };
2219 let mut enc = silk_encoder(bandwidth, None);
2220 let delay = enc.look_ahead(960);
2221 let (decoded, packets) = silk_roundtrip(&mut enc, pcm, 20);
2222 let reference = lowpass(pcm, band);
2223 let (corr, lag) = aligned_corr(&reference, &decoded, 2000);
2224 let bytes: usize = packets.iter().map(Vec::len).sum();
2225 eprintln!(
2226 "silk {name} {tag}: corr {corr:.4} at lag {lag} (look-ahead {delay}), {} kbps",
2227 bytes * 8 / (packets.len() * 20)
2228 );
2229 assert!(corr >= 0.8, "{name} {tag}: corr {corr:.4}");
2230
2231 // Reference oracle: the packets in an Ogg-Opus file decode cleanly.
2232 if Command::new("ffmpeg").arg("-version").output().is_ok() {
2233 let path = temp_path(&format!("silk-{name}-{tag}.opus"));
2234 write_ogg_opus(&path, &packets, opus_head(1, 120, None), 1, pcm.len(), 120);
2235 let out = Command::new("ffmpeg")
2236 .args(["-v", "warning", "-c:a", "libopus", "-i"])
2237 .arg(&path)
2238 .args(["-f", "null", "-"])
2239 .output()
2240 .unwrap();
2241 let stderr = String::from_utf8_lossy(&out.stderr);
2242 assert!(
2243 out.status.success() && stderr.trim().is_empty(),
2244 "{name} {tag}: ffmpeg: {stderr}"
2245 );
2246 let _ = fs::remove_file(&path);
2247 }
2248 }
2249 }
2250}
2251
2252#[test]
2253fn silk_mediumband_and_10ms_roundtrip() {
2254 let _timing = timing_shared();
2255 let pcm = speech_like();
2256 for (tag, bandwidth, frame_ms, config, cutoff, bps, floor) in [
2257 (
2258 "NB10",
2259 Bandwidth::Narrow,
2260 10usize,
2261 0u8,
2262 3500.0,
2263 12_000u32,
2264 0.86f64,
2265 ),
2266 ("MB10", Bandwidth::Medium, 10, 4, 5500.0, 16_000, 0.89),
2267 ("WB10", Bandwidth::Wide, 10, 8, 7000.0, 20_000, 0.89),
2268 ("MB20", Bandwidth::Medium, 20, 5, 5500.0, 16_000, 0.9),
2269 ] {
2270 let mut enc = silk_encoder(bandwidth, Some(bps));
2271 let (decoded, packets) = silk_roundtrip(&mut enc, &pcm, frame_ms);
2272 assert_eq!(packets[0][0] >> 3, config, "{tag}: wrong TOC config");
2273 let reference = lowpass(&pcm, cutoff);
2274 let (corr, lag) = aligned_corr(&reference, &decoded, 2000);
2275 let bytes: usize = packets.iter().map(Vec::len).sum();
2276 let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * frame_ms as f64);
2277 eprintln!(
2278 "silk {tag}: corr {corr:.4} at lag {lag}, {} frames, {kbps:.2} kbps",
2279 packets.len()
2280 );
2281 assert!(corr >= floor, "{tag}: corr {corr:.4}");
2282 if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len(), 120) {
2283 let (c, _) = aligned_corr(&oracle, &decoded, 2000);
2284 assert!(c >= 0.99, "{tag}: our decode vs oracle decode corr {c:.4}");
2285 }
2286 }
2287}
2288
2289#[test]
2290fn silk_multiframe_packets_roundtrip() {
2291 let _timing = timing_shared();
2292 let full = speech_like();
2293 let pcm = &full[..46_080];
2294 for (tag, bandwidth, frame_ms, config, cutoff, bps, floor) in [
2295 (
2296 "NB40",
2297 Bandwidth::Narrow,
2298 40usize,
2299 2u8,
2300 3500.0,
2301 16_000u32,
2302 0.9f64,
2303 ),
2304 ("MB40", Bandwidth::Medium, 40, 6, 5500.0, 20_000, 0.91),
2305 ("WB40", Bandwidth::Wide, 40, 10, 7000.0, 24_000, 0.91),
2306 ("WB60", Bandwidth::Wide, 60, 11, 7000.0, 24_000, 0.9),
2307 ] {
2308 let mut enc = silk_encoder(bandwidth, Some(bps));
2309 let (decoded, packets) = silk_roundtrip(&mut enc, pcm, frame_ms);
2310 let toc = ec_opus::Toc::new(packets[0][0]);
2311 assert_eq!(toc.config, config, "{tag}: wrong TOC config");
2312 assert_eq!(toc.code, 0, "{tag}: multiframe SILK uses one Opus frame");
2313 let reference = lowpass(pcm, cutoff);
2314 let (corr, lag) = aligned_corr(&reference, &decoded, 2500);
2315 let bytes: usize = packets.iter().map(Vec::len).sum();
2316 let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * frame_ms as f64);
2317 eprintln!(
2318 "silk {tag}: corr {corr:.4} at lag {lag}, {} frames, {kbps:.2} kbps",
2319 packets.len()
2320 );
2321 assert!(corr >= floor, "{tag}: corr {corr:.4} below {floor:.4}");
2322 if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len(), 120) {
2323 let (c, _) = aligned_corr(&oracle, &decoded, 2500);
2324 assert!(
2325 c >= 0.99,
2326 "{tag}: internal decode vs external decode corr {c:.4}"
2327 );
2328 }
2329 if Command::new("gst-launch-1.0")
2330 .arg("--version")
2331 .output()
2332 .is_ok()
2333 {
2334 let path = temp_path(&format!("silk-{tag}-gst.opus"));
2335 write_ogg_opus(&path, &packets, opus_head(1, 120, None), 1, pcm.len(), 120);
2336 let location = format!("location={}", path.display());
2337 let out = Command::new("gst-launch-1.0")
2338 .args([
2339 "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", "fakesink",
2340 ])
2341 .output()
2342 .unwrap();
2343 let stderr = String::from_utf8_lossy(&out.stderr);
2344 assert!(out.status.success(), "{tag}: gst decode: {stderr}");
2345 let _ = fs::remove_file(&path);
2346 }
2347 }
2348}
2349
2350fn stereo_speech_pair() -> Vec<f32> {
2351 let left = speech_like();
2352 let mut out = Vec::with_capacity(left.len() * 2);
2353 for (i, &l) in left.iter().enumerate() {
2354 let t = i as f64 / 48000.0;
2355 let r = 0.78 * l + 0.12 * (std::f64::consts::TAU * 310.0 * t).sin() as f32;
2356 out.push(l);
2357 out.push(r);
2358 }
2359 out
2360}
2361
2362fn aligned_channel_corr(reference: &[f32], decoded: &[f32], channels: usize, ch: usize) -> f64 {
2363 let b: Vec<f32> = decoded.chunks_exact(channels).map(|f| f[ch]).collect();
2364 aligned_corr(reference, &b, 2000).0
2365}
2366
2367#[test]
2368fn silk_stereo_speech_roundtrip() {
2369 let _timing = timing_shared();
2370 let pcm = stereo_speech_pair();
2371 let total = pcm.len() / 2;
2372 for (tag, bandwidth, per_channel_bps, cutoff, frame, config, code, frames) in [
2373 (
2374 "NB20",
2375 Bandwidth::Narrow,
2376 16_000u32,
2377 3500.0,
2378 960usize,
2379 1u8,
2380 0u8,
2381 1usize,
2382 ),
2383 ("MB20", Bandwidth::Medium, 20_000, 5500.0, 960, 5, 0, 1),
2384 ("WB20", Bandwidth::Wide, 24_000, 7000.0, 960, 9, 0, 1),
2385 ("NB40", Bandwidth::Narrow, 16_000, 3500.0, 1920, 2, 0, 1),
2386 ("MB40", Bandwidth::Medium, 20_000, 5500.0, 1920, 6, 0, 1),
2387 ("WB60", Bandwidth::Wide, 24_000, 7000.0, 2880, 11, 0, 1),
2388 ] {
2389 let frame_ms = frame / 48;
2390 let mono_frame_ms = frame_ms.min(20);
2391 let mut mono_floor = [0.0f64; 2];
2392 for ch in 0..2 {
2393 let mono: Vec<f32> = pcm.as_chunks::<2>().0.iter().map(|f| f[ch]).collect();
2394 let mut silk = silk_encoder(bandwidth, Some(per_channel_bps));
2395 let reference = lowpass(&mono, cutoff);
2396 let (decoded, _) = silk_roundtrip(&mut silk, &mono, mono_frame_ms);
2397 mono_floor[ch] = aligned_corr(&reference, &decoded, 2000).0;
2398 }
2399 let mut enc = Encoder::new(48000, 2, Application::Voip).unwrap();
2400 enc.set_mode(Some(ec_opus::Mode::Silk));
2401 enc.set_bandwidth(Some(bandwidth));
2402 enc.set_vbr_constrained(true);
2403 enc.set_bitrate(per_channel_bps * 2);
2404 let mut dec = Decoder::new(48000, 2).unwrap();
2405 let mut out = vec![0u8; 4096];
2406 let mut buf = vec![0.0f32; 5760 * 2];
2407 let mut decoded = Vec::new();
2408 let mut packets = Vec::new();
2409 let mut padded = pcm.clone();
2410 padded.resize(pcm.len().div_ceil(frame * 2) * frame * 2 + frame * 2, 0.0);
2411 for block in padded.chunks(frame * 2) {
2412 let len = enc.encode_float(block, frame, &mut out).expect("encode");
2413 let packet = Packet::parse(&out[..len], false).unwrap();
2414 let toc = packet.toc;
2415 assert_eq!(toc.config, config, "{tag}: wrong TOC config");
2416 assert_eq!(toc.code, code, "{tag}: wrong TOC code");
2417 assert_eq!(packet.frames.len(), frames, "{tag}: frame count");
2418 assert_eq!(packet.samples_48k(), frame, "{tag}: packet samples");
2419 assert!(toc.stereo, "{tag}: SILK TOC is not stereo");
2420 let n = dec.decode_float(&out[..len], &mut buf).expect("decode");
2421 assert_eq!(n, frame, "{tag}: decoded frame size");
2422 assert_eq!(dec.final_range(), enc.final_range(), "{tag}: range state");
2423 decoded.extend_from_slice(&buf[..n * 2]);
2424 packets.push(out[..len].to_vec());
2425 }
2426 let bytes: usize = packets.iter().map(Vec::len).sum();
2427 let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * frame_ms as f64);
2428 for ch in 0..2 {
2429 let source: Vec<f32> = pcm.as_chunks::<2>().0.iter().map(|f| f[ch]).collect();
2430 let reference = lowpass(&source, cutoff);
2431 let corr = aligned_channel_corr(&reference, &decoded, 2, ch);
2432 eprintln!(
2433 "silk stereo {tag} ch{ch}: corr {corr:.4}, mono {:.4}, {kbps:.2} kbps",
2434 mono_floor[ch]
2435 );
2436 assert!(
2437 corr + 0.01 >= mono_floor[ch],
2438 "{tag} ch{ch}: stereo corr {corr:.4} trails mono {:.4}",
2439 mono_floor[ch]
2440 );
2441 }
2442 if Command::new("ffmpeg").arg("-version").output().is_ok() {
2443 let path = temp_path(&format!("silk-stereo-{tag}.opus"));
2444 write_ogg_opus(
2445 &path,
2446 &packets,
2447 opus_head(2, enc.look_ahead(frame) as u16, None),
2448 2,
2449 total,
2450 enc.look_ahead(frame) as i64,
2451 );
2452 let out = Command::new("ffmpeg")
2453 .args(["-v", "warning", "-c:a", "libopus", "-i"])
2454 .arg(&path)
2455 .args(["-f", "null", "-"])
2456 .output()
2457 .unwrap();
2458 let stderr = String::from_utf8_lossy(&out.stderr);
2459 assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}");
2460 if Command::new("gst-launch-1.0")
2461 .arg("--version")
2462 .output()
2463 .is_ok()
2464 {
2465 let location = format!("location={}", path.display());
2466 let out = Command::new("gst-launch-1.0")
2467 .args([
2468 "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!",
2469 "fakesink",
2470 ])
2471 .output()
2472 .unwrap();
2473 let stderr = String::from_utf8_lossy(&out.stderr);
2474 assert!(out.status.success(), "{tag}: gst decode: {stderr}");
2475 }
2476 let _ = fs::remove_file(&path);
2477 }
2478 }
2479}
2480/// Reference oracle decode of `packets` as Ogg-Opus, or `None` without ffmpeg.
2481/// `pre_skip` must be the encoder's advertised [`Encoder::look_ahead`] for
2482/// these packets: it is what the oracle trims off the front, so a caller that
2483/// compares sample-for-sample against its own decode at that same offset only
2484/// lines up when the two agree.
2485fn oracle_decode(
2486 name: &str,
2487 packets: &[Vec<u8>],
2488 samples: usize,
2489 pre_skip: usize,
2490) -> Option<Vec<f32>> {
2491 if Command::new("ffmpeg").arg("-version").output().is_err() {
2492 return None;
2493 }
2494 let path = temp_path(&format!("{name}.opus"));
2495 write_ogg_opus(
2496 &path,
2497 packets,
2498 opus_head(1, pre_skip as u16, None),
2499 1,
2500 samples,
2501 pre_skip as i64,
2502 );
2503 let out = Command::new("ffmpeg")
2504 .args(["-v", "warning", "-c:a", "libopus", "-i"])
2505 .arg(&path)
2506 .args(["-f", "null", "-"])
2507 .output()
2508 .unwrap();
2509 let stderr = String::from_utf8_lossy(&out.stderr);
2510 assert!(
2511 out.status.success() && stderr.trim().is_empty(),
2512 "{name}: ffmpeg: {stderr}"
2513 );
2514 let decoded = ffmpeg_decode(&path, 1);
2515 let _ = fs::remove_file(&path);
2516 decoded
2517}
2518
2519fn silk_sources() -> Vec<(&'static str, Vec<f32>)> {
2520 let wav = fixture("wav16-mono-48000.wav");
2521 let mut sources = vec![("synthetic", speech_like())];
2522 if wav.exists() {
2523 let w = read_wav_mono(&wav);
2524 sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec()));
2525 }
2526 sources
2527}
2528
2529/// The public `Encoder` (Voip, mono) routes `set_bitrate` into the SILK
2530/// path it dispatches to.
2531#[test]
2532fn silk_packets_track_encoder_bitrate() {
2533 let _timing = timing_shared();
2534 let pcm = test_signal(1, 2.0);
2535 for kbps_target in [8u32, 12, 16] {
2536 let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap();
2537 enc.set_bitrate(kbps_target * 1000);
2538 let packets = encode_packets(&mut enc, &pcm, 1);
2539 let bytes: usize = packets.iter().map(Vec::len).sum();
2540 let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0);
2541 eprintln!("encoder bitrate target {kbps_target}: {kbps:.2} kbps");
2542 let ratio = kbps / kbps_target as f64;
2543 assert!(
2544 (0.8..=1.2).contains(&ratio),
2545 "target {kbps_target}: got {kbps:.2} kbps"
2546 );
2547 }
2548}
2549
2550// ---------------------------------------------------------------------------
2551// Hybrid (SILK 16 kHz + CELT from band 17, one range-coded stream).
2552
2553/// Encodes mono `pcm` as hybrid packets at `bps` and decodes them with our
2554/// decoder, `mute` = (celt, silk) layers dropped at the decoder; asserts
2555/// range-state parity packet for packet. Returns (decoded, packets).
2556fn hybrid_roundtrip(
2557 pcm: &[f32],
2558 bps: u32,
2559 bandwidth: Option<Bandwidth>,
2560 mute: (bool, bool),
2561) -> (Vec<f32>, Vec<Vec<u8>>) {
2562 let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap();
2563 enc.set_bitrate(bps);
2564 enc.set_bandwidth(bandwidth);
2565 let mut dec = Decoder::new(48000, 1).unwrap();
2566 dec.debug_mute_layers(mute.0, mute.1);
2567 let mut out = vec![0u8; 1500];
2568 let mut buf = vec![0f32; 5760];
2569 let (mut decoded, mut packets) = (Vec::new(), Vec::new());
2570 let mut padded = pcm.to_vec();
2571 padded.resize(pcm.len().div_ceil(960) * 960 + 960, 0.0);
2572 for block in padded.chunks(960) {
2573 let len = enc
2574 .encode_float(block, 960, &mut out)
2575 .expect("hybrid encode");
2576 let n = dec
2577 .decode_float(&out[..len], &mut buf)
2578 .expect("hybrid decode");
2579 assert_eq!(n, 960);
2580 assert_eq!(dec.final_range(), enc.final_range(), "range state diverged");
2581 decoded.extend_from_slice(&buf[..n]);
2582 packets.push(out[..len].to_vec());
2583 }
2584 (decoded, packets)
2585}
2586
2587/// The two layers of a hybrid packet reach the decoder's output at the same
2588/// delay: a click's low-band-only and high-band-only peaks coincide at the
2589/// encoder's documented look-ahead.
2590/// The delay [`hybrid_roundtrip`]'s encoder advertises for a 20 ms frame —
2591/// [`Encoder::look_ahead`] of that same configuration, so the lag assertions
2592/// track the layer's real delay instead of a constant.
2593fn hybrid_delay(bps: u32) -> usize {
2594 let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap();
2595 enc.set_bitrate(bps);
2596 enc.look_ahead(960)
2597}
2598
2599#[test]
2600fn hybrid_layers_align() {
2601 let _timing = timing_shared();
2602 let mut click = vec![0f32; 48000];
2603 // Well inside the stream so both layers' predictors are running.
2604 let at = 960 * 10 + 300;
2605 click[at] = 0.9;
2606 let peak = |x: &[f32]| {
2607 x.iter()
2608 .enumerate()
2609 .max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap())
2610 .unwrap()
2611 .0
2612 };
2613 let (lb, _) = hybrid_roundtrip(&click, 32_000, None, (true, false));
2614 let (hb, _) = hybrid_roundtrip(&click, 32_000, None, (false, true));
2615 let delay = hybrid_delay(32_000) as i64;
2616 let (plb, phb) = (peak(&lb) as i64 - at as i64, peak(&hb) as i64 - at as i64);
2617 eprintln!("hybrid click: LB peak +{plb}, HB peak +{phb}, look_ahead {delay}");
2618 // A fullband CELT click lands at exactly the encoder's advertised delay
2619 // (`celt_click_peak_offset`); the band-limited HB layer's main lobe sits
2620 // up to 2 samples early once transient frames keep their short blocks,
2621 // and SILK lands one sample late.
2622 assert!(
2623 (plb - phb).abs() <= 3,
2624 "layers misaligned: LB +{plb} vs HB +{phb}"
2625 );
2626 assert!(
2627 (phb - delay).abs() <= 2,
2628 "HB peak +{phb}, look_ahead {delay}"
2629 );
2630}
2631
2632/// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks
2633/// the input full-band and in the SILK layer's band alone, and the reference
2634/// oracle decodes the packets to the same signal.
2635///
2636/// The delay [`hybrid_roundtrip`]'s encoder advertises for a 20 ms frame is
2637/// [`Encoder::look_ahead`] of that same configuration, never a constant.
2638#[test]
2639fn hybrid_fb_roundtrip() {
2640 let _timing = timing_shared();
2641 for (name, pcm) in silk_sources() {
2642 let (decoded, packets) = hybrid_roundtrip(&pcm, 32_000, None, (false, false));
2643 let toc = ec_opus::Toc::new(packets[0][0]);
2644 assert_eq!(toc.config, 15, "{name}: TOC config {}", toc.config);
2645 let (corr, lag) = aligned_corr(&pcm, &decoded, 400);
2646 let (lb_only, _) = hybrid_roundtrip(&pcm, 32_000, None, (true, false));
2647 let lb_ref = lowpass(&pcm, 7000.0);
2648 let (lb_corr, lb_lag) = aligned_corr(&lb_ref, &lb_only, 400);
2649 let bytes: usize = packets.iter().map(Vec::len).sum();
2650 let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0);
2651 eprintln!(
2652 "hybrid FB {name}: corr {corr:.4} at lag {lag}, LB corr {lb_corr:.4} at lag {lb_lag}, {kbps:.1} kbps"
2653 );
2654 assert!(corr >= 0.9, "{name}: full-band corr {corr:.4}");
2655 let delay = hybrid_delay(32_000);
2656 assert!(
2657 (delay - 6..=delay + 6).contains(&lag),
2658 "{name}: aligned at lag {lag}, not the advertised {delay}"
2659 );
2660 assert!(lb_corr >= 0.9, "{name}: low-band corr {lb_corr:.4}");
2661 assert!(
2662 (28.0..=36.0).contains(&kbps),
2663 "{name}: {kbps:.1} kbps for a 32 kbps CBR target"
2664 );
2665 if let Some(oracle) = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len(), delay) {
2666 let n = oracle.len().min(decoded.len() - delay);
2667 let c = correlation(&oracle[..n], &decoded[delay..delay + n]);
2668 eprintln!("hybrid FB {name}: oracle vs ours corr {c:.4}");
2669 assert!(c >= 0.95, "{name}: oracle corr {c:.4}");
2670 }
2671 }
2672 // SWB when asked for it, and the rest of the automatic hybrid range
2673 // (SILK's share leaves CELT least at the bottom of it).
2674 let speech = speech_like();
2675 let (_, packets) =
2676 hybrid_roundtrip(&speech, 24_000, Some(Bandwidth::SuperWide), (false, false));
2677 assert_eq!(ec_opus::Toc::new(packets[0][0]).config, 13);
2678 for bps in [20_000u32, 24_000, 39_000] {
2679 let (decoded, packets) = hybrid_roundtrip(&speech, bps, None, (false, false));
2680 let (corr, _) = aligned_corr(&speech, &decoded, 400);
2681 let kbps = packets.iter().map(Vec::len).sum::<usize>() as f64 * 8.0
2682 / (packets.len() as f64 * 20.0);
2683 eprintln!(
2684 "hybrid {bps}: config {}, corr {corr:.4}, {kbps:.1} kbps",
2685 ec_opus::Toc::new(packets[0][0]).config
2686 );
2687 assert!(corr >= 0.9, "hybrid at {bps}: corr {corr:.4}");
2688 assert!(
2689 kbps <= bps as f64 / 1000.0 + 3.0,
2690 "hybrid at {bps}: {kbps:.1} kbps"
2691 );
2692 }
2693}
2694
2695fn hybrid_roundtrip_shape(
2696 pcm: &[f32],
2697 channels: usize,
2698 frame: usize,
2699 bps: u32,
2700 bandwidth: Option<Bandwidth>,
2701) -> (Vec<f32>, Vec<Vec<u8>>) {
2702 let mut enc = Encoder::new(48000, channels, Application::Voip).unwrap();
2703 enc.set_bitrate(bps);
2704 enc.set_bandwidth(bandwidth);
2705 let mut dec = Decoder::new(48000, channels).unwrap();
2706 let mut out = vec![0u8; 1500];
2707 let mut buf = vec![0f32; 5760 * channels];
2708 let (mut decoded, mut packets) = (Vec::new(), Vec::new());
2709 let mut padded = pcm.to_vec();
2710 padded.resize(
2711 pcm.len().div_ceil(frame * channels) * frame * channels + frame * channels,
2712 0.0,
2713 );
2714 for block in padded.chunks(frame * channels) {
2715 let len = enc
2716 .encode_float(block, frame, &mut out)
2717 .expect("hybrid encode");
2718 let n = dec
2719 .decode_float(&out[..len], &mut buf)
2720 .expect("hybrid decode");
2721 assert_eq!(n, frame);
2722 assert_eq!(dec.final_range(), enc.final_range(), "range state diverged");
2723 decoded.extend_from_slice(&buf[..n * channels]);
2724 packets.push(out[..len].to_vec());
2725 }
2726 (decoded, packets)
2727}
2728
2729#[test]
2730fn hybrid_shapes_roundtrip() {
2731 let _timing = timing_shared();
2732 for (tag, channels, frame, bps, bandwidth, config, floor) in [
2733 (
2734 "mono-swb10",
2735 1usize,
2736 480usize,
2737 24_000u32,
2738 Bandwidth::SuperWide,
2739 12u8,
2740 0.75f64,
2741 ),
2742 ("mono-fb10", 1, 480, 32_000, Bandwidth::Full, 14, 0.75),
2743 (
2744 "stereo-swb20",
2745 2,
2746 960,
2747 48_000,
2748 Bandwidth::SuperWide,
2749 13,
2750 0.75,
2751 ),
2752 ("stereo-fb20", 2, 960, 64_000, Bandwidth::Full, 15, 0.75),
2753 ("stereo-fb10", 2, 480, 64_000, Bandwidth::Full, 14, 0.70),
2754 ] {
2755 let pcm = if channels == 1 {
2756 speech_like()
2757 } else {
2758 stereo_speech_pair()
2759 };
2760 let (decoded, packets) =
2761 hybrid_roundtrip_shape(&pcm, channels, frame, bps, Some(bandwidth));
2762 let toc = ec_opus::Toc::new(packets[0][0]);
2763 assert_eq!(toc.config, config, "{tag}: TOC config {}", toc.config);
2764 assert_eq!(toc.stereo, channels == 2, "{tag}: TOC stereo flag");
2765 let mut worst = 1.0f64;
2766 for ch in 0..channels {
2767 let source: Vec<f32> = pcm.chunks_exact(channels).map(|f| f[ch]).collect();
2768 let got: Vec<f32> = decoded.chunks_exact(channels).map(|f| f[ch]).collect();
2769 let (corr, lag) = aligned_corr(&source, &got, 400);
2770 worst = worst.min(corr);
2771 eprintln!("hybrid {tag} ch{ch}: corr {corr:.4} at lag {lag}");
2772 }
2773 assert!(worst >= floor, "{tag}: worst corr {worst:.4}");
2774 let total = pcm.len() / channels;
2775 let path = temp_path(&format!("hybrid-{tag}.opus"));
2776 // The pre-skip is what `hybrid_roundtrip_shape`'s own encoder
2777 // advertises for this frame size, not a constant.
2778 let pre_skip = {
2779 let mut e = Encoder::new(48000, channels, Application::Voip).unwrap();
2780 e.set_bitrate(bps);
2781 e.look_ahead(frame)
2782 };
2783 write_ogg_opus(
2784 &path,
2785 &packets,
2786 opus_head(channels, pre_skip as u16, None),
2787 channels,
2788 total,
2789 pre_skip as i64,
2790 );
2791 if Command::new("ffmpeg").arg("-version").output().is_ok() {
2792 let out = Command::new("ffmpeg")
2793 .args(["-v", "warning", "-c:a", "libopus", "-i"])
2794 .arg(&path)
2795 .args(["-f", "null", "-"])
2796 .output()
2797 .unwrap();
2798 let stderr = String::from_utf8_lossy(&out.stderr);
2799 assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}");
2800 }
2801 if Command::new("gst-launch-1.0")
2802 .arg("--version")
2803 .output()
2804 .is_ok()
2805 {
2806 let location = format!("location={}", path.display());
2807 let out = Command::new("gst-launch-1.0")
2808 .args([
2809 "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", "fakesink",
2810 ])
2811 .output()
2812 .unwrap();
2813 let stderr = String::from_utf8_lossy(&out.stderr);
2814 assert!(out.status.success(), "{tag}: gst decode: {stderr}");
2815 }
2816 let _ = fs::remove_file(&path);
2817 }
2818
2819 let speech = stereo_speech_pair();
2820 let (_, packets) = hybrid_roundtrip_shape(&speech, 2, 960, 64_000, None);
2821 let toc = ec_opus::Toc::new(packets[0][0]);
2822 assert_eq!(toc.mode(), ec_opus::Mode::Hybrid);
2823 assert!(toc.stereo);
2824}
2825
2826// ---------------------------------------------------------------------------
2827// Encoder library gate vs ffmpeg libopus (encoders-only comparison)
2828// ---------------------------------------------------------------------------
2829//
2830// Both the ec-opus encoder and ffmpeg's libopus encoder encode the same real
2831// source PCM; BOTH bitstreams are decoded through ec-opus's own decoder, so
2832// the gap isolates the encoders (the decoder is held constant). A 14-row sweep
2833// (7 real sources × {64, 96} kbps) lands in `lanes/opus-gate-r1.sweep.txt`.
2834// `#[ignore]`'d: it shells out to ffmpeg and walks a multi-gigabyte library.
2835
2836/// Expand a leading `~` to the home directory (the std `Path` API cannot).
2837fn shellexpand(p: &str) -> PathBuf {
2838 if let Some(rest) = p.strip_prefix("~/")
2839 && let Some(home) = std::env::var_os("HOME")
2840 {
2841 return PathBuf::from(home).join(rest);
2842 }
2843 PathBuf::from(p)
2844}
2845
2846/// Decode any source into interleaved f32, 48 kHz, stereo, capped at `secs`.
2847fn ffmpeg_decode_pcm(path: &Path, secs: f64) -> Vec<f32> {
2848 let out = Command::new("ffmpeg")
2849 .args(["-v", "error", "-i"])
2850 .arg(path)
2851 .args([
2852 "-vn",
2853 "-t",
2854 &format!("{secs}"),
2855 "-ac",
2856 "2",
2857 "-ar",
2858 "48000",
2859 "-f",
2860 "f32le",
2861 "-acodec",
2862 "pcm_f32le",
2863 "-",
2864 ])
2865 .output()
2866 .expect("ffmpeg runs");
2867 assert!(
2868 out.status.success(),
2869 "ffmpeg source decode failed for {}: {}",
2870 path.display(),
2871 String::from_utf8_lossy(&out.stderr)
2872 );
2873 out.stdout
2874 .as_chunks::<4>()
2875 .0
2876 .iter()
2877 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
2878 .collect()
2879}
2880
2881/// Encode `src` to an Ogg/Opus file with ffmpeg's libopus at `kbps` (VBR on),
2882/// capped at `secs`. The realised rate is read back from the output file size.
2883fn ffmpeg_encode_libopus(src: &Path, kbps: u32, out: &Path, secs: f64) {
2884 let res = Command::new("ffmpeg")
2885 .args(["-y", "-v", "error", "-i"])
2886 .arg(src)
2887 .args([
2888 "-vn",
2889 "-t",
2890 &format!("{secs}"),
2891 "-ac",
2892 "2",
2893 "-ar",
2894 "48000",
2895 "-c:a",
2896 "libopus",
2897 "-b:a",
2898 &format!("{kbps}k"),
2899 "-vbr",
2900 "on",
2901 ])
2902 .arg(out)
2903 .output()
2904 .expect("ffmpeg runs");
2905 assert!(
2906 res.status.success(),
2907 "ffmpeg libopus encode failed for {} at {kbps}k: {}",
2908 src.display(),
2909 String::from_utf8_lossy(&res.stderr)
2910 );
2911}
2912
2913/// Lag-scan `decoded` against `source` over ±`max_lag` samples by mean-channel
2914/// correlation, then emit a `source`-length aligned copy of `decoded`. The lag
2915/// search runs on the first 10 s only (the task spec) — the encoder/decoder
2916/// algorithmic delay is constant, so the peak found there holds for the whole
2917/// file — and the correlation is computed inline without per-lag allocations.
2918/// The delay lands the peak at a positive lag; the symmetric scan keeps the
2919/// gate honest if a reference decoder shifts the other way.
2920fn align_to_source(
2921 source: &[f32],
2922 decoded: &[f32],
2923 channels: usize,
2924 max_lag: usize,
2925) -> (i32, Vec<f32>) {
2926 let sf = source.len() / channels;
2927 let df = decoded.len() / channels;
2928 let scan_frames = sf.min(df).min(48000 * 10);
2929 let scan = max_lag.min(scan_frames);
2930 let mut best = -1.0f64;
2931 let mut best_lag = 0i32;
2932 for lag in -(scan as i32)..=(scan as i32) {
2933 let i0 = if lag < 0 { (-lag) as usize } else { 0 };
2934 let j0 = if lag < 0 { 0 } else { lag as usize };
2935 let len = scan_frames.saturating_sub(i0.max(j0));
2936 if len < 4800 {
2937 continue;
2938 }
2939 let mut cacc = 0.0f64;
2940 for ch in 0..channels {
2941 let (mut sxy, mut sxx, mut syy) = (0.0f64, 0.0f64, 0.0f64);
2942 for i in 0..len {
2943 let a = source[(i0 + i) * channels + ch] as f64;
2944 let b = decoded[(j0 + i) * channels + ch] as f64;
2945 sxy += a * b;
2946 sxx += a * a;
2947 syy += b * b;
2948 }
2949 if sxx > 0.0 && syy > 0.0 {
2950 cacc += sxy / (sxx * syy).sqrt();
2951 }
2952 }
2953 let c = cacc / channels as f64;
2954 if c > best {
2955 best = c;
2956 best_lag = lag;
2957 }
2958 }
2959 // Build a source-length aligned copy using the chosen lag.
2960 let mut aligned = vec![0.0f32; sf * channels];
2961 let i0 = if best_lag < 0 {
2962 (-best_lag) as usize
2963 } else {
2964 0
2965 };
2966 let j0 = if best_lag < 0 { 0 } else { best_lag as usize };
2967 let len = sf.saturating_sub(i0).min(df.saturating_sub(j0));
2968 for i in 0..len {
2969 for ch in 0..channels {
2970 aligned[(i0 + i) * channels + ch] = decoded[(j0 + i) * channels + ch];
2971 }
2972 }
2973 (best_lag, aligned)
2974}
2975
2976/// Mean-channel normalized cross-correlation between two interleaved signals,
2977/// computed inline (no per-channel Vec allocation).
2978fn corr_interleaved(a: &[f32], b: &[f32], channels: usize) -> f64 {
2979 let n = (a.len() / channels).min(b.len() / channels);
2980 let mut acc = 0.0f64;
2981 for ch in 0..channels {
2982 let (mut sxy, mut sxx, mut syy) = (0.0f64, 0.0f64, 0.0f64);
2983 for i in 0..n {
2984 let av = a[i * channels + ch] as f64;
2985 let bv = b[i * channels + ch] as f64;
2986 sxy += av * bv;
2987 sxx += av * av;
2988 syy += bv * bv;
2989 }
2990 if sxx > 0.0 && syy > 0.0 {
2991 acc += sxy / (sxx * syy).sqrt();
2992 }
2993 }
2994 acc / channels as f64
2995}
2996
2997/// Per-second correlation statistics: `(min_second_corr, seconds_below_0.9)`,
2998/// computed inline without per-second Vec allocation.
2999fn per_second_corr(source: &[f32], decoded: &[f32], channels: usize) -> (f64, u32) {
3000 let n = (source.len() / channels).min(decoded.len() / channels);
3001 let sec = 48000usize;
3002 let mut min_c = 1.0f64;
3003 let mut drops = 0u32;
3004 let mut start = 0usize;
3005 while start + sec <= n {
3006 let mut acc = 0.0f64;
3007 for ch in 0..channels {
3008 let (mut sxy, mut sxx, mut syy) = (0.0f64, 0.0f64, 0.0f64);
3009 for i in 0..sec {
3010 let a = source[(start + i) * channels + ch] as f64;
3011 let b = decoded[(start + i) * channels + ch] as f64;
3012 sxy += a * b;
3013 sxx += a * a;
3014 syy += b * b;
3015 }
3016 if sxx > 0.0 && syy > 0.0 {
3017 acc += sxy / (sxx * syy).sqrt();
3018 }
3019 }
3020 let c = acc / channels as f64;
3021 min_c = min_c.min(c);
3022 if c < 0.9 {
3023 drops += 1;
3024 }
3025 start += sec;
3026 }
3027 (min_c, drops)
3028}
3029
3030#[test]
3031#[ignore = "library gate: hand-run 14-row sweep, 120s per source, needs ffmpeg libopus and the local ~/Music corpus (~12 min); the reelm@64k dropout that first failed it is fixed per lanes/opus-drop-r2.report.md, so only the corpus dependency keeps it out of the default suite"]
3032fn encoder_library_gate_vs_libopus() {
3033 let _timing = timing_shared();
3034 const SECS: f64 = 120.0; // 2 min cap; full 600s made the 14-row sweep infeasible
3035 const FRAME: usize = 960; // 20 ms at 48 kHz
3036 const CHANNELS: usize = 2;
3037 const MAX_LAG: usize = 2000;
3038
3039 let sources: &[(&str, &str)] = &[
3040 ("nik", "~/Music/reeln.mp4"),
3041 ("reelo", "~/Music/reelo.mp3"),
3042 ("her", "~/Music/reeli.mp3"),
3043 ("reell", "~/Music/reell.mp4"),
3044 ("reelm", "~/Music/reelm.wav"),
3045 ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
3046 ("hein", "~/Downloads/reelm.mp3"),
3047 ];
3048 let only: Vec<String> = std::env::var("SWEEP_ONLY")
3049 .unwrap_or_default()
3050 .split(',')
3051 .filter(|s| !s.is_empty())
3052 .map(|s| s.trim().to_owned())
3053 .collect();
3054 let sources: Vec<(String, PathBuf)> = sources
3055 .iter()
3056 .filter(|(tag, _)| only.is_empty() || only.iter().any(|o| o == tag))
3057 .map(|(tag, p)| (tag.to_string(), shellexpand(p)))
3058 .collect();
3059 assert!(!sources.is_empty(), "SWEEP_ONLY matched no sources");
3060
3061 let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes");
3062 fs::create_dir_all(&lanes_dir).unwrap();
3063 let sweep_path = lanes_dir.join("opus-gate-r1.sweep.txt");
3064 let scratch = lanes_dir.join("opus-gate-r1.scratch.ogg");
3065
3066 let mut rows: Vec<String> = Vec::new();
3067 let mut rate_violations: Vec<String> = Vec::new();
3068 let mut dropout_violations: Vec<String> = Vec::new();
3069
3070 for (tag, src) in &sources {
3071 if !src.exists() {
3072 eprintln!("SKIP {tag}: missing {}", src.display());
3073 continue;
3074 }
3075 let source_pcm = ffmpeg_decode_pcm(src, SECS);
3076 let source_frames = source_pcm.len() / CHANNELS;
3077 assert!(source_frames > 48_000, "{tag}: source too short");
3078 let seconds = source_frames as f64 / 48000.0;
3079 let source_i16 = to_i16(&source_pcm);
3080
3081 for &kbps in &[64u32, 96u32] {
3082 // Reference: ffmpeg libopus, VBR on, realised rate from file size.
3083 ffmpeg_encode_libopus(src, kbps, &scratch, SECS);
3084 let ref_bytes = fs::metadata(&scratch)
3085 .map(|m| m.len() as usize)
3086 .unwrap_or(0);
3087 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
3088 let (ref_dec, ref_ch) = decode_ogg(&scratch);
3089 assert_eq!(ref_ch, CHANNELS, "{tag}@{kbps}: ref not stereo");
3090 let (_, ref_aligned) = align_to_source(&source_pcm, &ref_dec, CHANNELS, MAX_LAG);
3091
3092 // Ours: ec-opus encoder at the reference's realised rate, decoded
3093 // by our own decoder; payload bytes give the realised rate.
3094 let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder");
3095 enc.set_bitrate((ref_kbps * 1000.0).round() as u32);
3096 enc.set_vbr_constrained(true);
3097 let (ours_dec, ours_bytes) = roundtrip_own(&mut enc, &source_pcm, CHANNELS, FRAME);
3098 let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0;
3099 // Drop the zero-padded tail of the final frame to match the source.
3100 let ours_trim: Vec<f32> = ours_dec
3101 .into_iter()
3102 .take(source_frames * CHANNELS)
3103 .collect();
3104 let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
3105 let ours_i16 = to_i16(&ours_aligned);
3106 let ref_i16 = to_i16(&ref_aligned);
3107
3108 // Equal-length i16 inputs for opus_compare (trim to common length).
3109 let cmp_frames = (source_i16.len() / CHANNELS)
3110 .min(ours_i16.len() / CHANNELS)
3111 .min(ref_i16.len() / CHANNELS);
3112 let trim = |v: &[i16]| -> Vec<i16> { v[..cmp_frames * CHANNELS].to_vec() };
3113 let s_i = trim(&source_i16);
3114 let o_i = trim(&ours_i16);
3115 let r_i = trim(&ref_i16);
3116 let q_ours = opus_compare(&s_i, &o_i, CHANNELS);
3117 let q_ref = opus_compare(&s_i, &r_i, CHANNELS);
3118 let err_ours = opus_compare_err(&s_i, &o_i, CHANNELS);
3119 let err_ref = opus_compare_err(&s_i, &r_i, CHANNELS);
3120 let err_ratio = if err_ref > 0.0 {
3121 err_ours / err_ref
3122 } else {
3123 f64::INFINITY
3124 };
3125
3126 let corr_ours = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS);
3127 let corr_ref = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS);
3128 let gap = corr_ref - corr_ours;
3129 let (minsec_ours, drop_ours) = per_second_corr(&source_pcm, &ours_aligned, CHANNELS);
3130 let (minsec_ref, drop_ref) = per_second_corr(&source_pcm, &ref_aligned, CHANNELS);
3131 let rate_pct = (ours_kbps / ref_kbps - 1.0) * 100.0;
3132
3133 if rate_pct.abs() > 5.0 {
3134 rate_violations.push(format!("{tag}@{kbps}k: rate {rate_pct:+.1}% (|>5%)"));
3135 }
3136 // Dropout gate: ours must not lose a second the reference kept.
3137 if drop_ours > 0 && drop_ref == 0 {
3138 dropout_violations.push(format!(
3139 "{tag}@{kbps}k: ours dropped {drop_ours}s below 0.9 corr, ref 0s"
3140 ));
3141 }
3142
3143 println!(
3144 "{tag}@{kbps}k: ref {ref_kbps:.1} ours {ours_kbps:.1} kbps ({rate_pct:+.1}%), \
3145 corr o={corr_ours:.4} r={corr_ref:.4} gap={gap:+.4}, \
3146 Q o={q_ours:.2} r={q_ref:.2}, err_ratio {err_ratio:.3}, \
3147 minsec o={minsec_ours:.4} r={minsec_ref:.4}, drop o={drop_ours} r={drop_ref}"
3148 );
3149 rows.push(format!(
3150 "{tag}\t{kbps}\t{ours_kbps:.1}\t{ref_kbps:.1}\t{rate_pct:+.1}\t\
3151 {corr_ours:.4}\t{corr_ref:.4}\t{gap:+.4}\t\
3152 {q_ours:.2}\t{q_ref:.2}\t{err_ratio:.3}\t\
3153 {minsec_ours:.4}\t{minsec_ref:.4}\t{drop_ours}\t{drop_ref}"
3154 ));
3155 }
3156 }
3157 let _ = fs::remove_file(&scratch);
3158
3159 let mut table = String::new();
3160 table.push_str("# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1)\n");
3161 table.push_str("# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo\n");
3162 table.push_str(
3163 "# source\tkbps\tours_kbps\tref_kbps\trate%\tcorr_ours\tcorr_ref\tgap\t\
3164 Q_ours\tQ_ref\terr_ratio\tminsec_ours\tminsec_ref\tdrop_ours\tdrop_ref\n",
3165 );
3166 for r in &rows {
3167 table.push_str(r);
3168 table.push('\n');
3169 }
3170 fs::write(&sweep_path, table).unwrap();
3171 println!("wrote {}", sweep_path.display());
3172
3173 // Rate gate: report violations, never panic.
3174 if !rate_violations.is_empty() {
3175 eprintln!("RATE GATE violations (|rate%| > 5):");
3176 for v in &rate_violations {
3177 eprintln!(" {v}");
3178 }
3179 } else {
3180 println!("RATE GATE: all rows within ±5%");
3181 }
3182 // Dropout gate: hard fail — a second the reference kept must not drop out.
3183 assert!(
3184 dropout_violations.is_empty(),
3185 "DROPOUT GATE failed (ours dropped seconds ref kept):\n {}",
3186 dropout_violations.join("\n ")
3187 );
3188 println!("DROPOUT GATE: passed (no ours-only dropouts)");
3189}
3190
3191// ---------------------------------------------------------------------------
3192// SILK / speech-rate library gate vs libopus (lane opus-silk r1).
3193//
3194// Source: ~/Music/reelm.wav (real interview speech) downmixed to MONO. Rows:
3195// 12k NB, 16k NB, 24k WB (SILK), 32k hybrid. Ours via Encoder::new(48000, 1,
3196// Application::Voip) with set_bitrate and set_bandwidth/set_mode as needed so
3197// Voip really picks SILK/Hybrid — the mode each row took is printed from the
3198// first packet's TOC config byte (RFC 6716 §3.1). Reference: ffmpeg libopus
3199// -application voip -b:a <rate>, mono, VBR on. RATE GATE ±5%, DROPOUT GATE.
3200// SIGN RULE (verbatim): gap = ref_corr - ours_corr; MORE NEGATIVE = OURS BETTER.
3201// Run: cargo test -p ec-opus --release --test conformance \
3202// silk_library_gate_vs_libopus -- --ignored --nocapture
3203// ---------------------------------------------------------------------------
3204
3205/// Mode label from a packet's TOC config byte (RFC 6716 §3.1): config = toc>>3.
3206fn toc_mode_label(toc: u8) -> &'static str {
3207 match toc >> 3 {
3208 0..=3 => "SILK-NB",
3209 4..=7 => "SILK-MB",
3210 8..=11 => "SILK-WB",
3211 12 | 13 => "Hybrid-SWB",
3212 14 | 15 => "Hybrid-FB",
3213 16..=31 => "CELT",
3214 _ => "??",
3215 }
3216}
3217
3218// corner-cut: near-duplicate of ffmpeg_decode_pcm / ffmpeg_encode_libopus with
3219// -ac 1 and -application voip. Parameterising the existing helpers would touch
3220// the stereo gate's callsites; keep this lane self-contained. Ceiling: only the
3221// SILK gate needs mono voip — merge when a second mono consumer appears.
3222/// Decode any source into interleaved f32, 48 kHz, MONO, capped at `secs`.
3223fn ffmpeg_decode_pcm_mono(path: &Path, secs: f64) -> Vec<f32> {
3224 let out = Command::new("ffmpeg")
3225 .args(["-v", "error", "-i"])
3226 .arg(path)
3227 .args([
3228 "-vn",
3229 "-t",
3230 &format!("{secs}"),
3231 "-ac",
3232 "1",
3233 "-ar",
3234 "48000",
3235 "-f",
3236 "f32le",
3237 "-acodec",
3238 "pcm_f32le",
3239 "-",
3240 ])
3241 .output()
3242 .expect("ffmpeg runs");
3243 assert!(
3244 out.status.success(),
3245 "ffmpeg mono decode failed for {}: {}",
3246 path.display(),
3247 String::from_utf8_lossy(&out.stderr)
3248 );
3249 out.stdout
3250 .as_chunks::<4>()
3251 .0
3252 .iter()
3253 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
3254 .collect()
3255}
3256
3257/// Encode `src` to a mono Ogg/Opus file with ffmpeg libopus, VoIP application,
3258/// at `kbps` (VBR on), capped at `secs`. Realised rate read back from file size.
3259fn ffmpeg_encode_libopus_mono_voip(src: &Path, kbps: u32, out: &Path, secs: f64) {
3260 let res = Command::new("ffmpeg")
3261 .args(["-y", "-v", "error", "-i"])
3262 .arg(src)
3263 .args([
3264 "-vn",
3265 "-t",
3266 &format!("{secs}"),
3267 "-ac",
3268 "1",
3269 "-ar",
3270 "48000",
3271 "-c:a",
3272 "libopus",
3273 "-application",
3274 "voip",
3275 "-b:a",
3276 &format!("{kbps}k"),
3277 "-vbr",
3278 "on",
3279 ])
3280 .arg(out)
3281 .output()
3282 .expect("ffmpeg runs");
3283 assert!(
3284 res.status.success(),
3285 "ffmpeg libopus mono voip encode failed at {kbps}k: {}",
3286 String::from_utf8_lossy(&res.stderr)
3287 );
3288}
3289
3290/// Same as [`roundtrip_own`] but also returns the encoded packets, so the SILK
3291/// gate can re-decode them through ffmpeg (decoder-symmetric comparison).
3292fn roundtrip_own_packets(
3293 enc: &mut Encoder,
3294 pcm: &[f32],
3295 channels: usize,
3296 frame: usize,
3297) -> (Vec<f32>, Vec<Vec<u8>>, usize) {
3298 let mut dec = Decoder::new(48000, channels).unwrap();
3299 let mut out = vec![0u8; 1500];
3300 let mut decoded = Vec::new();
3301 let mut packets = Vec::new();
3302 let mut buf = vec![0.0f32; 5760 * channels];
3303 let mut bytes = 0usize;
3304 let mut padded = Vec::new();
3305 for block in pcm.chunks(frame * channels) {
3306 let block = if block.len() < frame * channels {
3307 padded.clear();
3308 padded.extend_from_slice(block);
3309 padded.resize(frame * channels, 0.0);
3310 &padded[..]
3311 } else {
3312 block
3313 };
3314 let len = enc.encode_float(block, frame, &mut out).expect("encode");
3315 bytes += len;
3316 packets.push(out[..len].to_vec());
3317 let n = dec.decode_float(&out[..len], &mut buf).expect("decode");
3318 assert_eq!(n, frame, "decoded frame size");
3319 assert_eq!(
3320 dec.final_range(),
3321 enc.final_range(),
3322 "range state diverged between encoder and decoder"
3323 );
3324 decoded.extend_from_slice(&buf[..n * channels]);
3325 }
3326 (decoded, packets, bytes)
3327}
3328
3329/// First audio packet's TOC byte from Ogg-Opus bytes (skips OpusHead/OpusTags).
3330fn first_audio_toc(ogg: &[u8]) -> u8 {
3331 for p in ogg_packets(ogg) {
3332 if p.len() >= 8 && (&p[..8] == b"OpusHead" || &p[..8] == b"OpusTags") {
3333 continue;
3334 }
3335 if !p.is_empty() {
3336 return p[0];
3337 }
3338 }
3339 0
3340}
3341
3342#[test]
3343#[ignore = "library gate: hand-run mono VoIP sweep; blocked until ~/Music/reelm.wav is back in the corpus (hard-asserts src.exists) and it is a multi-minute ffmpeg run, not a suite test"]
3344fn silk_library_gate_vs_libopus() {
3345 let _timing = timing_shared();
3346 const SECS: f64 = 120.0; // 2 min cap
3347 const FRAME: usize = 960; // 20 ms at 48 kHz
3348 const CHANNELS: usize = 1; // MONO
3349 const MAX_LAG: usize = 2000;
3350
3351 let src = shellexpand("~/Music/reelm.wav");
3352 assert!(src.exists(), "source missing: {}", src.display());
3353
3354 let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes");
3355 fs::create_dir_all(&lanes_dir).unwrap();
3356 let sweep_path = lanes_dir.join("opus-mode-r1.sweep.txt");
3357 let ref_ogg = temp_path("opus-silk-r2-ref.opus");
3358 let ours_ogg = temp_path("opus-silk-r2-ours.opus");
3359
3360 // Source PCM: mono, 48 kHz.
3361 let source_pcm = ffmpeg_decode_pcm_mono(&src, SECS);
3362 let source_frames = source_pcm.len() / CHANNELS;
3363 assert!(source_frames > 48_000, "source too short");
3364 let seconds = source_frames as f64 / 48000.0;
3365
3366 // (label, kbps, forced bandwidth, forced mode, reference lowpass cutoff).
3367 // cutoff: NB 4 kHz, WB 8 kHz, hybrid-FB unfiltered (None) — compare each
3368 // encoder only against the band it can actually reproduce.
3369 type Row = (
3370 &'static str,
3371 u32,
3372 Option<Bandwidth>,
3373 Option<Mode>,
3374 Option<f64>,
3375 );
3376 let rows: &[Row] = &[
3377 // All rows auto since lane opus-mode: the selector is libopus's, so
3378 // the mode must match the reference's (asserted below) and the
3379 // comparison is full-band (no lowpass).
3380 ("12k", 12, None, None, None),
3381 ("16k", 16, None, None, None),
3382 ("24k", 24, None, None, None),
3383 ("32k", 32, None, None, None),
3384 ];
3385
3386 let mut out_rows: Vec<String> = Vec::new();
3387 let mut rate_violations: Vec<String> = Vec::new();
3388 let mut dropout_violations: Vec<String> = Vec::new();
3389 let mut lag_violations: Vec<String> = Vec::new();
3390
3391 for &(tag, kbps, bw, mode, cutoff) in rows {
3392 // Band-limited reference source for this row's corr/opus_compare.
3393 let ref_source: Vec<f32> = match cutoff {
3394 Some(hz) => lowpass(&source_pcm, hz),
3395 None => source_pcm.clone(),
3396 };
3397 let ref_source_i16 = to_i16(&ref_source);
3398
3399 // Reference: ffmpeg libopus, mono, voip, VBR; realised rate from size.
3400 ffmpeg_encode_libopus_mono_voip(&src, kbps, &ref_ogg, SECS);
3401 let ref_bytes = fs::metadata(&ref_ogg)
3402 .map(|m| m.len() as usize)
3403 .unwrap_or(0);
3404 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
3405 // SYMMETRY: ref decoded through ffmpeg libopus (the reference decoder),
3406 // NOT our own decoder — so both sides cross the same decoder. (r1 used
3407 // decode_ogg, our own MultistreamDecoder, for the ref side.)
3408 let ref_dec = ffmpeg_decode(&ref_ogg, CHANNELS).expect("ffmpeg libopus decode of ref");
3409 let ref_trim: Vec<f32> = ref_dec.into_iter().take(source_frames * CHANNELS).collect();
3410 let (lag_ref, ref_aligned) = align_to_source(&source_pcm, &ref_trim, CHANNELS, MAX_LAG);
3411 // REF MODE: libopus's actual mode from its first audio packet TOC.
3412 let ref_ogg_bytes = fs::read(&ref_ogg).expect("read ref ogg");
3413 let ref_mode = toc_mode_label(first_audio_toc(&ref_ogg_bytes));
3414
3415 // Ours: ec-opus Voip at the reference's realised rate.
3416 let mut enc = Encoder::new(48000, CHANNELS, Application::Voip).expect("encoder");
3417 enc.set_bitrate((ref_kbps * 1000.0).round() as u32);
3418 if let Some(b) = bw {
3419 enc.set_bandwidth(Some(b));
3420 }
3421 if let Some(m) = mode {
3422 enc.set_mode(Some(m));
3423 }
3424 enc.set_vbr_constrained(true);
3425 let pre_skip = enc.look_ahead(FRAME) as i64;
3426
3427 // Probe which mode the encoder actually picked, from the first TOC byte.
3428 let mut probe = enc.clone();
3429 let mut toc_buf = [0u8; 1500];
3430 probe
3431 .encode_float(&source_pcm[..FRAME * CHANNELS], FRAME, &mut toc_buf)
3432 .expect("encode probe");
3433 let mode_label = toc_mode_label(toc_buf[0]);
3434 assert_eq!(
3435 ref_mode, mode_label,
3436 "{tag}: mode mismatch ref={ref_mode} ours={mode_label} (MODE GATE)"
3437 );
3438
3439 // Own-decoder roundtrip (range-coder invariant) + packet capture.
3440 let (ours_own_dec, ours_packets, ours_bytes) =
3441 roundtrip_own_packets(&mut enc, &source_pcm, CHANNELS, FRAME);
3442 let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0;
3443
3444 // SYMMETRY: re-decode OUR packets through ffmpeg libopus too.
3445 write_ogg_opus(
3446 &ours_ogg,
3447 &ours_packets,
3448 opus_head(CHANNELS, pre_skip as u16, None),
3449 CHANNELS,
3450 source_frames,
3451 pre_skip,
3452 );
3453 let ours_dec = ffmpeg_decode(&ours_ogg, CHANNELS).expect("ffmpeg libopus decode of ours");
3454 let ours_trim: Vec<f32> = ours_dec
3455 .into_iter()
3456 .take(source_frames * CHANNELS)
3457 .collect();
3458 let (lag_ours, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
3459
3460 // Own-decoder aligned (extra column: decoder drift visibility).
3461 let ours_own_trim: Vec<f32> = ours_own_dec
3462 .into_iter()
3463 .take(source_frames * CHANNELS)
3464 .collect();
3465 let (_, ours_own_aligned) = align_to_source(&source_pcm, &ours_own_trim, CHANNELS, MAX_LAG);
3466
3467 // LAG GATE: a lag at the scan bound is an invalid measurement, not a result.
3468 if (lag_ours as i64).abs() >= MAX_LAG as i64 {
3469 lag_violations.push(format!(
3470 "{tag}: ours lag {lag_ours} hit scan bound {MAX_LAG}"
3471 ));
3472 }
3473 if (lag_ref as i64).abs() >= MAX_LAG as i64 {
3474 lag_violations.push(format!("{tag}: ref lag {lag_ref} hit scan bound {MAX_LAG}"));
3475 }
3476
3477 let ours_i16 = to_i16(&ours_aligned);
3478 let ref_i16 = to_i16(&ref_aligned);
3479 let cmp_frames = (ref_source_i16.len() / CHANNELS)
3480 .min(ours_i16.len() / CHANNELS)
3481 .min(ref_i16.len() / CHANNELS);
3482 let trim = |v: &[i16]| -> Vec<i16> { v[..cmp_frames * CHANNELS].to_vec() };
3483 let s_i = trim(&ref_source_i16);
3484 let o_i = trim(&ours_i16);
3485 let r_i = trim(&ref_i16);
3486 let q_ours = opus_compare(&s_i, &o_i, CHANNELS);
3487 let q_ref = opus_compare(&s_i, &r_i, CHANNELS);
3488 let err_ours = opus_compare_err(&s_i, &o_i, CHANNELS);
3489 let err_ref = opus_compare_err(&s_i, &r_i, CHANNELS);
3490 let err_ratio = if err_ref > 0.0 {
3491 err_ours / err_ref
3492 } else {
3493 f64::INFINITY
3494 };
3495
3496 // Primary corr: band-limited reference. Secondary: full-band source.
3497 let corr_ours_bl = corr_interleaved(&ref_source, &ours_aligned, CHANNELS);
3498 let corr_ref_bl = corr_interleaved(&ref_source, &ref_aligned, CHANNELS);
3499 let gap = corr_ref_bl - corr_ours_bl; // SIGN RULE: more negative = ours better
3500 let corr_ours_fb = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS);
3501 let corr_ref_fb = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS);
3502 let corr_ours_owndec = corr_interleaved(&ref_source, &ours_own_aligned, CHANNELS);
3503 let (minsec_ours, drop_ours) = per_second_corr(&ref_source, &ours_aligned, CHANNELS);
3504 let (minsec_ref, drop_ref) = per_second_corr(&ref_source, &ref_aligned, CHANNELS);
3505 let rate_pct = (ours_kbps / ref_kbps - 1.0) * 100.0;
3506
3507 if rate_pct.abs() > 5.0 {
3508 rate_violations.push(format!("{tag}: rate {rate_pct:+.1}% (|>5%)"));
3509 }
3510 if drop_ours > 0 && drop_ref == 0 {
3511 dropout_violations.push(format!(
3512 "{tag}: ours dropped {drop_ours}s below 0.9 corr, ref 0s"
3513 ));
3514 }
3515 let row = format!(
3516 "{tag}: ref_mode={ref_mode} mode={mode_label}, ref {ref_kbps:.1} ours {ours_kbps:.1} kbps ({rate_pct:+.1}%), \
3517 lag o={lag_ours} r={lag_ref}, \
3518 corr_bl o={corr_ours_bl:.4} r={corr_ref_bl:.4} gap={gap:+.4}, \
3519 corr_fb o={corr_ours_fb:.4} r={corr_ref_fb:.4}, corr_owndec o={corr_ours_owndec:.4}, \
3520 Q o={q_ours:.2} r={q_ref:.2}, err_ratio {err_ratio:.3}, \
3521 minsec o={minsec_ours:.4} r={minsec_ref:.4}, drop o={drop_ours} r={drop_ref}"
3522 );
3523 println!("{row}");
3524 out_rows.push(row);
3525 }
3526 let _ = fs::remove_file(&ref_ogg);
3527 let _ = fs::remove_file(&ours_ogg);
3528
3529 // Rate gate: report violations, never panic.
3530 let rate_gate = if rate_violations.is_empty() {
3531 "RATE GATE: all rows within ±5%".to_string()
3532 } else {
3533 let mut s = "RATE GATE violations (|rate%| > 5):".to_string();
3534 for v in &rate_violations {
3535 s.push_str("\n ");
3536 s.push_str(v);
3537 }
3538 s
3539 };
3540 if rate_violations.is_empty() {
3541 println!("{rate_gate}");
3542 } else {
3543 eprintln!("{rate_gate}");
3544 }
3545 // Lag gate: hard fail — a measurement at the scan bound is not a result.
3546 assert!(
3547 lag_violations.is_empty(),
3548 "LAG GATE failed (lag at scan bound):\n {}",
3549 lag_violations.join("\n ")
3550 );
3551 let lag_gate = "LAG GATE: passed (no lag at scan bound)";
3552 println!("{lag_gate}");
3553 // Dropout gate: hard fail — a second the reference kept must not drop out.
3554 assert!(
3555 dropout_violations.is_empty(),
3556 "DROPOUT GATE failed (ours dropped seconds ref kept):\n {}",
3557 dropout_violations.join("\n ")
3558 );
3559 let drop_gate = "DROPOUT GATE: passed (no ours-only dropouts)";
3560 println!("{drop_gate}");
3561
3562 // Sweep file: raw rows + GATE lines (lane deliverable).
3563 let mut table = String::new();
3564 table.push_str("# ec-opus SILK/speech-rate gate vs ffmpeg libopus (r2)\n");
3565 table.push_str("# mono, 120s cap, VBR, 48kHz, Application::Voip; source reelm.wav\n");
3566 table.push_str("# r2: symmetric ffmpeg-libopus decode (both sides), lag gate, band-limited ref, ref mode\n");
3567 for r in &out_rows {
3568 table.push_str(r);
3569 table.push('\n');
3570 }
3571 table.push_str(&rate_gate);
3572 table.push('\n');
3573 table.push_str(lag_gate);
3574 table.push('\n');
3575 table.push_str(drop_gate);
3576 table.push('\n');
3577 fs::write(&sweep_path, table).unwrap();
3578 println!("wrote {}", sweep_path.display());
3579}
3580
3581// ---------------------------------------------------------------------------
3582// ORACLE: decode both our packets and ffmpeg-libopus ref packets through our
3583// own SilkDecoder, read back the per-frame `Indices`, and print side-by-side
3584// for the worst seconds to name the divergence mechanism.
3585// Run: SWEEP_ONLY=reelm cargo test -p ec-opus --release --test conformance \
3586// silk_silkq_oracle -- --ignored --nocapture
3587// ---------------------------------------------------------------------------
3588#[test]
3589#[ignore = "probe: per-frame SILK Indices side-by-side oracle dump; unblocks when ~/Music/reelm.wav is back in the corpus (hard-asserts src.exists)"]
3590fn silk_silkq_oracle() {
3591 let _timing = timing_shared();
3592 const SECS: f64 = 120.0;
3593 const FRAME: usize = 960; // 20 ms at 48 kHz
3594 const CHANNELS: usize = 1;
3595 const KBPS: u32 = 12;
3596 const TARGET_SECS: &[usize] = &[3, 39, 51, 5, 1];
3597
3598 let src = shellexpand("~/Music/reelm.wav");
3599 assert!(src.exists(), "source missing: {}", src.display());
3600 let source_pcm = ffmpeg_decode_pcm_mono(&src, SECS);
3601
3602 let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes");
3603 fs::create_dir_all(&lanes_dir).unwrap();
3604 let ref_ogg = temp_path("opus-silkq-oracle-ref.opus");
3605
3606 // Reference: ffmpeg libopus mono voip at 12k.
3607 ffmpeg_encode_libopus_mono_voip(&src, KBPS, &ref_ogg, SECS);
3608 let ref_ogg_bytes = fs::read(&ref_ogg).expect("read ref ogg");
3609 let ref_packets: Vec<Vec<u8>> = ogg_packets(&ref_ogg_bytes)
3610 .into_iter()
3611 .skip(2)
3612 .filter(|p| !p.is_empty())
3613 .collect();
3614 let _ = fs::remove_file(&ref_ogg);
3615
3616 // Ours: ec-opus Voip at 12k.
3617 let mut enc = Encoder::new(48000, CHANNELS, Application::Voip).expect("encoder");
3618 enc.set_bitrate(KBPS * 1000);
3619 enc.set_vbr_constrained(true);
3620 let mut out = vec![0u8; 1500];
3621 let mut ours_packets: Vec<Vec<u8>> = Vec::new();
3622 let mut padded = Vec::new();
3623 for block in source_pcm.chunks(FRAME * CHANNELS) {
3624 let block = if block.len() < FRAME * CHANNELS {
3625 padded.clear();
3626 padded.extend_from_slice(block);
3627 padded.resize(FRAME * CHANNELS, 0.0);
3628 &padded[..]
3629 } else {
3630 block
3631 };
3632 let len = enc.encode_float(block, FRAME, &mut out).expect("encode");
3633 ours_packets.push(out[..len].to_vec());
3634 }
3635
3636 let ours_ix = collect_indices(&ours_packets);
3637 let ref_ix = collect_indices(&ref_packets);
3638
3639 eprintln!(
3640 "ours frames: {} ref frames: {}",
3641 ours_ix.len(),
3642 ref_ix.len()
3643 );
3644
3645 // Print side-by-side for target seconds (50 frames/sec at 20ms).
3646 let frames_per_sec = 50usize;
3647 let mut out_str = String::new();
3648 out_str.push_str("# reelm@12k SILK oracle: ours vs ffmpeg-libopus indices (r1)\n");
3649 out_str.push_str("# mono, 120s, 20ms frames, VBR constrained, 48kHz, Application::Voip\n");
3650 out_str.push_str(&format!(
3651 "# ours_frames={} ref_frames={}\n",
3652 ours_ix.len(),
3653 ref_ix.len()
3654 ));
3655 out_str.push_str("# sig: 0=unvoiced 2=voiced | per: LTP codebook | nlsf_i: 4=nointerp\n");
3656 out_str.push_str("# gains/ltp are 4 subframe indices; lag/contour only for voiced\n\n");
3657
3658 for &sec in TARGET_SECS {
3659 let start = sec * frames_per_sec;
3660 let end = start + frames_per_sec;
3661 out_str.push_str(&format!(
3662 "=== second {} (frames {}–{}) ===\n",
3663 sec,
3664 start,
3665 end - 1
3666 ));
3667 out_str.push_str("frame side sig qoff gains[4] nlsf_i lag cont per ltp[4] ltpscl seed bytes\n");
3668 for f in start..end {
3669 let ours = ours_ix.get(f);
3670 let refr = ref_ix.get(f);
3671 if ours.is_none() && refr.is_none() {
3672 continue;
3673 }
3674 for (side, item) in [("O", ours), ("R", refr)] {
3675 match item {
3676 Some((ix, bytes)) => {
3677 let voiced = ix.signal_type == 2;
3678 let lag_str = if voiced {
3679 format!("{:4}", ix.lag_index)
3680 } else {
3681 " -".to_string()
3682 };
3683 let cont_str = if voiced {
3684 format!("{:4}", ix.contour_index)
3685 } else {
3686 " -".to_string()
3687 };
3688 let per_str = if voiced {
3689 format!("{}", ix.per_index)
3690 } else {
3691 "-".to_string()
3692 };
3693 let ltp_str = if voiced {
3694 format!(
3695 "[{},{},{},{}]",
3696 ix.ltp_index[0], ix.ltp_index[1], ix.ltp_index[2], ix.ltp_index[3]
3697 )
3698 } else {
3699 "[-,-,-,-]".to_string()
3700 };
3701 let ltpscl_str = if voiced {
3702 format!("{}", ix.ltp_scale_index)
3703 } else {
3704 "-".to_string()
3705 };
3706 out_str.push_str(&format!(
3707 "{:5} {} {:2} {:2} [{:2},{:2},{:2},{:2}] {:2} {} {} {} {} {} {:2} {:3}\n",
3708 f, side, ix.signal_type, ix.quant_offset_type,
3709 ix.gains[0], ix.gains[1], ix.gains[2], ix.gains[3],
3710 ix.nlsf_interp_coef_q2,
3711 lag_str, cont_str, per_str, ltp_str, ltpscl_str,
3712 ix.seed, bytes,
3713 ));
3714 }
3715 None => {
3716 out_str.push_str(&format!("{:5} {} -- missing --\n", f, side));
3717 }
3718 }
3719 }
3720 }
3721 out_str.push('\n');
3722 }
3723
3724 // Summarize divergence statistics across ALL frames.
3725 let n = ours_ix.len().min(ref_ix.len());
3726 let mut sig_mismatch = 0;
3727 let mut qoff_mismatch = 0;
3728 let mut gain_diff_sum = 0i64;
3729 let mut nlsf_interp_diff = 0;
3730 let mut ltp_per_mismatch = 0;
3731 let mut ltp_idx_diff_sum = 0i64;
3732 let mut voiced_both = 0;
3733 let mut lag_diff_sum = 0i64;
3734 let mut bytes_ours = 0u64;
3735 let mut bytes_ref = 0u64;
3736 for i in 0..n {
3737 let (o, ob) = &ours_ix[i];
3738 let (r, rb) = &ref_ix[i];
3739 if o.signal_type != r.signal_type {
3740 sig_mismatch += 1;
3741 }
3742 if o.quant_offset_type != r.quant_offset_type {
3743 qoff_mismatch += 1;
3744 }
3745 for k in 0..4 {
3746 gain_diff_sum += (o.gains[k] as i64 - r.gains[k] as i64).abs();
3747 }
3748 if o.nlsf_interp_coef_q2 != r.nlsf_interp_coef_q2 {
3749 nlsf_interp_diff += 1;
3750 }
3751 if o.signal_type == 2 && r.signal_type == 2 {
3752 voiced_both += 1;
3753 if o.per_index != r.per_index {
3754 ltp_per_mismatch += 1;
3755 }
3756 for k in 0..4 {
3757 ltp_idx_diff_sum += (o.ltp_index[k] as i64 - r.ltp_index[k] as i64).abs();
3758 }
3759 lag_diff_sum += (o.lag_index as i64 - r.lag_index as i64).abs();
3760 }
3761 bytes_ours += *ob as u64;
3762 bytes_ref += *rb as u64;
3763 }
3764 out_str.push_str("=== divergence summary (all frames) ===\n");
3765 out_str.push_str(&format!("frames compared: {}\n", n));
3766 out_str.push_str(&format!(
3767 "signal_type mismatch: {} ({:.1}%)\n",
3768 sig_mismatch,
3769 100.0 * sig_mismatch as f64 / n as f64
3770 ));
3771 out_str.push_str(&format!(
3772 "quant_offset mismatch: {} ({:.1}%)\n",
3773 qoff_mismatch,
3774 100.0 * qoff_mismatch as f64 / n as f64
3775 ));
3776 out_str.push_str(&format!(
3777 "avg |gain diff| per subframe: {:.2}\n",
3778 gain_diff_sum as f64 / (n as f64 * 4.0)
3779 ));
3780 out_str.push_str(&format!(
3781 "nlsf_interp mismatch: {} ({:.1}%)\n",
3782 nlsf_interp_diff,
3783 100.0 * nlsf_interp_diff as f64 / n as f64
3784 ));
3785 out_str.push_str(&format!("voiced_both: {}\n", voiced_both));
3786 out_str.push_str(&format!(
3787 " LTP per_index mismatch: {} ({:.1}%)\n",
3788 ltp_per_mismatch,
3789 100.0 * ltp_per_mismatch as f64 / voiced_both.max(1) as f64
3790 ));
3791 out_str.push_str(&format!(
3792 " avg |ltp_index diff| per subframe: {:.2}\n",
3793 ltp_idx_diff_sum as f64 / (voiced_both.max(1) as f64 * 4.0)
3794 ));
3795 out_str.push_str(&format!(
3796 " avg |lag diff|: {:.2}\n",
3797 lag_diff_sum as f64 / voiced_both.max(1) as f64
3798 ));
3799 out_str.push_str(&format!(
3800 "total bytes: ours={} ref={} ratio={:.3}\n",
3801 bytes_ours,
3802 bytes_ref,
3803 bytes_ours as f64 / bytes_ref.max(1) as f64
3804 ));
3805
3806 let out_path = lanes_dir.join("opus-silkq-r1.oracle.txt");
3807 fs::write(&out_path, &out_str).unwrap();
3808 println!("wrote {}", out_path.display());
3809 print!("{}", out_str);
3810}
3811
3812/// Decode a SILK stream packet-by-packet through a fresh `SilkDecoder`,
3813/// snapshotting each frame's coded indices — the oracle diagnostic's view of
3814/// what the bitstream actually coded (our encoder's packets and a reference
3815/// encoder's alike).
3816fn collect_indices(packets: &[Vec<u8>]) -> Vec<(ec_opus::SilkDecIndices, usize)> {
3817 let mut silk = ec_opus::SilkDecoder::new(16000, 1);
3818 let mut results = Vec::new();
3819 let mut silk_pcm = vec![0i16; 320]; // 20ms at 16kHz
3820 for pkt in packets {
3821 if pkt.len() <= 1 {
3822 continue; // DTX / empty
3823 }
3824 let parsed = match ec_opus::Packet::parse(pkt, false) {
3825 Ok(p) => p,
3826 Err(_) => continue,
3827 };
3828 let toc = parsed.toc;
3829 let mode = toc.mode();
3830 if mode == ec_opus::Mode::Celt {
3831 continue;
3832 }
3833 let internal_rate = if mode == ec_opus::Mode::Hybrid {
3834 16000
3835 } else {
3836 match toc.bandwidth() {
3837 ec_opus::Bandwidth::Narrow => 8000,
3838 ec_opus::Bandwidth::Medium => 12000,
3839 _ => 16000,
3840 }
3841 };
3842 let payload_ms = (toc.frame_size_48k() / 48).max(10);
3843 let mut first = true;
3844 for frame_data in &parsed.frames {
3845 if frame_data.len() <= 1 {
3846 first = false;
3847 continue;
3848 }
3849 let mut dec = ec_opus::RangeDecoder::new(frame_data);
3850 let _ = silk.decode(
3851 &mut dec,
3852 &mut silk_pcm,
3853 payload_ms,
3854 internal_rate,
3855 1,
3856 first,
3857 ec_opus::SilkFrameMode::Normal,
3858 );
3859 let ix = silk.last_indices();
3860 let bytes = frame_data.len();
3861 results.push((ix, bytes));
3862 first = false;
3863 }
3864 }
3865 results
3866}
3867
3868// ---------------------------------------------------------------------------
3869// SILK 12k spectral divergence: WHERE the 12 kbps Voip err_ratio outlier
3870// carries its error. Same machinery as spectral_divergence_vs_libopus, but
3871// mono/Application::Voip/12 kbps on reelm.wav, both sides decoded through
3872// ffmpeg libopus (gate symmetry), with the index oracle on the worst frames.
3873// Run:
3874// cargo test -p ec-opus --release --test conformance \
3875// silk_spectral_divergence_12k -- --ignored --nocapture
3876// Writes lanes/opus-silkq-r2.bands.txt.
3877// ---------------------------------------------------------------------------
3878
3879#[test]
3880#[ignore = "probe: per-band spectral divergence dump at 12k; unblocks when ~/Music/reelm.wav is back in the corpus (hard-asserts src.exists)"]
3881fn silk_spectral_divergence_12k() {
3882 let _timing = timing_shared();
3883 const SECS: f64 = 120.0;
3884 const FRAME: usize = 960; // 20 ms at 48 kHz
3885 const CHANNELS: usize = 1;
3886 const MAX_LAG: usize = 2000;
3887 const KBPS: u32 = 12;
3888
3889 let src = shellexpand("~/Music/reelm.wav");
3890 assert!(src.exists(), "source missing: {}", src.display());
3891 let source_pcm = ffmpeg_decode_pcm_mono(&src, SECS);
3892 let source_frames = source_pcm.len() / CHANNELS;
3893 assert!(source_frames > 48_000, "source too short");
3894 let seconds = source_frames as f64 / 48000.0;
3895
3896 let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes");
3897 fs::create_dir_all(&lanes_dir).unwrap();
3898 let ref_ogg = temp_path("opus-silkq-r2-ref.opus");
3899 let ours_ogg = temp_path("opus-silkq-r2-ours.opus");
3900
3901 // Reference: ffmpeg libopus mono voip at 12k, decoded by ffmpeg libopus.
3902 ffmpeg_encode_libopus_mono_voip(&src, KBPS, &ref_ogg, SECS);
3903 let ref_bytes = fs::metadata(&ref_ogg)
3904 .map(|m| m.len() as usize)
3905 .unwrap_or(0);
3906 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
3907 let ref_dec = ffmpeg_decode(&ref_ogg, CHANNELS).expect("ffmpeg libopus decode of ref");
3908 let ref_trim: Vec<f32> = ref_dec.into_iter().take(source_frames * CHANNELS).collect();
3909 let (_, ref_aligned) = align_to_source(&source_pcm, &ref_trim, CHANNELS, MAX_LAG);
3910 let ref_ogg_bytes = fs::read(&ref_ogg).expect("read ref ogg");
3911 let ref_packets: Vec<Vec<u8>> = ogg_packets(&ref_ogg_bytes)
3912 .into_iter()
3913 .skip(2)
3914 .filter(|p| !p.is_empty())
3915 .collect();
3916 let _ = fs::remove_file(&ref_ogg);
3917
3918 // Ours: ec-opus Voip at the reference's realised rate; our packets
3919 // re-decoded through ffmpeg libopus so both sides cross the same decoder.
3920 let mut enc = Encoder::new(48000, CHANNELS, Application::Voip).expect("encoder");
3921 enc.set_bitrate((ref_kbps * 1000.0).round() as u32);
3922 enc.set_vbr_constrained(true);
3923 let pre_skip = enc.look_ahead(FRAME) as i64;
3924 let mut out = vec![0u8; 1500];
3925 let mut ours_packets: Vec<Vec<u8>> = Vec::new();
3926 let mut padded = Vec::new();
3927 for block in source_pcm.chunks(FRAME * CHANNELS) {
3928 let block = if block.len() < FRAME * CHANNELS {
3929 padded.clear();
3930 padded.extend_from_slice(block);
3931 padded.resize(FRAME * CHANNELS, 0.0);
3932 &padded[..]
3933 } else {
3934 block
3935 };
3936 let len = enc.encode_float(block, FRAME, &mut out).expect("encode");
3937 ours_packets.push(out[..len].to_vec());
3938 }
3939 write_ogg_opus(
3940 &ours_ogg,
3941 &ours_packets,
3942 opus_head(CHANNELS, pre_skip as u16, None),
3943 CHANNELS,
3944 source_frames,
3945 pre_skip,
3946 );
3947 let ours_bytes: usize = ours_packets.iter().map(|p| p.len()).sum();
3948 let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0;
3949 let ours_dec = ffmpeg_decode(&ours_ogg, CHANNELS).expect("ffmpeg libopus decode of ours");
3950 let _ = fs::remove_file(&ours_ogg);
3951 let ours_trim: Vec<f32> = ours_dec
3952 .into_iter()
3953 .take(source_frames * CHANNELS)
3954 .collect();
3955 let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
3956
3957 // opus_compare totals, per-band eb², per-frame ef² — both vs the source.
3958 let cmp_frames = source_frames
3959 .min(ours_aligned.len() / CHANNELS)
3960 .min(ref_aligned.len() / CHANNELS);
3961 let take = |v: &[f32]| -> Vec<i16> { to_i16(&v[..cmp_frames * CHANNELS]) };
3962 let s_i = take(&source_pcm);
3963 let o_i = take(&ours_aligned);
3964 let r_i = take(&ref_aligned);
3965 let (err_o, eb2_o, ef2_o) = opus_compare_err_parts(&s_i, &o_i, CHANNELS);
3966 let (err_r, eb2_r, ef2_r) = opus_compare_err_parts(&s_i, &r_i, CHANNELS);
3967 let nframes = ef2_o.len();
3968 assert_eq!(nframes, ef2_r.len(), "frame counts differ");
3969
3970 // Raw (unmasked) band energies: spectral shape + dominant-band lookup.
3971 let as_f64 = |v: &[i16]| -> Vec<f64> { v.iter().map(|&x| x as f64).collect() };
3972 let mut bands_s = Vec::new();
3973 let mut bands_o = Vec::new();
3974 let mut bands_r = Vec::new();
3975 let mut scratch_ps = Vec::new();
3976 band_energy(
3977 &as_f64(&s_i),
3978 CHANNELS,
3979 nframes,
3980 &mut Some(&mut bands_s),
3981 &mut scratch_ps,
3982 );
3983 band_energy(
3984 &as_f64(&o_i),
3985 CHANNELS,
3986 nframes,
3987 &mut Some(&mut bands_o),
3988 &mut scratch_ps,
3989 );
3990 band_energy(
3991 &as_f64(&r_i),
3992 CHANNELS,
3993 nframes,
3994 &mut Some(&mut bands_r),
3995 &mut scratch_ps,
3996 );
3997
3998 // Oracle indices both sides; FFT frame xi -> 20 ms packet index.
3999 let ours_ix = collect_indices(&ours_packets);
4000 let ref_ix = collect_indices(&ref_packets);
4001 let pkt_of = |xi: usize| xi * WIN_STEP / (FRAME * CHANNELS);
4002
4003 let mut report = String::new();
4004 report.push_str("# reelm@12k SILK per-band divergence: ours vs ffmpeg-libopus (r2)\n");
4005 report.push_str("# mono, 120s, 20ms frames, VBR constrained, 48kHz, Application::Voip\n");
4006 report.push_str(&format!(
4007 "# rates: ours {ours_kbps:.2} kbps, ref {ref_kbps:.2} kbps; \
4008 err ours={err_o:.3} ref={err_r:.3} ratio={:.2}; nframes={nframes}\n",
4009 err_o / err_r
4010 ));
4011
4012 // (1) 21-band table: which bands carry the error.
4013 let sum_o: f64 = eb2_o.iter().sum();
4014 let sum_r: f64 = eb2_r.iter().sum();
4015 report.push_str(
4016 "# eb2 = band's mean share of the pre-squared frame error; \
4017 dln = mean ln(E_test/E_src); band i ends at CELT_EBANDS[i+1]*240 Hz\n",
4018 );
4019 report.push_str("# band lo_hz hi_hz dln_o dln_r eb2_o eb2_r ratio share_o share_r\n");
4020 for bi in 0..NBANDS {
4021 let (mut dol, mut drl) = (0.0f64, 0.0f64);
4022 for xi in 0..nframes {
4023 let sl = bands_s[(xi * NBANDS + bi) * CHANNELS].ln();
4024 dol += bands_o[(xi * NBANDS + bi) * CHANNELS].ln() - sl;
4025 drl += bands_r[(xi * NBANDS + bi) * CHANNELS].ln() - sl;
4026 }
4027 dol /= nframes as f64;
4028 drl /= nframes as f64;
4029 let ratio = if eb2_r[bi] > 0.0 {
4030 eb2_o[bi] / eb2_r[bi]
4031 } else {
4032 f64::INFINITY
4033 };
4034 report.push_str(&format!(
4035 "{:5} {:5} {:6} {:+.3} {:+.3} {:.3e} {:.3e} {:>7} {:5.1}% {:5.1}%\n",
4036 bi,
4037 CELT_EBANDS[bi] * 240,
4038 CELT_EBANDS[bi + 1] * 240,
4039 dol,
4040 drl,
4041 eb2_o[bi],
4042 eb2_r[bi],
4043 ratio,
4044 100.0 * eb2_o[bi] / sum_o,
4045 100.0 * eb2_r[bi] / sum_r,
4046 ));
4047 }
4048
4049 // (2) top-15 frames by ef2(ours), with the dominant band and the oracle.
4050 let mut by_ef2: Vec<usize> = (0..nframes).collect();
4051 by_ef2.sort_by(|&a, &b| ef2_o[b].partial_cmp(&ef2_o[a]).unwrap());
4052 report.push_str(
4053 "\n# top-15 frames by ef2(ours) (ef2 = frame's squared opus_compare error); \
4054 dom = argmax_b (lnE_o - lnE_s)^2, raw bands\n",
4055 );
4056 report.push_str(
4057 "# t(s) fft pkt ef2_o ef2_r dom domband_hz | side sig qoff gains[4] nlsf_i lag cont per ltp[4] ltpscl seed bytes\n",
4058 );
4059 for &xi in by_ef2.iter().take(15) {
4060 let pkt = pkt_of(xi);
4061 let t = (xi * WIN_STEP) as f64 / 48000.0;
4062 let (mut dom, mut dom_v) = (0usize, -1.0f64);
4063 for bi in 0..NBANDS {
4064 let sl = bands_s[(xi * NBANDS + bi) * CHANNELS].ln();
4065 let d = bands_o[(xi * NBANDS + bi) * CHANNELS].ln() - sl;
4066 if d * d > dom_v {
4067 dom_v = d * d;
4068 dom = bi;
4069 }
4070 }
4071 report.push_str(&format!(
4072 "{:7.3} {:5} {:4} {:.3e} {:.3e} {:2} {}-{}Hz\n",
4073 t,
4074 xi,
4075 pkt,
4076 ef2_o[xi],
4077 ef2_r[xi],
4078 dom,
4079 CELT_EBANDS[dom] * 240,
4080 CELT_EBANDS[dom + 1] * 240
4081 ));
4082 for (side, ixv) in [(" O", ours_ix.get(pkt)), (" R", ref_ix.get(pkt))] {
4083 match ixv {
4084 Some((ix, bytes)) => {
4085 let voiced = ix.signal_type == 2;
4086 let opt = |v: String, on: bool| if on { v } else { "-".to_owned() };
4087 report.push_str(&format!(
4088 " {side} sig={} qoff={} gains=[{},{},{},{}] nlsf_i={} lag={} cont={} per={} ltp=[{},{},{},{}] ltpscl={} seed={} bytes={}\n",
4089 ix.signal_type,
4090 ix.quant_offset_type,
4091 ix.gains[0],
4092 ix.gains[1],
4093 ix.gains[2],
4094 ix.gains[3],
4095 ix.nlsf_interp_coef_q2,
4096 opt(format!("{}", ix.lag_index), voiced),
4097 opt(format!("{}", ix.contour_index), voiced),
4098 opt(format!("{}", ix.per_index), voiced),
4099 opt(format!("{}", ix.ltp_index[0]), voiced),
4100 opt(format!("{}", ix.ltp_index[1]), voiced),
4101 opt(format!("{}", ix.ltp_index[2]), voiced),
4102 opt(format!("{}", ix.ltp_index[3]), voiced),
4103 opt(format!("{}", ix.ltp_scale_index), voiced),
4104 ix.seed,
4105 bytes
4106 ));
4107 }
4108 None => report.push_str(&format!(" {side} -- missing --\n")),
4109 }
4110 }
4111 }
4112
4113 // (3) tail vs body: how much of the total error the worst frames carry,
4114 // and whether the 11x ratio survives de-tailing (err = (Σef2/n)^(1/16)).
4115 let tail = |ef2: &[f64]| -> (usize, f64, f64, usize, f64) {
4116 let mut s = ef2.to_vec();
4117 s.sort_by(|a, b| b.partial_cmp(a).unwrap());
4118 let tot: f64 = s.iter().sum();
4119 let k = (s.len() / 100).max(1);
4120 let top1: f64 = s[..k].iter().sum();
4121 let (mut half, mut acc) = (s.len(), 0.0);
4122 for (i, v) in s.iter().enumerate() {
4123 acc += v;
4124 if acc >= 0.5 * tot {
4125 half = i + 1;
4126 break;
4127 }
4128 }
4129 (k, top1 / tot, half as f64 / s.len() as f64, half, tot)
4130 };
4131 let root16 = |tot: f64, n: usize| tot.powf(1.0 / 16.0) / (n as f64).powf(1.0 / 16.0);
4132 let (k, sh1_o, halff_o, half_o, _tot_o) = tail(&ef2_o);
4133 let (_, sh1_r, halff_r, half_r, _tot_r) = tail(&ef2_r);
4134 report.push_str(&format!(
4135 "# tail: top-1% ({k} frames) carry {:.2}% of ours' Σef2 vs {:.2}% of ref's; \
4136 50% of ours' err sits in the worst {half_o} frames ({:.2}%) \
4137 vs ref's worst {half_r} ({:.2}%)\n",
4138 100.0 * sh1_o,
4139 100.0 * sh1_r,
4140 100.0 * halff_o,
4141 100.0 * halff_r
4142 ));
4143 // De-tailed: drop each side's worst 50 frames (of 24k FFT frames/pkt-mapped).
4144 let clip50 = |ef2: &[f64]| -> f64 {
4145 let mut s = ef2.to_vec();
4146 s.sort_by(|a, b| b.partial_cmp(a).unwrap());
4147 s[50..].iter().sum()
4148 };
4149 let err_o_clip = root16(clip50(&ef2_o), nframes);
4150 let err_r_clip = root16(clip50(&ef2_r), nframes);
4151 report.push_str(&format!(
4152 "# de-tailed (worst 50 of {nframes} FFT frames dropped per side): \
4153 err ours={err_o_clip:.3} ref={err_r_clip:.3} ratio={:.2} (was {err_o:.3}/{err_r:.3}/{:.2})\n",
4154 err_o_clip / err_r_clip,
4155 err_o / err_r
4156 ));
4157 // Burst signature: per 20 ms packet, does first-subframe gain >= 60 or a
4158 // starved packet (<= 20 bytes) line up with the packet's mean ef2?
4159 let mut pkt_ef2 = vec![0.0f64; ours_packets.len()];
4160 let mut pkt_cnt = vec![0u32; ours_packets.len()];
4161 // Index loop kept: the index also drives other lookups or parallel arrays.
4162 #[allow(clippy::needless_range_loop)]
4163 for xi in 0..nframes {
4164 let p = pkt_of(xi).min(pkt_ef2.len() - 1);
4165 pkt_ef2[p] += ef2_o[xi];
4166 pkt_cnt[p] += 1;
4167 }
4168 let mut g_hi = (0.0f64, 0usize); // (sum, count) packets with gains[0] >= 60
4169 let mut g_lo = (0.0f64, 0usize);
4170 let mut b_lo = (0.0f64, 0usize); // bytes <= 20
4171 let mut b_hi = (0.0f64, 0usize);
4172 for (i, (ix, bytes)) in ours_ix.iter().enumerate() {
4173 if i >= pkt_ef2.len() {
4174 break;
4175 }
4176 let mean = if pkt_cnt[i] > 0 {
4177 pkt_ef2[i] / pkt_cnt[i] as f64
4178 } else {
4179 0.0
4180 };
4181 if ix.gains[0] >= 60 {
4182 g_hi.0 += mean;
4183 g_hi.1 += 1;
4184 } else {
4185 g_lo.0 += mean;
4186 g_lo.1 += 1;
4187 }
4188 if *bytes <= 20 {
4189 b_lo.0 += mean;
4190 b_lo.1 += 1;
4191 } else {
4192 b_hi.0 += mean;
4193 b_hi.1 += 1;
4194 }
4195 }
4196 report.push_str(&format!(
4197 "# burst signature: packets with gains[0]>=60: {}/{}, mean ef2 {:.3e}; \
4198 gains[0]<60: mean ef2 {:.3e} || packets <=20 bytes: {}/{}, mean ef2 {:.3e}; \
4199 >20 bytes: mean ef2 {:.3e}\n",
4200 g_hi.1,
4201 g_hi.1 + g_lo.1,
4202 if g_hi.1 > 0 {
4203 g_hi.0 / g_hi.1 as f64
4204 } else {
4205 f64::NAN
4206 },
4207 if g_lo.1 > 0 {
4208 g_lo.0 / g_lo.1 as f64
4209 } else {
4210 f64::NAN
4211 },
4212 b_lo.1,
4213 b_lo.1 + b_hi.1,
4214 if b_lo.1 > 0 {
4215 b_lo.0 / b_lo.1 as f64
4216 } else {
4217 f64::NAN
4218 },
4219 if b_hi.1 > 0 {
4220 b_hi.0 / b_hi.1 as f64
4221 } else {
4222 f64::NAN
4223 },
4224 ));
4225
4226 let out_path = lanes_dir.join("opus-silkq-r2.bands.txt");
4227 fs::write(&out_path, &report).unwrap();
4228 println!("wrote {}", out_path.display());
4229 print!("{}", report);
4230}
4231
4232// ---------------------------------------------------------------------------
4233// Harness: feed identical raw PCM (.sw, s16le interleaved) to our opus_compare
4234// so it can be checked against the C `opus_compare` tool on the SAME bytes.
4235// Run: SW_REF=a.sw SW_TEST=b.sw SW_CH=2 cargo test -p ec-opus --release \
4236// opus_compare_harness -- --ignored --nocapture
4237// ---------------------------------------------------------------------------
4238#[test]
4239#[ignore = "probe: needs hand-supplied SW_REF/SW_TEST .sw files to cross-check our opus_compare against the C tool; asserts nothing without those env vars"]
4240fn opus_compare_harness() {
4241 let _timing = timing_shared();
4242 let ref_path = std::env::var("SW_REF").expect("SW_REF");
4243 let test_path = std::env::var("SW_TEST").expect("SW_TEST");
4244 let channels: usize = std::env::var("SW_CH")
4245 .ok()
4246 .and_then(|s| s.parse().ok())
4247 .unwrap_or(2);
4248 let x = read_i16(Path::new(&ref_path));
4249 let y = read_i16(Path::new(&test_path));
4250 assert_eq!(
4251 x.len(),
4252 y.len(),
4253 "sample counts differ: {} ({} samples) vs {} ({} samples)",
4254 ref_path,
4255 x.len() / channels,
4256 test_path,
4257 y.len() / channels
4258 );
4259 let err = opus_compare_err(&x, &y, channels);
4260 let q = opus_compare(&x, &y, channels);
4261 println!(
4262 "HARNESS err={err:.6} Q={q:.4} ch={channels} n={}",
4263 x.len() / channels
4264 );
4265}
4266
4267// ---------------------------------------------------------------------------
4268// Harness: read a source .sw, encode via ec-opus at SW_KBPS, decode, align,
4269// write the aligned decoded pair to SW_OUT_SRC / SW_OUT_DEC (.sw s16le), and
4270// print our opus_compare err/Q. The dumped .sw files can then be fed to the C
4271// `opus_compare` tool on IDENTICAL bytes for a byte-exact cross-check.
4272// Run: SW_SRC=in.sw SW_KBPS=96 SW_OUT_SRC=as.sw SW_OUT_DEC=ad.sw \
4273// cargo test -p ec-opus --release opus_compare_harness_ours -- --ignored --nocapture
4274// ---------------------------------------------------------------------------
4275#[test]
4276#[ignore = "probe: needs hand-supplied SW_SRC/SW_KBPS/SW_OUT_SRC/SW_OUT_DEC to round-trip a .sw through our encoder; only writes .sw dumps, asserts nothing"]
4277fn opus_compare_harness_ours() {
4278 let _timing = timing_shared();
4279 let src_path = std::env::var("SW_SRC").expect("SW_SRC");
4280 let kbps: u32 = std::env::var("SW_KBPS")
4281 .ok()
4282 .and_then(|s| s.parse().ok())
4283 .expect("SW_KBPS");
4284 let channels: usize = std::env::var("SW_CH")
4285 .ok()
4286 .and_then(|s| s.parse().ok())
4287 .unwrap_or(2);
4288 let out_src = std::env::var("SW_OUT_SRC").expect("SW_OUT_SRC");
4289 let out_dec = std::env::var("SW_OUT_DEC").expect("SW_OUT_DEC");
4290
4291 let src_i16 = read_i16(Path::new(&src_path));
4292 let src_f32: Vec<f32> = src_i16.iter().map(|&v| v as f32 / 32768.0).collect();
4293 let mut enc = Encoder::new(48000, channels, Application::Audio).expect("encoder");
4294 enc.set_bitrate(kbps * 1000);
4295 enc.set_vbr_constrained(true);
4296 let (dec_f32, _bytes) = roundtrip_own(&mut enc, &src_f32, channels, 960);
4297 let (lag, aligned) = align_to_source(&src_f32, &dec_f32, channels, 2000);
4298 // Trim both to the common aligned length.
4299 let n = (src_f32.len() / channels).min(aligned.len() / channels);
4300 let mut s_i16 = vec![0i16; n * channels];
4301 let mut d_i16 = vec![0i16; n * channels];
4302 for i in 0..n {
4303 for ch in 0..channels {
4304 s_i16[i * channels + ch] = (src_f32[i * channels + ch] * 32768.0)
4305 .round()
4306 .clamp(-32768.0, 32767.0) as i16;
4307 d_i16[i * channels + ch] = (aligned[i * channels + ch] * 32768.0)
4308 .round()
4309 .clamp(-32768.0, 32767.0) as i16;
4310 }
4311 }
4312 fs::write(&out_src, bytemap(&s_i16)).unwrap();
4313 fs::write(&out_dec, bytemap(&d_i16)).unwrap();
4314 let err = opus_compare_err(&s_i16, &d_i16, channels);
4315 let q = opus_compare(&s_i16, &d_i16, channels);
4316 let c = corr_interleaved(&src_f32[..n * channels], &aligned, channels);
4317 println!("HARNESS_OURS lag={lag} corr={c:.4} err={err:.6} Q={q:.4} kbps={kbps} n={n}");
4318}
4319
4320fn bytemap(p: &[i16]) -> Vec<u8> {
4321 let mut b = Vec::with_capacity(p.len() * 2);
4322 for &v in p {
4323 b.extend_from_slice(&v.to_le_bytes());
4324 }
4325 b
4326}
4327
4328/// Self-contained regression guard for `opus_compare_err` / `opus_compare`.
4329///
4330/// The pinned numbers below were cross-validated against the reference C
4331/// `opus_compare` tool (built from `opus_compare.c`) on byte-identical raw
4332/// PCM, so they encode the spectral error algorithm's expected output, not
4333/// any particular codec. Two cases:
4334/// * identical signals -> C err=0.000000, Q=100.0 (exact)
4335/// * mild perturbation -> C err=4.444987, Q=-593.31 (exact to 6 dp)
4336///
4337/// The perturbation case sits in the practical error range (same band as the
4338/// real-audio validation pairs); the identical case pins the zero-error path
4339/// with no floating-point tolerance. No audio files or external tools needed.
4340#[test]
4341fn opus_compare_err_pinned_against_c() {
4342 let _timing = timing_shared();
4343 const N: usize = 48000 * 4; // 4 s per channel
4344 let t: Vec<f64> = (0..N).map(|i| i as f64 / 48000.0).collect();
4345
4346 let base = |c: usize| -> Vec<f64> {
4347 let ph = 0.5 * c as f64;
4348 let ph2 = 0.3 * c as f64;
4349 t.iter()
4350 .map(|&tt| {
4351 0.3 * (2.0 * std::f64::consts::PI * 440.0 * tt).sin()
4352 + 0.2 * (2.0 * std::f64::consts::PI * 442.0 * tt + ph).sin()
4353 + 0.15 * (2.0 * std::f64::consts::PI * (800.0 + 200.0 * tt) * tt + ph2).sin()
4354 })
4355 .collect()
4356 };
4357 let to_i16s = |sig: &[f64]| -> Vec<i16> {
4358 sig.iter()
4359 .map(|&v| (v.clamp(-1.0, 1.0) * 32767.0) as i16)
4360 .collect()
4361 };
4362 let stereo = |l: &[f64], r: &[f64]| -> Vec<i16> {
4363 let mut o = Vec::with_capacity(N * 2);
4364 let li = to_i16s(l);
4365 let ri = to_i16s(r);
4366 for i in 0..N {
4367 o.push(li[i]);
4368 o.push(ri[i]);
4369 }
4370 o
4371 };
4372
4373 let b0 = base(0);
4374 let b1 = base(1);
4375
4376 // Case 1: identical -> zero error, Q=100 (exact, no tolerance).
4377 let a = stereo(&b0, &b1);
4378 let err_id = opus_compare_err(&a, &a, 2);
4379 let q_id = opus_compare(&a, &a, 2);
4380 assert_eq!(err_id, 0.0, "identical signals must give err=0");
4381 assert_eq!(q_id, 100.0, "identical signals must give Q=100");
4382
4383 // Case 2: mild perturbation (+0.5 dB on L, quiet 1500 Hz partial on L).
4384 let gain = 10f64.powf(0.5 / 10.0);
4385 let lp: Vec<f64> = t
4386 .iter()
4387 .zip(b0.iter())
4388 .map(|(&tt, &bv)| bv * gain + 0.02 * (2.0 * std::f64::consts::PI * 1500.0 * tt).sin())
4389 .collect();
4390 let b = stereo(&lp, &b1);
4391 let err = opus_compare_err(&a, &b, 2);
4392 let q = opus_compare(&a, &b, 2);
4393 // Pinned to the C reference value (4.444987); tolerance absorbs libm
4394 // transcendental rounding differences across toolchains.
4395 assert!(
4396 (err - 4.444987).abs() < 1e-3,
4397 "pinned err drift: got {err:.6}, expected 4.444987 (C-validated)"
4398 );
4399 assert!(
4400 (q - -593.31).abs() < 0.5,
4401 "pinned Q drift: got {q:.4}, expected -593.31 (C-validated)"
4402 );
4403}
4404
4405/// libopus CELT band edges (copy of `celt.rs::E_BANDS`, which is pub(crate)):
4406/// band `i` ends at `CELT_EBANDS[i] * 240` Hz at 48 kHz.
4407const CELT_EBANDS: [usize; NBANDS + 1] = [
4408 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100,
4409];
4410
4411/// Startup leak repro (lane-opus-reell): the first frames of the reell source
4412/// (digital silence then an attack) through the library gate's encoder
4413/// settings and our decoder. Prints per-frame CELT facts; fails if the decode
4414/// peak exceeds 4x the input peak in any frame.
4415#[test]
4416fn celt_silence_then_attack_decodes_bounded() {
4417 let _timing = timing_shared();
4418 let fs = 960usize;
4419 let ch = 2usize;
4420 let src = shellexpand("~/Music/reell.mp4");
4421 if !src.exists() {
4422 eprintln!("SKIP: missing {}", src.display());
4423 return;
4424 }
4425 let pcm = ffmpeg_decode_pcm(&src, 1.0);
4426 let mut enc = Encoder::new(48000, ch, Application::Audio).unwrap();
4427 enc.set_bitrate(96_000);
4428 enc.set_vbr_constrained(true);
4429 let mut dec = Decoder::new(48000, ch).unwrap();
4430 let mut bad = Vec::new();
4431 for frame in 0..12 {
4432 let slice = &pcm[frame * fs * ch..(frame + 1) * fs * ch];
4433 let in_peak = slice.iter().fold(0f32, |a, &x| a.max(x.abs()));
4434 let pcm_i16 = to_i16(slice);
4435 let mut buf = [0u8; 1500];
4436 let n = enc.encode(&pcm_i16, fs, &mut buf).unwrap();
4437 let mut out = vec![0f32; fs * ch];
4438 let got = dec.decode_float(&buf[..n], &mut out).unwrap();
4439 let d = dec.last_celt_diag().clone();
4440 let peak = out[..got * ch].iter().fold(0f32, |a, &x| a.max(x.abs()));
4441 let emax = d.old_band_e.iter().cloned().fold(f32::MIN, f32::max);
4442 println!(
4443 "frame {frame}: in_peak {in_peak:.5} bytes {n} dec(sil {} intra {} trans {} bits {}) bandE max {emax:.2} peak {peak:.5}",
4444 d.silence, d.intra, d.transient, d.total_bits
4445 );
4446 if peak > 4.0 * in_peak.max(1e-4) {
4447 bad.push(frame);
4448 }
4449 }
4450 assert!(bad.is_empty(), "decode peak >4x input in frames {bad:?}");
4451}
4452
4453/// Per-frame allocation diagnostics for SHORT-block (transient) frames at a
4454/// fixed bitrate: decodes both our stream and libopus's with our decoder, then
4455/// prints per-band mean pulses, fine_quant, alloc_trim, coded_bands, intensity,
4456/// dual_stereo share, spread/tf histograms, total_bits — ours vs ref, split by
4457/// the decoder's transient flag. Output: `lanes/opus-sb-r1.bits.txt`.
4458#[test]
4459#[ignore = "probe: per-frame short-block allocation dump over the local corpus; a multi-minute ffmpeg report run, not a suite gate"]
4460fn short_block_bits_vs_libopus() {
4461 let _timing = timing_shared();
4462 const SECS: f64 = 120.0;
4463 const FRAME: usize = 960;
4464 const CHANNELS: usize = 2;
4465 let kbps_env: u32 = std::env::var("SWEEP_KBPS")
4466 .ok()
4467 .and_then(|v| v.parse().ok())
4468 .unwrap_or(64);
4469 #[allow(non_snake_case)]
4470 let KBPS: u32 = kbps_env;
4471
4472 let all: &[(&str, &str)] = &[
4473 ("reell", "~/Music/reell.mp4"),
4474 ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
4475 ("her", "~/Music/reeli.mp3"),
4476 ("reelm", "~/Music/reelm.wav"),
4477 ("hein", "~/Downloads/reelm.mp3"),
4478 ];
4479 let only: Vec<String> = std::env::var("SWEEP_ONLY")
4480 .unwrap_or_else(|_| "reelm,hein".to_owned())
4481 .split(',')
4482 .filter(|s| !s.is_empty())
4483 .map(|s| s.trim().to_owned())
4484 .collect();
4485 let sources: Vec<(String, PathBuf)> = all
4486 .iter()
4487 .filter(|(tag, _)| only.iter().any(|o| o == tag))
4488 .map(|(tag, p)| (tag.to_string(), shellexpand(p)))
4489 .collect();
4490 assert!(!sources.is_empty(), "SWEEP_ONLY matched no sources");
4491
4492 let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes");
4493 fs::create_dir_all(&lanes_dir).unwrap();
4494 let out_path = lanes_dir.join("opus-sb-r1.bits.txt");
4495 let scratch = lanes_dir.join("opus-sb-r1.scratch.ogg");
4496 let nb = ec_opus::celt::NB_BANDS;
4497 let mut report = String::new();
4498
4499 for (tag, src) in &sources {
4500 if !src.exists() {
4501 eprintln!("SKIP {tag}: missing {}", src.display());
4502 continue;
4503 }
4504 let source_pcm = ffmpeg_decode_pcm(src, SECS);
4505 let seconds = source_pcm.len() as f64 / CHANNELS as f64 / 48000.0;
4506
4507 // Reference: ffmpeg libopus at KBPS, VBR.
4508 ffmpeg_encode_libopus(src, KBPS, &scratch, SECS);
4509 let ref_bytes = fs::metadata(&scratch)
4510 .map(|m| m.len() as usize)
4511 .unwrap_or(0);
4512 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
4513 let ref_pkts: Vec<Vec<u8>> = ogg_packets(&fs::read(&scratch).unwrap())
4514 .into_iter()
4515 .skip(2)
4516 .collect();
4517
4518 // Decode ref packets with our decoder, capture per-frame CELT diag.
4519 let mut ref_diags: Vec<ec_opus::celt::CeltDecDiag> = Vec::new();
4520 {
4521 let mut d = Decoder::new(48000, CHANNELS).unwrap();
4522 let mut buf = vec![0.0f32; 5760 * CHANNELS];
4523 for p in &ref_pkts {
4524 if p.is_empty() {
4525 continue;
4526 }
4527 let toc = ec_opus::Toc::new(p[0]);
4528 if d.decode_float(p, &mut buf).is_ok() && toc.mode() != Mode::Silk {
4529 ref_diags.push(d.last_celt_diag().clone());
4530 }
4531 }
4532 }
4533
4534 // Ours at the reference's realised rate.
4535 let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder");
4536 enc.set_bitrate((ref_kbps * 1000.0).round() as u32);
4537 enc.set_vbr_constrained(true);
4538 let mut dec = Decoder::new(48000, CHANNELS).unwrap();
4539 let mut packet = vec![0u8; 1500];
4540 let mut dbuf = vec![0.0f32; 5760 * CHANNELS];
4541 let mut ours_diags: Vec<ec_opus::celt::CeltDecDiag> = Vec::new();
4542 let mut ours_bytes = 0usize;
4543 for block in source_pcm.chunks(FRAME * CHANNELS) {
4544 let mut padded = block.to_vec();
4545 padded.resize(FRAME * CHANNELS, 0.0);
4546 let len = enc
4547 .encode_float(&padded, FRAME, &mut packet)
4548 .expect("encode");
4549 ours_bytes += len;
4550 let toc = ec_opus::Toc::new(packet[0]);
4551 if dec.decode_float(&packet[..len], &mut dbuf).is_ok() && toc.mode() != Mode::Silk {
4552 ours_diags.push(dec.last_celt_diag().clone());
4553 }
4554 }
4555 let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0;
4556
4557 report.push_str(&format!(
4558 "\n# source {tag} @{KBPS}k: ours {ours_kbps:.1} kbps, ref {ref_kbps:.1} kbps; \
4559 ours_celt {} frames, ref_celt {} frames\n",
4560 ours_diags.len(),
4561 ref_diags.len()
4562 ));
4563
4564 for (label, is_trans) in [("LONG", false), ("SHORT", true)] {
4565 let ours_t: Vec<&ec_opus::celt::CeltDecDiag> = ours_diags
4566 .iter()
4567 .filter(|d| d.transient == is_trans)
4568 .collect();
4569 let ref_t: Vec<&ec_opus::celt::CeltDecDiag> = ref_diags
4570 .iter()
4571 .filter(|d| d.transient == is_trans)
4572 .collect();
4573 let on = ours_t.len();
4574 let rn = ref_t.len();
4575 if on == 0 && rn == 0 {
4576 continue;
4577 }
4578 report.push_str(&format!("## {label}: ours {on} frames, ref {rn} frames\n"));
4579
4580 // Per-band mean pulses.
4581 report.push_str("# mean pulses per band (ours / ref)\n");
4582 report.push_str("# band_hz\tours\tref\tdiff\n");
4583 // Index loop kept: the index also drives other lookups or parallel arrays.
4584 #[allow(clippy::needless_range_loop)]
4585 for i in 0..nb {
4586 let om: f64 =
4587 ours_t.iter().map(|d| d.pulses[i] as f64).sum::<f64>() / on.max(1) as f64;
4588 let rm: f64 =
4589 ref_t.iter().map(|d| d.pulses[i] as f64).sum::<f64>() / rn.max(1) as f64;
4590 report.push_str(&format!(
4591 "{}\t{:.1}\t{:.1}\t{:.1}\n",
4592 CELT_EBANDS[i] * 240,
4593 om,
4594 rm,
4595 om - rm
4596 ));
4597 }
4598
4599 // Per-band mean fine_quant.
4600 report.push_str("# mean fine_quant per band (ours / ref)\n");
4601 report.push_str("# band_hz\tours\tref\n");
4602 // Index loop kept: the index also drives other lookups or parallel arrays.
4603 #[allow(clippy::needless_range_loop)]
4604 for i in 0..nb {
4605 let om: f64 =
4606 ours_t.iter().map(|d| d.fine_quant[i] as f64).sum::<f64>() / on.max(1) as f64;
4607 let rm: f64 =
4608 ref_t.iter().map(|d| d.fine_quant[i] as f64).sum::<f64>() / rn.max(1) as f64;
4609 report.push_str(&format!("{}\t{:.2}\t{:.2}\n", CELT_EBANDS[i] * 240, om, rm));
4610 }
4611
4612 // Aggregate stats.
4613 let mean = |v: &[&ec_opus::celt::CeltDecDiag],
4614 f: &dyn Fn(&ec_opus::celt::CeltDecDiag) -> f64|
4615 -> f64 {
4616 v.iter().map(|d| f(d)).sum::<f64>() / v.len().max(1) as f64
4617 };
4618 let mean_band_hz = |v: &[&ec_opus::celt::CeltDecDiag],
4619 f: &dyn Fn(&ec_opus::celt::CeltDecDiag) -> usize|
4620 -> f64 {
4621 let m = v.iter().map(|d| f(d)).sum::<usize>() / v.len().max(1);
4622 CELT_EBANDS[m] as f64 * 240.0
4623 };
4624 let dual_share = |v: &[&ec_opus::celt::CeltDecDiag]| -> f64 {
4625 v.iter().filter(|d| d.dual_stereo).count() as f64 / v.len().max(1) as f64
4626 };
4627 let fmt_hist = |h: [usize; 4]| -> String {
4628 h.iter()
4629 .map(|x| x.to_string())
4630 .collect::<Vec<_>>()
4631 .join(", ")
4632 };
4633 let spread_hist = |v: &[&ec_opus::celt::CeltDecDiag]| -> [usize; 4] {
4634 let mut h = [0usize; 4];
4635 for d in v {
4636 h[d.spread.min(3)] += 1;
4637 }
4638 h
4639 };
4640 let tf_hist = |v: &[&ec_opus::celt::CeltDecDiag]| -> [usize; 4] {
4641 let mut h = [0usize; 4];
4642 for d in v {
4643 for &t in &d.tf_res {
4644 h[(t + 1).clamp(0, 3) as usize] += 1;
4645 }
4646 }
4647 h
4648 };
4649
4650 let trim_hist = |v: &[&ec_opus::celt::CeltDecDiag]| -> [usize; 11] {
4651 let mut h = [0usize; 11];
4652 for d in v {
4653 h[d.alloc_trim.clamp(0, 10) as usize] += 1;
4654 }
4655 h
4656 };
4657 report.push_str(&format!(
4658 "# alloc_trim hist [0..10]: ours {:?} ref {:?}\n",
4659 trim_hist(&ours_t),
4660 trim_hist(&ref_t)
4661 ));
4662 report.push_str("# mean dynalloc boost per band (1/8 bit) ours / ref\n");
4663 // Index loop kept: the index also drives other lookups or parallel arrays.
4664 #[allow(clippy::needless_range_loop)]
4665 for b in 0..nb {
4666 let mo = mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| {
4667 d.offsets[b] as f64
4668 });
4669 let mr = mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| {
4670 d.offsets[b] as f64
4671 });
4672 if mo != 0.0 || mr != 0.0 {
4673 report.push_str(&format!("{}\t{:.1}\t{:.1}\n", CELT_EBANDS[b] * 240, mo, mr));
4674 }
4675 }
4676 report.push_str(&format!(
4677 "# alloc_trim mean: ours {:.2} ref {:.2}\n",
4678 mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.alloc_trim
4679 as f64),
4680 mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.alloc_trim
4681 as f64),
4682 ));
4683 report.push_str(&format!(
4684 "# coded_bands mean Hz: ours {:.0} ref {:.0}\n",
4685 mean_band_hz(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.coded_bands),
4686 mean_band_hz(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.coded_bands),
4687 ));
4688 report.push_str(&format!(
4689 "# intensity mean Hz: ours {:.0} ref {:.0}\n",
4690 mean_band_hz(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.intensity),
4691 mean_band_hz(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.intensity),
4692 ));
4693 report.push_str(&format!(
4694 "# dual_stereo share: ours {:.3} ref {:.3}\n",
4695 dual_share(&ours_t),
4696 dual_share(&ref_t),
4697 ));
4698 report.push_str(&format!(
4699 "# total_bits mean: ours {:.0} ref {:.0}\n",
4700 mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.total_bits
4701 as f64),
4702 mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.total_bits
4703 as f64),
4704 ));
4705 report.push_str(&format!(
4706 "# balance mean: ours {:.0} ref {:.0}\n",
4707 mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.balance as f64),
4708 mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.balance as f64),
4709 ));
4710 report.push_str(&format!(
4711 "# spread hist [0..3]: ours [{}] ref [{}]\n",
4712 fmt_hist(spread_hist(&ours_t)),
4713 fmt_hist(spread_hist(&ref_t)),
4714 ));
4715 report.push_str(&format!(
4716 "# tf_res hist [-1..2]: ours [{}] ref [{}]\n",
4717 fmt_hist(tf_hist(&ours_t)),
4718 fmt_hist(tf_hist(&ref_t)),
4719 ));
4720 }
4721 }
4722
4723 fs::write(&out_path, &report).unwrap();
4724 eprintln!("wrote {}", out_path.display());
4725}
4726
4727// ---------------------------------------------------------------------------
4728// opus_compare error map, any gate source (lane opus-her r1, generalised r3).
4729//
4730// Source/rate/tag come from EC_ERRMAP_SRC / EC_ERRMAP_KBPS / EC_ERRMAP_TAG
4731// (default: her@96, the row this was first written for). This localises it: both encoders run through
4732// the gate's exact path, opus_compare's per-2.5 ms hop ef² is bucketed into
4733// 1 s windows, and the top-10 windows (by ours/ref window ratio and by ours
4734// error share) are printed with our encoder flags plus both encoders' coded
4735// decisions — libopus's packets decoded with our decoder, the reell-r2 method.
4736// Frame mapping is in source-sample time (±1 frame of codec delay).
4737// Output: lanes/<EC_ERRMAP_TAG>.map.txt (default `opus-her-r1`). HER_KBPS (or
4738// EC_ERRMAP_KBPS) overrides the rate, EC_ERRMAP_SRC the source file: the map is
4739// the same analysis for any row of the library gate, not just her@96.
4740// ---------------------------------------------------------------------------
4741
4742/// Per-frame ours-vs-libopus coded decisions over a window of frames, decoded
4743/// with our own decoder on both sides. FRAME_SRC / FRAME_KBPS / FRAME_FROM /
4744/// FRAME_TO pick the source, rate and frame range (diagnostic).
4745#[test]
4746#[ignore = "probe: FRAME_SRC/FRAME_FROM/FRAME_TO-driven per-frame decision dump; returns silently when FRAME_SRC is missing, so it can never be a suite gate"]
4747fn frame_decisions_vs_libopus() {
4748 let _timing = timing_shared();
4749 const CH: usize = 2;
4750 let src_s = std::env::var("FRAME_SRC").unwrap_or_else(|_| "~/Music/reell.mp4".into());
4751 let src = shellexpand(&src_s);
4752 if !src.exists() {
4753 eprintln!("SKIP: missing {}", src.display());
4754 return;
4755 }
4756 let kbps: u32 = std::env::var("FRAME_KBPS")
4757 .ok()
4758 .and_then(|v| v.parse().ok())
4759 .unwrap_or(64);
4760 let from: usize = std::env::var("FRAME_FROM")
4761 .ok()
4762 .and_then(|v| v.parse().ok())
4763 .unwrap_or(0);
4764 let to: usize = std::env::var("FRAME_TO")
4765 .ok()
4766 .and_then(|v| v.parse().ok())
4767 .unwrap_or(6);
4768 let secs = (to as f64 * 0.02 + 1.0).max(2.0);
4769 let pcm = ffmpeg_decode_pcm(&src, secs);
4770 let scratch = std::env::temp_dir().join("ec-opus-frame-dec.opus");
4771 ffmpeg_encode_libopus(&src, kbps, &scratch, secs);
4772 let ref_pkts: Vec<Vec<u8>> = ogg_packets(&fs::read(&scratch).unwrap())
4773 .into_iter()
4774 .skip(2)
4775 .collect();
4776
4777 let show = |tag: &str, f: usize, bytes: usize, d: &ec_opus::celt::CeltDecDiag| {
4778 let e: Vec<String> = d.old_band_e[..NB_BANDS_DIAG]
4779 .iter()
4780 .map(|v| format!("{v:.1}"))
4781 .collect();
4782 println!(
4783 "f{f} {tag}: bytes {bytes} sil {} intra {} trans {} ac {} trim {} spread {} cb {} \
4784 tf {:?} pulses {:?} fine {:?} E {}",
4785 d.silence,
4786 d.intra,
4787 d.transient,
4788 d.anti_collapse,
4789 d.alloc_trim,
4790 d.spread,
4791 d.coded_bands,
4792 &d.tf_res[..NB_BANDS_DIAG],
4793 &d.pulses[..NB_BANDS_DIAG],
4794 &d.fine_quant[..NB_BANDS_DIAG],
4795 e.join(",")
4796 );
4797 };
4798
4799 let mut d = Decoder::new(48000, CH).unwrap();
4800 let mut buf = vec![0.0f32; 5760 * CH];
4801 let mut ref_rows = Vec::new();
4802 for p in ref_pkts.iter().take(to) {
4803 let ok = !p.is_empty()
4804 && ec_opus::Toc::new(p[0]).mode() != Mode::Silk
4805 && d.decode_float(p, &mut buf).is_ok();
4806 ref_rows.push(if ok {
4807 Some((p.len(), d.last_celt_diag().clone()))
4808 } else {
4809 None
4810 });
4811 }
4812
4813 // Encode at the reference's REALISED rate, like the library gate does:
4814 // ffmpeg's libopus overshoots its -b:a target by up to 12% on these
4815 // sources, and a flat target makes every byte column meaningless.
4816 let ref_bytes: usize = ref_pkts.iter().take(to).map(Vec::len).sum();
4817 let ref_kbps = ref_bytes as f64 * 8.0 / (ref_pkts.len().min(to) as f64 * 0.02) / 1000.0;
4818 println!("ffmpeg target {kbps} kbps, realised {ref_kbps:.1} kbps");
4819 let mut enc = Encoder::new(48000, CH, Application::Audio).unwrap();
4820 enc.set_bitrate((ref_kbps * 1000.0).round() as u32);
4821 enc.set_vbr_constrained(true);
4822 let mut dec = Decoder::new(48000, CH).unwrap();
4823 let mut out = vec![0u8; 1500];
4824 let mut ours_rows = Vec::new();
4825 for block in pcm.as_chunks::<{ 960 * CH }>().0.iter().take(to) {
4826 let n = enc.encode_float(block, 960, &mut out).unwrap();
4827 let ok = ec_opus::Toc::new(out[0]).mode() != Mode::Silk
4828 && dec.decode_float(&out[..n], &mut buf).is_ok();
4829 ours_rows.push(if ok {
4830 Some((n, dec.last_celt_diag().clone()))
4831 } else {
4832 None
4833 });
4834 }
4835
4836 if to - from <= 40 {
4837 for f in from..to {
4838 match ours_rows.get(f).and_then(|x| x.as_ref()) {
4839 Some((n, d)) => show("ours", f, *n, d),
4840 None => println!("f{f} ours: (silk/absent)"),
4841 }
4842 match ref_rows.get(f).and_then(|x| x.as_ref()) {
4843 Some((n, d)) => show("ref ", f, *n, d),
4844 None => println!("f{f} ref : (silk/absent)"),
4845 }
4846 }
4847 }
4848
4849 // Aggregate over the frames BOTH sides coded as CELT, split by whether
4850 // either side called the frame transient: which coded decision differs.
4851 let mut agg = [(0usize, [0.0f64; 8]); 2];
4852 let mut trans_diff = 0usize;
4853 for f in from..to {
4854 let (Some((no, o)), Some((nr, r))) = (
4855 ours_rows.get(f).and_then(|x| x.as_ref()),
4856 ref_rows.get(f).and_then(|x| x.as_ref()),
4857 ) else {
4858 continue;
4859 };
4860 if o.transient != r.transient {
4861 trans_diff += 1;
4862 }
4863 let slot = usize::from(o.transient || r.transient);
4864 let tf = |d: &ec_opus::celt::CeltDecDiag| {
4865 d.tf_res[..NB_BANDS_DIAG].iter().sum::<i32>() as f64 / NB_BANDS_DIAG as f64
4866 };
4867 let a = &mut agg[slot];
4868 a.0 += 1;
4869 for (k, v) in [
4870 *no as f64,
4871 *nr as f64,
4872 o.alloc_trim as f64,
4873 r.alloc_trim as f64,
4874 tf(o),
4875 tf(r),
4876 f64::from(u8::from(o.anti_collapse)),
4877 f64::from(u8::from(r.anti_collapse)),
4878 ]
4879 .into_iter()
4880 .enumerate()
4881 {
4882 a.1[k] += v;
4883 }
4884 }
4885 println!("frames {from}..{to}, transient-flag disagreements {trans_diff}");
4886 for (slot, name) in [(1usize, "transient"), (0, "steady ")] {
4887 let (n, v) = agg[slot];
4888 if n == 0 {
4889 continue;
4890 }
4891 let m = |k: usize| v[k] / n as f64;
4892 println!(
4893 "{name} n={n}: bytes o {:.1} r {:.1} | trim o {:.2} r {:.2} | mean tf_res o {:.3} \
4894 r {:.3} | anti_collapse o {:.2} r {:.2}",
4895 m(0),
4896 m(1),
4897 m(2),
4898 m(3),
4899 m(4),
4900 m(5),
4901 m(6),
4902 m(7)
4903 );
4904 }
4905}
4906
4907const NB_BANDS_DIAG: usize = ec_opus::celt::NB_BANDS;
4908
4909// ---------------------------------------------------------------------------
4910// Rate against the target: the CBR default must land within 5% of the bitrate
4911// asked for, on stereo music and speech.
4912// ---------------------------------------------------------------------------
4913
4914/// Encodes each corpus source at 32, 64 and 128 kbps (default CBR), decodes it
4915/// with our decoder, and asserts the realised rate is within 5% of the target and
4916/// that no CBR packet exceeds its byte budget (the D2b packet budget). Speech is
4917/// coded in Voip mode, where SILK packets come from. Corpus-backed like the
4918/// library gates: `cargo test --release -p ec-opus --test conformance
4919/// encoder_rate_target_gate -- --ignored --nocapture` with the sources in place.
4920#[test]
4921#[ignore = "corpus gate: needs ffmpeg and the ~/Music, ~/Downloads sources (about 3 min)"]
4922fn encoder_rate_target_gate() {
4923 let _timing = timing_shared();
4924 const SECS: f64 = 120.0;
4925 const FRAME: usize = 960; // 20 ms at 48 kHz
4926 const CHANNELS: usize = 2;
4927 const MAX_LAG: usize = 2000;
4928 let sources: &[(&str, &str, &str)] = &[
4929 ("nik", "music", "~/Music/reeln.mp4"),
4930 ("reelo", "music", "~/Music/reelo.mp3"),
4931 ("her", "music", "~/Music/reeli.mp3"),
4932 ("reell", "music", "~/Music/reell.mp4"),
4933 ("hein", "speech", "~/Downloads/reelm.mp3"),
4934 ];
4935 let mut rows = Vec::new();
4936 let mut violations = Vec::new();
4937 for &(tag, kind, path) in sources {
4938 let src = shellexpand(path);
4939 if !src.exists() {
4940 eprintln!("SKIP {tag}: missing {}", src.display());
4941 continue;
4942 }
4943 let pcm = ffmpeg_decode_pcm(&src, SECS);
4944 let frames = pcm.len() / CHANNELS;
4945 assert!(frames > 48_000, "{tag}: source too short");
4946 let seconds = frames as f64 / 48000.0;
4947 for &kbps in &[32u32, 64, 128] {
4948 // Speech goes through Voip, which is where SILK packets come from.
4949 let app = if kind == "speech" {
4950 Application::Voip
4951 } else {
4952 Application::Audio
4953 };
4954 let mut enc = Encoder::new(48000, CHANNELS, app).expect("encoder");
4955 enc.set_bitrate(kbps * 1000);
4956 // CBR packet budget, as the encoder derives it (payload bytes).
4957 let budget =
4958 ((kbps as u64 * 1000 * FRAME as u64 + 4 * 48000) / (8 * 48000)) as usize - 1;
4959 let mut dec = Decoder::new(48000, CHANNELS).unwrap();
4960 let mut out = vec![0u8; 1500];
4961 let mut buf = vec![0.0f32; 5760 * CHANNELS];
4962 let mut decoded = Vec::new();
4963 let mut bytes = 0usize;
4964 let (mut over, mut under) = (0usize, 0usize);
4965 let mut padded = Vec::new();
4966 for block in pcm.chunks(FRAME * CHANNELS) {
4967 let block = if block.len() < FRAME * CHANNELS {
4968 padded.clear();
4969 padded.extend_from_slice(block);
4970 padded.resize(FRAME * CHANNELS, 0.0);
4971 &padded[..]
4972 } else {
4973 block
4974 };
4975 let len = enc.encode_float(block, FRAME, &mut out).expect("encode");
4976 bytes += len;
4977 let payload = len - 1;
4978 over += usize::from(payload > budget);
4979 under += usize::from(payload < budget);
4980 let n = dec.decode_float(&out[..len], &mut buf).expect("decode");
4981 decoded.extend_from_slice(&buf[..n * CHANNELS]);
4982 }
4983 let real = bytes as f64 * 8.0 / seconds / 1000.0;
4984 let pct = (real / kbps as f64 - 1.0) * 100.0;
4985 let (_, aligned) = align_to_source(&pcm, &decoded, CHANNELS, MAX_LAG);
4986 let cmp = (pcm.len().min(aligned.len())) / CHANNELS * CHANNELS;
4987 let q = opus_compare(&to_i16(&pcm[..cmp]), &to_i16(&aligned[..cmp]), CHANNELS);
4988 println!(
4989 "{tag} ({kind}) @{kbps}k: realised {real:.2} kbps ({pct:+.2}%), Q {q:.2}, \
4990 budget {budget} B: {over} over, {under} under"
4991 );
4992 if pct.abs() > 5.0 {
4993 violations.push(format!("{tag} ({kind}) @{kbps}k: {pct:+.2}% (|>5%|)"));
4994 }
4995 if over > 0 {
4996 violations.push(format!(
4997 "{tag} ({kind}) @{kbps}k: {over} packets over the {budget} B budget"
4998 ));
4999 }
5000 rows.push(format!(
5001 "{tag}\t{kind}\t{kbps}\t{real:.2}\t{pct:+.2}\t{q:.2}\t{over}\t{under}"
5002 ));
5003 }
5004 }
5005 assert!(!rows.is_empty(), "no rate rows: no corpus source present");
5006 assert!(
5007 violations.is_empty(),
5008 "rate or packet budget violated:\n{}",
5009 violations.join("\n")
5010 );
5011}