Files
Liber-public/crates/liber-audio/tests/engine.rs
T

204 lines
8.4 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Mandatory test 1: time-stretch at 0.5×, 1.5× and 3× keeps the duration within tolerance and the pitch unchanged;
//! silence trimming never cuts speech (a fixture with marked speech regions); the position after a kill and restart
//! is within one second. Fixtures are generated here (no audio files in git).
use liber_audio::boost::Boost;
use liber_audio::player::{
Chapter, MAX_BLOCK_MS, Saver, Sleep, chapter_at, next_chapter, previous_chapter, skip, tidy,
};
use liber_audio::silence::{TrimConfig, Trimmer, trim};
use liber_audio::stretch::stretch;
const RATE: u32 = 16_000;
/// A voiced, speech-like tone: a fundamental and two harmonics, gently amplitude-modulated (syllables).
fn voice(f0: f32, secs: f32) -> Vec<f32> {
let n = (RATE as f32 * secs) as usize;
(0..n)
.map(|i| {
let t = i as f32 / RATE as f32;
let w = 2.0 * std::f32::consts::PI * f0 * t;
let env = 0.6 + 0.4 * (2.0 * std::f32::consts::PI * 4.0 * t).sin();
0.3 * env * (w.sin() + 0.5 * (2.0 * w).sin() + 0.25 * (3.0 * w).sin())
})
.collect()
}
/// The fundamental by autocorrelation over a middle stretch (lags for 60–500 Hz).
fn pitch(x: &[f32]) -> f32 {
let mid = &x[x.len() / 4..x.len() * 3 / 4];
let seg = &mid[..mid.len().min(8_000)];
let (lo, hi) = ((RATE / 500) as usize, (RATE / 60) as usize);
let mut best = (0.0f32, lo);
for lag in lo..hi {
let c: f32 = seg.iter().zip(&seg[lag..]).map(|(a, b)| a * b).sum::<f32>() / (seg.len() - lag) as f32;
if c > best.0 {
best = (c, lag);
}
}
// Parabolic interpolation around the peak for sub-sample precision.
let lag = best.1;
let ac = |l: usize| seg.iter().zip(&seg[l..]).map(|(a, b)| a * b).sum::<f32>() / (seg.len() - l) as f32;
let (y0, y1, y2) = (ac(lag - 1), ac(lag), ac(lag + 1));
let d = 0.5 * (y0 - y2) / (y0 - 2.0 * y1 + y2);
RATE as f32 / (lag as f32 + if d.is_finite() { d } else { 0.0 })
}
#[test]
fn stretch_keeps_pitch_and_scales_duration() {
let input = voice(180.0, 4.0);
let p_in = pitch(&input);
for speed in [0.5, 1.5, 3.0] {
let out = stretch(&input, RATE, 1, speed);
let want = input.len() as f64 / speed;
let ratio = out.len() as f64 / want;
let p_out = pitch(&out);
println!("speed {speed}: length {:.3} of the ideal, pitch {p_in:.1} → {p_out:.1} Hz", ratio);
assert!((ratio - 1.0).abs() < 0.03, "speed {speed}: duration off by {:.1}%", (ratio - 1.0) * 100.0);
assert!(((p_out - p_in) / p_in).abs() < 0.02, "speed {speed}: pitch {p_in} → {p_out}");
}
}
#[test]
fn stretch_streams_with_speed_changes_and_stereo() {
let mono = voice(200.0, 2.0);
let stereo: Vec<f32> = mono.iter().flat_map(|&x| [x, -x]).collect();
let out = stretch(&stereo, RATE, 2, 1.5);
assert_eq!(out.len() % 2, 0);
// The channels stay opposite: the same alignment is applied to both.
let max_sum = out.chunks(2).map(|f| (f[0] + f[1]).abs()).fold(0.0f32, f32::max);
assert!(max_sum < 1e-4, "{max_sum}");
// NaN and out-of-range speeds are refused or clamped.
let mut s = liber_audio::stretch::Stretcher::new(RATE, 1);
s.set_speed(f64::NAN);
assert_eq!(s.speed(), 1.0);
s.set_speed(9.0);
assert_eq!(s.speed(), 3.0);
}
/// Speech regions (marked) and pauses of 100, 250, 600 and 2,000 ms.
fn speech_and_pauses() -> (Vec<f32>, Vec<(usize, usize)>, Vec<usize>) {
let mut x = Vec::new();
let mut speech = Vec::new();
let pauses_ms = [100, 250, 600, 2_000];
for (i, p) in pauses_ms.iter().enumerate() {
let s = x.len();
x.extend(voice(150.0 + 20.0 * i as f32, 0.7));
speech.push((s, x.len()));
x.extend(std::iter::repeat_n(0.0005f32, (RATE as usize * p) / 1000));
}
let s = x.len();
x.extend(voice(170.0, 0.5));
speech.push((s, x.len()));
(x, speech, pauses_ms.to_vec())
}
#[test]
fn trimming_never_cuts_speech() {
let (x, speech, pauses) = speech_and_pauses();
let cfg = TrimConfig::default();
let out = trim(&x, RATE, 1, cfg);
let loud = |v: &[f32]| v.iter().filter(|s| s.abs() > 0.01).count();
let speech_loud: usize = speech.iter().map(|&(a, b)| loud(&x[a..b])).sum();
assert_eq!(loud(&out), speech_loud, "every loud sample of speech is still there");
// Short pauses (< 300 ms) stay; long ones become 150 ms (± one 10 ms frame each).
let ms = |n: usize| n as i64 * 1000 / RATE as i64;
let speech_ms: i64 = speech.iter().map(|&(a, b)| ms(b - a)).sum();
let want: i64 = speech_ms
+ pauses.iter().map(|&p| if p >= cfg.long_ms as usize { cfg.keep_ms as i64 } else { p as i64 }).sum::<i64>();
let got = ms(out.len());
assert!((got - want).abs() <= 40, "output {got} ms, want {want} ms");
// Turned off, nothing changes.
let mut t = Trimmer::new(RATE, 1, cfg);
t.enabled = false;
t.push(&x);
t.finish();
assert_eq!(t.pull().len(), x.len());
}
#[test]
fn trimmed_time_maps_back_to_the_books_time() {
let (x, speech, _) = speech_and_pauses();
let mut t = Trimmer::new(RATE, 1, TrimConfig::default());
t.push(&x);
t.finish();
let out = t.pull();
// The last speech region starts at the same place in the book whichever way it is counted.
let (last_start, _) = *speech.last().unwrap();
let out_start = out.len() - (x.len() - last_start);
let back = t.input_frame(out_start as u64) as usize;
assert!((back as i64 - last_start as i64).abs() <= (RATE / 100) as i64, "{back} vs {last_start}");
}
#[test]
fn boost_never_clips_and_lifts_presence() {
let mut b = Boost::new(RATE, 1);
let mut loud: Vec<f32> = voice(200.0, 1.0).iter().map(|s| s * 4.0).collect();
b.process(&mut loud);
assert!(loud.iter().all(|s| s.abs() <= 1.0 && s.is_finite()));
// A 2.5 kHz tone comes out louder relative to a 100 Hz tone than it went in.
let tone = |f: f32| -> Vec<f32> {
(0..RATE as usize).map(|i| 0.05 * (2.0 * std::f32::consts::PI * f * i as f32 / RATE as f32).sin()).collect()
};
let rms = |v: &[f32]| (v[v.len() / 2..].iter().map(|x| x * x).sum::<f32>() / (v.len() / 2) as f32).sqrt();
let (mut lo, mut hi) = (tone(100.0), tone(2_500.0));
Boost::new(RATE, 1).process(&mut lo);
Boost::new(RATE, 1).process(&mut hi);
assert!(rms(&hi) > rms(&lo) * 1.3, "presence {} vs low {}", rms(&hi), rms(&lo));
}
/// A deterministic generator, so the test needs no `rand`.
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
self.0 >> 33
}
}
#[test]
fn a_killed_player_resumes_within_a_second() {
// Playback in blocks of up to MAX_BLOCK_MS; the app is killed at a random moment; on restart the player reads the
// last saved position. Across 2,000 kills it is never more than a second behind.
let mut g = Lcg(11);
for _ in 0..2_000 {
let mut saver = Saver::default();
let (mut now, mut pos, mut saved) = (0u64, 0u64, 0u64);
let kill_at = 1_000 + g.next() % 600_000;
while now < kill_at {
let block = 1 + g.next() % MAX_BLOCK_MS;
now += block;
pos += block;
if saver.tick(now) {
saved = pos;
}
}
assert!(pos - saved <= 1_000, "{} ms behind", pos - saved);
}
}
#[test]
fn chapters_skips_and_the_sleep_timer() {
let raw = vec![
Chapter { title: "Two".into(), start_ms: 60_000, end_ms: 0 },
Chapter { title: "".into(), start_ms: 0, end_ms: 0 },
Chapter { title: "Beyond".into(), start_ms: 999_999, end_ms: 0 },
Chapter { title: "Dup".into(), start_ms: 60_000, end_ms: 0 },
];
let ch = tidy(raw, 120_000).expect("chapters");
assert_eq!(ch.len(), 2);
assert_eq!(ch[0].title, "Chapter 1");
assert_eq!((ch[0].end_ms, ch[1].end_ms), (60_000, 120_000));
assert_eq!(chapter_at(&ch, 61_000), Some(1));
assert_eq!(previous_chapter(&ch, 61_000), 0, "within 3 s of a start: the chapter before");
assert_eq!(previous_chapter(&ch, 90_000), 60_000);
assert_eq!(next_chapter(&ch, 1_000), Some(60_000));
assert_eq!(next_chapter(&ch, 61_000), None);
assert_eq!(skip(5_000, -15_000, 120_000), 0);
assert_eq!(skip(119_000, 30_000, 120_000), 120_000);
let s = Sleep::minutes(1_000, 10);
assert!(!s.due(600_999, 0) && s.due(601_000, 0));
let e = Sleep::end_of_chapter(&ch, 61_000, 120_000);
assert!(!e.due(0, 119_999) && e.due(0, 120_000));
}