Files
stimmwerk/src/audio/recorder.rs
wlkns-dev e7e69b7a51 Singtrainer: Phasen 0-6, Stimmfinder und Latenzkalibrierung
Rust-Desktop-App (egui/eframe, cpal) zum Singüben.

- Audio: Geräteauswahl, Pegelanzeige, Mixer ohne Locks im Callback
  (Backing, Original-Gesang, Führungston, Aufnahme, Klick), Dekodierung
  mit symphonia, Resampling mit rubato, Mikroaufnahme als WAV
- Pitch: YIN mit Konfidenz, Median-Glättung, Oktavsprung-Schutz
- Live-Ansicht: scrollende Tonhöhenkurve, Referenzton
- Chart: NoteChart (TOML), Scoring (Tonhöhe oktavtolerant, Timing,
  Stabilität), Session mit Countdown, Testchart
- Aufnahme und Review: Session-Datei (JSON) mit Mikrospur, Verlauf,
  Wiedergabe solo oder gemischt
- Stimmfinder: Sprechlage, Legato, Sirene, Haltetöne, Tessitura,
  Profil-Verlauf, Transponierung und Warnung für Charts
- Latenzkalibrierung: Klickzug, Einsatzerkennung, Offset in der Config
- Simulationsmodus (--sim) und Tests ohne Audiogerät

Manuelle Abnahmen am Gerät stehen noch aus (siehe README).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-31 00:40:13 +01:00

190 lines
6.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.

