forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

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