Tunal/crates/tunal-player/tests/waveform.rs
astar76 9ea6cc342c S033: tests for thumbs, tags, MusicBrainz, player, ssh, SFTP and MTP
Fixes: key passphrase retried up to three times; zero track/disc number reads as none.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-19 04:58:55 -06:00

171 lines
6.1 KiB
Rust

//! Decoding and waveform peaks on fixtures; no audio device is needed.
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tunal_player::{Error, Waveform, Waveforms};
fn fixture(name: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures")
.join(name)
}
fn wait(w: &Waveforms, path: &Path, buckets: usize) -> Result<Arc<Waveform>, Error> {
let (tx, rx) = mpsc::channel();
w.request(path, buckets, move |r| tx.send(r).unwrap());
rx.recv_timeout(Duration::from_secs(30)).unwrap()
}
/// A mono 16-bit WAV: `quiet` seconds of silence then `loud` seconds of full-scale square wave.
fn write_wav(path: &Path, rate: u32, channels: u16, quiet: u32, loud: u32) {
let frames = |secs: u32| (rate * secs) as usize;
let mut data = Vec::new();
for _ in 0..frames(quiet) {
for _ in 0..channels {
data.extend(0i16.to_le_bytes());
}
}
for i in 0..frames(loud) {
let v: i16 = if i % 2 == 0 { 32767 } else { -32768 };
for _ in 0..channels {
data.extend(v.to_le_bytes());
}
}
let mut out = Vec::new();
out.extend(b"RIFF");
out.extend((36 + data.len() as u32).to_le_bytes());
out.extend(b"WAVEfmt ");
out.extend(16u32.to_le_bytes());
out.extend(1u16.to_le_bytes());
out.extend(channels.to_le_bytes());
out.extend(rate.to_le_bytes());
out.extend((rate * u32::from(channels) * 2).to_le_bytes());
out.extend((channels * 2).to_le_bytes());
out.extend(16u16.to_le_bytes());
out.extend(b"data");
out.extend((data.len() as u32).to_le_bytes());
out.extend(data);
fs::write(path, out).unwrap();
}
#[test]
fn every_fixture_decodes_with_about_one_second_and_a_signal() {
let w = Waveforms::new();
for name in ["t.flac", "t.mp3", "t.ogg", "t.m4a", "t.wav"] {
let wave = wait(&w, &fixture(name), 20).unwrap_or_else(|e| panic!("{name}: {e}"));
assert_eq!(wave.peaks.len(), 20, "{name}");
let secs = wave.duration.as_secs_f64();
assert!((0.9..=1.2).contains(&secs), "{name}: {secs}");
let top = wave.peaks.iter().map(|p| p.1).fold(0.0, f32::max);
let bottom = wave.peaks.iter().map(|p| p.0).fold(0.0, f32::min);
assert!(top > 0.05 && top <= 0.3, "{name}: max {top}");
assert!((-0.3..-0.05).contains(&bottom), "{name}: min {bottom}");
for (lo, hi) in &wave.peaks {
assert!(lo <= hi, "{name}");
}
}
}
#[test]
fn buckets_follow_the_loudness_over_time() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("half.wav");
// Two seconds of silence, then two seconds at full scale.
write_wav(&path, 8000, 1, 2, 2);
let wave = wait(&Waveforms::new(), &path, 8).unwrap();
assert_eq!(wave.peaks.len(), 8);
assert!((wave.duration.as_secs_f64() - 4.0).abs() < 0.01);
for (i, (lo, hi)) in wave.peaks.iter().enumerate() {
if i < 4 {
assert_eq!((*lo, *hi), (0.0, 0.0), "bucket {i} is silent");
} else {
assert!(*hi > 0.99 && *lo < -0.99, "bucket {i}: {lo} {hi}");
}
}
}
#[test]
fn stereo_peaks_cover_all_channels_and_duration_counts_frames() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("st.wav");
write_wav(&path, 8000, 2, 0, 1);
let wave = wait(&Waveforms::new(), &path, 4).unwrap();
assert!((wave.duration.as_secs_f64() - 1.0).abs() < 0.01);
assert!(wave.peaks.iter().all(|p| p.1 > 0.99 && p.0 < -0.99));
}
#[test]
fn more_buckets_than_blocks_still_gives_that_many() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("short.wav");
write_wav(&path, 8000, 1, 0, 1);
// 8000 frames are ~32 blocks of 256; ask for far more buckets.
let wave = wait(&Waveforms::new(), &path, 500).unwrap();
assert_eq!(wave.peaks.len(), 500);
}
#[test]
fn results_are_cached_by_path_mtime_and_bucket_count() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("c.wav");
write_wav(&path, 8000, 1, 0, 1);
let w = Waveforms::new();
let first = wait(&w, &path, 10).unwrap();
// A cached request is answered on the caller's thread, with the same allocation.
let second = Arc::new(Mutex::new(None));
let slot = second.clone();
w.request(&path, 10, move |r| *slot.lock().unwrap() = Some(r));
let hit = second
.lock()
.unwrap()
.take()
.expect("answered at once")
.unwrap();
assert!(Arc::ptr_eq(&first, &hit));
// Another bucket count is a separate entry.
let other = wait(&w, &path, 11).unwrap();
assert_eq!(other.peaks.len(), 11);
assert!(!Arc::ptr_eq(&first, &other));
// A changed file is decoded again.
write_wav(&path, 8000, 1, 1, 1);
let f = fs::File::options().write(true).open(&path).unwrap();
f.set_modified(std::time::SystemTime::now() + Duration::from_secs(120))
.unwrap();
drop(f);
let changed = wait(&w, &path, 10).unwrap();
assert!(!Arc::ptr_eq(&first, &changed));
assert!((changed.duration.as_secs_f64() - 2.0).abs() < 0.01);
}
#[test]
fn errors_for_missing_garbage_and_unsupported_files() {
let dir = tempfile::tempdir().unwrap();
let w = Waveforms::new();
assert!(matches!(
wait(&w, &dir.path().join("none.wav"), 4),
Err(Error::Io(_))
));
let junk = dir.path().join("junk.mp3");
fs::write(&junk, vec![0x13u8; 4096]).unwrap();
assert!(wait(&w, &junk, 4).is_err());
let empty = dir.path().join("empty.flac");
fs::write(&empty, b"").unwrap();
assert!(wait(&w, &empty, 4).is_err());
}
#[test]
fn a_cancelled_request_ends_with_cancelled() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("long.wav");
// 600 s of mono audio at 8 kHz is about 9 MB: long enough to cancel mid-decode.
write_wav(&path, 8000, 1, 0, 600);
let (tx, rx) = mpsc::channel();
let ticket = Waveforms::new().request(&path, 10, move |r| tx.send(r).unwrap());
ticket.cancel();
let result = rx.recv_timeout(Duration::from_secs(30)).unwrap();
assert_eq!(result.unwrap_err(), Error::Cancelled);
}