//! RFC 6716 conformance: the official test vectors, the `opus_compare` quality //! metric, real-file oracles against ffmpeg. //! //! All of it lives in one test binary on purpose — a file per feature costs a //! serial link-and-run for every build. use std::fs; use std::path::{Path, PathBuf}; use ec_opus::Decoder; /// One packet of an `opus_demo` test vector file. struct VectorPacket { payload: Vec, /// The reference decoder's range state after this packet. final_range: u32, } /// The `.bit` files are `opus_demo` output: per packet, a big-endian length, a /// big-endian final range, then the packet itself. fn read_vector(path: &Path) -> Vec { let data = fs::read(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); let mut out = Vec::new(); let mut i = 0; while i + 8 <= data.len() { let len = u32::from_be_bytes(data[i..i + 4].try_into().unwrap()) as usize; let rng = u32::from_be_bytes(data[i + 4..i + 8].try_into().unwrap()); i += 8; if i + len > data.len() { break; } out.push(VectorPacket { payload: data[i..i + len].to_vec(), final_range: rng, }); i += len; } out } /// Decodes a vector at 48 kHz stereo, returning the samples and how many /// packets ended with the reference range state. fn decode_vector(packets: &[VectorPacket]) -> (Vec, usize, usize) { let mut dec = Decoder::new(48000, 2).unwrap(); let mut pcm = Vec::new(); let mut buf = vec![0.0f32; 5760 * 2]; let mut matched = 0; let mut decoded = 0; for p in packets { match dec.decode_float(&p.payload, &mut buf) { Ok(n) => { pcm.extend_from_slice(&buf[..n * 2]); decoded += 1; if dec.final_range() == p.final_range { matched += 1; } } Err(e) => { panic!("packet {decoded} failed: {e}"); } } } (pcm, matched, decoded) } // --------------------------------------------------------------------------- // The conformance metric // --------------------------------------------------------------------------- // // RFC 6716 Section 6 defines a compliant decoder as one whose output stays // "within the thresholds specified by the opus_compare.c tool" against the // reference decoder's output for each test vector. That tool is a weighted // spectral comparison, reimplemented here so the check needs no C toolchain: // // 1. Both signals are cut into 480-sample Hann windows at a 120-sample hop // and turned into per-bin power spectra (bins 0..200 of 240). // 2. The reference's per-band energy is spread by a masking model: 10 dB per // Bark upwards, 15 dB downwards, -3 dB per 2.5 ms in time, 1 % crosstalk // between channels. A tenth of that masking energy is added to both // spectra, so error under a strong signal counts for less. // 3. Consecutive frames are averaged pairwise, then per bin the ratio // r = Y/X contributes r - log(r) - 1 (zero when equal, growing either // way); bins 79..81 are damped because the SILK/CELT crossover is free. // 4. The per-band mean is squared, averaged over bands, squared again, // raised to the fourth power per frame, averaged, and the 16th root taken. // Quality is 100*(1 - 0.5*ln(1+err)/ln(1.13)); 0 is the pass threshold and // 100 means identical output. // // A quality of 0 was calibrated to additive white noise at 48 dB SNR. const NBANDS: usize = 21; const BANDS: [usize; NBANDS + 1] = [ 0, 2, 4, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 68, 80, 96, 120, 156, 200, ]; const WIN_SIZE: usize = 480; const WIN_STEP: usize = 120; const NFREQS: usize = 240; /// A complex FFT of size `15 * 2^k`, which is what a 480-sample window needs. /// Same decomposition the decoder uses; duplicated here so the test measures /// the reference metric rather than the decoder's own code. struct Fft15 { n: usize, sub: ec_dsp::Fft, } impl Fft15 { fn new(n: usize) -> Fft15 { assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two()); Fft15 { n, sub: ec_dsp::Fft::new(n / 15), } } /// Power spectrum of a real signal, bins `0..n/2`. fn power(&mut self, x: &[f64], out: &mut [f64]) { let n = self.n; let l = n / 15; let mut re = vec![0.0f64; n]; let mut im = vec![0.0f64; n]; for n2 in 0..l { for k1 in 0..15 { let (mut sr, mut si) = (0.0, 0.0); for n1 in 0..15 { let a = 2.0 * std::f64::consts::PI * ((k1 * n1) % 15) as f64 / 15.0; sr += x[l * n1 + n2] * a.cos(); si += x[l * n1 + n2] * a.sin(); } let a = 2.0 * std::f64::consts::PI * (k1 * n2) as f64 / n as f64; let (c, s) = (a.cos(), a.sin()); re[k1 * l + n2] = sr * c - si * s; im[k1 * l + n2] = sr * s + si * c; } } for k1 in 0..15 { let rr = &mut re[k1 * l..(k1 + 1) * l]; let ii = &mut im[k1 * l..(k1 + 1) * l]; self.sub.inverse_split(rr, ii); for k2 in 0..l { let idx = k1 + 15 * k2; if idx < out.len() { let (r, i) = (rr[k2] * l as f64, ii[k2] * l as f64); out[idx] = r * r + i * i; } } } } } /// Per-bin power spectra and per-band energies, `band_energy()` in the tool. fn band_energy( signal: &[f64], channels: usize, nframes: usize, bands: &mut Option<&mut Vec>, ps: &mut Vec, ) { let mut fft = Fft15::new(WIN_SIZE); let window: Vec = (0..WIN_SIZE) .map(|j| 0.5 - 0.5 * (2.0 * std::f64::consts::PI / (WIN_SIZE - 1) as f64 * j as f64).cos()) .collect(); ps.resize(nframes * NFREQS * channels, 0.0); if let Some(b) = bands { b.resize(nframes * NBANDS * channels, 0.0); } let mut frame = vec![0.0f64; WIN_SIZE]; let mut spec = vec![0.0f64; NFREQS]; for xi in 0..nframes { for ci in 0..channels { for k in 0..WIN_SIZE { frame[k] = window[k] * signal[(xi * WIN_STEP + k) * channels + ci]; } spec.fill(0.0); fft.power(&frame, &mut spec); for bi in 0..NBANDS { let mut p = 0.0; for xj in BANDS[bi]..BANDS[bi + 1] { let v = spec[xj] + 100000.0; ps[(xi * NFREQS + xj) * channels + ci] = v; p += v; } if let Some(b) = bands { b[(xi * NBANDS + bi) * channels + ci] = p / (BANDS[bi + 1] - BANDS[bi]) as f64; } } } } } /// The raw `opus_compare` spectral error (before the quality mapping): /// 0 is identical output, growing with divergence. Used by the encoder gate /// to take an `err_ratio` of ours-vs-reference before the monotonic quality /// transform flattens the high-error tail. fn opus_compare_err(reference: &[i16], test: &[i16], channels: usize) -> f64 { opus_compare_err_parts(reference, test, channels).0 } /// `opus_compare_err` with the intermediates the per-band divergence /// diagnostic needs: `(err, per-band mean eb², per-frame ef²)`. The per-band /// mean is each band's additive share of the pre-squared frame error /// `ef = mean(eb²)`; the numerics are the wrapped function's, unchanged /// (guarded by `opus_compare_err_pinned_against_c`). fn opus_compare_err_parts( reference: &[i16], test: &[i16], channels: usize, ) -> (f64, Vec, Vec) { assert_eq!(reference.len(), test.len(), "sample counts must match"); let x: Vec = reference.iter().map(|&v| v as f64).collect(); let y: Vec = test.iter().map(|&v| v as f64).collect(); let xlength = x.len() / channels; assert!(xlength >= WIN_SIZE, "not enough samples to compare"); let nframes = (xlength - WIN_SIZE + WIN_STEP) / WIN_STEP; let mut band_eb2 = vec![0.0f64; NBANDS]; let mut frame_ef2 = Vec::with_capacity(nframes); let mut xb = Vec::new(); let mut big_x = Vec::new(); let mut big_y = Vec::new(); band_energy(&x, channels, nframes, &mut Some(&mut xb), &mut big_x); band_energy(&y, channels, nframes, &mut None, &mut big_y); for xi in 0..nframes { // Frequency masking, low to high then high to low. for bi in 1..NBANDS { for ci in 0..channels { xb[(xi * NBANDS + bi) * channels + ci] += 0.1 * xb[(xi * NBANDS + bi - 1) * channels + ci]; } } for bi in (0..NBANDS - 1).rev() { for ci in 0..channels { xb[(xi * NBANDS + bi) * channels + ci] += 0.03 * xb[(xi * NBANDS + bi + 1) * channels + ci]; } } // Temporal masking. if xi > 0 { for bi in 0..NBANDS { for ci in 0..channels { xb[(xi * NBANDS + bi) * channels + ci] += 0.5 * xb[((xi - 1) * NBANDS + bi) * channels + ci]; } } } // Crosstalk between channels. if channels == 2 { for bi in 0..NBANDS { let l = xb[(xi * NBANDS + bi) * channels]; let r = xb[(xi * NBANDS + bi) * channels + 1]; xb[(xi * NBANDS + bi) * channels] += 0.01 * r; xb[(xi * NBANDS + bi) * channels + 1] += 0.01 * l; } } // Apply the masking to both spectra. for bi in 0..NBANDS { for xj in BANDS[bi]..BANDS[bi + 1] { for ci in 0..channels { let m = 0.1 * xb[(xi * NBANDS + bi) * channels + ci]; big_x[(xi * NFREQS + xj) * channels + ci] += m; big_y[(xi * NFREQS + xj) * channels + ci] += m; } } } } // Average consecutive frames to make the comparison less twitchy. for bi in 0..NBANDS { for xj in BANDS[bi]..BANDS[bi + 1] { for ci in 0..channels { let mut xtmp = big_x[xj * channels + ci]; let mut ytmp = big_y[xj * channels + ci]; for xi in 1..nframes { let xtmp2 = big_x[(xi * NFREQS + xj) * channels + ci]; let ytmp2 = big_y[(xi * NFREQS + xj) * channels + ci]; big_x[(xi * NFREQS + xj) * channels + ci] += xtmp; big_y[(xi * NFREQS + xj) * channels + ci] += ytmp; xtmp = xtmp2; ytmp = ytmp2; } } } } let max_compare = BANDS[NBANDS]; let mut err = 0.0f64; for xi in 0..nframes { let mut ef = 0.0f64; for bi in 0..NBANDS { let mut eb = 0.0f64; for xj in BANDS[bi]..BANDS[bi + 1].min(max_compare) { for ci in 0..channels { let re = big_y[(xi * NFREQS + xj) * channels + ci] / big_x[(xi * NFREQS + xj) * channels + ci]; let mut im = re - re.ln() - 1.0; // The SILK/CELT crossover may differ in its filters. if (79..=81).contains(&xj) { im *= 0.1; } if xj == 80 { im *= 0.1; } eb += im; } } eb /= ((BANDS[bi + 1] - BANDS[bi]) * channels) as f64; let eb2 = eb * eb; band_eb2[bi] += eb2; ef += eb2; } ef /= NBANDS as f64; ef *= ef; let ef2 = ef * ef; frame_ef2.push(ef2); err += ef2; } err = (err / nframes as f64).powf(1.0 / 16.0); for b in &mut band_eb2 { *b /= nframes as f64; } (err, band_eb2, frame_ef2) } /// The `opus_compare` quality metric: >= 0 passes, 100 is identical output. fn opus_compare(reference: &[i16], test: &[i16], channels: usize) -> f64 { let err = opus_compare_err(reference, test, channels); 100.0 * (1.0 - 0.5 * (1.0 + err).ln() / 1.13f64.ln()) } /// `FLOAT2INT16`: what `opus_demo` writes, so the metric sees the same samples. fn to_i16(pcm: &[f32]) -> Vec { pcm.iter() .map(|&v| (v * 32768.0).round().clamp(-32768.0, 32767.0) as i16) .collect() } fn read_i16(path: &Path) -> Vec { let d = fs::read(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); d.as_chunks::<2>() .0 .iter() .map(|c| i16::from_le_bytes([c[0], c[1]])) .collect() } /// The RFC 8251 updated vectors (`opus_newvectors`), fetched by /// `scripts/fetch-vectors.sh opus-rfc8251`. Each `testvectorNN.bit` has two /// stereo references: `testvectorNN.dec` (with the CELT 180-degree phase shift /// of RFC 8251 Section 10) and `testvectorNNm.dec` (without it). An /// implementation is compliant when it matches either set. fn vectors_dir_8251() -> PathBuf { ec_testkit::root().join("vectors/opus-rfc8251/opus_newvectors") } /// Runs one RFC 8251 vector (stereo) against one of its reference files. Returns /// `(range-exact, decoded packets, quality %)`; the caller decides what passes. fn run_rfc8251(name: &str, reference: &str) -> (usize, usize, f64) { let dir = vectors_dir_8251(); let bit = ec_testkit::fixture(&format!("vectors/opus-rfc8251/opus_newvectors/{name}.bit")); let packets = read_vector(&bit); let (pcm, matched, decoded) = decode_vector(&packets); let refs = read_i16(&dir.join(reference)); let mine = to_i16(&pcm); assert_eq!( refs.len(), mine.len(), "{reference}: decoded {} samples, reference has {}", mine.len(), refs.len() ); let identical = refs.iter().zip(&mine).filter(|(a, b)| a == b).count(); let quality = opus_compare(&refs, &mine, 2); println!( "{reference}: {matched}/{decoded} packets range-exact, {:.4} % samples identical, quality {quality:.2} %", 100.0 * identical as f64 / refs.len() as f64 ); (matched, decoded, quality) } /// RFC 8251 Section 11: "An implementation is compliant as long as it passes /// either set of vectors." A set passes when every vector in it has all packets /// range-exact and quality >= 0. The `.dec` set (with the CELT 180-degree phase /// shift) and the `m` set (without it) are both run and both reported. #[test] fn rfc8251_test_vectors() { let mut dec_ok = true; let mut m_ok = true; for name in VECTORS { let (dm, dd, dq) = run_rfc8251(name, &format!("{name}.dec")); let (mm, md, mq) = run_rfc8251(name, &format!("{name}m.dec")); dec_ok &= dm == dd && dq >= 0.0; m_ok &= mm == md && mq >= 0.0; } println!("RFC 8251 set `.dec` passes: {dec_ok}; set `m` passes: {m_ok}"); assert!( dec_ok || m_ok, "neither RFC 8251 set passes (see the per-vector lines above)" ); } /// Every vector in the RFC 6716 suite, in the order the RFC lists them. const VECTORS: [&str; 12] = [ "testvector01", "testvector02", "testvector03", "testvector04", "testvector05", "testvector06", "testvector07", "testvector08", "testvector09", "testvector10", "testvector11", "testvector12", ]; // --------------------------------------------------------------------------- // Real files: the Ogg-Opus fixtures, against ffmpeg // --------------------------------------------------------------------------- use ec_opus::MultistreamDecoder; use std::process::Command; /// Splits an Ogg stream into packets (RFC 3533): a page header, a segment /// table, and packets that end on any segment shorter than 255 bytes. fn ogg_packets(data: &[u8]) -> Vec> { let mut packets = Vec::new(); let mut partial: Vec = Vec::new(); let mut i = 0; while i + 27 <= data.len() { assert_eq!(&data[i..i + 4], b"OggS", "not an Ogg page at {i}"); let nsegs = data[i + 26] as usize; let table = &data[i + 27..i + 27 + nsegs]; let mut body = i + 27 + nsegs; for &len in table { let len = len as usize; partial.extend_from_slice(&data[body..body + len]); body += len; if len < 255 { packets.push(core::mem::take(&mut partial)); } } i = body; } packets } /// The RFC 7845 identification header: channel count, pre-skip and the /// multistream layout. struct OpusHead { channels: usize, pre_skip: usize, streams: usize, coupled: usize, mapping: Vec, } fn parse_opus_head(p: &[u8]) -> OpusHead { assert_eq!(&p[..8], b"OpusHead"); let channels = p[9] as usize; let pre_skip = u16::from_le_bytes([p[10], p[11]]) as usize; let family = p[18]; if family == 0 { OpusHead { channels, pre_skip, streams: 1, coupled: channels - 1, mapping: (0..channels as u8).collect(), } } else { OpusHead { channels, pre_skip, streams: p[19] as usize, coupled: p[20] as usize, mapping: p[21..21 + channels].to_vec(), } } } fn fixture(name: &str) -> PathBuf { ec_testkit::fixture(&format!("audio/{name}")) } /// ffmpeg's decode of the same file, interleaved `f32` in ffmpeg's channel /// order, with the pre-skip already removed. /// /// The decoder is forced to `libopus` — the reference implementation. ffmpeg's /// own native Opus decoder is a third implementation and deviates from libopus /// by as much as 0.97 correlation on this very fixture's coupled surround /// streams, so it makes a poor oracle. fn ffmpeg_decode(path: &Path, channels: usize) -> Vec { let out = ec_testkit::ffmpeg() .args(["-v", "error", "-c:a", "libopus", "-i"]) .arg(path) .args([ "-f", "f32le", "-ar", "48000", "-ac", &channels.to_string(), "-", ]) .output() .expect("run ffmpeg"); assert!( out.status.success(), "ffmpeg could not decode {}", path.display() ); out.stdout .as_chunks::<4>() .0 .iter() .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) .collect() } /// Decodes an Ogg-Opus file with the multistream decoder, pre-skip removed. fn decode_ogg(path: &Path) -> (Vec, usize) { let data = fs::read(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); let packets = ogg_packets(&data); let head = parse_opus_head(&packets[0]); let mut dec = MultistreamDecoder::with_rate(48000, head.streams, head.coupled, &head.mapping); let mut pcm = Vec::new(); for p in packets.iter().skip(2) { if p.is_empty() { continue; } let frame = dec.decode_packet(p).expect("decode"); pcm.extend_from_slice(&frame); } pcm.drain(..head.pre_skip * head.channels); (pcm, head.channels) } fn correlation(a: &[f32], b: &[f32]) -> f64 { let n = a.len().min(b.len()); let (mut sxy, mut sxx, mut syy) = (0.0f64, 0.0f64, 0.0f64); for i in 0..n { sxy += a[i] as f64 * b[i] as f64; sxx += (a[i] as f64).powi(2); syy += (b[i] as f64).powi(2); } if sxx == 0.0 || syy == 0.0 { return if sxx == syy { 1.0 } else { 0.0 }; } sxy / (sxx * syy).sqrt() } /// Power at `freq` in a channel, by the Goertzel algorithm. fn tone_power(x: &[f32], channels: usize, ch: usize, freq: f64) -> f64 { let n = x.len() / channels; let w = 2.0 * std::f64::consts::PI * freq / 48000.0; let coeff = 2.0 * w.cos(); let (mut s1, mut s2) = (0.0f64, 0.0f64); for i in 0..n { let s = x[i * channels + ch] as f64 + coeff * s1 - s2; s2 = s1; s1 = s; } (s1 * s1 + s2 * s2 - coeff * s1 * s2) / (n * n) as f64 } #[test] fn ogg_opus_fixtures_match_ffmpeg() { // Mapping family 1 puts 5.1 in Vorbis order; ffmpeg hands its own order // back, so the comparison permutes one into the other. const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3]; for (name, channels) in [ ("opus-ogg-mono-48000.opus", 1usize), ("opus-ogg-stereo-48000.opus", 2), ("opus-ogg-5.1-48000.opus", 6), ] { let path = fixture(name); let reference = ffmpeg_decode(&path, channels); let (mine, ch) = decode_ogg(&path); assert_eq!(ch, channels, "{name}: channel count"); let mut worst = 1.0f64; let n = (reference.len() / channels).min(mine.len() / channels); assert!(n > 48000, "{name}: only {n} samples decoded"); for c in 0..channels { let their_c = if channels == 6 { VORBIS_TO_FFMPEG_5_1[c] } else { c }; let a: Vec = (0..n).map(|i| mine[i * channels + c]).collect(); let b: Vec = (0..n).map(|i| reference[i * channels + their_c]).collect(); let corr = correlation(&a, &b); println!("{name}: channel {c} correlation {corr:.5}"); worst = worst.min(corr); } assert!( worst >= 0.99, "{name}: worst channel correlation {worst:.5}" ); } } #[test] fn five_one_channels_land_in_the_right_places() { // The fixture carries one distinct sine per channel, so a channel-order // bug shows up as a channel playing the wrong tone. The tones themselves // come from the reference decode rather than from an assumption about how // ffmpeg laid the fixture out; what is asserted is that this decoder's // Vorbis-order output is the reference's 5.1-order output permuted. const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3]; const TONES: [f64; 6] = [220.0, 440.0, 660.0, 55.0, 880.0, 1320.0]; let path = fixture("opus-ogg-5.1-48000.opus"); let reference = ffmpeg_decode(&path, 6); let (pcm, channels) = decode_ogg(&path); assert_eq!(channels, 6); let dominant = |x: &[f32], ch: usize| -> usize { let mut best = (0usize, 0.0f64); for (t, &f) in TONES.iter().enumerate() { let p = tone_power(x, 6, ch, f); if p > best.1 { best = (t, p); } } best.0 }; let mut seen = [false; 6]; for (c, &their) in VORBIS_TO_FFMPEG_5_1.iter().enumerate() { let want = dominant(&reference, their); let got = dominant(&pcm, c); println!( "channel {c}: {} Hz (reference channel {their} carries {} Hz)", TONES[got], TONES[want] ); assert_eq!(got, want, "channel {c} carries the wrong tone"); assert!(!seen[got], "tone {} Hz appears on two channels", TONES[got]); seen[got] = true; } } // --------------------------------------------------------------------------- // Encoder: self-consistency (range-exact against our own decoder) // --------------------------------------------------------------------------- use ec_opus::{Application, Bandwidth, Encoder, Mode, MultistreamEncoder, Packet}; /// A deterministic music-like test signal: several detuned partials plus a /// swept component per channel, loud enough to exercise every band. fn test_signal(channels: usize, secs: f64) -> Vec { let n = (48000.0 * secs) as usize; let mut out = Vec::with_capacity(n * channels); for i in 0..n { let t = i as f64 / 48000.0; for c in 0..channels { let base = 220.0 * (c as f64 * 0.5 + 1.0); let sweep = 400.0 + 3000.0 * (0.5 + 0.5 * (0.13 * t).sin()); let v = 0.35 * (std::f64::consts::TAU * base * t).sin() + 0.2 * (std::f64::consts::TAU * base * 3.01 * t).sin() + 0.12 * (std::f64::consts::TAU * sweep * t).sin() + 0.08 * (std::f64::consts::TAU * 9000.0 * (1.0 + 0.02 * c as f64) * t).sin(); out.push(v as f32); } } out } /// Encodes `pcm` in `frame`-sample packets and decodes each with our own /// decoder, asserting the range coder states agree packet for packet — the /// same bit-exact check the RFC vectors put on the decoder, now closing the /// loop over the encoder. Returns the decoded signal and total packet bytes. fn roundtrip_own( enc: &mut Encoder, pcm: &[f32], channels: usize, frame: usize, ) -> (Vec, usize) { let mut dec = Decoder::new(48000, channels).unwrap(); let mut out = vec![0u8; 1500]; let mut decoded = Vec::new(); let mut buf = vec![0.0f32; 5760 * channels]; let mut bytes = 0usize; let mut padded = Vec::new(); for block in pcm.chunks(frame * channels) { let block = if block.len() < frame * channels { padded.clear(); padded.extend_from_slice(block); padded.resize(frame * channels, 0.0); &padded[..] } else { block }; let len = enc.encode_float(block, frame, &mut out).expect("encode"); bytes += len; let n = dec.decode_float(&out[..len], &mut buf).expect("decode"); assert_eq!(n, frame, "decoded frame size"); assert_eq!( dec.final_range(), enc.final_range(), "range state diverged between encoder and decoder" ); decoded.extend_from_slice(&buf[..n * channels]); } (decoded, bytes) } /// Worst-channel correlation against the source with the encoder's own /// delay removed — `delay` is [`Encoder::look_ahead`] for the frame size the /// round trip used, never a constant (it moved 120 -> 312 when the CELT layer /// took libopus's Fs/250 input delay). fn delayed_corr(source: &[f32], decoded: &[f32], channels: usize, delay: usize) -> f64 { let n = (decoded.len() / channels).saturating_sub(delay); let n = n.min(source.len() / channels); let mut worst = 1.0f64; for c in 0..channels { let a: Vec = (0..n).map(|i| source[i * channels + c]).collect(); let b: Vec = (0..n) .map(|i| decoded[(i + delay) * channels + c]) .collect(); worst = worst.min(correlation(&a, &b)); } worst } /// Every rate from the product's table, mono and stereo, 20 ms CBR: the /// encoder must be decodable by its own decoder range-exactly (asserted in /// the helper) and land close to the source. The cross-implementation checks /// against libopus live below — self-consistency alone proves nothing about /// the world (the incumbent's exact disease). #[test] fn encoder_roundtrips_at_every_rate() { for channels in [1usize, 2] { let pcm = test_signal(channels, 2.0); for kbps in [32u32, 64, 96, 128, 160, 165, 192, 256, 320, 510] { let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap(); enc.set_bitrate(kbps * 1000); let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, channels, 960); let corr = delayed_corr(&pcm, &decoded, channels, enc.look_ahead(960)); let rate = bytes as f64 * 8.0 / 2.0 / 1000.0; println!("{channels} ch {kbps:>3} kbps: corr {corr:.4}, actual {rate:.1} kbps"); let floor = if kbps < 64 { 0.8 } else { 0.9 }; assert!( corr >= floor, "{channels} ch {kbps} kbps: correlation {corr:.4}" ); } } } #[test] // Expectations are libopus 1.6's (opus_encoder.c mode_thresholds and the // voice/music bandwidth tables blended by voice_est) since lane opus-mode; // matched against ffmpeg libopus on real speech in lanes/opus-mode-r1.sweep.txt. fn encoder_mode_follows_application_bitrate_channels_and_frame_size() { #[derive(Clone, Copy, Debug)] struct Case { app: Application, channels: usize, bps: u32, frame: usize, mode_request: Option, bandwidth_request: Option, mode: Mode, bandwidth: Bandwidth, config: u8, code: u8, frames: usize, } let cases = [ Case { app: Application::Voip, channels: 1, bps: 8_000, frame: 480, mode_request: None, bandwidth_request: None, mode: Mode::Celt, bandwidth: Bandwidth::Narrow, config: 18, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 1, bps: 12_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Silk, bandwidth: Bandwidth::Wide, config: 9, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 1, bps: 13_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Silk, bandwidth: Bandwidth::Wide, config: 9, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 1, bps: 16_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 1, bps: 19_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 1, bps: 20_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 1, bps: 39_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 1, bps: 40_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 0, frames: 1, }, Case { app: Application::Audio, channels: 1, bps: 16_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 0, frames: 1, }, Case { app: Application::Audio, channels: 1, bps: 64_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Celt, bandwidth: Bandwidth::Full, config: 31, code: 0, frames: 1, }, Case { app: Application::LowDelay, channels: 1, bps: 16_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Celt, bandwidth: Bandwidth::Full, config: 31, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 2, bps: 16_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 2, bps: 24_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 2, bps: 32_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 2, bps: 38_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 2, bps: 40_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 2, bps: 78_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Celt, bandwidth: Bandwidth::Full, config: 31, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 2, bps: 80_000, frame: 960, mode_request: None, bandwidth_request: None, mode: Mode::Celt, bandwidth: Bandwidth::Full, config: 31, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 2, bps: 32_000, frame: 480, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 14, code: 0, frames: 1, }, Case { app: Application::Voip, channels: 2, bps: 32_000, frame: 1920, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 3, frames: 2, }, Case { app: Application::Voip, channels: 2, bps: 32_000, frame: 2880, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 3, frames: 3, }, Case { app: Application::Voip, channels: 1, bps: 16_000, frame: 1920, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 3, frames: 2, }, Case { app: Application::Voip, channels: 1, bps: 19_000, frame: 2880, mode_request: None, bandwidth_request: None, mode: Mode::Hybrid, bandwidth: Bandwidth::Full, config: 15, code: 3, frames: 3, }, Case { app: Application::Audio, channels: 1, bps: 64_000, frame: 480, mode_request: Some(Mode::Silk), bandwidth_request: Some(Bandwidth::Medium), mode: Mode::Silk, bandwidth: Bandwidth::Medium, config: 4, code: 0, frames: 1, }, ]; for case in cases { let mut enc = Encoder::new(48000, case.channels, case.app).unwrap(); enc.set_bitrate(case.bps); enc.set_mode(case.mode_request); enc.set_bandwidth(case.bandwidth_request); let pcm = vec![0.0f32; case.frame * case.channels]; let mut out = vec![0u8; 4096]; let n = enc.encode_float(&pcm, case.frame, &mut out).unwrap(); let packet = Packet::parse(&out[..n], false).unwrap(); let toc = packet.toc; assert_eq!(toc.mode(), case.mode, "{case:?}"); assert_eq!(toc.bandwidth(), case.bandwidth, "{case:?}"); assert_eq!(toc.config, case.config, "{case:?}"); let cbr_padded = case.code == 0 && toc.code == 3 && case.mode == Mode::Silk; assert!(toc.code == case.code || cbr_padded, "{case:?}"); assert_eq!( toc.stereo, case.channels == 2 && case.bps > 16_000, "{case:?}" ); assert_eq!(packet.frames.len(), case.frames, "{case:?}"); assert_eq!(packet.samples_48k(), case.frame, "{case:?}"); assert!(n > 1, "{case:?}: empty packet"); } } /// All four CELT frame sizes survive the loop, and constrained VBR both /// stays decodable and lands near its target. #[test] fn encoder_frame_sizes_and_vbr() { let pcm = test_signal(2, 1.0); for frame in [120usize, 240, 480, 960] { let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); enc.set_bitrate(128_000); let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, frame); let corr = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(frame)); println!("frame {frame}: corr {corr:.4}"); assert!(corr >= 0.85, "frame {frame}: correlation {corr:.4}"); } let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); enc.set_bitrate(128_000); enc.set_vbr_constrained(true); let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, 2, 960); let corr = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(960)); let rate = bytes as f64 * 8.0 / 1.0 / 1000.0; println!("cvbr 128k: corr {corr:.4}, actual {rate:.1} kbps"); assert!(corr >= 0.9, "cvbr: correlation {corr:.4}"); assert!( (90.0..=150.0).contains(&rate), "cvbr at 128k landed on {rate:.1} kbps" ); } // --------------------------------------------------------------------------- // Encoder: the world must decode it. Self-consistency alone was the // incumbent's disease (correlation 0.06 against libopus at 256 kbps while // its own round trip passed), so every claim here runs through ffmpeg's // libopus — the reference implementation — via Ogg-Opus files this crate // muxed itself. // --------------------------------------------------------------------------- use ec_core::registry::{CodecId, CodecParameters, MediaParameters, Muxer, StreamInfo}; use ec_core::{ChannelLayout, Packet as CorePacket, TimeBase}; use ec_ogg::OggMuxer; /// The RFC 7845 identification header for this encoder — built by the crate's /// own [`ec_opus::ogg`] helper, so a muxer and the encoder cannot disagree. /// `pre_skip` is the encoder's [`Encoder::look_ahead`]: 312, the CELT overlap /// plus its input delay compensation, for every CELT call site; SILK's own /// delay for SILK. fn opus_head(channels: usize, pre_skip: u16, layout: Option<(usize, usize, &[u8])>) -> Vec { let mapping = layout.map(|(streams, coupled, table)| (1u8, streams as u8, coupled as u8, table)); ec_opus::ogg::opus_head(channels as u8, pre_skip, 48000, 0, mapping) } /// Muxes packets into an Ogg-Opus file whose final granule trims the stream /// to exactly `total_samples` — RFC 7845 end-trimming plus the pre-skip /// accounting. fn write_ogg_opus( path: &Path, packets: &[Vec], head: Vec, channels: usize, total_samples: usize, pre_skip: i64, ) { let file = std::io::BufWriter::new(fs::File::create(path).unwrap()); let mut mux = OggMuxer::new(file); let tb = TimeBase::from_rate(48000); let mut params = CodecParameters::new(CodecId::Opus); params.extradata = Some(head.into()); if let MediaParameters::Audio(a) = &mut params.media { a.sample_rate = 48000; a.layout = ChannelLayout::from_count(channels); } mux.add_stream(StreamInfo::new(0, tb, params)).unwrap(); let mut pts = 0i64; for (idx, p) in packets.iter().enumerate() { let last = idx == packets.len() - 1; let packet_dur = ec_opus::Packet::parse(p, false).unwrap().samples_48k() as i64; let dur = if last { total_samples as i64 + pre_skip - pts } else { packet_dur }; let pkt = CorePacket::new(0, tb, p.clone()) .with_pts(pts) .with_duration(dur); mux.write_packet(&pkt).unwrap(); pts += packet_dur; } mux.finish().unwrap(); } /// Encodes `pcm` (plus one flush frame for the 120-sample delay) as 20 ms /// packets. fn encode_packets(enc: &mut Encoder, pcm: &[f32], channels: usize) -> Vec> { let mut out = vec![0u8; 1500]; let mut packets = Vec::new(); let mut padded = Vec::new(); for block in pcm.chunks(960 * channels) { let block = if block.len() < 960 * channels { padded.clear(); padded.extend_from_slice(block); padded.resize(960 * channels, 0.0); &padded[..] } else { block }; let len = enc.encode_float(block, 960, &mut out).expect("encode"); packets.push(out[..len].to_vec()); } // One silent frame flushes the delay past the end trim. let silence = vec![0.0f32; 960 * channels]; let len = enc.encode_float(&silence, 960, &mut out).expect("encode"); packets.push(out[..len].to_vec()); packets } fn temp_path(name: &str) -> PathBuf { std::env::temp_dir().join(format!("ec-opus-enc-{}-{name}", std::process::id())) } /// The full product rate table, mono and stereo, decoded by libopus: the /// worst-channel correlation and the opus_compare quality, per rate. The /// incumbent fails this file's 256 kbps row at correlation 0.06; the MUST /// bars here are correlation >= 0.9 at 96/165/256 kbps. #[test] fn oracle_decodes_our_packets_across_the_rate_table() { for channels in [1usize, 2] { let pcm = test_signal(channels, 2.0); let total = pcm.len() / channels; let mut table = Vec::new(); for kbps in [16u32, 32, 64, 96, 128, 160, 165, 192, 256, 320, 510] { let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap(); enc.set_bitrate(kbps * 1000); let packets = encode_packets(&mut enc, &pcm, channels); let path = temp_path(&format!("{channels}ch-{kbps}k.opus")); write_ogg_opus( &path, &packets, opus_head(channels, enc.look_ahead(960) as u16, None), channels, total, enc.look_ahead(960) as i64, ); let reference = ffmpeg_decode(&path, channels); let _ = fs::remove_file(&path); let n = (reference.len() / channels).min(total); assert!( n >= total - 960, "{channels} ch {kbps} kbps: libopus returned {n} of {total} samples" ); let mut worst = 1.0f64; for c in 0..channels { let a: Vec = (0..n).map(|i| pcm[i * channels + c]).collect(); let b: Vec = (0..n).map(|i| reference[i * channels + c]).collect(); worst = worst.min(correlation(&a, &b)); } let quality = opus_compare( &to_i16(&pcm[..n * channels]), &to_i16(&reference[..n * channels]), channels, ); table.push(format!( "{channels} ch {kbps:>3} kbps: worst corr {worst:.4}, opus_compare {quality:.1}" )); let floor = match kbps { // 16 kbps fullband CELT is the honest bottom of the range: // reported, held to "clearly the same signal", not to hi-fi. 0..=19 => { if channels == 1 { 0.6 } else { // Stereo SILK with the libopus LR_to_MS rate split // and panned-mono rule (lane opus-silkq r4): .4534. 0.44 } } 20..=39 => 0.6, 40..=95 => 0.8, _ => 0.9, }; assert!( worst >= floor, "{channels} ch {kbps} kbps: libopus heard correlation {worst:.4} (floor {floor})" ); if kbps >= 96 { assert!( quality >= 0.0, "{channels} ch {kbps} kbps: opus_compare {quality:.1}" ); } } for line in table { println!("{line}"); } } // SILK, mono, the speech-rate corner: libopus must hear what our decoder hears. let pcm = test_signal(1, 2.0); let total = pcm.len(); for kbps in [8u32, 12, 16] { let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); enc.set_bitrate(kbps * 1000); let pre_skip = enc.look_ahead(960) as u16; let packets = encode_packets(&mut enc, &pcm, 1); let path = temp_path(&format!("silk-1ch-{kbps}k.opus")); write_ogg_opus( &path, &packets, opus_head(1, pre_skip, None), 1, total, pre_skip as i64, ); let reference = ffmpeg_decode(&path, 1); let _ = fs::remove_file(&path); let mut dec = Decoder::new(48000, 1).unwrap(); let mut buf = vec![0f32; 5760]; let mut ours = Vec::new(); for p in &packets { let n = dec.decode_float(p, &mut buf).unwrap(); ours.extend_from_slice(&buf[..n]); } let ours = &ours[pre_skip as usize..]; let n = reference.len().min(ours.len()).min(total); let corr = correlation(&ours[..n], &reference[..n]); println!("silk 1 ch {kbps:>3} kbps: oracle vs ours corr {corr:.4}"); assert!(corr >= 0.99, "silk {kbps} kbps: correlation {corr:.4}"); } } /// 5.1 multistream: one distinct tone per channel, encoded with the /// mapping-family-1 layout and decoded by libopus — every channel must come /// back in its place (order-preserved) at correlation >= 0.9. #[test] fn five_one_encode_end_to_end() { const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3]; const TONES: [f64; 6] = [220.0, 440.0, 660.0, 55.0, 880.0, 1320.0]; let total = 96000usize; // Vorbis order input, one tone per channel plus a quiet upper partial so // every stream codes real content. let mut pcm = Vec::with_capacity(total * 6); for i in 0..total { let t = i as f64 / 48000.0; for f in TONES { let v = 0.4 * (std::f64::consts::TAU * f * t).sin() + 0.05 * (std::f64::consts::TAU * f * 7.03 * t).sin(); pcm.push(v as f32); } } let mut enc = MultistreamEncoder::surround_5_1(48000).unwrap(); enc.set_bitrate(384_000); let mut out = vec![0u8; 8 * 1500]; let mut packets = Vec::new(); for block in pcm.as_chunks::<{ 960 * 6 }>().0 { let len = enc.encode_float(block, 960, &mut out).expect("encode"); packets.push(out[..len].to_vec()); } let silence = vec![0.0f32; 960 * 6]; let len = enc.encode_float(&silence, 960, &mut out).expect("encode"); packets.push(out[..len].to_vec()); let (streams, coupled, mapping) = enc.layout(); let pre_skip = enc.look_ahead(960); let head = opus_head(6, pre_skip as u16, Some((streams, coupled, mapping))); let path = temp_path("5.1.opus"); write_ogg_opus(&path, &packets, head, 6, total, pre_skip as i64); let reference = ffmpeg_decode(&path, 6); let _ = fs::remove_file(&path); let n = (reference.len() / 6).min(total); assert!(n >= total - 960, "libopus returned {n} of {total} samples"); for (c, &their) in VORBIS_TO_FFMPEG_5_1.iter().enumerate() { let a: Vec = (0..n).map(|i| pcm[i * 6 + c]).collect(); let b: Vec = (0..n).map(|i| reference[i * 6 + their]).collect(); let corr = correlation(&a, &b); println!("5.1 channel {c} ({} Hz): corr {corr:.4}", TONES[c]); assert!( corr >= 0.9, "5.1 channel {c} came back at correlation {corr:.4}" ); } } /// The muxed file's duration must be exact: the final granule trims the /// flush frame so a 2.000 s input probes as 2.000 s, and the sample count /// libopus hands back is exactly the input length. #[test] fn ogg_opus_round_trip_duration_is_exact() { let pcm = test_signal(2, 2.0); let total = pcm.len() / 2; let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); enc.set_bitrate(128_000); let packets = encode_packets(&mut enc, &pcm, 2); let path = temp_path("duration.opus"); let pre_skip = enc.look_ahead(960); write_ogg_opus( &path, &packets, opus_head(2, pre_skip as u16, None), 2, total, pre_skip as i64, ); let probe = ec_testkit::ffprobe() .args([ "-v", "error", "-show_entries", "stream=duration", "-of", "default=noprint_wrappers=1", ]) .arg(&path) .output(); if let Ok(p) = probe && p.status.success() { let text = String::from_utf8_lossy(&p.stdout); let dur: f64 = text .trim() .strip_prefix("duration=") .unwrap_or("0") .parse() .unwrap_or(0.0); // ffprobe reports Ogg-Opus durations *including* the pre-skip — its // own 3.000 s encode probes as 3.0065 (312/48000 more). Ours carries // the same pre-skip our encoder advertises, so exact is 2.000 s plus // it; the decoded sample count below is the pre-skip-free half. let expected = (total as f64 + pre_skip as f64) / 48000.0; assert!( (dur - expected).abs() < 1e-6, "ffprobe reports {dur} s, expected {expected} s (2.000 s + pre-skip)" ); } let decoded = ffmpeg_decode(&path, 2); assert_eq!( decoded.len() / 2, total, "libopus decoded {} samples of {total}", decoded.len() / 2 ); let _ = fs::remove_file(&path); } /// Malformed input must come back as an error, never a panic: the decoders /// index tables with values the bitstream chooses, so this throws well-formed /// TOC bytes at random payloads to make sure every mode is actually entered. #[test] fn garbage_payloads_never_panic() { let mut state = 0x12345678u32; let mut rand = move || { state ^= state << 13; state ^= state >> 17; state ^= state << 5; state }; let mut dec = Decoder::new(48000, 2).unwrap(); let mut ms = MultistreamDecoder::with_rate(48000, 4, 2, &[0, 4, 1, 2, 3, 5]); let mut out = vec![0.0f32; 5760 * 6]; for config in 0..32u8 { for stereo in 0..2u8 { for code in 0..4u8 { let toc = (config << 3) | (stereo << 2) | code; for trial in 0..40 { let len = 2 + (rand() as usize % 400); let mut packet = vec![toc]; for _ in 0..len { packet.push(rand() as u8); } if trial % 2 == 0 { dec.reset(); } let _ = dec.decode_float(&packet, &mut out); let _ = ms.decode_float(&packet, &mut out); } } } } // Truncations of a real packet, which exercise the mid-frame paths. let path = ec_testkit::fixture("vectors/opus-rfc6716/opus_testvectors/testvector10.bit"); for p in read_vector(&path).iter().take(200) { for cut in 1..p.payload.len().min(64) { let _ = dec.decode_float(&p.payload[..cut], &mut out); } } } // --------------------------------------------------------------------------- // SILK encoder (mono, 20 ms, NB/WB) // --------------------------------------------------------------------------- /// A 1 s speech-like signal at 48 kHz: 0.6 s of a pitch-modulated pulse train /// through a formant-ish AR(2) filter, then 0.4 s of filtered noise. fn speech_like() -> Vec { let mut out = Vec::with_capacity(48000); let (mut y1, mut y2) = (0f32, 0f32); let mut phase = 0f64; let mut s = 12345u32; for i in 0..48000 { let t = i as f64 / 48000.0; let e = if t < 0.6 { let f0 = 120.0 + 30.0 * (2.0 * std::f64::consts::PI * 2.0 * t).sin(); phase += f0 / 48000.0; if phase >= 1.0 { phase -= 1.0; 1.0 } else { 0.0 } } else { s = s.wrapping_mul(1664525).wrapping_add(1013904223); ((s >> 8) as f32 / (1u32 << 24) as f32 - 0.5) * 0.3 }; // Resonance near 700 Hz, radius 0.97. let (r, w) = (0.97f32, 2.0 * std::f32::consts::PI * 700.0 / 48000.0); let y = e + 2.0 * r * w.cos() * y1 - r * r * y2; y2 = y1; y1 = y; out.push(y * 0.03); } out } /// 16-bit PCM mono WAV at 48 kHz, as `f32`. fn read_wav_mono(path: &Path) -> Vec { let d = fs::read(path).unwrap(); assert_eq!(u16::from_le_bytes([d[22], d[23]]), 1, "mono fixture"); assert_eq!(u32::from_le_bytes([d[24], d[25], d[26], d[27]]), 48000); let mut pos = 12; loop { let id = &d[pos..pos + 4]; let len = u32::from_le_bytes([d[pos + 4], d[pos + 5], d[pos + 6], d[pos + 7]]) as usize; if id == b"data" { return d[pos + 8..pos + 8 + len] .as_chunks::<2>() .0 .iter() .map(|c| i16::from_le_bytes([c[0], c[1]]) as f32 / 32768.0) .collect(); } pos += 8 + len + (len & 1); } } /// Windowed-sinc low-pass at `cutoff_hz` (48 kHz input), zero-phase. fn lowpass(x: &[f32], cutoff_hz: f64) -> Vec { let taps = 127usize; let c = cutoff_hz / 48000.0; let h: Vec = (0..taps) .map(|i| { let m = i as f64 - (taps - 1) as f64 / 2.0; let sinc = if m == 0.0 { 2.0 * c } else { (2.0 * std::f64::consts::PI * c * m).sin() / (std::f64::consts::PI * m) }; sinc * (0.54 - 0.46 * (2.0 * std::f64::consts::PI * i as f64 / (taps - 1) as f64).cos()) }) .collect(); let half = (taps - 1) / 2; (0..x.len()) .map(|n| { h.iter() .enumerate() .map(|(k, &hk)| { let idx = n as isize + half as isize - k as isize; if idx >= 0 && (idx as usize) < x.len() { hk * x[idx as usize] as f64 } else { 0.0 } }) .sum::() as f32 }) .collect() } fn silk_encoder(bandwidth: Bandwidth, bps: Option) -> Encoder { let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); enc.set_mode(Some(Mode::Silk)); enc.set_bandwidth(Some(bandwidth)); enc.set_vbr_constrained(true); if let Some(bps) = bps { enc.set_bitrate(bps); } enc } /// Encodes `pcm` in `frame_ms` frames, decodes each packet with our decoder /// asserting the range-coder invariant, returns (decoded 48 kHz, packets). fn silk_roundtrip(enc: &mut Encoder, pcm: &[f32], frame_ms: usize) -> (Vec, Vec>) { let frame = 48 * frame_ms; let mut dec = Decoder::new(48000, 1).unwrap(); let mut out = vec![0u8; 1500]; let mut buf = vec![0f32; 5760]; let mut decoded = Vec::new(); let mut packets = Vec::new(); let mut padded = pcm.to_vec(); padded.resize(pcm.len().div_ceil(frame) * frame + frame, 0.0); for block in padded.chunks(frame) { let len = enc .encode_float(block, frame, &mut out) .expect("silk encode"); let n = dec .decode_float(&out[..len], &mut buf) .expect("silk decode"); assert_eq!(n, frame); assert_eq!(dec.final_range(), enc.final_range(), "range state diverged"); decoded.extend_from_slice(&buf[..n]); packets.push(out[..len].to_vec()); } (decoded, packets) } /// Correlation after aligning `decoded` to `reference` at the best lag in /// `[0, max_lag)`; the peak must be interior (a peak at the search bound is /// no measurement). fn aligned_corr(reference: &[f32], decoded: &[f32], max_lag: usize) -> (f64, usize) { let (mut best, mut best_lag) = (-1.0f64, 0usize); for lag in 0..max_lag { let c = correlation(reference, &decoded[lag..]); if c > best { best = c; best_lag = lag; } } assert!(best_lag + 1 < max_lag, "alignment peak at the search bound"); (best, best_lag) } #[test] fn silk_mono_nb_wb_roundtrip() { let wav = fixture("wav16-mono-48000.wav"); let mut sources = vec![("synthetic", speech_like())]; let w = read_wav_mono(&wav); sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec())); for (name, pcm) in &sources { for wideband in [false, true] { let (bandwidth, band, tag) = if wideband { (Bandwidth::Wide, 7000.0, "WB") } else { (Bandwidth::Narrow, 3500.0, "NB") }; let mut enc = silk_encoder(bandwidth, None); let delay = enc.look_ahead(960); let (decoded, packets) = silk_roundtrip(&mut enc, pcm, 20); let reference = lowpass(pcm, band); let (corr, lag) = aligned_corr(&reference, &decoded, 2000); let bytes: usize = packets.iter().map(Vec::len).sum(); eprintln!( "silk {name} {tag}: corr {corr:.4} at lag {lag} (look-ahead {delay}), {} kbps", bytes * 8 / (packets.len() * 20) ); assert!(corr >= 0.8, "{name} {tag}: corr {corr:.4}"); // Reference oracle: the packets in an Ogg-Opus file decode cleanly. let path = temp_path(&format!("silk-{name}-{tag}.opus")); write_ogg_opus(&path, &packets, opus_head(1, 120, None), 1, pcm.len(), 120); let out = ec_testkit::ffmpeg() .args(["-v", "warning", "-c:a", "libopus", "-i"]) .arg(&path) .args(["-f", "null", "-"]) .output() .unwrap(); let stderr = String::from_utf8_lossy(&out.stderr); assert!( out.status.success() && stderr.trim().is_empty(), "{name} {tag}: ffmpeg: {stderr}" ); let _ = fs::remove_file(&path); } } } #[test] fn silk_mediumband_and_10ms_roundtrip() { let pcm = speech_like(); for (tag, bandwidth, frame_ms, config, cutoff, bps, floor) in [ ( "NB10", Bandwidth::Narrow, 10usize, 0u8, 3500.0, 12_000u32, 0.86f64, ), ("MB10", Bandwidth::Medium, 10, 4, 5500.0, 16_000, 0.89), ("WB10", Bandwidth::Wide, 10, 8, 7000.0, 20_000, 0.89), ("MB20", Bandwidth::Medium, 20, 5, 5500.0, 16_000, 0.9), ] { let mut enc = silk_encoder(bandwidth, Some(bps)); let (decoded, packets) = silk_roundtrip(&mut enc, &pcm, frame_ms); assert_eq!(packets[0][0] >> 3, config, "{tag}: wrong TOC config"); let reference = lowpass(&pcm, cutoff); let (corr, lag) = aligned_corr(&reference, &decoded, 2000); let bytes: usize = packets.iter().map(Vec::len).sum(); let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * frame_ms as f64); eprintln!( "silk {tag}: corr {corr:.4} at lag {lag}, {} frames, {kbps:.2} kbps", packets.len() ); assert!(corr >= floor, "{tag}: corr {corr:.4}"); let oracle = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len(), 120); let (c, _) = aligned_corr(&oracle, &decoded, 2000); assert!(c >= 0.99, "{tag}: our decode vs oracle decode corr {c:.4}"); } } #[test] fn silk_multiframe_packets_roundtrip() { let full = speech_like(); let pcm = &full[..46_080]; for (tag, bandwidth, frame_ms, config, cutoff, bps, floor) in [ ( "NB40", Bandwidth::Narrow, 40usize, 2u8, 3500.0, 16_000u32, 0.9f64, ), ("MB40", Bandwidth::Medium, 40, 6, 5500.0, 20_000, 0.91), ("WB40", Bandwidth::Wide, 40, 10, 7000.0, 24_000, 0.91), ("WB60", Bandwidth::Wide, 60, 11, 7000.0, 24_000, 0.9), ] { let mut enc = silk_encoder(bandwidth, Some(bps)); let (decoded, packets) = silk_roundtrip(&mut enc, pcm, frame_ms); let toc = ec_opus::Toc::new(packets[0][0]); assert_eq!(toc.config, config, "{tag}: wrong TOC config"); assert_eq!(toc.code, 0, "{tag}: multiframe SILK uses one Opus frame"); let reference = lowpass(pcm, cutoff); let (corr, lag) = aligned_corr(&reference, &decoded, 2500); let bytes: usize = packets.iter().map(Vec::len).sum(); let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * frame_ms as f64); eprintln!( "silk {tag}: corr {corr:.4} at lag {lag}, {} frames, {kbps:.2} kbps", packets.len() ); assert!(corr >= floor, "{tag}: corr {corr:.4} below {floor:.4}"); let oracle = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len(), 120); let (c, _) = aligned_corr(&oracle, &decoded, 2500); assert!( c >= 0.99, "{tag}: internal decode vs external decode corr {c:.4}" ); if Command::new("gst-launch-1.0") .arg("--version") .output() .is_ok() { let path = temp_path(&format!("silk-{tag}-gst.opus")); write_ogg_opus(&path, &packets, opus_head(1, 120, None), 1, pcm.len(), 120); let location = format!("location={}", path.display()); let out = Command::new("gst-launch-1.0") .args([ "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", "fakesink", ]) .output() .unwrap(); let stderr = String::from_utf8_lossy(&out.stderr); assert!(out.status.success(), "{tag}: gst decode: {stderr}"); let _ = fs::remove_file(&path); } } } fn stereo_speech_pair() -> Vec { let left = speech_like(); let mut out = Vec::with_capacity(left.len() * 2); for (i, &l) in left.iter().enumerate() { let t = i as f64 / 48000.0; let r = 0.78 * l + 0.12 * (std::f64::consts::TAU * 310.0 * t).sin() as f32; out.push(l); out.push(r); } out } fn aligned_channel_corr(reference: &[f32], decoded: &[f32], channels: usize, ch: usize) -> f64 { let b: Vec = decoded.chunks_exact(channels).map(|f| f[ch]).collect(); aligned_corr(reference, &b, 2000).0 } #[test] fn silk_stereo_speech_roundtrip() { let pcm = stereo_speech_pair(); let total = pcm.len() / 2; for (tag, bandwidth, per_channel_bps, cutoff, frame, config, code, frames) in [ ( "NB20", Bandwidth::Narrow, 16_000u32, 3500.0, 960usize, 1u8, 0u8, 1usize, ), ("MB20", Bandwidth::Medium, 20_000, 5500.0, 960, 5, 0, 1), ("WB20", Bandwidth::Wide, 24_000, 7000.0, 960, 9, 0, 1), ("NB40", Bandwidth::Narrow, 16_000, 3500.0, 1920, 2, 0, 1), ("MB40", Bandwidth::Medium, 20_000, 5500.0, 1920, 6, 0, 1), ("WB60", Bandwidth::Wide, 24_000, 7000.0, 2880, 11, 0, 1), ] { let frame_ms = frame / 48; let mono_frame_ms = frame_ms.min(20); let mut mono_floor = [0.0f64; 2]; for ch in 0..2 { let mono: Vec = pcm.as_chunks::<2>().0.iter().map(|f| f[ch]).collect(); let mut silk = silk_encoder(bandwidth, Some(per_channel_bps)); let reference = lowpass(&mono, cutoff); let (decoded, _) = silk_roundtrip(&mut silk, &mono, mono_frame_ms); mono_floor[ch] = aligned_corr(&reference, &decoded, 2000).0; } let mut enc = Encoder::new(48000, 2, Application::Voip).unwrap(); enc.set_mode(Some(ec_opus::Mode::Silk)); enc.set_bandwidth(Some(bandwidth)); enc.set_vbr_constrained(true); enc.set_bitrate(per_channel_bps * 2); let mut dec = Decoder::new(48000, 2).unwrap(); let mut out = vec![0u8; 4096]; let mut buf = vec![0.0f32; 5760 * 2]; let mut decoded = Vec::new(); let mut packets = Vec::new(); let mut padded = pcm.clone(); padded.resize(pcm.len().div_ceil(frame * 2) * frame * 2 + frame * 2, 0.0); for block in padded.chunks(frame * 2) { let len = enc.encode_float(block, frame, &mut out).expect("encode"); let packet = Packet::parse(&out[..len], false).unwrap(); let toc = packet.toc; assert_eq!(toc.config, config, "{tag}: wrong TOC config"); assert_eq!(toc.code, code, "{tag}: wrong TOC code"); assert_eq!(packet.frames.len(), frames, "{tag}: frame count"); assert_eq!(packet.samples_48k(), frame, "{tag}: packet samples"); assert!(toc.stereo, "{tag}: SILK TOC is not stereo"); let n = dec.decode_float(&out[..len], &mut buf).expect("decode"); assert_eq!(n, frame, "{tag}: decoded frame size"); assert_eq!(dec.final_range(), enc.final_range(), "{tag}: range state"); decoded.extend_from_slice(&buf[..n * 2]); packets.push(out[..len].to_vec()); } let bytes: usize = packets.iter().map(Vec::len).sum(); let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * frame_ms as f64); for ch in 0..2 { let source: Vec = pcm.as_chunks::<2>().0.iter().map(|f| f[ch]).collect(); let reference = lowpass(&source, cutoff); let corr = aligned_channel_corr(&reference, &decoded, 2, ch); eprintln!( "silk stereo {tag} ch{ch}: corr {corr:.4}, mono {:.4}, {kbps:.2} kbps", mono_floor[ch] ); assert!( corr + 0.01 >= mono_floor[ch], "{tag} ch{ch}: stereo corr {corr:.4} trails mono {:.4}", mono_floor[ch] ); } let path = temp_path(&format!("silk-stereo-{tag}.opus")); write_ogg_opus( &path, &packets, opus_head(2, enc.look_ahead(frame) as u16, None), 2, total, enc.look_ahead(frame) as i64, ); let out = ec_testkit::ffmpeg() .args(["-v", "warning", "-c:a", "libopus", "-i"]) .arg(&path) .args(["-f", "null", "-"]) .output() .unwrap(); let stderr = String::from_utf8_lossy(&out.stderr); assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}"); if Command::new("gst-launch-1.0") .arg("--version") .output() .is_ok() { let location = format!("location={}", path.display()); let out = Command::new("gst-launch-1.0") .args([ "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", "fakesink", ]) .output() .unwrap(); let stderr = String::from_utf8_lossy(&out.stderr); assert!(out.status.success(), "{tag}: gst decode: {stderr}"); } let _ = fs::remove_file(&path); } } /// Reference oracle decode of `packets` as Ogg-Opus, or `None` without ffmpeg. /// `pre_skip` must be the encoder's advertised [`Encoder::look_ahead`] for /// these packets: it is what the oracle trims off the front, so a caller that /// compares sample-for-sample against its own decode at that same offset only /// lines up when the two agree. fn oracle_decode(name: &str, packets: &[Vec], samples: usize, pre_skip: usize) -> Vec { let path = temp_path(&format!("{name}.opus")); write_ogg_opus( &path, packets, opus_head(1, pre_skip as u16, None), 1, samples, pre_skip as i64, ); let out = ec_testkit::ffmpeg() .args(["-v", "warning", "-c:a", "libopus", "-i"]) .arg(&path) .args(["-f", "null", "-"]) .output() .unwrap(); let stderr = String::from_utf8_lossy(&out.stderr); assert!( out.status.success() && stderr.trim().is_empty(), "{name}: ffmpeg: {stderr}" ); let decoded = ffmpeg_decode(&path, 1); let _ = fs::remove_file(&path); decoded } fn libopus_untrimmed(name: &str, pcm: &[f32]) -> Vec { let raw = temp_path(&format!("{name}.f32")); let opus = temp_path(&format!("{name}.opus")); let bytes: Vec = pcm.iter().flat_map(|x| x.to_le_bytes()).collect(); fs::write(&raw, bytes).unwrap(); let encode = ec_testkit::ffmpeg() .args([ "-v", "error", "-y", "-f", "f32le", "-ar", "48000", "-ac", "1", "-i", ]) .arg(&raw) .args([ "-c:a", "libopus", "-application", "voip", "-b:a", "32000", "-vbr", "off", "-frame_duration", "20", "-fflags", "+bitexact", ]) .arg(&opus) .output() .unwrap(); assert!( encode.status.success(), "{name}: ffmpeg encode: {}", String::from_utf8_lossy(&encode.stderr) ); let decode = ec_testkit::ffmpeg() .args([ "-v", "error", "-flags2", "+skip_manual", "-c:a", "libopus", "-i", ]) .arg(&opus) .args(["-f", "f32le", "-ar", "48000", "-ac", "1", "-"]) .output() .unwrap(); assert!( decode.status.success(), "{name}: ffmpeg decode: {}", String::from_utf8_lossy(&decode.stderr) ); let _ = fs::remove_file(&raw); let _ = fs::remove_file(&opus); decode .stdout .as_chunks::<4>() .0 .iter() .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) .collect() } fn silk_sources() -> Vec<(&'static str, Vec)> { let wav = fixture("wav16-mono-48000.wav"); let mut sources = vec![("synthetic", speech_like())]; let w = read_wav_mono(&wav); sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec())); sources } /// The public `Encoder` (Voip, mono) routes `set_bitrate` into the SILK /// path it dispatches to. #[test] fn silk_packets_track_encoder_bitrate() { let pcm = test_signal(1, 2.0); for kbps_target in [8u32, 12, 16] { let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); enc.set_bitrate(kbps_target * 1000); let packets = encode_packets(&mut enc, &pcm, 1); let bytes: usize = packets.iter().map(Vec::len).sum(); let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0); eprintln!("encoder bitrate target {kbps_target}: {kbps:.2} kbps"); let ratio = kbps / kbps_target as f64; assert!( (0.8..=1.2).contains(&ratio), "target {kbps_target}: got {kbps:.2} kbps" ); } } // --------------------------------------------------------------------------- // Hybrid (SILK 16 kHz + CELT from band 17, one range-coded stream). /// Encodes mono `pcm` as hybrid packets at `bps` and decodes them with our /// decoder; asserts range-state parity packet for packet. Returns (decoded, packets). fn hybrid_roundtrip( pcm: &[f32], bps: u32, bandwidth: Option, mode: Option, ) -> (Vec, Vec>) { let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); enc.set_bitrate(bps); enc.set_bandwidth(bandwidth); enc.set_mode(mode); let mut dec = Decoder::new(48000, 1).unwrap(); let mut out = vec![0u8; 1500]; let mut buf = vec![0f32; 5760]; let (mut decoded, mut packets) = (Vec::new(), Vec::new()); let mut padded = pcm.to_vec(); padded.resize(pcm.len().div_ceil(960) * 960 + 960, 0.0); for block in padded.chunks(960) { let len = enc .encode_float(block, 960, &mut out) .expect("hybrid encode"); let n = dec .decode_float(&out[..len], &mut buf) .expect("hybrid decode"); assert_eq!(n, 960); assert_eq!(dec.final_range(), enc.final_range(), "range state diverged"); decoded.extend_from_slice(&buf[..n]); packets.push(out[..len].to_vec()); } (decoded, packets) } /// The delay [`hybrid_roundtrip`]'s encoder advertises for a 20 ms frame — /// [`Encoder::look_ahead`] of that same configuration, so the lag assertions /// track the layer's real delay instead of a constant. fn hybrid_delay(bps: u32) -> usize { let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); enc.set_bitrate(bps); enc.look_ahead(960) } /// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks /// the input full-band, and the reference oracle decodes the packets to the /// same signal. /// /// The delay [`hybrid_roundtrip`]'s encoder advertises for a 20 ms frame is /// [`Encoder::look_ahead`] of that same configuration, never a constant. #[test] fn hybrid_fb_roundtrip() { for (name, pcm) in silk_sources() { let (decoded, packets) = hybrid_roundtrip(&pcm, 32_000, None, None); let toc = ec_opus::Toc::new(packets[0][0]); assert_eq!(toc.config, 15, "{name}: TOC config {}", toc.config); let (corr, lag) = aligned_corr(&pcm, &decoded, 400); let bytes: usize = packets.iter().map(Vec::len).sum(); let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0); eprintln!("hybrid FB {name}: corr {corr:.4} at lag {lag}, {kbps:.1} kbps"); assert!(corr >= 0.9, "{name}: full-band corr {corr:.4}"); let delay = hybrid_delay(32_000); let libopus = libopus_untrimmed(&format!("hybrid-lag-{name}"), &pcm); let (_, libopus_lag) = aligned_corr(&pcm, &libopus, 400); assert!( lag.abs_diff(libopus_lag) <= 6, "{name}: aligned at lag {lag}, libopus at {libopus_lag}" ); assert!( (28.0..=36.0).contains(&kbps), "{name}: {kbps:.1} kbps for a 32 kbps CBR target" ); let oracle = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len(), delay); let n = oracle.len().min(decoded.len() - delay); let c = correlation(&oracle[..n], &decoded[delay..delay + n]); eprintln!("hybrid FB {name}: oracle vs ours corr {c:.4}"); assert!(c >= 0.95, "{name}: oracle corr {c:.4}"); } // SWB when asked for it, and the rest of the automatic hybrid range // (SILK's share leaves CELT least at the bottom of it). let speech = speech_like(); let (_, packets) = hybrid_roundtrip(&speech, 24_000, Some(Bandwidth::SuperWide), None); assert_eq!(ec_opus::Toc::new(packets[0][0]).config, 13); for bps in [20_000u32, 24_000, 39_000] { let (decoded, packets) = hybrid_roundtrip(&speech, bps, None, None); let (corr, _) = aligned_corr(&speech, &decoded, 400); let kbps = packets.iter().map(Vec::len).sum::() as f64 * 8.0 / (packets.len() as f64 * 20.0); eprintln!( "hybrid {bps}: config {}, corr {corr:.4}, {kbps:.1} kbps", ec_opus::Toc::new(packets[0][0]).config ); assert!(corr >= 0.9, "hybrid at {bps}: corr {corr:.4}"); assert!( kbps <= bps as f64 / 1000.0 + 3.0, "hybrid at {bps}: {kbps:.1} kbps" ); } } fn hybrid_roundtrip_shape( pcm: &[f32], channels: usize, frame: usize, bps: u32, bandwidth: Option, ) -> (Vec, Vec>) { let mut enc = Encoder::new(48000, channels, Application::Voip).unwrap(); enc.set_bitrate(bps); enc.set_bandwidth(bandwidth); let mut dec = Decoder::new(48000, channels).unwrap(); let mut out = vec![0u8; 1500]; let mut buf = vec![0f32; 5760 * channels]; let (mut decoded, mut packets) = (Vec::new(), Vec::new()); let mut padded = pcm.to_vec(); padded.resize( pcm.len().div_ceil(frame * channels) * frame * channels + frame * channels, 0.0, ); for block in padded.chunks(frame * channels) { let len = enc .encode_float(block, frame, &mut out) .expect("hybrid encode"); let n = dec .decode_float(&out[..len], &mut buf) .expect("hybrid decode"); assert_eq!(n, frame); assert_eq!(dec.final_range(), enc.final_range(), "range state diverged"); decoded.extend_from_slice(&buf[..n * channels]); packets.push(out[..len].to_vec()); } (decoded, packets) } #[test] fn hybrid_shapes_roundtrip() { for (tag, channels, frame, bps, bandwidth, config, floor) in [ ( "mono-swb10", 1usize, 480usize, 24_000u32, Bandwidth::SuperWide, 12u8, 0.75f64, ), ("mono-fb10", 1, 480, 32_000, Bandwidth::Full, 14, 0.75), ( "stereo-swb20", 2, 960, 48_000, Bandwidth::SuperWide, 13, 0.75, ), ("stereo-fb20", 2, 960, 64_000, Bandwidth::Full, 15, 0.75), ("stereo-fb10", 2, 480, 64_000, Bandwidth::Full, 14, 0.70), ] { let pcm = if channels == 1 { speech_like() } else { stereo_speech_pair() }; let (decoded, packets) = hybrid_roundtrip_shape(&pcm, channels, frame, bps, Some(bandwidth)); let toc = ec_opus::Toc::new(packets[0][0]); assert_eq!(toc.config, config, "{tag}: TOC config {}", toc.config); assert_eq!(toc.stereo, channels == 2, "{tag}: TOC stereo flag"); let mut worst = 1.0f64; for ch in 0..channels { let source: Vec = pcm.chunks_exact(channels).map(|f| f[ch]).collect(); let got: Vec = decoded.chunks_exact(channels).map(|f| f[ch]).collect(); let (corr, lag) = aligned_corr(&source, &got, 400); worst = worst.min(corr); eprintln!("hybrid {tag} ch{ch}: corr {corr:.4} at lag {lag}"); } assert!(worst >= floor, "{tag}: worst corr {worst:.4}"); let total = pcm.len() / channels; let path = temp_path(&format!("hybrid-{tag}.opus")); // The pre-skip is what `hybrid_roundtrip_shape`'s own encoder // advertises for this frame size, not a constant. let pre_skip = { let mut e = Encoder::new(48000, channels, Application::Voip).unwrap(); e.set_bitrate(bps); e.look_ahead(frame) }; write_ogg_opus( &path, &packets, opus_head(channels, pre_skip as u16, None), channels, total, pre_skip as i64, ); let out = ec_testkit::ffmpeg() .args(["-v", "warning", "-c:a", "libopus", "-i"]) .arg(&path) .args(["-f", "null", "-"]) .output() .unwrap(); let stderr = String::from_utf8_lossy(&out.stderr); assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}"); if Command::new("gst-launch-1.0") .arg("--version") .output() .is_ok() { let location = format!("location={}", path.display()); let out = Command::new("gst-launch-1.0") .args([ "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", "fakesink", ]) .output() .unwrap(); let stderr = String::from_utf8_lossy(&out.stderr); assert!(out.status.success(), "{tag}: gst decode: {stderr}"); } let _ = fs::remove_file(&path); } let speech = stereo_speech_pair(); let (_, packets) = hybrid_roundtrip_shape(&speech, 2, 960, 64_000, None); let toc = ec_opus::Toc::new(packets[0][0]); assert_eq!(toc.mode(), ec_opus::Mode::Hybrid); assert!(toc.stereo); } #[test] fn opus_compare_err_pinned_against_c() { const N: usize = 48000 * 4; let t: Vec = (0..N).map(|i| i as f64 / 48000.0).collect(); let base = |c: usize| -> Vec { let ph = 0.5 * c as f64; let ph2 = 0.3 * c as f64; t.iter() .map(|&tt| { 0.3 * (2.0 * std::f64::consts::PI * 440.0 * tt).sin() + 0.2 * (2.0 * std::f64::consts::PI * 442.0 * tt + ph).sin() + 0.15 * (2.0 * std::f64::consts::PI * (800.0 + 200.0 * tt) * tt + ph2).sin() }) .collect() }; let to_i16s = |sig: &[f64]| -> Vec { sig.iter() .map(|&v| (v.clamp(-1.0, 1.0) * 32767.0) as i16) .collect() }; let stereo = |l: &[f64], r: &[f64]| -> Vec { let mut o = Vec::with_capacity(N * 2); let li = to_i16s(l); let ri = to_i16s(r); for i in 0..N { o.push(li[i]); o.push(ri[i]); } o }; let b0 = base(0); let b1 = base(1); let a = stereo(&b0, &b1); let err_id = opus_compare_err(&a, &a, 2); let q_id = opus_compare(&a, &a, 2); assert_eq!(err_id, 0.0, "identical signals must give err=0"); assert_eq!(q_id, 100.0, "identical signals must give Q=100"); // Case 2: mild perturbation (+0.5 dB on L, quiet 1500 Hz partial on L). let gain = 10f64.powf(0.5 / 10.0); let lp: Vec = t .iter() .zip(b0.iter()) .map(|(&tt, &bv)| bv * gain + 0.02 * (2.0 * std::f64::consts::PI * 1500.0 * tt).sin()) .collect(); let b = stereo(&lp, &b1); let err = opus_compare_err(&a, &b, 2); let q = opus_compare(&a, &b, 2); // Pinned to the C reference value (4.444987); tolerance absorbs libm // transcendental rounding differences across toolchains. assert!( (err - 4.444987).abs() < 1e-3, "pinned err drift: got {err:.6}, expected 4.444987 (C-validated)" ); assert!( (q - -593.31).abs() < 0.5, "pinned Q drift: got {q:.4}, expected -593.31 (C-validated)" ); }