//! Aufnahme der trockenen Mikrospur als WAV (mono, f32) in einem eigenen Thread.
//!
//! Der Thread zählt alle Eingangs-Samples mit. Beim Start meldet er den Index des ersten
//! geschriebenen Samples; geteilt durch die Samplerate ist das exakt die Eingangszeit, die auch
//! der Pitch-Verlauf benutzt. So decken sich WAV-Datei und Pitch-Zeitachse.
use rtrb::Consumer;
use std::io::BufWriter;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::thread::JoinHandle;
use std::time::Duration;
type Writer = hound::WavWriter<BufWriter<std::fs::File>>;
enum Cmd {
Start(PathBuf, Sender<Result<u64, String>>),
Stop(Sender<Result<(), String>>),
}
pub struct Recorder {
tx: Sender<Cmd>,
rate: u32,
handle: Option<JoinHandle<()>>,
}
const REPLY_TIMEOUT: Duration = Duration::from_secs(2);
impl Recorder {
pub fn spawn(rx: Consumer<f32>, rate: u32, stop: Arc<AtomicBool>) -> Self {
let (tx, cmd_rx) = channel();
let handle = std::thread::spawn(move || run(rx, rate, cmd_rx, stop));
Self {
tx,
rate,
handle: Some(handle),
}
}
/// Beginnt eine Aufnahme; liefert die Eingangszeit (s) des ersten Samples.
pub fn start(&self, path: &Path) -> Result<f64, String> {
let (reply, answer) = channel();
self.tx
.send(Cmd::Start(path.to_path_buf(), reply))
.map_err(|_| "Aufnahme-Thread beendet".to_string())?;
let index = answer
.recv_timeout(REPLY_TIMEOUT)
.map_err(|_| "Aufnahme antwortet nicht".to_string())??;
Ok(index as f64 / self.rate as f64)
}
/// Beendet die Aufnahme und schließt die Datei (Header wird finalisiert).
pub fn stop(&self) -> Result<(), String> {
let (reply, answer) = channel();
self.tx
.send(Cmd::Stop(reply))
.map_err(|_| "Aufnahme-Thread beendet".to_string())?;
answer
.recv_timeout(REPLY_TIMEOUT)
.map_err(|_| "Aufnahme antwortet nicht".to_string())?
}
/// Wartet auf das Ende des Threads (nach gesetztem Stop-Flag).
pub fn join(&mut self) {
if let Some(h) = self.handle.take() {
let _ = h.join();
}
}
}
fn open(path: &Path, rate: u32) -> Result<Writer, String> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("Ordner anlegen: {e}"))?;
}
let spec = hound::WavSpec {
channels: 1,
sample_rate: rate,
bits_per_sample: 32,
sample_format: hound::SampleFormat::Float,
};
hound::WavWriter::create(path, spec).map_err(|e| format!("WAV anlegen: {e}"))
}
fn run(mut rx: Consumer<f32>, rate: u32, cmds: Receiver<Cmd>, stop: Arc<AtomicBool>) {
let mut consumed: u64 = 0;
let mut writer: Option<Writer> = None;
let mut write_error: Option<String> = None;
while !stop.load(Ordering::Relaxed) {
// Erst alles Aufgelaufene verarbeiten, dann Kommandos – so ist `consumed` aktuell.
let avail = rx.slots();
if avail > 0
&& let Ok(chunk) = rx.read_chunk(avail)
{
let (a, b) = chunk.as_slices();
if let Some(w) = writer.as_mut() {
for &s in a.iter().chain(b) {
if let Err(e) = w.write_sample(s) {
write_error.get_or_insert(format!("WAV schreiben: {e}"));
break;
}
}
}
consumed += (a.len() + b.len()) as u64;
chunk.commit_all();
}
while let Ok(cmd) = cmds.try_recv() {
match cmd {
Cmd::Start(path, reply) => {
// Eine laufende Aufnahme sauber beenden, bevor eine neue beginnt.
if let Some(w) = writer.take() {
let _ = w.finalize();
}
write_error = None;
let r = open(&path, rate).map(|w| {
writer = Some(w);
consumed
});
let _ = reply.send(r);
}
Cmd::Stop(reply) => {
let r = match writer.take() {
Some(w) => w.finalize().map_err(|e| format!("WAV abschließen: {e}")),
None => Ok(()),
};
let _ = reply.send(write_error.take().map_or(r, Err));
}
}
}
if avail == 0 {
std::thread::sleep(Duration::from_millis(3));
}
}
if let Some(w) = writer.take() {
let _ = w.finalize();
}
}
#[cfg(test)]
mod tests {
use super::*;
use rtrb::RingBuffer;
#[test]
fn records_from_reported_index_and_finalizes_wav() {
let (mut tx, rx) = RingBuffer::<f32>::new(48_000);
let stop = Arc::new(AtomicBool::new(false));
let mut rec = Recorder::spawn(rx, 1000, stop.clone());
let path = std::env::temp_dir()
.join(format!("singtrainer-rec-{}", std::process::id()))
.join("mic.wav");
// 500 Samples vor dem Start → Startindex muss 500 melden.
for i in 0..500 {
tx.push(i as f32).unwrap();
}
std::thread::sleep(Duration::from_millis(60));
let t0 = rec.start(&path).unwrap();
assert!((t0 - 0.5).abs() < 1e-9, "{t0}");
for i in 500..800 {
tx.push(i as f32).unwrap();
}
std::thread::sleep(Duration::from_millis(60));
rec.stop().unwrap();
stop.store(true, Ordering::Relaxed);
rec.join();
let mut r = hound::WavReader::open(&path).unwrap();
assert_eq!(r.spec().sample_rate, 1000);
assert_eq!(r.spec().channels, 1);
let samples: Vec<f32> = r.samples::<f32>().map(Result::unwrap).collect();
assert_eq!(samples.len(), 300);
assert_eq!(samples[0], 500.0);
assert_eq!(*samples.last().unwrap(), 799.0);
}
#[test]
fn stop_without_start_is_ok_and_bad_path_errors() {
let (_tx, rx) = RingBuffer::<f32>::new(16);
let stop = Arc::new(AtomicBool::new(false));
let mut rec = Recorder::spawn(rx, 48_000, stop.clone());
assert!(rec.stop().is_ok());
assert!(rec.start(Path::new("/proc/nope/mic.wav")).is_err());
stop.store(true, Ordering::Relaxed);
rec.join();
}
}