S022: audio player backend with symphonia, rubato and cpal, plus waveform peaks

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-18 13:53:04 -06:00
commit 3867facdea
11 changed files with 1461 additions and 6 deletions

435
Cargo.lock generated
View file

@ -160,6 +160,28 @@ version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "alsa"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d"
dependencies = [
"alsa-sys",
"bitflags 2.13.2",
"cfg-if",
"libc",
]
[[package]]
name = "alsa-sys"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad7569085a265dd3f607ebecce7458eaab2132a84393534c95b18dcbc3f31e04"
dependencies = [
"libc",
"pkg-config",
]
[[package]]
name = "android-activity"
version = "0.6.1"
@ -850,12 +872,62 @@ dependencies = [
"libc",
]
[[package]]
name = "core_detect"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]]
name = "coreaudio-rs"
version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58"
dependencies = [
"bitflags 2.13.2",
"libc",
"objc2-audio-toolbox",
"objc2-core-audio",
"objc2-core-audio-types",
"objc2-core-foundation",
]
[[package]]
name = "countme"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7704b5fdd17b18ae31c4c1da5a2e0305a2bf17b5249300a9ee9ed7b72114c636"
[[package]]
name = "cpal"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f02e8d0327b42d3e2e4ab2119af397344eb9fc54a34bf0ddeaa1277af8681f1"
dependencies = [
"alsa",
"block2 0.6.2",
"coreaudio-rs",
"dasp_sample",
"jni",
"js-sys",
"libc",
"mach2",
"ndk",
"ndk-context",
"num-derive",
"num-traits",
"objc2 0.6.5",
"objc2-audio-toolbox",
"objc2-avf-audio",
"objc2-core-audio",
"objc2-core-audio-types",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"web-sys",
"windows",
"windows-core",
]
[[package]]
name = "crc32fast"
version = "1.5.5"
@ -944,6 +1016,12 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
[[package]]
name = "dasp_sample"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
[[package]]
name = "data-encoding"
version = "2.11.1"
@ -1099,6 +1177,20 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
[[package]]
name = "encoding_rs"
version = "0.8.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5"
dependencies = [
"cfg-if",
"core_detect",
"multiversion_no_op",
"rustversion",
"scopeguard",
"simdutf8",
]
[[package]]
name = "endi"
version = "1.1.1"
@ -1177,6 +1269,12 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "extended"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365"
[[package]]
name = "fastrand"
version = "2.5.0"
@ -2801,6 +2899,12 @@ dependencies = [
"num-traits",
]
[[package]]
name = "mach2"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b"
[[package]]
name = "material-colors"
version = "0.5.0"
@ -2928,6 +3032,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "multiversion_no_op"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
[[package]]
name = "naga"
version = "30.0.2"
@ -3064,6 +3174,35 @@ dependencies = [
"bitflags 2.13.2",
]
[[package]]
name = "num-complex"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
dependencies = [
"num-traits",
]
[[package]]
name = "num-derive"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@ -3151,6 +3290,32 @@ dependencies = [
"objc2-quartz-core 0.3.2",
]
[[package]]
name = "objc2-audio-toolbox"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08"
dependencies = [
"bitflags 2.13.2",
"libc",
"objc2 0.6.5",
"objc2-core-audio",
"objc2-core-audio-types",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
]
[[package]]
name = "objc2-avf-audio"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be"
dependencies = [
"bitflags 2.13.2",
"objc2 0.6.5",
"objc2-foundation 0.3.2",
]
[[package]]
name = "objc2-cloud-kit"
version = "0.2.2"
@ -3175,6 +3340,29 @@ dependencies = [
"objc2-foundation 0.2.2",
]
[[package]]
name = "objc2-core-audio"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2"
dependencies = [
"dispatch2",
"objc2 0.6.5",
"objc2-core-audio-types",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
]
[[package]]
name = "objc2-core-audio-types"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c"
dependencies = [
"bitflags 2.13.2",
"objc2 0.6.5",
]
[[package]]
name = "objc2-core-data"
version = "0.2.2"
@ -3194,7 +3382,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
dependencies = [
"bitflags 2.13.2",
"block2 0.6.2",
"dispatch2",
"libc",
"objc2 0.6.5",
]
@ -3282,6 +3472,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags 2.13.2",
"block2 0.6.2",
"libc",
"objc2 0.6.5",
"objc2-core-foundation",
]
@ -3783,6 +3974,15 @@ dependencies = [
"syn 3.0.10",
]
[[package]]
name = "primal-check"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08"
dependencies = [
"num-integer",
]
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
@ -3929,6 +4129,15 @@ dependencies = [
"yoke",
]
[[package]]
name = "realfft"
version = "3.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "538895ccf2006b473aafbe8d72770e21038961ab67aae34f3c577485fc703a7d"
dependencies = [
"rustfft",
]
[[package]]
name = "redox_syscall"
version = "0.4.1"
@ -4091,6 +4300,24 @@ dependencies = [
"unicode-width",
]
[[package]]
name = "rtrb"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5974e397833d890f2f74963408e0d4a6cd8eda2f6a445ae06750291b5d7a997e"
[[package]]
name = "rubato"
version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5258099699851cfd0082aeb645feb9c084d9a5e1f1b8d5372086b989fc5e56a1"
dependencies = [
"num-complex",
"num-integer",
"num-traits",
"realfft",
]
[[package]]
name = "rustc-hash"
version = "1.1.0"
@ -4112,6 +4339,20 @@ dependencies = [
"semver",
]
[[package]]
name = "rustfft"
version = "6.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89"
dependencies = [
"num-complex",
"num-integer",
"num-traits",
"primal-check",
"strength_reduce",
"transpose",
]
[[package]]
name = "rustix"
version = "0.38.44"
@ -4622,6 +4863,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "strength_reduce"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"
[[package]]
name = "strict-num"
version = "0.1.1"
@ -4679,6 +4926,178 @@ dependencies = [
"zeno",
]
[[package]]
name = "symphonia"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039"
dependencies = [
"lazy_static",
"symphonia-bundle-flac",
"symphonia-bundle-mp3",
"symphonia-codec-aac",
"symphonia-codec-adpcm",
"symphonia-codec-pcm",
"symphonia-codec-vorbis",
"symphonia-core",
"symphonia-format-isomp4",
"symphonia-format-mkv",
"symphonia-format-ogg",
"symphonia-format-riff",
"symphonia-metadata",
]
[[package]]
name = "symphonia-bundle-flac"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c91565e180aea25d9b80a910c546802526ffd0072d0b8974e3ebe59b686c9976"
dependencies = [
"log",
"symphonia-core",
"symphonia-metadata",
"symphonia-utils-xiph",
]
[[package]]
name = "symphonia-bundle-mp3"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4872dd6bb56bf5eac799e3e957aa1981086c3e613b27e0ac23b176054f7c57ed"
dependencies = [
"lazy_static",
"log",
"symphonia-core",
"symphonia-metadata",
]
[[package]]
name = "symphonia-codec-aac"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c263845aa86881416849c1729a54c7f55164f8b96111dba59de46849e73a790"
dependencies = [
"lazy_static",
"log",
"symphonia-core",
]
[[package]]
name = "symphonia-codec-adpcm"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dddc50e2bbea4cfe027441eece77c46b9f319748605ab8f3443350129ddd07f"
dependencies = [
"log",
"symphonia-core",
]
[[package]]
name = "symphonia-codec-pcm"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e89d716c01541ad3ebe7c91ce4c8d38a7cf266a3f7b2f090b108fb0cb031d95"
dependencies = [
"log",
"symphonia-core",
]
[[package]]
name = "symphonia-codec-vorbis"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f025837c309cd69ffef572750b4a2257b59552c5399a5e49707cc5b1b85d1c73"
dependencies = [
"log",
"symphonia-core",
"symphonia-utils-xiph",
]
[[package]]
name = "symphonia-core"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af"
dependencies = [
"arrayvec",
"bitflags 1.3.2",
"bytemuck",
"lazy_static",
"log",
]
[[package]]
name = "symphonia-format-isomp4"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "243739585d11f81daf8dac8d9f3d18cc7898f6c09a259675fc364b382c30e0a5"
dependencies = [
"encoding_rs",
"log",
"symphonia-core",
"symphonia-metadata",
"symphonia-utils-xiph",
]
[[package]]
name = "symphonia-format-mkv"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "122d786d2c43a49beb6f397551b4a050d8229eaa54c7ddf9ee4b98899b8742d0"
dependencies = [
"lazy_static",
"log",
"symphonia-core",
"symphonia-metadata",
"symphonia-utils-xiph",
]
[[package]]
name = "symphonia-format-ogg"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b4955c67c1ed3aa8ae8428d04ca8397fbef6a19b2b051e73b5da8b1435639cb"
dependencies = [
"log",
"symphonia-core",
"symphonia-metadata",
"symphonia-utils-xiph",
]
[[package]]
name = "symphonia-format-riff"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2d7c3df0e7d94efb68401d81906eae73c02b40d5ec1a141962c592d0f11a96f"
dependencies = [
"extended",
"log",
"symphonia-core",
"symphonia-metadata",
]
[[package]]
name = "symphonia-metadata"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16"
dependencies = [
"encoding_rs",
"lazy_static",
"log",
"symphonia-core",
]
[[package]]
name = "symphonia-utils-xiph"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16"
dependencies = [
"symphonia-core",
"symphonia-metadata",
]
[[package]]
name = "syn"
version = "2.0.119"
@ -5001,6 +5420,16 @@ dependencies = [
"once_cell",
]
[[package]]
name = "transpose"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e"
dependencies = [
"num-integer",
"strength_reduce",
]
[[package]]
name = "ttf-parser"
version = "0.25.1"
@ -5047,6 +5476,12 @@ version = "0.1.0"
[[package]]
name = "tunal-player"
version = "0.1.0"
dependencies = [
"cpal",
"rtrb",
"rubato",
"symphonia",
]
[[package]]
name = "tunal-tags"

