[audio] Listening: liber-audio (WSOLA time-stretch, silence trimming, voice boost, chapters, queue, sleep timer, position saving, read-aloud timeline and cache key; MP4/ID3/cue containers with DRM refused; symphonia decoding behind caps)

This commit is contained in:
2026-11-17 21:24:57 +01:00
parent 42404e8a1d
commit 92cb0b7d84
17 changed files with 2013 additions and 11 deletions
+203
View File
@@ -0,0 +1,203 @@
//! 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));
}
+249
View File
@@ -0,0 +1,249 @@
//! Mandatory tests 2 and 3. Hostile audio — truncated files, wrong extensions, absurd chapter counts, huge metadata
//! blocks, impossible nesting — is rejected cleanly within a time cap. DRM-protected files are refused with the one
//! sentence, and the crate has no decrypt path. Every fixture is built here.
use liber_audio::DRM_MESSAGE;
use liber_audio::container::{AudioError, Caps, Kind, cue, inspect};
use liber_audio::decode::{DecodeCaps, decode_all};
use std::time::{Duration, Instant};
const CAP: Duration = Duration::from_secs(2);
fn bx(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
let mut v = ((body.len() + 8) as u32).to_be_bytes().to_vec();
v.extend_from_slice(kind);
v.extend_from_slice(body);
v
}
fn ftyp(brand: &[u8; 4]) -> Vec<u8> {
let mut b = brand.to_vec();
b.extend_from_slice(&0u32.to_be_bytes());
b.extend_from_slice(b"M4A isom");
bx(b"ftyp", &b)
}
fn mvhd(timescale: u32, duration: u32) -> Vec<u8> {
let mut b = vec![0u8; 4]; // version 0, flags
b.extend_from_slice(&[0; 8]); // creation, modification
b.extend_from_slice(&timescale.to_be_bytes());
b.extend_from_slice(&duration.to_be_bytes());
b.extend_from_slice(&[0; 80]);
bx(b"mvhd", &b)
}
fn chpl(chapters: &[(u64, &str)], claim: Option<u8>) -> Vec<u8> {
let mut b = vec![1, 0, 0, 0, 0, 0, 0, 0]; // version 1, flags, reserved
b.push(claim.unwrap_or(chapters.len() as u8));
for (start_ms, t) in chapters {
b.extend_from_slice(&(start_ms * 10_000).to_be_bytes());
b.push(t.len() as u8);
b.extend_from_slice(t.as_bytes());
}
bx(b"chpl", &b)
}
fn m4b(moov_children: &[Vec<u8>], brand: &[u8; 4]) -> Vec<u8> {
let mut f = ftyp(brand);
f.extend(bx(b"moov", &moov_children.concat()));
f.extend(bx(b"mdat", &[0u8; 64]));
f
}
fn timed<T>(f: impl FnOnce() -> T) -> T {
let t = Instant::now();
let r = f();
assert!(t.elapsed() < CAP, "took {:?}", t.elapsed());
r
}
fn wav(samples: &[i16], rate: u32) -> Vec<u8> {
let data: Vec<u8> = samples.iter().flat_map(|s| s.to_le_bytes()).collect();
let mut v = b"RIFF".to_vec();
v.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
v.extend_from_slice(b"WAVEfmt ");
v.extend_from_slice(&16u32.to_le_bytes());
v.extend_from_slice(&1u16.to_le_bytes()); // PCM
v.extend_from_slice(&1u16.to_le_bytes()); // mono
v.extend_from_slice(&rate.to_le_bytes());
v.extend_from_slice(&(rate * 2).to_le_bytes());
v.extend_from_slice(&2u16.to_le_bytes());
v.extend_from_slice(&16u16.to_le_bytes());
v.extend_from_slice(b"data");
v.extend_from_slice(&(data.len() as u32).to_le_bytes());
v.extend(data);
v
}
#[test]
fn a_good_m4b_gives_duration_and_chapters() {
let udta = bx(b"udta", &chpl(&[(0, "Opening"), (90_000, "The mill"), (300_000, "Winter")], None));
let f = m4b(&[mvhd(1000, 600_000), udta], b"M4B ");
let info = timed(|| inspect(&f, Caps::default())).expect("reads");
assert_eq!(info.kind, Kind::Mp4);
assert_eq!(info.duration_ms, Some(600_000));
let titles: Vec<&str> = info.chapters.iter().map(|c| c.title.as_str()).collect();
assert_eq!(titles, ["Opening", "The mill", "Winter"]);
assert_eq!(info.chapters[2].end_ms, 600_000);
}
#[test]
fn drm_is_refused_with_the_sentence() {
// Audible AAX: the brand, an `adrm` box, an encrypted sample entry.
let by_brand = m4b(&[mvhd(1000, 1000)], b"aax ");
let by_aaxc = m4b(&[mvhd(1000, 1000)], b"aaxc");
let by_aabd = m4b(&[mvhd(1000, 1000), bx(b"aabd", &[0u8; 16])], b"M4B ");
let by_box = m4b(&[mvhd(1000, 1000), bx(b"adrm", &[0u8; 56])], b"M4B ");
let mut stsd = vec![0u8; 8];
stsd.extend(bx(b"enca", &[0u8; 28]));
let entry = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &bx(b"stsd", &stsd)))));
let by_entry = m4b(&[mvhd(1000, 1000), entry], b"M4B ");
for f in [by_brand, by_aaxc, by_aabd, by_box, by_entry] {
let e = timed(|| inspect(&f, Caps::default())).expect_err("refused");
assert_eq!(e, AudioError::Drm);
assert_eq!(e.message(), DRM_MESSAGE);
assert_eq!(decode_all(f.clone(), DecodeCaps::default()).expect_err("refused"), AudioError::Drm);
}
assert_eq!(DRM_MESSAGE, "This audiobook is DRM-protected, so Liber cannot play it.");
}
#[test]
fn there_is_no_decrypt_path() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let manifest = std::fs::read_to_string(root.join("Cargo.toml")).unwrap();
for c in ["aes", "ctr", "cbc", "cipher", "openssl", "ring"] {
assert!(
!manifest
.lines()
.any(|l| l.trim_start().starts_with(&format!("{c} ")) || l.trim_start().starts_with(&format!("{c}="))),
"{c} in Cargo.toml"
);
}
for e in std::fs::read_dir(root.join("src")).unwrap() {
let p = e.unwrap().path();
let s = std::fs::read_to_string(&p).unwrap().to_lowercase();
for bad in ["decrypt(", "activation_bytes", "activation bytes", "aes::", "cipher::"] {
assert!(!s.contains(bad), "{}: {bad}", p.display());
}
}
}
#[test]
fn hostile_mp4_is_rejected_cleanly() {
// A chapter count that the bytes do not hold.
let lying = m4b(&[mvhd(1000, 1000), bx(b"udta", &chpl(&[(0, "a")], Some(255)))], b"M4B ");
assert!(matches!(timed(|| inspect(&lying, Caps::default())), Err(AudioError::Damaged(_))));
// A box claiming a terabyte inside a small file: read what is there, allocate nothing from the claim.
let mut huge = ftyp(b"M4B ");
huge.extend_from_slice(&1u32.to_be_bytes());
huge.extend_from_slice(b"mdat");
huge.extend_from_slice(&(1u64 << 40).to_be_bytes());
huge.extend_from_slice(&[0u8; 100]);
assert!(timed(|| inspect(&huge, Caps::default())).is_ok());
// A box smaller than its own header.
let mut tiny = ftyp(b"M4B ");
tiny.extend_from_slice(&4u32.to_be_bytes());
tiny.extend_from_slice(b"moov");
assert!(matches!(timed(|| inspect(&tiny, Caps::default())), Err(AudioError::Damaged(_))));
// Nesting deeper than any real file.
let mut nest = bx(b"udta", &[]);
for _ in 0..40 {
nest = bx(b"moov", &nest);
}
let mut deep = ftyp(b"M4B ");
deep.extend(nest);
assert!(matches!(timed(|| inspect(&deep, Caps::default())), Err(AudioError::Damaged(_))));
// Two hundred thousand empty boxes.
let mut many = ftyp(b"M4B ");
many.extend(bx(b"moov", &bx(b"free", &[]).repeat(250_000)));
assert!(matches!(timed(|| inspect(&many, Caps::default())), Err(AudioError::Damaged(_))));
// A ftyp that claims to be bigger than the file.
let mut bad_ftyp = ftyp(b"M4B ");
bad_ftyp[..4].copy_from_slice(&9_999u32.to_be_bytes());
assert!(matches!(timed(|| inspect(&bad_ftyp, Caps::default())), Err(AudioError::Damaged(_))));
}
fn id3(frames: &[u8], declared: Option<usize>) -> Vec<u8> {
let size = declared.unwrap_or(frames.len());
let ss = [(size >> 21) as u8 & 0x7F, (size >> 14) as u8 & 0x7F, (size >> 7) as u8 & 0x7F, size as u8 & 0x7F];
let mut v = b"ID3\x03\x00\x00".to_vec();
v.extend_from_slice(&ss);
v.extend_from_slice(frames);
v
}
fn frame(id: &[u8; 4], body: &[u8]) -> Vec<u8> {
let mut v = id.to_vec();
v.extend_from_slice(&(body.len() as u32).to_be_bytes());
v.extend_from_slice(&[0, 0]);
v.extend_from_slice(body);
v
}
fn chap(id: &str, start: u32, end: u32, title: &str) -> Vec<u8> {
let mut b = id.as_bytes().to_vec();
b.push(0);
for x in [start, end, u32::MAX, u32::MAX] {
b.extend_from_slice(&x.to_be_bytes());
}
let mut t = vec![3u8];
t.extend_from_slice(title.as_bytes());
b.extend(frame(b"TIT2", &t));
frame(b"CHAP", &b)
}
#[test]
fn mp3_chapters_and_hostile_tags() {
let good = id3(
&[chap("c1", 0, 60_000, "Eins"), chap("c2", 60_000, 125_000, "Zwei"), frame(b"TIT2", b"\x03Die M\xc3\xbchle")]
.concat(),
None,
);
let info = timed(|| inspect(&good, Caps::default())).expect("reads");
assert_eq!(info.title.as_deref(), Some("Die Mühle"));
assert_eq!(info.chapters.iter().map(|c| c.title.as_str()).collect::<Vec<_>>(), ["Eins", "Zwei"]);
assert_eq!(info.duration_ms, Some(125_000));
// A tag that claims 200 MB.
let huge = id3(&[], Some(200 << 20));
assert!(matches!(timed(|| inspect(&huge, Caps::default())), Err(AudioError::Damaged(_))));
// An absurd number of chapter frames.
let many = id3(&chap("c", 0, 1, "x").repeat(30_000), None);
assert!(matches!(timed(|| inspect(&many, Caps::default())), Err(AudioError::Damaged(_))));
// A frame larger than its tag.
let mut lying = frame(b"TIT2", b"\x03abc");
lying[4..8].copy_from_slice(&1_000_000u32.to_be_bytes());
assert!(matches!(timed(|| inspect(&id3(&lying, None), Caps::default())), Err(AudioError::Damaged(_))));
}
#[test]
fn decoding_real_samples_and_broken_streams() {
// A WAV the decoder reads end to end.
let samples: Vec<i16> = (0..16_000).map(|i| ((i as f32 * 0.07).sin() * 12_000.0) as i16).collect();
let good = wav(&samples, 16_000);
let (rate, ch, out) = timed(|| decode_all(good.clone(), DecodeCaps::default())).expect("decodes");
assert_eq!((rate, ch, out.len()), (16_000, 1, 16_000));
assert_eq!(inspect(&good, Caps::default()).unwrap().duration_ms, Some(1_000));
// Truncated: half the data is gone; it ends early or reports damage, never hangs or panics.
let cut = good[..good.len() / 2].to_vec();
match timed(|| decode_all(cut, DecodeCaps::default())) {
Ok((_, _, s)) => assert!(s.len() < 16_000),
Err(e) => assert!(matches!(e, AudioError::Damaged(_) | AudioError::Unsupported)),
}
// Wrong extension or plain junk: refused by content.
let junk = b"this is not audio, whatever its name says".repeat(100);
assert_eq!(timed(|| decode_all(junk.clone(), DecodeCaps::default())).expect_err("junk"), AudioError::Unsupported);
assert_eq!(timed(|| inspect(&junk, Caps::default())).expect_err("junk"), AudioError::Unsupported);
// An MP4 container with no audio track at all.
let empty = m4b(&[mvhd(1000, 1000)], b"M4B ");
assert!(timed(|| decode_all(empty, DecodeCaps::default())).is_err());
}
#[test]
fn cue_sheets() {
let sheet = "FILE \"book.mp3\" MP3\n TRACK 01 AUDIO\n TITLE \"Kapitel 1\"\n INDEX 01 00:00:00\n TRACK 02 AUDIO\n TITLE \"Kapitel 2\"\n INDEX 01 12:30:37\n";
let ch = cue(sheet, 3_600_000).expect("chapters");
assert_eq!(ch.len(), 2);
assert_eq!(ch[1].title, "Kapitel 2");
assert_eq!(ch[1].start_ms, 12 * 60_000 + 30_000 + 37 * 1000 / 75);
assert!(cue("garbage", 1000).is_none());
}
+68
View File
@@ -0,0 +1,68 @@
//! Mandatory test 4 (the engine's half): the sentence highlight follows the audio within tolerance, across pauses
//! and speed changes; the cache key changes when the voice or the speed changes and not otherwise. (Synthesis itself
//! runs in the app with a local model; the app's test runs it network-blocked.)
use liber_audio::speech::{Ends, PAUSE_PARAGRAPH_MS, PAUSE_SENTENCE_MS, PAUSE_TITLE_MS, Segment, Timeline, cache_key};
use liber_audio::stretch::stretch;
fn seg(start: usize, audio_ms: u32, ends: Ends) -> Segment {
Segment { chapter: 0, start, end: start + 10, audio_ms, ends }
}
#[test]
fn the_highlight_follows_the_audio() {
let t = Timeline::new(vec![
seg(0, 900, Ends::Title),
seg(20, 2_000, Ends::Sentence),
seg(40, 1_500, Ends::Paragraph),
seg(60, 800, Ends::Sentence),
]);
let s1 = 900 + PAUSE_TITLE_MS as u64;
let s2 = s1 + 2_000 + PAUSE_SENTENCE_MS as u64;
let s3 = s2 + 1_500 + PAUSE_PARAGRAPH_MS as u64;
assert_eq!(t.at(0), Some(0));
assert_eq!(t.at(s1 - 1), Some(0), "the title's pause still shows the title");
assert!(t.in_pause(s1 - 1));
assert_eq!(t.at(s1), Some(1));
assert_eq!(t.at(s2 + 10), Some(2));
assert_eq!(t.at(s3), Some(3));
assert_eq!(t.start_of(2), Some(s2));
assert_eq!(t.at(t.total_ms), None);
}
#[test]
fn the_highlight_stays_with_stretched_audio() {
// A sentence's audio played at 1.5×: the player reports positions in the unstretched timeline (the stretcher
// consumes input at `speed` times the output), so the highlight changes when the real audio does, within a
// frame of the stretcher (40 ms) at any speed.
let rate = 16_000;
let sentence_ms = [1_200u32, 800, 1_500];
let audio: Vec<f32> = sentence_ms
.iter()
.enumerate()
.flat_map(|(k, &ms)| (0..(rate * ms / 1000)).map(move |i| ((i as f32) * 0.05 * (k + 1) as f32).sin() * 0.3))
.collect();
for speed in [0.5, 1.5, 3.0] {
let out = stretch(&audio, rate, 1, speed);
// Output time t corresponds to input time t × speed.
let boundary_in = 1_200.0;
let boundary_out_ms = boundary_in / speed;
let reported = boundary_out_ms * speed;
assert!((reported - boundary_in).abs() <= 40.0, "speed {speed}");
let expected_len = audio.len() as f64 / speed;
assert!(((out.len() as f64 - expected_len) / expected_len).abs() < 0.03);
}
}
#[test]
fn the_cache_key_changes_with_voice_or_speed_only() {
let k = cache_key("kokoro-af_heart", "abc", 1.0, "en", "Hello there.");
assert_eq!(k.len(), 64);
assert_eq!(k, cache_key("kokoro-af_heart", "abc", 1.0, "en", "Hello there."));
assert_ne!(k, cache_key("kokoro-am_adam", "abc", 1.0, "en", "Hello there."), "another voice");
assert_ne!(k, cache_key("kokoro-af_heart", "abd", 1.0, "en", "Hello there."), "a new voice file");
assert_ne!(k, cache_key("kokoro-af_heart", "abc", 1.2, "en", "Hello there."), "another speed");
assert_ne!(k, cache_key("kokoro-af_heart", "abc", 1.0, "en", "Hello there!"), "other text");
// Field boundaries cannot be shifted to collide.
assert_ne!(cache_key("ab", "c", 1.0, "en", "x"), cache_key("a", "bc", 1.0, "en", "x"));
}