M13.4: opus SILK (NB/MB/WB, mid/side stereo) and hybrid (SWB/FB) modes
Application/Mode/Bandwidth API with OpusEncoder::with_application and with_mode; SILK analysis-by-synthesis encoder mirroring the decoder's fixed-point reconstruction with noise feedback, LTP, NLSF quantisation and per-frame rate control; hybrid CELT from band 17 in the shared range coder; pre-skip 120 in every mode. Oracle tests against filmcraft-opus and ffmpeg (native opus + libopus). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a30cf38180
commit
3eeba31c43
@@ -0,0 +1,285 @@
|
||||
//! Shared helpers for the SILK/hybrid round-trip tests: synthetic signals, encoding, decoding
|
||||
//! with FilmCraft's spec-derived decoder, delay-searched SNR and an Ogg Opus writer for ffmpeg.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use effectcraft_opusenc::OpusEncoder;
|
||||
|
||||
pub const SR: f64 = 48_000.0;
|
||||
pub const FRAME: usize = OpusEncoder::FRAME_SIZE;
|
||||
|
||||
/// Two-pole resonator state.
|
||||
struct Reson {
|
||||
y1: f64,
|
||||
y2: f64,
|
||||
}
|
||||
|
||||
impl Reson {
|
||||
fn run(&mut self, x: f64, f: f64, bw: f64) -> f64 {
|
||||
let r = (-std::f64::consts::PI * bw / SR).exp();
|
||||
let a1 = 2.0 * r * (2.0 * std::f64::consts::PI * f / SR).cos();
|
||||
let a2 = -r * r;
|
||||
let g = 1.0 - r;
|
||||
let y = g * x + a1 * self.y1 + a2 * self.y2;
|
||||
self.y2 = self.y1;
|
||||
self.y1 = y;
|
||||
y
|
||||
}
|
||||
}
|
||||
|
||||
/// Speech-like test signal: a glottal pulse train (100–200 Hz, gliding pitch) through three
|
||||
/// formant resonators whose frequencies change per syllable, with syllable envelopes, short
|
||||
/// pauses and a little aspiration noise.
|
||||
pub fn speech(len: usize, seed: u32) -> Vec<f32> {
|
||||
let vowels: [[f64; 3]; 5] = [[730.0, 1090.0, 2440.0], [270.0, 2290.0, 3010.0], [530.0, 1840.0, 2480.0], [570.0, 840.0, 2410.0], [300.0, 870.0, 2240.0]];
|
||||
let syl = (0.24 * SR) as usize;
|
||||
let mut out = Vec::with_capacity(len);
|
||||
let mut res = [Reson { y1: 0.0, y2: 0.0 }, Reson { y1: 0.0, y2: 0.0 }, Reson { y1: 0.0, y2: 0.0 }];
|
||||
let mut phase = 0.0f64;
|
||||
let mut s = seed;
|
||||
let mut prev_glottal = 0.0;
|
||||
for n in 0..len {
|
||||
let t = n as f64 / SR;
|
||||
let k = n / syl;
|
||||
let pos = (n % syl) as f64 / syl as f64;
|
||||
// Every fourth syllable is a pause.
|
||||
let pause = k % 4 == 3;
|
||||
let env = if pause { 0.0 } else { (std::f64::consts::PI * pos).sin().powf(0.7) };
|
||||
let f0 = 100.0 + 50.0 * (1.0 + (2.0 * std::f64::consts::PI * 0.9 * t).sin()) + 15.0 * ((k * 7) % 5) as f64 - 30.0 * pos;
|
||||
phase += f0 / SR;
|
||||
if phase >= 1.0 {
|
||||
phase -= 1.0;
|
||||
}
|
||||
// Rosenberg-like glottal flow; its derivative excites the vocal tract.
|
||||
let g = if phase < 0.4 {
|
||||
0.5 * (1.0 - (std::f64::consts::PI * phase / 0.4).cos())
|
||||
} else if phase < 0.56 {
|
||||
(std::f64::consts::FRAC_PI_2 * (phase - 0.4) / 0.16).cos()
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let dg = (g - prev_glottal) * 40.0;
|
||||
prev_glottal = g;
|
||||
s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
|
||||
let noise = ((s >> 8) as f64 / (1u32 << 24) as f64 - 0.5) * 0.02;
|
||||
let v = vowels[(k * 3 + 1) % 5];
|
||||
let w = vowels[(k * 3 + 4) % 5];
|
||||
let mix = pos;
|
||||
let mut x = dg + noise;
|
||||
let mut y = 0.0;
|
||||
for (i, r) in res.iter_mut().enumerate() {
|
||||
let f = v[i] * (1.0 - mix) + w[i] * mix;
|
||||
y += r.run(x, f, 60.0 + 40.0 * i as f64) * [1.0, 0.6, 0.3][i];
|
||||
}
|
||||
x = y * env * 1.2;
|
||||
out.push(x as f32);
|
||||
}
|
||||
let peak = out.iter().fold(0f32, |m, v| m.max(v.abs()));
|
||||
let g = 0.5 / peak.max(1e-9);
|
||||
out.iter().map(|v| v * g).collect()
|
||||
}
|
||||
|
||||
/// Music-like test signal: three-note chords of harmonic tones (six partials each), changing
|
||||
/// every half second with soft attacks and releases.
|
||||
pub fn music(len: usize) -> Vec<f32> {
|
||||
let chords: [[f64; 3]; 4] = [[261.63, 329.63, 392.0], [220.0, 277.18, 329.63], [174.61, 220.0, 261.63], [196.0, 246.94, 293.66]];
|
||||
let seg = (0.5 * SR) as usize;
|
||||
(0..len)
|
||||
.map(|n| {
|
||||
let t = n as f64 / SR;
|
||||
let k = n / seg;
|
||||
let pos = (n % seg) as f64 / seg as f64;
|
||||
let env = (pos * 20.0).min(1.0) * ((1.0 - pos) * 10.0).min(1.0);
|
||||
let mut x = 0.0;
|
||||
for (j, &f) in chords[k % 4].iter().enumerate() {
|
||||
for h in 1..=6 {
|
||||
x += (2.0 * std::f64::consts::PI * f * h as f64 * t + j as f64).sin() / h as f64;
|
||||
}
|
||||
}
|
||||
(0.12 * env * x) as f32
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn interleave(planar: &[Vec<f32>]) -> Vec<f32> {
|
||||
let c = planar.len();
|
||||
let len = planar[0].len();
|
||||
let mut pcm = vec![0f32; len * c];
|
||||
for (ch, p) in planar.iter().enumerate() {
|
||||
for (i, &v) in p.iter().enumerate() {
|
||||
pcm[i * c + ch] = v;
|
||||
}
|
||||
}
|
||||
pcm
|
||||
}
|
||||
|
||||
/// Encodes planar input (padding the tail so the encoder delay is flushed).
|
||||
pub fn encode(mut enc: OpusEncoder, planar: &[Vec<f32>]) -> (OpusEncoder, Vec<Vec<u8>>) {
|
||||
let c = planar.len();
|
||||
let len = planar[0].len();
|
||||
let total = len + enc.pre_skip() as usize + 16;
|
||||
let frames = total.div_ceil(FRAME);
|
||||
let mut pcm = interleave(planar);
|
||||
pcm.resize(frames * FRAME * c, 0.0);
|
||||
let packets = pcm.chunks(FRAME * c).map(|f| enc.encode_float(f)).collect();
|
||||
(enc, packets)
|
||||
}
|
||||
|
||||
/// Decodes with filmcraft-opus, drops the pre-skip and returns planar channels (full length).
|
||||
pub fn decode(head: &[u8], packets: &[Vec<u8>]) -> Vec<Vec<f32>> {
|
||||
let mut dec = filmcraft_opus::Decoder::new(head).expect("OpusHead");
|
||||
dec.set_trim_pre_skip(true);
|
||||
let mut out: Vec<Vec<f32>> = vec![Vec::new(); dec.channels()];
|
||||
for p in packets {
|
||||
let planes = dec.decode(Some(p)).expect("decode");
|
||||
for (o, p) in out.iter_mut().zip(planes) {
|
||||
o.extend_from_slice(&p);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Waveform SNR (dB) of `dec[i + shift]` against `orig[i]`, excluding the first and last 20 ms.
|
||||
pub fn snr_at(orig: &[f32], dec: &[f32], shift: isize) -> f64 {
|
||||
let (mut s, mut e) = (0f64, 0f64);
|
||||
for i in FRAME..orig.len() - FRAME {
|
||||
let j = i as isize + shift;
|
||||
let d = if j >= 0 && (j as usize) < dec.len() { dec[j as usize] as f64 } else { 0.0 };
|
||||
s += (orig[i] as f64).powi(2);
|
||||
e += (orig[i] as f64 - d).powi(2);
|
||||
}
|
||||
10.0 * (s / e.max(1e-30)).log10()
|
||||
}
|
||||
|
||||
/// Best SNR over residual delays of ±`range` samples: (SNR dB, delay).
|
||||
pub fn snr_search(orig: &[f32], dec: &[f32], range: isize) -> (f64, isize) {
|
||||
(-range..=range).map(|d| (snr_at(orig, dec, d), d)).fold((f64::MIN, 0), |a, b| if b.0 > a.0 { b } else { a })
|
||||
}
|
||||
|
||||
/// Segmental SNR (dB): mean over 20 ms segments holding signal (each clamped to [-10, 40]).
|
||||
pub fn seg_snr(orig: &[f32], dec: &[f32], shift: isize) -> f64 {
|
||||
let mut acc = 0f64;
|
||||
let mut n = 0;
|
||||
let mut i = FRAME;
|
||||
while i + FRAME <= orig.len() - FRAME {
|
||||
let (mut s, mut e) = (0f64, 0f64);
|
||||
for k in i..i + FRAME {
|
||||
let j = k as isize + shift;
|
||||
let d = if j >= 0 && (j as usize) < dec.len() { dec[j as usize] as f64 } else { 0.0 };
|
||||
s += (orig[k] as f64).powi(2);
|
||||
e += (orig[k] as f64 - d).powi(2);
|
||||
}
|
||||
if s / FRAME as f64 > 1e-5 {
|
||||
acc += (10.0 * (s / e.max(1e-30)).log10()).clamp(-10.0, 40.0);
|
||||
n += 1;
|
||||
}
|
||||
i += FRAME;
|
||||
}
|
||||
acc / n.max(1) as f64
|
||||
}
|
||||
|
||||
/// Average bitrate (bits per second) of a packet sequence of 20 ms packets.
|
||||
pub fn bitrate(packets: &[Vec<u8>]) -> f64 {
|
||||
packets.iter().map(|p| p.len() * 8).sum::<usize>() as f64 / (packets.len() as f64 * 0.02)
|
||||
}
|
||||
|
||||
/// Low-pass filtered copy (FFT brick wall) used to compare band-limited modes fairly.
|
||||
pub fn lowpass(x: &[f32], fc: f64) -> Vec<f32> {
|
||||
let n = x.len().next_power_of_two();
|
||||
let mut re: Vec<f64> = x.iter().map(|&v| v as f64).collect();
|
||||
re.resize(n, 0.0);
|
||||
let mut im = vec![0f64; n];
|
||||
fft(&mut re, &mut im, false);
|
||||
for k in 0..n {
|
||||
let f = (k.min(n - k)) as f64 * SR / n as f64;
|
||||
if f > fc {
|
||||
re[k] = 0.0;
|
||||
im[k] = 0.0;
|
||||
}
|
||||
}
|
||||
fft(&mut re, &mut im, true);
|
||||
re[..x.len()].iter().map(|&v| (v / n as f64) as f32).collect()
|
||||
}
|
||||
|
||||
pub fn fft(re: &mut [f64], im: &mut [f64], inverse: bool) {
|
||||
let n = re.len();
|
||||
let mut j = 0;
|
||||
for i in 1..n {
|
||||
let mut bit = n >> 1;
|
||||
while j & bit != 0 {
|
||||
j ^= bit;
|
||||
bit >>= 1;
|
||||
}
|
||||
j |= bit;
|
||||
if i < j {
|
||||
re.swap(i, j);
|
||||
im.swap(i, j);
|
||||
}
|
||||
}
|
||||
let mut len = 2;
|
||||
while len <= n {
|
||||
let ang = if inverse { 2.0 } else { -2.0 } * std::f64::consts::PI / len as f64;
|
||||
for s in (0..n).step_by(len) {
|
||||
for k in 0..len / 2 {
|
||||
let (wr, wi) = ((ang * k as f64).cos(), (ang * k as f64).sin());
|
||||
let (a, b) = (s + k, s + k + len / 2);
|
||||
let tr = re[b] * wr - im[b] * wi;
|
||||
let ti = re[b] * wi + im[b] * wr;
|
||||
re[b] = re[a] - tr;
|
||||
im[b] = im[a] - ti;
|
||||
re[a] += tr;
|
||||
im[a] += ti;
|
||||
}
|
||||
}
|
||||
len <<= 1;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Ogg Opus (RFC 3533 + RFC 7845) for the ffmpeg oracle ----
|
||||
|
||||
fn ogg_crc(data: &[u8]) -> u32 {
|
||||
let mut crc = 0u32;
|
||||
for &b in data {
|
||||
crc ^= (b as u32) << 24;
|
||||
for _ in 0..8 {
|
||||
crc = if crc & 0x8000_0000 != 0 { (crc << 1) ^ 0x04C1_1DB7 } else { crc << 1 };
|
||||
}
|
||||
}
|
||||
crc
|
||||
}
|
||||
|
||||
fn ogg_page(out: &mut Vec<u8>, packet: &[u8], header_type: u8, granule: u64, seq: u32) {
|
||||
let mut lacing = vec![255u8; packet.len() / 255];
|
||||
lacing.push((packet.len() % 255) as u8);
|
||||
let start = out.len();
|
||||
out.extend_from_slice(b"OggS");
|
||||
out.push(0);
|
||||
out.push(header_type);
|
||||
out.extend_from_slice(&granule.to_le_bytes());
|
||||
out.extend_from_slice(&0x4543_4F50u32.to_le_bytes());
|
||||
out.extend_from_slice(&seq.to_le_bytes());
|
||||
out.extend_from_slice(&0u32.to_le_bytes());
|
||||
out.push(lacing.len() as u8);
|
||||
out.extend_from_slice(&lacing);
|
||||
out.extend_from_slice(packet);
|
||||
let crc = ogg_crc(&out[start..]);
|
||||
out[start + 22..start + 26].copy_from_slice(&crc.to_le_bytes());
|
||||
}
|
||||
|
||||
/// An Ogg Opus file holding `packets` for `len` samples of audio.
|
||||
pub fn ogg_opus(enc: &OpusEncoder, packets: &[Vec<u8>], len: usize) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
ogg_page(&mut out, &enc.opus_head(), 0x02, 0, 0);
|
||||
let vendor = b"effectcraft-opusenc";
|
||||
let mut tags = b"OpusTags".to_vec();
|
||||
tags.extend_from_slice(&(vendor.len() as u32).to_le_bytes());
|
||||
tags.extend_from_slice(vendor);
|
||||
tags.extend_from_slice(&0u32.to_le_bytes());
|
||||
ogg_page(&mut out, &tags, 0, 0, 1);
|
||||
let pre_skip = enc.pre_skip() as u64;
|
||||
for (i, p) in packets.iter().enumerate() {
|
||||
let last = i + 1 == packets.len();
|
||||
let granule = if last { pre_skip + len as u64 } else { ((i + 1) * FRAME) as u64 };
|
||||
ogg_page(&mut out, p, if last { 0x04 } else { 0 }, granule, i as u32 + 2);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//! ffmpeg as a second, external oracle: every mode/bandwidth written as Ogg Opus must decode
|
||||
//! without errors with both ffmpeg's native `opus` decoder and `libopus`, honour the pre-skip
|
||||
//! and end granule, and reproduce the input. Skipped when ffmpeg is not installed.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
use common::*;
|
||||
use effectcraft_opusenc::{Bandwidth, Mode, OpusEncoder};
|
||||
|
||||
const FFMPEG: &str = "/opt/homebrew/bin/ffmpeg";
|
||||
|
||||
fn ffmpeg() -> Option<&'static str> {
|
||||
[FFMPEG, "ffmpeg"].into_iter().find(|exe| Command::new(exe).arg("-version").output().is_ok_and(|o| o.status.success()))
|
||||
}
|
||||
|
||||
/// Decodes an Ogg Opus file with ffmpeg's decoder `codec`; returns interleaved f32 output.
|
||||
fn ffmpeg_decode(exe: &str, codec: &str, file: &[u8], channels: usize, tag: &str) -> Option<Vec<f32>> {
|
||||
let has = Command::new(exe).args(["-hide_banner", "-decoders"]).output().ok()?;
|
||||
if !String::from_utf8_lossy(&has.stdout).lines().any(|l| l.split_whitespace().nth(1) == Some(codec)) {
|
||||
eprintln!("ffmpeg has no {codec} decoder; skipping it");
|
||||
return None;
|
||||
}
|
||||
let path = std::env::temp_dir().join(format!("effectcraft-opusenc-{}-{tag}.opus", std::process::id()));
|
||||
std::fs::write(&path, file).unwrap();
|
||||
let out = Command::new(exe)
|
||||
.args(["-v", "error", "-c:a", codec, "-i"])
|
||||
.arg(&path)
|
||||
.args(["-f", "f32le", "-ac", &channels.to_string(), "-ar", "48000", "-"])
|
||||
.output()
|
||||
.expect("run ffmpeg");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "ffmpeg ({codec}) failed: {stderr}");
|
||||
// ffmpeg's native decoder also makes its raw-PCM muxer print a timestamp complaint for
|
||||
// narrowband SILK streams written by libopus itself; that line is about ffmpeg's own
|
||||
// timestamping, not the bitstream, so it is the one message tolerated.
|
||||
let errors: Vec<&str> = stderr.lines().filter(|l| !l.trim().is_empty() && !l.contains("non monotonically increasing dts to muxer")).collect();
|
||||
assert!(errors.is_empty(), "ffmpeg ({codec}) reported errors: {errors:?}");
|
||||
Some(out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ffmpeg_decodes_every_mode() {
|
||||
let Some(exe) = ffmpeg() else {
|
||||
eprintln!("ffmpeg not installed; skipping the oracle test");
|
||||
return;
|
||||
};
|
||||
let len = 48_000;
|
||||
let sp = speech(len + 30_000, 3);
|
||||
let left = sp[..len].to_vec();
|
||||
let right: Vec<f32> = sp[30_000..].iter().map(|v| v * 0.7).collect();
|
||||
let cases = [
|
||||
(1usize, Mode::Silk, Bandwidth::Narrowband, 8_000u32, 3_400.0, 8.0),
|
||||
(1, Mode::Silk, Bandwidth::Mediumband, 11_000, 5_000.0, 10.0),
|
||||
(1, Mode::Silk, Bandwidth::Wideband, 16_000, 7_000.0, 12.0),
|
||||
(2, Mode::Silk, Bandwidth::Wideband, 32_000, 7_000.0, 12.0),
|
||||
(1, Mode::Hybrid, Bandwidth::SuperWideband, 24_000, 24_000.0, 10.0),
|
||||
(1, Mode::Hybrid, Bandwidth::Fullband, 32_000, 24_000.0, 10.0),
|
||||
(2, Mode::Hybrid, Bandwidth::Fullband, 64_000, 24_000.0, 10.0),
|
||||
(2, Mode::Celt, Bandwidth::Fullband, 96_000, 24_000.0, 10.0),
|
||||
];
|
||||
for (c, mode, bw, rate, fc, min_snr) in cases {
|
||||
let planar: Vec<Vec<f32>> = if c == 1 { vec![left.clone()] } else { vec![left.clone(), right.clone()] };
|
||||
let (enc, packets) = encode(OpusEncoder::with_mode(c as u8, rate, mode, bw), &planar);
|
||||
let file = ogg_opus(&enc, &packets, len);
|
||||
for codec in ["opus", "libopus"] {
|
||||
let Some(dec) = ffmpeg_decode(exe, codec, &file, c, &format!("{mode:?}{bw:?}{c}{codec}")) else {
|
||||
continue;
|
||||
};
|
||||
assert_eq!(dec.len(), len * c, "{codec}: pre-skip and end granule must be honoured");
|
||||
for (ch, x) in planar.iter().enumerate() {
|
||||
let d: Vec<f32> = (0..len).map(|i| dec[i * c + ch]).collect();
|
||||
let (snr, delay) = snr_search(&lowpass(x, fc), &d, 6);
|
||||
eprintln!("ffmpeg {codec:7} {mode:?}/{bw:?} {c} ch @ {} kb/s, channel {ch}: SNR {snr:.1} dB (residual delay {delay})", rate / 1000);
|
||||
assert!(snr > min_snr, "{codec} {mode:?}/{bw:?}: SNR {snr:.1} dB");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
//! SILK, hybrid and CELT round trips through FilmCraft's spec-derived Opus decoder: every
|
||||
//! mode/bandwidth decodes, waveform quality on speech-like and music-like signals, bitrate
|
||||
//! tracking, stereo, the application tables and delay alignment.
|
||||
|
||||
mod common;
|
||||
|
||||
use common::*;
|
||||
use effectcraft_opusenc::{Application, Bandwidth, Mode, OpusEncoder};
|
||||
|
||||
struct Run {
|
||||
snr: f64,
|
||||
seg: f64,
|
||||
delay: isize,
|
||||
kbps: f64,
|
||||
packets: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Encodes `planar`, decodes, and measures each channel against `reference` (searching a
|
||||
/// residual delay of up to ±6 samples).
|
||||
fn run(enc: OpusEncoder, planar: &[Vec<f32>], reference: &[Vec<f32>]) -> Vec<Run> {
|
||||
let (enc, packets) = encode(enc, planar);
|
||||
let dec = decode(&enc.opus_head(), &packets);
|
||||
let kbps = bitrate(&packets) / 1000.0;
|
||||
reference
|
||||
.iter()
|
||||
.zip(&dec)
|
||||
.map(|(r, d)| {
|
||||
assert!(d.len() >= r.len(), "decoded {} < {}", d.len(), r.len());
|
||||
assert!(d.iter().all(|v| v.is_finite()));
|
||||
let (snr, delay) = snr_search(r, d, 6);
|
||||
Run { snr, seg: seg_snr(r, d, delay), delay, kbps, packets: packets.clone() }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn mono(mode: Mode, bw: Bandwidth, rate: u32, x: &[f32], fc: f64) -> Run {
|
||||
let reference = if fc < 20_000.0 { lowpass(x, fc) } else { x.to_vec() };
|
||||
run(OpusEncoder::with_mode(1, rate, mode, bw), &[x.to_vec()], &[reference]).remove(0)
|
||||
}
|
||||
|
||||
/// Upper edge of the band a SILK bandwidth keeps (for band-limited references).
|
||||
fn band_edge(bw: Bandwidth) -> f64 {
|
||||
match bw {
|
||||
Bandwidth::Narrowband => 3_400.0,
|
||||
Bandwidth::Mediumband => 5_000.0,
|
||||
Bandwidth::Wideband => 7_000.0,
|
||||
_ => 24_000.0,
|
||||
}
|
||||
}
|
||||
|
||||
const LEN: usize = 96_000;
|
||||
|
||||
#[test]
|
||||
fn every_mode_and_bandwidth_decodes() {
|
||||
let sp = speech(LEN + 40_000, 11);
|
||||
let left = sp[..LEN].to_vec();
|
||||
let right: Vec<f32> = sp[40_000..].iter().map(|v| v * 0.6).collect();
|
||||
for (mode, bw, config, rate) in [
|
||||
(Mode::Silk, Bandwidth::Narrowband, 1u8, 8_000u32),
|
||||
(Mode::Silk, Bandwidth::Mediumband, 5, 11_000),
|
||||
(Mode::Silk, Bandwidth::Wideband, 9, 16_000),
|
||||
(Mode::Hybrid, Bandwidth::SuperWideband, 13, 24_000),
|
||||
(Mode::Hybrid, Bandwidth::Fullband, 15, 32_000),
|
||||
(Mode::Celt, Bandwidth::Fullband, 31, 64_000),
|
||||
] {
|
||||
for c in [1usize, 2] {
|
||||
let planar = if c == 1 { vec![left.clone()] } else { vec![left.clone(), right.clone()] };
|
||||
let reference: Vec<Vec<f32>> = planar.iter().map(|x| lowpass(x, band_edge(bw))).collect();
|
||||
let enc = OpusEncoder::with_mode(c as u8, rate * c as u32, mode, bw);
|
||||
assert_eq!((enc.mode(), enc.bandwidth()), (mode, bw));
|
||||
let res = run(enc, &planar, &reference);
|
||||
for p in &res[0].packets {
|
||||
assert_eq!(p[0], (config << 3) | if c == 2 { 4 } else { 0 }, "TOC of {mode:?}/{bw:?}");
|
||||
assert!(p.len() >= 3 && p.len() <= 1276);
|
||||
}
|
||||
for (ch, r) in res.iter().enumerate() {
|
||||
eprintln!(
|
||||
"{mode:?}/{bw:?} {c} ch @ {} kb/s: {:.1} kb/s, channel {ch} SNR {:.1} dB, segSNR {:.1} dB, residual delay {}",
|
||||
rate * c as u32 / 1000,
|
||||
r.kbps,
|
||||
r.snr,
|
||||
r.seg,
|
||||
r.delay
|
||||
);
|
||||
assert!(r.snr > 8.0, "{mode:?}/{bw:?} {c} ch channel {ch}: SNR {:.1} dB", r.snr);
|
||||
assert!(r.delay.abs() <= 1, "{mode:?}/{bw:?}: residual delay {} (pre-skip mismatch)", r.delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silk_speech_quality() {
|
||||
let x = speech(LEN, 7);
|
||||
for (bw, rate, min_snr) in [
|
||||
(Bandwidth::Narrowband, 8_000u32, 10.0),
|
||||
(Bandwidth::Mediumband, 11_000, 14.0),
|
||||
(Bandwidth::Wideband, 12_000, 14.0),
|
||||
(Bandwidth::Wideband, 16_000, 18.0),
|
||||
(Bandwidth::Wideband, 24_000, 24.0),
|
||||
] {
|
||||
let r = mono(Mode::Silk, bw, rate, &x, band_edge(bw));
|
||||
eprintln!("SILK {bw:?} speech @ {} kb/s: {:.1} kb/s, SNR {:.1} dB, segSNR {:.1} dB", rate / 1000, r.kbps, r.snr, r.seg);
|
||||
assert!(r.snr > min_snr && r.seg > min_snr - 3.0, "SILK {bw:?} @ {rate}: SNR {:.1} / seg {:.1}", r.snr, r.seg);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silk_beats_celt_on_speech_at_low_rate() {
|
||||
let x = speech(LEN, 5);
|
||||
// Both measured against the full-band input.
|
||||
let silk = mono(Mode::Silk, Bandwidth::Wideband, 12_000, &x, 24_000.0);
|
||||
let celt = mono(Mode::Celt, Bandwidth::Fullband, 12_000, &x, 24_000.0);
|
||||
eprintln!(
|
||||
"12 kb/s mono speech: SILK WB {:.1} dB (seg {:.1}) at {:.1} kb/s vs CELT {:.1} dB (seg {:.1}) at {:.1} kb/s",
|
||||
silk.snr, silk.seg, silk.kbps, celt.snr, celt.seg, celt.kbps
|
||||
);
|
||||
assert!(silk.snr > celt.snr + 3.0, "SILK {:.1} dB vs CELT {:.1} dB", silk.snr, celt.snr);
|
||||
assert!(silk.seg > celt.seg + 3.0, "SILK seg {:.1} dB vs CELT seg {:.1} dB", silk.seg, celt.seg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hybrid_quality() {
|
||||
let sp = speech(LEN, 9);
|
||||
let mu = music(LEN);
|
||||
for (name, x, bw, rate, min_snr) in [
|
||||
("speech", &sp, Bandwidth::SuperWideband, 24_000u32, 18.0),
|
||||
("speech", &sp, Bandwidth::Fullband, 32_000, 20.0),
|
||||
("music", &mu, Bandwidth::SuperWideband, 24_000, 9.0),
|
||||
("music", &mu, Bandwidth::Fullband, 32_000, 10.0),
|
||||
] {
|
||||
let r = mono(Mode::Hybrid, bw, rate, x, 24_000.0);
|
||||
eprintln!("hybrid {bw:?} {name} @ {} kb/s: {:.1} kb/s, SNR {:.1} dB, segSNR {:.1} dB", rate / 1000, r.kbps, r.snr, r.seg);
|
||||
assert!(r.snr > min_snr, "hybrid {bw:?} {name}: SNR {:.1} dB", r.snr);
|
||||
// Constant packet size.
|
||||
assert!(r.packets.iter().all(|p| p.len() == rate as usize / 400));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silk_music_quality() {
|
||||
let x = music(LEN);
|
||||
for (rate, min_snr) in [(12_000u32, 5.0), (16_000, 8.0), (24_000, 13.0)] {
|
||||
let r = mono(Mode::Silk, Bandwidth::Wideband, rate, &x, 7_000.0);
|
||||
eprintln!("SILK WB music @ {} kb/s: {:.1} kb/s, SNR {:.1} dB", rate / 1000, r.kbps, r.snr);
|
||||
assert!(r.snr > min_snr, "SILK music @ {rate}: SNR {:.1} dB", r.snr);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitrate_tracking() {
|
||||
let sp = speech(LEN, 13);
|
||||
let mu = music(LEN);
|
||||
for (name, x) in [("speech", &sp), ("music", &mu)] {
|
||||
for (mode, bw, rate) in [
|
||||
(Mode::Silk, Bandwidth::Narrowband, 6_000u32),
|
||||
(Mode::Silk, Bandwidth::Narrowband, 9_000),
|
||||
(Mode::Silk, Bandwidth::Mediumband, 11_000),
|
||||
(Mode::Silk, Bandwidth::Wideband, 12_000),
|
||||
(Mode::Silk, Bandwidth::Wideband, 20_000),
|
||||
(Mode::Silk, Bandwidth::Wideband, 32_000),
|
||||
(Mode::Hybrid, Bandwidth::SuperWideband, 20_000),
|
||||
(Mode::Hybrid, Bandwidth::Fullband, 36_000),
|
||||
] {
|
||||
let r = mono(mode, bw, rate, x, band_edge(bw));
|
||||
let ratio = r.kbps * 1000.0 / rate as f64;
|
||||
eprintln!("{name} {mode:?}/{bw:?} target {} kb/s: actual {:.2} kb/s ({:+.0} %), SNR {:.1} dB", rate / 1000, r.kbps, (ratio - 1.0) * 100.0, r.snr);
|
||||
assert!((0.75..=1.25).contains(&ratio), "{name} {mode:?}/{bw:?} @ {rate}: {:.2} kb/s", r.kbps);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stereo_silk_and_hybrid() {
|
||||
let sp = speech(LEN + 40_000, 21);
|
||||
let a = sp[..LEN].to_vec();
|
||||
let b: Vec<f32> = sp[40_000..].iter().map(|v| v * 0.7).collect();
|
||||
let mu = music(LEN);
|
||||
let cases: Vec<(&str, Vec<f32>, Vec<f32>)> = vec![
|
||||
("dual mono", a.clone(), a.clone()),
|
||||
("panned", a.iter().map(|v| v * 0.9).collect(), a.iter().map(|v| v * 0.35).collect()),
|
||||
("independent", a.clone(), b),
|
||||
("speech+music", a.iter().zip(&mu).map(|(x, y)| 0.8 * x + 0.3 * y).collect(), a.iter().zip(&mu).map(|(x, y)| 0.3 * x + 0.8 * y).collect()),
|
||||
];
|
||||
for (name, l, r) in &cases {
|
||||
for (mode, bw, rate, min_snr) in [(Mode::Silk, Bandwidth::Wideband, 32_000u32, 9.0), (Mode::Hybrid, Bandwidth::Fullband, 64_000, 9.0)] {
|
||||
let fc = band_edge(bw);
|
||||
let res = run(OpusEncoder::with_mode(2, rate, mode, bw), &[l.clone(), r.clone()], &[lowpass(l, fc), lowpass(r, fc)]);
|
||||
eprintln!("stereo {name} {mode:?}/{bw:?} @ {} kb/s: {:.1} kb/s, L {:.1} dB, R {:.1} dB", rate / 1000, res[0].kbps, res[0].snr, res[1].snr);
|
||||
assert!(res[0].snr > min_snr && res[1].snr > min_snr, "stereo {name} {mode:?}: L {:.1} R {:.1}", res[0].snr, res[1].snr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn application_tables_and_pre_skip() {
|
||||
let cases = [
|
||||
(Application::Voip, 1u8, 8_000u32, Mode::Silk, Bandwidth::Narrowband),
|
||||
(Application::Voip, 1, 11_000, Mode::Silk, Bandwidth::Mediumband),
|
||||
(Application::Voip, 1, 16_000, Mode::Silk, Bandwidth::Wideband),
|
||||
(Application::Voip, 1, 24_000, Mode::Hybrid, Bandwidth::SuperWideband),
|
||||
(Application::Voip, 1, 32_000, Mode::Hybrid, Bandwidth::Fullband),
|
||||
(Application::Voip, 1, 48_000, Mode::Celt, Bandwidth::Fullband),
|
||||
(Application::Voip, 2, 32_000, Mode::Silk, Bandwidth::Wideband),
|
||||
(Application::Audio, 1, 12_000, Mode::Silk, Bandwidth::Wideband),
|
||||
(Application::Audio, 1, 24_000, Mode::Hybrid, Bandwidth::Fullband),
|
||||
(Application::Audio, 2, 48_000, Mode::Hybrid, Bandwidth::Fullband),
|
||||
(Application::Audio, 1, 64_000, Mode::Celt, Bandwidth::Fullband),
|
||||
(Application::Audio, 2, 128_000, Mode::Celt, Bandwidth::Fullband),
|
||||
];
|
||||
for (app, c, rate, mode, bw) in cases {
|
||||
let e = OpusEncoder::with_application(c, rate, app);
|
||||
assert_eq!((e.mode(), e.bandwidth(), e.application()), (mode, bw, app), "{app:?} {c} ch @ {rate}");
|
||||
assert_eq!(e.pre_skip(), 120, "every mode is aligned to a 120-sample delay");
|
||||
}
|
||||
assert_eq!(OpusEncoder::new(2, 128_000).mode(), Mode::Celt);
|
||||
assert_eq!(OpusEncoder::new(1, 12_000).application(), Application::Audio);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "unsupported mode/bandwidth")]
|
||||
fn invalid_mode_bandwidth_panics() {
|
||||
let _ = OpusEncoder::with_mode(1, 16_000, Mode::Silk, Bandwidth::Fullband);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silk_and_hybrid_silence() {
|
||||
for (mode, bw, rate) in [(Mode::Silk, Bandwidth::Wideband, 16_000u32), (Mode::Hybrid, Bandwidth::Fullband, 32_000)] {
|
||||
let x = vec![0f32; 48_000];
|
||||
let (enc, packets) = encode(OpusEncoder::with_mode(1, rate, mode, bw), std::slice::from_ref(&x));
|
||||
let dec = decode(&enc.opus_head(), &packets);
|
||||
let peak = dec[0].iter().fold(0f32, |m, v| m.max(v.abs()));
|
||||
let kbps = bitrate(&packets) / 1000.0;
|
||||
eprintln!("{mode:?} silence: {kbps:.2} kb/s, decoded peak {peak:.2e}");
|
||||
assert!(peak < 1e-3, "{mode:?} silence decodes to peak {peak}");
|
||||
if mode == Mode::Silk {
|
||||
assert!(kbps < 4.0, "SILK silence costs {kbps:.2} kb/s");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user