View file

@ -24,3 +24,7 @@ md-5 = "0.11"
ureq = { version = "3", default-features = false, features = ["rustls", "gzip"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
symphonia = { version = "0.5", features = ["mp3", "aac", "isomp4"] }
cpal = "0.18"
rubato = "0.16"
rtrb = "0.4"

View file

@ -10,11 +10,11 @@ Play audio files with symphonia + cpal (D-005): play, pause, seek, volume, posit
docs/DECISIONS.md D-005; symphonia and cpal docs in ~/.cargo/registry.
## Steps
- [ ] Decode thread (symphonia: mp3, flac, vorbis, aac/mp4, wav) → lock-free ring buffer → cpal output on the default device; resample with `rubato` when rates differ.
- [ ] Controls and events: play/pause/stop/seek/volume; position ~10×/s only while playing; ended; error.
- [ ] Waveform: decode off-thread into N min/max buckets, cancelable, cached by path + mtime.
- [ ] Example `--example play -- <file>` at volume 0 prints positions and bucket count.
- [ ] PROGRESS entry, INDEX line, commit `S022: …`
- [x] Decode thread (symphonia: mp3, flac, vorbis, aac/mp4, wav) → lock-free ring buffer → cpal output on the default device; resample with `rubato` when rates differ.
- [x] Controls and events: play/pause/stop/seek/volume; position ~10×/s only while playing; ended; error.
- [x] Waveform: decode off-thread into N min/max buckets, cancelable, cached by path + mtime.
- [x] Example `--example play -- <file>` at volume 0 prints positions and bucket count.
- [x] PROGRESS entry, INDEX line, commit `S022: …`
## End criteria
- `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass.

View file

@ -48,7 +48,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v
## 08 Audio player
- [ ] [S022 — Audio player backend](08%20Audio%20player/S022-player-backend.md) · Opus medium
- [x] [S022 — Audio player backend](08%20Audio%20player/S022-player-backend.md) · Opus medium
- [ ] [S023 — Quick player with waveform seek bar](08%20Audio%20player/S023-player-ui.md) · Opus medium
## 09 Devices

View file

@ -4,3 +4,9 @@ version.workspace = true
edition.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
symphonia.workspace = true
cpal.workspace = true
rubato.workspace = true
rtrb.workspace = true

View file

@ -0,0 +1,91 @@
//! Smoke run: `cargo run -p tunal-player --example play -- [--volume V] [--buckets N] <file>`
//!
//! Plays the file (volume 0 by default) with a pause and a seek on the way, prints every
//! event, and prints the waveform bucket count. Exits after the end or 15 s.
use std::sync::mpsc;
use std::time::{Duration, Instant};
use tunal_player::{Event, Player, Waveforms};
fn main() {
let mut volume = 0.0;
let mut buckets = 800;
let mut file = None;
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--volume" => volume = args.next().and_then(|v| v.parse().ok()).unwrap_or(0.0),
"--buckets" => buckets = args.next().and_then(|v| v.parse().ok()).unwrap_or(800),
_ => file = Some(arg),
}
}
let Some(file) = file else {
eprintln!("usage: play [--volume V] [--buckets N] <file>");
std::process::exit(2);
};
let started = Instant::now();
let waveforms = Waveforms::new();
let (wave_tx, wave_rx) = mpsc::channel();
let _ticket = waveforms.request(&file, buckets, move |r| {
let _ = wave_tx.send(r);
});
let (tx, rx) = mpsc::channel();
let player = Player::new(move |e| {
let _ = tx.send(e);
});
player.set_volume(volume);
player.open(&file);
player.play();
let mut paused = false;
let mut seeked = false;
let deadline = started + Duration::from_secs(15);
while Instant::now() < deadline {
let Ok(event) = rx.recv_timeout(Duration::from_millis(50)) else {
continue;
};
let t = started.elapsed().as_secs_f32();
match &event {
Event::Position(p) => println!("{t:6.2}s position {:.2}", p.as_secs_f32()),
e => println!("{t:6.2}s {e:?}"),
}
match event {
Event::Position(p) if !paused && p >= Duration::from_millis(1000) => {
paused = true;
player.pause();
std::thread::sleep(Duration::from_millis(300));
player.seek(Duration::from_millis(2500));
player.play();
}
Event::Position(_) if paused && !seeked => seeked = true,
Event::Ended | Event::Error(_) => break,
_ => {}
}
}
drop(player);
match wave_rx.recv_timeout(Duration::from_secs(30)) {
Ok(Ok(w)) => {
let loudest = w.peaks.iter().fold(0f32, |m, &(lo, hi)| m.max(-lo).max(hi));
println!(
"waveform: {} buckets, {:.2}s, peak {loudest:.3}",
w.peaks.len(),
w.duration.as_secs_f32()
);
}
Ok(Err(e)) => println!("waveform: {e}"),
Err(_) => println!("waveform: timed out"),
}
// A second request for the same file is served from the cache.
let t = Instant::now();
waveforms.request(&file, buckets, move |r| {
println!(
"waveform again: {} in {:?}",
r.map_or_else(|e| e.to_string(), |w| format!("{} buckets", w.peaks.len())),
t.elapsed()
);
});
}

View file

@ -1 +1,343 @@
//! Audio playback and waveform data.
//!
//! [`Player`] decodes with symphonia on its own thread and plays through cpal on the default
//! output device; [`Waveforms`] computes min/max peaks for a seek bar.
mod output;
mod source;
mod waveform;
use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
pub use waveform::{WaveTicket, Waveform, Waveforms};
use output::Output;
use source::Source;
/// How often `Event::Position` is sent while playing.
const POSITION_INTERVAL: Duration = Duration::from_millis(100);
/// How often the engine tops up the output ring while playing.
const FILL_INTERVAL: Duration = Duration::from_millis(20);
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
/// The container or codec can't be decoded (e.g. Opus).
Unsupported,
Io(String),
Decode(String),
/// No audio output device.
NoDevice,
Output(String),
/// A waveform request was cancelled.
Cancelled,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Unsupported => f.write_str("unsupported audio format"),
Error::Io(e) => write!(f, "read error: {e}"),
Error::Decode(e) => write!(f, "decode error: {e}"),
Error::NoDevice => f.write_str("no audio output device"),
Error::Output(e) => write!(f, "audio output error: {e}"),
Error::Cancelled => f.write_str("cancelled"),
}
}
}
impl std::error::Error for Error {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum State {
Stopped,
Playing,
Paused,
}
#[derive(Clone, Debug)]
pub enum Event {
/// A file was opened; playback starts with [`Player::play`].
Opened {
path: PathBuf,
duration: Option<Duration>,
},
State(State),
/// Sent about 10×/s while playing, and once after open, pause, stop and seek.
Position(Duration),
/// The track played to its end; the player is stopped at the start again.
Ended,
Error(Error),
}
pub(crate) enum Command {
Open(PathBuf),
Play,
Pause,
Stop,
Seek(Duration),
OutputError(String),
Quit,
}
/// One track at a time. Commands are queued to the engine thread; results arrive as
/// [`Event`]s on the callback given to [`Player::new`], called on that thread.
pub struct Player {
commands: Sender<Command>,
volume: Arc<AtomicU32>,
thread: Option<JoinHandle<()>>,
}
impl Player {
pub fn new(on_event: impl Fn(Event) + Send + 'static) -> Self {
let (commands, rx) = mpsc::channel();
let volume = Arc::new(AtomicU32::new(1.0f32.to_bits()));
let engine = Engine {
on_event: Box::new(on_event),
rx,
commands: commands.clone(),
volume: volume.clone(),
source: None,
output: None,
state: State::Stopped,
base: Duration::ZERO,
exhausted: false,
last_position: Instant::now(),
};
let thread = std::thread::Builder::new()
.name("tunal-player".into())
.spawn(move || engine.run())
.expect("spawn player thread");
Player {
commands,
volume,
thread: Some(thread),
}
}
/// Stops the current track and opens `path`.
pub fn open(&self, path: impl Into<PathBuf>) {
self.send(Command::Open(path.into()));
}
pub fn play(&self) {
self.send(Command::Play);
}
pub fn pause(&self) {
self.send(Command::Pause);
}
pub fn stop(&self) {
self.send(Command::Stop);
}
pub fn seek(&self, to: Duration) {
self.send(Command::Seek(to));
}
/// Linear gain, clamped to 0..=1; takes effect at once.
pub fn set_volume(&self, volume: f32) {
let v = volume.clamp(0.0, 1.0);
self.volume.store(v.to_bits(), Ordering::Relaxed);
}
pub fn volume(&self) -> f32 {
f32::from_bits(self.volume.load(Ordering::Relaxed))
}
fn send(&self, command: Command) {
let _ = self.commands.send(command);
}
}
impl Drop for Player {
fn drop(&mut self) {
self.send(Command::Quit);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
struct Engine {
on_event: Box<dyn Fn(Event) + Send>,
rx: Receiver<Command>,
commands: Sender<Command>,
volume: Arc<AtomicU32>,
source: Option<Source>,
/// Present while playing or paused mid-track; dropped on stop, seek and end.
output: Option<Output>,
state: State,
/// Track position where `output` started.
base: Duration,
/// The source has no more frames for the current output.
exhausted: bool,
last_position: Instant,
}
impl Engine {
fn run(mut self) {
loop {
let command = if self.state == State::Playing {
match self.rx.recv_timeout(FILL_INTERVAL) {
Ok(c) => Some(c),
Err(RecvTimeoutError::Timeout) => None,
Err(RecvTimeoutError::Disconnected) => return,
}
} else {
// Idle: block until told otherwise.
match self.rx.recv() {
Ok(c) => Some(c),
Err(_) => return,
}
};
match command {
Some(Command::Quit) => return,
Some(c) => {
if let Err(e) = self.handle(c) {
self.fail(e);
}
}
None => {}
}
if self.state == State::Playing
&& let Err(e) = self.tick()
{
self.fail(e);
}
}
}
fn handle(&mut self, command: Command) -> Result<(), Error> {
match command {
Command::Open(path) => {
self.output = None;
self.source = None;
self.set_state(State::Stopped);
let source = Source::open(&path)?;
let duration = source.duration;
self.source = Some(source);
self.base = Duration::ZERO;
self.exhausted = false;
self.emit(Event::Opened { path, duration });
self.emit(Event::Position(Duration::ZERO));
}
Command::Play => {
let Some(source) = &mut self.source else {
return Ok(());
};
if self.state == State::Playing {
return Ok(());
}
if self.output.is_none() {
let mut output =
Output::new(source.rate, self.volume.clone(), self.commands.clone())?;
self.exhausted = !output.fill(source)?;
self.output = Some(output);
}
self.output.as_ref().expect("output just built").play()?;
self.set_state(State::Playing);
self.last_position = Instant::now();
}
Command::Pause => {
if self.state == State::Playing {
if let Some(output) = &self.output {
output.pause()?;
}
self.set_state(State::Paused);
self.emit(Event::Position(self.position()));
}
}
Command::Stop => {
if self.source.is_some() {
self.rewind()?;
self.set_state(State::Stopped);
self.emit(Event::Position(Duration::ZERO));
}
}
Command::Seek(to) => {
let Some(source) = &mut self.source else {
return Ok(());
};
let to = source.duration.map_or(to, |d| to.min(d));
self.output = None;
source.seek(to)?;
self.base = to;
self.exhausted = false;
self.emit(Event::Position(to));
if self.state == State::Playing {
self.state = State::Paused;
self.handle(Command::Play)?;
}
}
Command::OutputError(e) => return Err(Error::Output(e)),
Command::Quit => {}
}
Ok(())
}
/// While playing: top up the ring, report the position, detect the end.
fn tick(&mut self) -> Result<(), Error> {
let (Some(output), Some(source)) = (&mut self.output, &mut self.source) else {
return Ok(());
};
if !self.exhausted {
self.exhausted = !output.fill(source)?;
} else if output.flush() && output.drained() {
self.rewind()?;
self.set_state(State::Stopped);
self.emit(Event::Ended);
self.emit(Event::Position(Duration::ZERO));
return Ok(());
}
if self.last_position.elapsed() >= POSITION_INTERVAL {
self.last_position = Instant::now();
self.emit(Event::Position(self.position()));
}
Ok(())
}
fn position(&self) -> Duration {
let played = self.output.as_ref().map_or(Duration::ZERO, |o| {
Duration::from_secs_f64(o.played_frames() as f64 / f64::from(o.rate))
});
self.base + played
}
/// Drops the output and puts the source back at the start.
fn rewind(&mut self) -> Result<(), Error> {
self.output = None;
self.base = Duration::ZERO;
self.exhausted = false;
match &mut self.source {
Some(source) => source.seek(Duration::ZERO),
None => Ok(()),
}
}
/// Reports `error` and stops; the file stays open when it can be.
fn fail(&mut self, error: Error) {
self.emit(Event::Error(error));
if self.rewind().is_err() {
self.source = None;
}
self.set_state(State::Stopped);
}
fn set_state(&mut self, state: State) {
if self.state != state {
self.state = state;
self.emit(Event::State(state));
}
}
fn emit(&self, event: Event) {
(self.on_event)(event);
}
}

View file

@ -0,0 +1,242 @@
//! Output on the default device: source frames → channel map → resampler → ring → cpal callback.
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::mpsc::Sender;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{ErrorKind, FromSample, SampleFormat, SizedSample, Stream, StreamConfig};
use rtrb::{Consumer, Producer, RingBuffer};
use rubato::{FftFixedIn, Resampler};
use crate::source::Source;
use crate::{Command, Error};
/// Frames per resampler input chunk.
const CHUNK: usize = 1024;
pub(crate) struct Output {
stream: Stream,
producer: Producer<f32>,
pub rate: u32,
channels: usize,
/// Frames the callback has played since this output was built.
played: Arc<AtomicU64>,
resampler: Option<Resample>,
/// Converted interleaved samples not yet in the ring, from `pending_at` on.
pending: Vec<f32>,
pending_at: usize,
}
struct Resample {
inner: FftFixedIn<f32>,
input: Vec<Vec<f32>>,
/// Output frames still to drop for the resampler's delay.
delay: usize,
}
impl Output {
pub fn new(
source_rate: u32,
volume: Arc<AtomicU32>,
commands: Sender<Command>,
) -> Result<Self, Error> {
let device = cpal::default_host()
.default_output_device()
.ok_or(Error::NoDevice)?;
let supported = device.default_output_config().map_err(output_error)?;
let config = supported.config();
let channels = usize::from(config.channels);
// Half a second of audio.
let (producer, consumer) = RingBuffer::new(config.sample_rate as usize * channels / 2);
let played = Arc::new(AtomicU64::new(0));
let shared = Callback {
consumer,
channels,
volume,
played: played.clone(),
};
let stream = match supported.sample_format() {
SampleFormat::F32 => build::<f32>(&device, &config, shared, commands),
SampleFormat::F64 => build::<f64>(&device, &config, shared, commands),
SampleFormat::I16 => build::<i16>(&device, &config, shared, commands),
SampleFormat::I32 => build::<i32>(&device, &config, shared, commands),
SampleFormat::U16 => build::<u16>(&device, &config, shared, commands),
SampleFormat::U8 => build::<u8>(&device, &config, shared, commands),
f => Err(Error::Output(format!("sample format {f} not supported"))),
}?;
let resampler = if source_rate == config.sample_rate {
None
} else {
let inner = FftFixedIn::new(
source_rate as usize,
config.sample_rate as usize,
CHUNK,
2,
channels,
)
.map_err(|e| Error::Output(e.to_string()))?;
Some(Resample {
delay: inner.output_delay(),
inner,
input: vec![Vec::with_capacity(CHUNK * 2); channels],
})
};
Ok(Output {
stream,
producer,
rate: config.sample_rate,
channels,
played,
resampler,
pending: Vec::new(),
pending_at: 0,
})
}
pub fn play(&self) -> Result<(), Error> {
self.stream.play().map_err(output_error)
}
pub fn pause(&self) -> Result<(), Error> {
self.stream.pause().map_err(output_error)
}
pub fn played_frames(&self) -> u64 {
self.played.load(Ordering::Relaxed)
}
/// True once every sample handed to the ring has been played.
pub fn drained(&self) -> bool {
self.pending_at >= self.pending.len()
&& self.producer.slots() == self.producer.buffer().capacity()
}
/// Tops up the ring from `source`. Returns false once the source is exhausted.
pub fn fill(&mut self, source: &mut Source) -> Result<bool, Error> {
while self.flush() {
let in_ch = source.channels;
let frames = source.next()?;
let more = frames.is_some();
self.convert(frames.unwrap_or(&[]), in_ch, !more)?;
if !more {
self.flush();
return Ok(false);
}
}
Ok(true)
}
/// Moves `pending` into the ring; true when all of it fit.
pub fn flush(&mut self) -> bool {
let (_, rest) = self
.producer
.push_partial_slice(&self.pending[self.pending_at..]);
if !rest.is_empty() {
self.pending_at = self.pending.len() - rest.len();
return false;
}
self.pending.clear();
self.pending_at = 0;
true
}
/// Maps `input` (interleaved, `in_ch` channels) to our channels and rate into `pending`.
fn convert(&mut self, input: &[f32], in_ch: usize, last: bool) -> Result<(), Error> {
let out_ch = self.channels;
let frames = input.chunks_exact(in_ch);
let Some(resample) = &mut self.resampler else {
for frame in frames {
map_frame(frame, out_ch, |_, s| self.pending.push(s));
}
return Ok(());
};
for frame in frames {
map_frame(frame, out_ch, |c, s| resample.input[c].push(s));
}
loop {
let need = resample.inner.input_frames_next();
let have = resample.input[0].len();
let out = if have >= need {
let chunk: Vec<&[f32]> = resample.input.iter().map(|c| &c[..need]).collect();
resample.inner.process(&chunk, None)
} else if last && have > 0 {
resample.inner.process_partial(Some(&resample.input), None)
} else {
return Ok(());
}
.map_err(|e| Error::Output(e.to_string()))?;
for channel in &mut resample.input {
channel.drain(..need.min(have));
}
let len = out[0].len();
let skip = resample.delay.min(len);
resample.delay -= skip;
for i in skip..len {
self.pending.extend(out.iter().map(|c| c[i]));
}
}
}
}
/// Mono feeds every output channel, mono output averages; otherwise channels map by index.
fn map_frame(frame: &[f32], out_ch: usize, mut put: impl FnMut(usize, f32)) {
if out_ch == 1 {
put(0, frame.iter().sum::<f32>() / frame.len() as f32);
return;
}
for c in 0..out_ch {
let s = match frame.len() {
1 => frame[0],
n if c < n => frame[c],
_ => 0.0,
};
put(c, s);
}
}
struct Callback {
consumer: Consumer<f32>,
channels: usize,
volume: Arc<AtomicU32>,
played: Arc<AtomicU64>,
}
fn build<T: SizedSample + FromSample<f32>>(
device: &cpal::Device,
config: &StreamConfig,
mut cb: Callback,
commands: Sender<Command>,
) -> Result<Stream, Error> {
device
.build_output_stream(
*config,
move |data: &mut [T], _| {
let volume = f32::from_bits(cb.volume.load(Ordering::Relaxed));
let available = cb.consumer.slots().min(data.len());
let n = available - available % cb.channels;
if let Ok(chunk) = cb.consumer.read_chunk(n) {
let (a, b) = chunk.as_slices();
for (out, s) in data.iter_mut().zip(a.iter().chain(b)) {
*out = T::from_sample(s * volume);
}
chunk.commit_all();
}
data[n..].fill(T::EQUILIBRIUM);
cb.played
.fetch_add((n / cb.channels) as u64, Ordering::Relaxed);
},
move |e| {
let _ = commands.send(Command::OutputError(e.to_string()));
},
None,
)
.map_err(output_error)
}
fn output_error(e: cpal::Error) -> Error {
match e.kind() {
ErrorKind::DeviceNotAvailable | ErrorKind::HostUnavailable => Error::NoDevice,
_ => Error::Output(e.to_string()),
}
}

View file

@ -0,0 +1,196 @@
//! A decoded audio file: interleaved `f32` frames from symphonia, with accurate seeking.
use std::fs::File;
use std::io::ErrorKind;
use std::path::Path;
use std::time::Duration;
use symphonia::core::audio::SampleBuffer;
use symphonia::core::codecs::{CODEC_TYPE_NULL, Decoder, DecoderOptions};
use symphonia::core::errors::{Error as SymError, SeekErrorKind};
use symphonia::core::formats::{FormatOptions, FormatReader, SeekMode, SeekTo};
use symphonia::core::io::MediaSourceStream;
use symphonia::core::meta::MetadataOptions;
use symphonia::core::probe::Hint;
use symphonia::core::units::{Time, TimeBase};
use crate::Error;
pub(crate) struct Source {
format: Box<dyn FormatReader>,
decoder: Box<dyn Decoder>,
track_id: u32,
time_base: Option<TimeBase>,
pub rate: u32,
pub channels: usize,
pub duration: Option<Duration>,
buf: Option<SampleBuffer<f32>>,
/// Samples at the start of `buf` that precede a seek target.
offset: usize,
/// The first packet, decoded by `open` to learn the signal spec, is still unread.
primed: bool,
/// After a seek: drop samples before this timestamp.
seek_ts: Option<u64>,
ended: bool,
}
impl Source {
pub fn open(path: &Path) -> Result<Self, Error> {
let file = File::open(path).map_err(|e| Error::Io(e.to_string()))?;
let stream = MediaSourceStream::new(Box::new(file), Default::default());
let mut hint = Hint::new();
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
hint.with_extension(ext);
}
let options = FormatOptions {
enable_gapless: true,
..Default::default()
};
let probed = symphonia::default::get_probe()
.format(&hint, stream, &options, &MetadataOptions::default())
.map_err(Error::from)?;
let format = probed.format;
let track = format
.tracks()
.iter()
.find(|t| t.codec_params.codec != CODEC_TYPE_NULL)
.ok_or(Error::Unsupported)?;
let params = track.codec_params.clone();
let track_id = track.id;
let decoder = symphonia::default::get_codecs()
.make(&params, &DecoderOptions::default())
.map_err(Error::from)?;
let mut source = Source {
format,
decoder,
track_id,
time_base: params.time_base,
rate: 0,
channels: 0,
duration: None,
buf: None,
offset: 0,
primed: false,
seek_ts: None,
ended: false,
};
if !source.decode_next()? {
return Err(Error::Decode("no audio".into()));
}
source.primed = true;
source.duration = match (params.n_frames, params.time_base) {
(Some(n), Some(tb)) => Some(time_to_duration(tb.calc_time(n))),
(Some(n), None) => Some(Duration::from_secs_f64(n as f64 / f64::from(source.rate))),
_ => None,
};
Ok(source)
}
/// Next interleaved frames (`channels` samples each), `None` at the end of the stream.
pub fn next(&mut self) -> Result<Option<&[f32]>, Error> {
if self.primed {
self.primed = false;
} else if !self.decode_next()? {
return Ok(None);
}
Ok(self.buf.as_ref().map(|b| &b.samples()[self.offset..]))
}
pub fn seek(&mut self, to: Duration) -> Result<(), Error> {
self.primed = false;
self.ended = false;
self.seek_ts = None;
let time = Time::from(to.as_secs_f64());
let target = SeekTo::Time {
time,
track_id: Some(self.track_id),
};
match self.format.seek(SeekMode::Accurate, target) {
Ok(seeked) => {
self.decoder.reset();
self.seek_ts = Some(seeked.required_ts);
Ok(())
}
Err(SymError::SeekError(SeekErrorKind::OutOfRange)) => {
self.ended = true;
Ok(())
}
Err(e) => Err(e.into()),
}
}
/// Decodes the next packet of our track into `buf`; false at the end of the stream.
fn decode_next(&mut self) -> Result<bool, Error> {
while !self.ended {
let packet = match self.format.next_packet() {
Ok(p) => p,
Err(SymError::IoError(e)) if e.kind() == ErrorKind::UnexpectedEof => break,
Err(SymError::ResetRequired) => break,
Err(e) => return Err(e.into()),
};
if packet.track_id() != self.track_id {
continue;
}
if let Some(req) = self.seek_ts
&& packet.ts() + packet.dur() <= req
{
continue;
}
let decoded = match self.decoder.decode(&packet) {
Ok(d) => d,
// A damaged packet: skip it, like other players do.
Err(SymError::DecodeError(_)) => continue,
Err(e) => return Err(e.into()),
};
let spec = *decoded.spec();
let channels = spec.channels.count();
if self.rate == 0 {
self.rate = spec.rate;
self.channels = channels;
} else if channels != self.channels {
continue;
}
let fits = self
.buf
.as_ref()
.is_some_and(|b| b.capacity() >= decoded.capacity());
if !fits {
self.buf = Some(SampleBuffer::new(decoded.capacity() as u64, spec));
}
let buf = self.buf.as_mut().expect("buffer just set");
self.offset = 0;
buf.copy_interleaved_ref(decoded);
if let Some(req) = self.seek_ts.take() {
let ticks = req.saturating_sub(packet.ts());
let frames = match self.time_base {
Some(tb) => (ticks as f64 * f64::from(tb.numer) / f64::from(tb.denom)
* f64::from(self.rate))
.round() as usize,
None => ticks as usize,
};
let drop = (frames * self.channels).min(buf.len());
if drop == buf.len() {
continue;
}
self.offset = drop;
}
return Ok(true);
}
self.ended = true;
Ok(false)
}
}
fn time_to_duration(t: Time) -> Duration {
Duration::from_secs(t.seconds) + Duration::from_secs_f64(t.frac)
}
impl From<SymError> for Error {
fn from(e: SymError) -> Self {
match e {
SymError::Unsupported(_) => Error::Unsupported,
SymError::IoError(e) => Error::Io(e.to_string()),
e => Error::Decode(e.to_string()),
}
}
}

View file

@ -0,0 +1,131 @@
//! 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;
/// 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(path)?;
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)),
})
}

View file

@ -77,5 +77,13 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done,
- Found: the local watch (S006) also reports reads (opening a file, listing the folder). The model ignores events whose stat is unchanged, and the folder's own event unless it is gone; the shared playlist watch compares mtime/size. Without that, listing and watch looped.
- Later: filter access events in `LocalLocation::watch` itself (debouncer-mini hides the event kind); back/up navigation and per-folder sort in `.directory` (S010, S015).
## S022 — Audio player backend
- Done: `tunal-player`. `Player::new(on_event: Fn(Event) + Send)` (engine thread; events called there): `open(path)`, `play()`, `pause()`, `stop()`, `seek(Duration)`, `set_volume(0..=1)` (atomic, immediate), `volume()`; drop joins the thread. `Event::{Opened { path, duration }, State(State::{Stopped, Playing, Paused}), Position(Duration) (~10×/s while playing, once after open/pause/stop/seek), Ended (then Stopped at 0), Error(Error)}`. `Error::{Unsupported, Io, Decode, NoDevice, Output, Cancelled}` (Clone, Display).
- Pipeline: symphonia 0.5 (mp3, flac, vorbis/ogg, aac/mp4, wav; accurate seek, gapless) → channel map (mono fans out, mono out averages) → rubato 0.16 `FftFixedIn` when rates differ (delay trimmed) → rtrb 0.4 ring (0.5 s) → cpal 0.18 default device (f32/f64/i16/i32/u16/u8). Pause = `stream.pause()`, engine blocks on its channel when not playing; stop/seek/end drop the stream. Device missing → `Error::NoDevice`.
- `Waveforms::request(path, buckets, done) -> WaveTicket` (`cancel()`): own thread, `(min, max)` per bucket over all channels + duration; memory cache by (path, mtime, buckets), hit calls `done` at once on the caller thread. Example `play [--volume V] [--buckets N] <file>`.
- Verified: workspace build, clippy -D warnings, fmt --check; example on ffmpeg fixtures in the scratchpad (wav, mp3, flac, ogg, m4a, mono 22.05 kHz): positions advance, pause, seek to 2.5 s, Ended, 800 buckets, cache hit ~30 µs; opus → `Unsupported`; missing file → `Io`; `ALSA_CONFIG_PATH=<empty>` → `NoDevice`, waveform still fine.
- Not done: audible check not done (volume 0); cancel path of waveforms exercised only by code; mid-stream spec changes skip the packet; device loss mid-play reports `Output` error and stops (no reconnect).
- Later: waveform worker pool instead of a thread per request; resume on default-device change.
## Later
-