mod common;
use common::*;
use opus_pure::{Application, Bandwidth, OpusDecoder, OpusEncoder, Signal, packet};
struct InStep {
enc: OpusEncoder,
dec: OpusDecoder,
rate: i32,
buf: Vec<u8>,
pcm: Vec<f32>,
modes: Vec<&'static str>,
packets: usize,
buf_len: usize,
frames_per_packet: Vec<usize>,
}
impl InStep {
fn new(rate: i32, channels: usize, app: Application) -> Self {
Self {
enc: OpusEncoder::new(rate, channels, app).expect("encoder"),
dec: OpusDecoder::new(rate, channels).expect("decoder"),
rate,
buf: vec![0u8; 4000],
pcm: vec![0.0f32; (rate as usize / 1000) * 120 * channels],
modes: Vec::new(),
packets: 0,
buf_len: 0,
frames_per_packet: Vec::new(),
}
}
fn step(&mut self, input: &[f32], frame: usize, what: &str) {
let len = self
.enc
.encode(input, frame, &mut self.buf)
.unwrap_or_else(|e| panic!("{what}: packet {} failed to encode: {e:?}", self.packets));
let enc_range = self.enc.final_range();
self.buf_len = len;
let packet = &self.buf[..len];
self.modes.push(packet_mode(packet));
self.frames_per_packet
.push(packet::frame_count(packet).expect("the encoder emitted an unparseable packet"));
let max = (self.rate as usize / 1000) * 120;
self.dec
.decode(packet, max, &mut self.pcm)
.unwrap_or_else(|e| panic!("{what}: packet {} failed to decode: {e:?}", self.packets));
if enc_range != 0 {
assert_eq!(
self.dec.final_range(),
enc_range,
"{what}: packet {} left the decoder's range coder at {:#010x}, \
the encoder ended it at {enc_range:#010x} — the entropy decode \
diverged",
self.packets,
self.dec.final_range()
);
}
self.packets += 1;
}
}
fn widen(mono: &[f32], channels: usize) -> Vec<f32> {
if channels == 1 {
return mono.to_vec();
}
mono.iter()
.enumerate()
.flat_map(|(i, &s)| [s, s * 0.6 + mono[i / 3 % mono.len()] * 0.3])
.collect()
}
#[test]
fn range_coder_state_agrees_on_every_packet() {
const RATES: [(i32, usize); 6] = [
(8_000, 1),
(12_000, 1),
(16_000, 2),
(24_000, 1),
(48_000, 1),
(48_000, 2),
];
let mut checked = 0usize;
let mut split = 0usize;
for &(rate, channels) in &RATES {
for &ms in &[10usize, 20, 40, 60, 80, 100, 120] {
for &bitrate in &[8_000, 24_000, 64_000, 128_000] {
for &app in &[Application::Voip, Application::Audio] {
let frame = (rate as usize / 1000) * ms;
let packets = if ms >= 80 { 10 } else { 20 };
let mono = speech_like(rate, frame * packets);
let pcm = widen(&mono, channels);
let what = format!("{rate} Hz/{channels}ch/{ms} ms/{bitrate} bps/{app:?}");
let mut s = InStep::new(rate, channels, app);
s.enc.bitrate_bps = bitrate;
for f in 0..pcm.len() / (frame * channels) {
let lo = f * frame * channels;
s.step(&pcm[lo..lo + frame * channels], frame, &what);
}
checked += s.packets;
split += s.frames_per_packet.iter().filter(|&&n| n > 1).count();
}
}
}
}
assert!(checked > 5_000, "only {checked} packets checked");
assert!(
split > 1_000,
"only {split} of {checked} packets held more than one frame"
);
}
#[test]
fn range_state_holds_across_forced_transitions() {
#[rustfmt::skip]
const STEPS: [(Bandwidth, i32, Signal); 8] = [
(Bandwidth::Narrowband, 8_000, Signal::Voice), (Bandwidth::Fullband, 128_000, Signal::Music), (Bandwidth::Superwideband, 12_000, Signal::Voice), (Bandwidth::Wideband, 20_000, Signal::Voice), (Bandwidth::Fullband, 256_000, Signal::Music), (Bandwidth::Fullband, 20_000, Signal::Voice), (Bandwidth::Mediumband, 24_000, Signal::Voice), (Bandwidth::Fullband, 128_000, Signal::Music), ];
for &channels in &[1usize, 2] {
let rate = 48_000;
let frame = 960; let mono = speech_like(rate, frame * (STEPS.len() * 4));
let pcm = widen(&mono, channels);
let what = format!("forced transitions, {channels}ch");
let mut s = InStep::new(rate, channels, Application::Voip);
for f in 0..pcm.len() / (frame * channels) {
let (bw, bitrate, signal) = STEPS[(f / 4) % STEPS.len()];
s.enc.force_bandwidth = Some(bw);
s.enc.bitrate_bps = bitrate;
s.enc.signal_type = Some(signal);
let lo = f * frame * channels;
s.step(&pcm[lo..lo + frame * channels], frame, &what);
}
let switches = s.modes.windows(2).filter(|w| w[0] != w[1]).count();
for mode in ["silk", "hybrid", "celt"] {
assert!(
s.modes.contains(&mode),
"{what}: never reached {mode} — the stream is not testing transitions \
(saw {:?})",
dedup(&s.modes)
);
}
assert!(
switches >= 6,
"{what}: only {switches} mode switches in {} packets",
s.packets
);
}
}
#[test]
fn dtx_and_fec_streams_keep_the_decoder_in_step() {
for &(dtx, fec, loss) in &[(true, false, 0), (false, true, 20), (true, true, 30)] {
for &(rate, channels) in &[(16_000i32, 1usize), (48_000, 2)] {
let frame = (rate as usize / 1000) * 20;
let mut mono = speech_like(rate, frame * 30);
for (i, s) in mono.iter_mut().enumerate() {
if (i / (frame * 5)) % 2 == 1 {
*s = 0.0;
}
}
let pcm = widen(&mono, channels);
let what = format!("{rate} Hz/{channels}ch dtx={dtx} fec={fec} loss={loss}%");
let mut s = InStep::new(rate, channels, Application::Voip);
s.enc.bitrate_bps = 24_000;
s.enc.use_dtx = dtx;
s.enc.use_inband_fec = fec;
s.enc.packet_loss_perc = loss;
for f in 0..pcm.len() / (frame * channels) {
let lo = f * frame * channels;
s.step(&pcm[lo..lo + frame * channels], frame, &what);
}
assert!(s.packets > 25, "{what}: only {} packets", s.packets);
}
}
}
fn dedup(modes: &[&'static str]) -> Vec<&'static str> {
let mut out: Vec<&'static str> = Vec::new();
for m in modes {
if out.last() != Some(m) {
out.push(m);
}
}
out
}
#[test]
fn digitally_silent_hybrid_frames_still_code_a_celt_layer() {
for &channels in &[1usize, 2] {
let (rate, frame) = (48_000i32, 960usize);
let mut mono = speech_like(rate, frame * 12);
for s in mono.iter_mut().skip(frame * 4).take(frame * 4) {
*s = 0.0;
}
let pcm = widen(&mono, channels);
let what = format!("silent hybrid, {channels}ch");
let mut s = InStep::new(rate, channels, Application::Voip);
s.enc.force_bandwidth = Some(Bandwidth::Superwideband);
s.enc.bitrate_bps = 24_000;
s.enc.signal_type = Some(Signal::Voice);
let mut silent_lens = Vec::new();
for f in 0..pcm.len() / (frame * channels) {
let lo = f * frame * channels;
s.step(&pcm[lo..lo + frame * channels], frame, &what);
if (5..8).contains(&f) {
silent_lens.push(s.buf_len);
}
}
assert!(
s.modes.contains(&"hybrid"),
"{what}: never reached hybrid, so the silence path was not exercised"
);
for (i, &len) in silent_lens.iter().enumerate() {
assert!(
len > 22,
"{what}: silent frame {i} coded {len} bytes — too small to carry \
a CELT layer, so the silence shortcut was taken in hybrid"
);
}
}
}
#[test]
fn split_packets_keep_the_decoder_in_step() {
let rate = 48_000i32;
const PINNED: [(&str, Bandwidth, i32, Signal); 3] = [
("silk", Bandwidth::Wideband, 32_000, Signal::Voice),
("hybrid", Bandwidth::Fullband, 20_000, Signal::Voice),
("celt", Bandwidth::Fullband, 96_000, Signal::Music),
];
for &(mode, bw, bitrate, signal) in &PINNED {
for &channels in &[1usize, 2] {
for &ms in &[40usize, 60, 80, 100, 120] {
let frame = (rate as usize / 1000) * ms;
let mono = speech_like(rate, frame * 10);
let pcm = widen(&mono, channels);
let what = format!("{mode}-pinned {channels}ch {ms} ms");
let mut s = InStep::new(rate, channels, Application::Voip);
s.enc.force_bandwidth = Some(bw);
s.enc.bitrate_bps = bitrate;
s.enc.signal_type = Some(signal);
for f in 0..pcm.len() / (frame * channels) {
let lo = f * frame * channels;
s.step(&pcm[lo..lo + frame * channels], frame, &what);
}
assert!(
s.modes.iter().all(|m| *m == mode),
"{what}: meant to pin {mode}, got {:?}",
dedup(&s.modes)
);
if ms >= 80 {
assert!(
s.frames_per_packet.iter().all(|&n| n > 1),
"{what}: {ms} ms must be several frames, saw {:?}",
s.frames_per_packet
);
}
assert!(s.packets >= 10, "{what}: only {} packets", s.packets);
}
}
}
}