Tunal/crates/tunal-player/src/waveform.rs
astar76 49e0b67043 player: ffmpeg fallback for formats symphonia can't decode
Symphonia now has all its pure-Rust codecs and formats. What it can't
decode (Opus, WMA, AC-3, the sound of video files) goes through the
ffmpeg CLI: ffprobe for rate and length, raw f32 PCM piped into the same
output, seeking by restarting with -ss, the child killed on stop. Missing
ffmpeg keeps the unsupported error. A Handle lets another thread close
the playing file while it is rewritten and resume it in place (D-041).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-19 06:56:46 -06:00

133 lines
4.2 KiB
Rust

//! Min/max peaks of a whole track, decoded off-thread and cached by path + mtime.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};
use crate::Error;
use crate::source::Source;
/// Frames per fine block; blocks are merged into the requested bucket count at the end.
const BLOCK: usize = 256;
/// Rate a file only ffmpeg decodes is read at for peaks: plenty for a seek bar.
const PEAK_RATE: u32 = 8000;
/// Cached waveforms kept before the cache is emptied.
const CACHE_LIMIT: usize = 256;
#[derive(Clone, Debug)]
pub struct Waveform {
/// One `(min, max)` pair per bucket, samples in -1..=1 over all channels.
pub peaks: Vec<(f32, f32)>,
pub duration: Duration,
}
type Key = (PathBuf, SystemTime, usize);
#[derive(Clone, Default)]
pub struct Waveforms {
cache: Arc<Mutex<HashMap<Key, Arc<Waveform>>>>,
}
/// Cancels the request it came from; dropping it does not.
pub struct WaveTicket {
cancel: Arc<AtomicBool>,
}
impl WaveTicket {
pub fn cancel(&self) {
self.cancel.store(true, Ordering::Relaxed);
}
}
impl Waveforms {
pub fn new() -> Self {
Self::default()
}
/// Computes `buckets` peaks of `path` on a new thread. `done` runs on that thread, or at
/// once on the caller's thread for a cached result.
pub fn request(
&self,
path: impl Into<PathBuf>,
buckets: usize,
done: impl FnOnce(Result<Arc<Waveform>, Error>) + Send + 'static,
) -> WaveTicket {
let cancel = Arc::new(AtomicBool::new(false));
let ticket = WaveTicket {
cancel: cancel.clone(),
};
let path = path.into();
let mtime = match std::fs::metadata(&path).and_then(|m| m.modified()) {
Ok(t) => t,
Err(e) => {
done(Err(Error::Io(e.to_string())));
return ticket;
}
};
let key = (path, mtime, buckets);
if let Some(hit) = self.cache.lock().expect("waveform cache").get(&key) {
done(Ok(hit.clone()));
return ticket;
}
let cache = self.cache.clone();
std::thread::spawn(move || {
let result = compute(&key.0, buckets, &cancel).map(Arc::new);
if let Ok(waveform) = &result {
let mut cache = cache.lock().expect("waveform cache");
if cache.len() >= CACHE_LIMIT {
cache.clear();
}
cache.insert(key, waveform.clone());
}
done(result);
});
ticket
}
}
/// Decodes `path` into `buckets` min/max pairs; checks `cancel` between packets.
pub fn compute(path: &Path, buckets: usize, cancel: &AtomicBool) -> Result<Waveform, Error> {
let mut source = Source::open_with(path, Some(PEAK_RATE))?;
let channels = source.channels;
let rate = source.rate;
let mut blocks: Vec<(f32, f32)> = Vec::new();
let (mut lo, mut hi, mut in_block) = (0f32, 0f32, 0usize);
let mut frames = 0u64;
while let Some(samples) = source.next()? {
if cancel.load(Ordering::Relaxed) {
return Err(Error::Cancelled);
}
for frame in samples.chunks_exact(channels) {
for &s in frame {
lo = lo.min(s);
hi = hi.max(s);
}
in_block += 1;
if in_block == BLOCK {
blocks.push((lo, hi));
(lo, hi, in_block) = (0.0, 0.0, 0);
}
}
frames += (samples.len() / channels) as u64;
}
if in_block > 0 {
blocks.push((lo, hi));
}
let peaks = (0..buckets)
.map(|i| {
let start = i * blocks.len() / buckets;
let end = ((i + 1) * blocks.len() / buckets).max(start + 1);
blocks
.get(start..end.min(blocks.len()))
.unwrap_or(&[])
.iter()
.fold((0f32, 0f32), |(lo, hi), &(a, b)| (lo.min(a), hi.max(b)))
})
.collect();
Ok(Waveform {
peaks,
duration: Duration::from_secs_f64(frames as f64 / f64::from(rate)),
})
}