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>
393 lines
14 KiB
Rust
393 lines
14 KiB
Rust
//! Latenzkalibrierung: Klickzug über den Ausgang, Aufnahme über Mikro oder Loopback, Versatz messen.
|
||
//! Die Ablauflogik (`calib_*`) kommt ohne egui aus.
|
||
|
||
use super::App;
|
||
use crate::audio::{ChartAudio, store_f32};
|
||
use crate::calib::{self, CalibResult, Verdict};
|
||
use eframe::egui::{self, Color32};
|
||
use std::path::PathBuf;
|
||
use std::sync::atomic::Ordering;
|
||
|
||
/// Laufende Messung (nur mit Audio-Engine).
|
||
pub(super) struct CalibRun {
|
||
pub clicks_ms: Vec<f64>,
|
||
}
|
||
|
||
pub(super) struct CalibState {
|
||
pub run: Option<CalibRun>,
|
||
pub result: Option<CalibResult>,
|
||
pub message: Option<String>,
|
||
/// Zählt Messungen; variiert das Rauschen der Simulation.
|
||
pub count: u64,
|
||
}
|
||
|
||
impl CalibState {
|
||
pub fn new() -> Self {
|
||
Self {
|
||
run: None,
|
||
result: None,
|
||
message: None,
|
||
count: 0,
|
||
}
|
||
}
|
||
}
|
||
|
||
pub(super) fn default_wav_path() -> PathBuf {
|
||
crate::config::Config::data_dir()
|
||
.join("calibration")
|
||
.join("last.wav")
|
||
}
|
||
|
||
impl App {
|
||
/// Audio für den Kalibrier-Tab: nur der Klickzug.
|
||
pub(super) fn calib_audio(&self) -> ChartAudio {
|
||
ChartAudio {
|
||
calibration: Some((
|
||
calib::schedule(&self.config.calib),
|
||
self.config.calib.clone(),
|
||
)),
|
||
..Default::default()
|
||
}
|
||
}
|
||
|
||
pub(super) fn calib_start(&mut self) {
|
||
let cfg = self.config.calib.clone();
|
||
let clicks_ms = calib::schedule(&cfg);
|
||
self.calib.count += 1;
|
||
self.calib.result = None;
|
||
self.calib.message = None;
|
||
|
||
if self.sim_start.is_some() {
|
||
// Simulation: künstliche Aufnahme mit 87 ms Latenz, leichtem Jitter und Rauschen.
|
||
let rec = calib::synth_recording(
|
||
48_000.0,
|
||
&clicks_ms,
|
||
&cfg,
|
||
87.0,
|
||
2.0,
|
||
0.02,
|
||
self.calib.count,
|
||
);
|
||
self.calib.result = Some(calib::analyze(&rec, 48_000.0, &clicks_ms, &cfg));
|
||
self.calib.message = Some("Simulation: künstliche Aufnahme mit 87 ms Latenz".into());
|
||
return;
|
||
}
|
||
let Some(engine) = &self.engine else {
|
||
self.calib.message = Some("Kein Audio-Ausgang.".into());
|
||
return;
|
||
};
|
||
let Some(rate) = engine.output_rate else {
|
||
self.calib.message = Some("Kein Audio-Ausgang.".into());
|
||
return;
|
||
};
|
||
if let Err(e) = engine.start_recording(&self.calib_wav) {
|
||
self.calib.message = Some(format!("Keine Aufnahme möglich: {e}"));
|
||
return;
|
||
}
|
||
// Wie eine Session: Aufnahme zuerst, dann die Wiedergabe ab -Vorlauf.
|
||
let s = &engine.shared;
|
||
store_f32(&s.gain_click, 1.0);
|
||
s.seek.store(
|
||
-(cfg.lead_in_ms * 0.001 * rate as f64) as i64,
|
||
Ordering::Relaxed,
|
||
);
|
||
s.playing.store(true, Ordering::Relaxed);
|
||
self.calib.run = Some(CalibRun { clicks_ms });
|
||
}
|
||
|
||
/// Fortschritt in ms der Chart-Zeit (negativ im Vorlauf), solange gemessen wird.
|
||
pub(super) fn calib_progress_ms(&self) -> Option<f64> {
|
||
self.calib.run.as_ref()?;
|
||
let e = self.engine.as_ref()?;
|
||
Some(e.shared.pos_frames.load(Ordering::Relaxed) as f64 / e.output_rate? as f64 * 1000.0)
|
||
}
|
||
|
||
/// Jeden Frame: beendet die Messung nach dem letzten Klick.
|
||
pub(super) fn calib_poll(&mut self) {
|
||
let end = calib::run_end_ms(&self.config.calib);
|
||
if self.calib_progress_ms().is_some_and(|ms| ms >= end) {
|
||
self.calib_finish();
|
||
}
|
||
}
|
||
|
||
pub(super) fn calib_finish(&mut self) {
|
||
let Some(run) = self.calib.run.take() else {
|
||
return;
|
||
};
|
||
let Some(engine) = &self.engine else { return };
|
||
engine.shared.playing.store(false, Ordering::Relaxed);
|
||
if let Err(e) = engine.stop_recording() {
|
||
self.calib.message = Some(format!("Aufnahme fehlerhaft: {e}"));
|
||
return;
|
||
}
|
||
match calib::read_wav_mono(&self.calib_wav) {
|
||
Ok((samples, rate)) => {
|
||
self.calib.result = Some(calib::analyze(
|
||
&samples,
|
||
rate,
|
||
&run.clicks_ms,
|
||
&self.config.calib,
|
||
));
|
||
}
|
||
Err(e) => self.calib.message = Some(format!("Aufnahme lesen: {e:#}")),
|
||
}
|
||
}
|
||
|
||
/// Bricht eine laufende Messung ab und verwirft die Aufnahme.
|
||
pub(super) fn calib_cancel(&mut self) {
|
||
if self.calib.run.take().is_some()
|
||
&& let Some(e) = &self.engine
|
||
{
|
||
e.shared.playing.store(false, Ordering::Relaxed);
|
||
let _ = e.stop_recording();
|
||
self.calib.message = Some("Messung abgebrochen".into());
|
||
}
|
||
}
|
||
|
||
/// Übernimmt den gemessenen Versatz in die Config und speichert sie. Eine instabile Messung
|
||
/// wird nur mit `force` übernommen; Messungen ohne verwertbares Ergebnis nie.
|
||
pub(super) fn calib_apply(&mut self, force: bool) -> Result<f64, String> {
|
||
let r = self
|
||
.calib
|
||
.result
|
||
.as_ref()
|
||
.ok_or("Keine Messung vorhanden")?;
|
||
let offset = match (r.verdict, r.offset_ms) {
|
||
(Verdict::Good, Some(o)) => o,
|
||
(Verdict::Unstable, Some(o)) if force => o,
|
||
_ => return Err("Messung nicht verwertbar; Aufbau prüfen und wiederholen".into()),
|
||
};
|
||
let offset = (offset * 10.0).round() / 10.0;
|
||
self.config.audio.latency_offset_ms = offset;
|
||
self.config
|
||
.save_to(&self.config_path)
|
||
.map_err(|e| format!("Config speichern: {e:#}"))?;
|
||
Ok(offset)
|
||
}
|
||
|
||
pub(super) fn calib_ui(&mut self, ui: &mut egui::Ui) {
|
||
self.calib_poll();
|
||
let cfg = self.config.calib.clone();
|
||
ui.heading("Latenzkalibrierung");
|
||
ui.label(
|
||
"Misst, wie lange ein Klick vom Ausgang bis in die Aufnahme braucht. Dieser Versatz wird beim \
|
||
Scoring und im Review abgezogen.",
|
||
);
|
||
ui.label(
|
||
"Aufbau: Kopfhörer mit der Hörmuschel direkt an die Mikrofonkapsel halten (oder Ausgang per \
|
||
Kabel auf den Eingang legen, Loopback). Im Raum möglichst ruhig, Eigenstimme/Direct-Monitoring \
|
||
aus. Der Eingangspegel unten sollte bei jedem Klick deutlich ausschlagen.",
|
||
);
|
||
if let Some(e) = &self.engine {
|
||
// Während der Kalibrierung nur den Klick hören.
|
||
let s = &e.shared;
|
||
for g in [
|
||
&s.gain_backing,
|
||
&s.gain_vocals,
|
||
&s.gain_guide,
|
||
&s.gain_monitor,
|
||
&s.gain_rec,
|
||
] {
|
||
store_f32(g, 0.0);
|
||
}
|
||
store_f32(&s.gain_click, 1.0);
|
||
}
|
||
let running = self.calib.run.is_some();
|
||
ui.horizontal(|ui| {
|
||
if running {
|
||
if ui.button("■ Abbrechen").clicked() {
|
||
self.calib_cancel();
|
||
}
|
||
if let Some(ms) = self.calib_progress_ms() {
|
||
let first = cfg.first_click_ms;
|
||
let done = if ms < first {
|
||
0
|
||
} else {
|
||
(((ms - first) / cfg.spacing_ms).floor() as usize + 1).min(cfg.click_count)
|
||
};
|
||
ui.label(format!(
|
||
"{} … Klick {done}/{}",
|
||
if ms < 0.0 { "Vorlauf" } else { "läuft" },
|
||
cfg.click_count
|
||
));
|
||
}
|
||
} else if ui.button("▶ Messung starten").clicked() {
|
||
self.calib_start();
|
||
}
|
||
});
|
||
if let Some(m) = &self.calib.message {
|
||
ui.colored_label(Color32::from_rgb(230, 170, 60), m);
|
||
}
|
||
|
||
if let Some(r) = self.calib.result.clone() {
|
||
ui.separator();
|
||
let (text, color) = match r.verdict {
|
||
Verdict::Good => ("Messung gut".to_string(), Color32::from_rgb(90, 200, 120)),
|
||
Verdict::Unstable => (
|
||
format!(
|
||
"Messung unruhig: Streuung über {:.0} ms. Mikro näher an den Kopfhörer, leiser Raum, \
|
||
Pegel prüfen, dann wiederholen.",
|
||
cfg.max_spread_ms
|
||
),
|
||
Color32::from_rgb(230, 170, 60),
|
||
),
|
||
Verdict::TooFew => (
|
||
format!(
|
||
"Zu wenige Klicks erkannt (mindestens {} nötig). Lautstärke erhöhen, Aufbau prüfen.",
|
||
cfg.min_valid
|
||
),
|
||
Color32::from_rgb(230, 100, 80),
|
||
),
|
||
Verdict::Implausible => (
|
||
"Versatz unplausibel; Aufbau prüfen und wiederholen.".to_string(),
|
||
Color32::from_rgb(230, 100, 80),
|
||
),
|
||
};
|
||
ui.colored_label(color, text);
|
||
if let (Some(o), Some(sp)) = (r.offset_ms, r.spread_ms) {
|
||
ui.label(
|
||
egui::RichText::new(format!("Versatz {o:.1} ms (Streuung ± {sp:.1} ms)"))
|
||
.size(22.0)
|
||
.strong(),
|
||
);
|
||
}
|
||
ui.horizontal_wrapped(|ui| {
|
||
for (i, (o, kept)) in r.offsets_ms.iter().zip(&r.kept).enumerate() {
|
||
let t = o.map_or(format!("{}: –", i + 1), |v| format!("{}: {v:.1}", i + 1));
|
||
if *kept {
|
||
ui.label(t);
|
||
} else {
|
||
ui.weak(format!("{t} (verworfen)"));
|
||
}
|
||
}
|
||
});
|
||
ui.horizontal(|ui| {
|
||
let usable =
|
||
matches!(r.verdict, Verdict::Good | Verdict::Unstable) && r.offset_ms.is_some();
|
||
let label = if r.verdict == Verdict::Good {
|
||
"Übernehmen"
|
||
} else {
|
||
"Trotzdem übernehmen"
|
||
};
|
||
if ui.add_enabled(usable, egui::Button::new(label)).clicked() {
|
||
self.calib.message =
|
||
Some(match self.calib_apply(r.verdict == Verdict::Unstable) {
|
||
Ok(o) => format!("Versatz {o:.1} ms gespeichert"),
|
||
Err(e) => e,
|
||
});
|
||
}
|
||
});
|
||
}
|
||
|
||
ui.separator();
|
||
ui.horizontal(|ui| {
|
||
ui.label("Aktueller Versatz");
|
||
ui.add(
|
||
egui::DragValue::new(&mut self.config.audio.latency_offset_ms)
|
||
.range(0.0..=500.0)
|
||
.suffix(" ms")
|
||
.speed(0.5),
|
||
);
|
||
if ui.button("Speichern").clicked() {
|
||
self.calib.message = Some(match self.config.save_to(&self.config_path) {
|
||
Ok(()) => "Config gespeichert".into(),
|
||
Err(e) => format!("Config speichern: {e:#}"),
|
||
});
|
||
}
|
||
if ui.button("Auf 0 setzen").clicked() {
|
||
self.config.audio.latency_offset_ms = 0.0;
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use crate::config::Config;
|
||
|
||
fn test_app(name: &str) -> App {
|
||
let mut app = App::new(true, false, false);
|
||
let dir = std::env::temp_dir().join(format!(
|
||
"singtrainer-calibapp-{}-{name}",
|
||
std::process::id()
|
||
));
|
||
let _ = std::fs::remove_dir_all(&dir);
|
||
app.config_path = dir.join("config.toml");
|
||
app.calib_wav = dir.join("last.wav");
|
||
app.config.audio.latency_offset_ms = 0.0;
|
||
app
|
||
}
|
||
|
||
#[test]
|
||
fn simulated_measurement_is_applied_and_persisted() {
|
||
let mut app = test_app("apply");
|
||
app.calib_start();
|
||
let r = app.calib.result.clone().expect("Ergebnis");
|
||
assert_eq!(r.verdict, Verdict::Good, "{r:?}");
|
||
assert!((r.offset_ms.unwrap() - 87.0).abs() < 3.0, "{r:?}");
|
||
|
||
let applied = app.calib_apply(false).unwrap();
|
||
assert!((applied - 87.0).abs() < 3.0);
|
||
assert_eq!(app.config.audio.latency_offset_ms, applied);
|
||
let text = std::fs::read_to_string(&app.config_path).unwrap();
|
||
let saved: Config = toml::from_str(&text).unwrap();
|
||
assert_eq!(
|
||
saved.audio.latency_offset_ms, applied,
|
||
"in der Config gespeichert"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn repeated_simulated_measurements_agree_within_10ms() {
|
||
let mut app = test_app("repeat");
|
||
let offsets: Vec<f64> = (0..4)
|
||
.map(|_| {
|
||
app.calib_start();
|
||
app.calib.result.as_ref().unwrap().offset_ms.unwrap()
|
||
})
|
||
.collect();
|
||
let (lo, hi) = offsets
|
||
.iter()
|
||
.fold((f64::MAX, f64::MIN), |a, v| (a.0.min(*v), a.1.max(*v)));
|
||
assert!(hi - lo < 10.0, "{offsets:?}");
|
||
assert_ne!(offsets[0], offsets[1], "jede Messung hat anderes Rauschen");
|
||
}
|
||
|
||
#[test]
|
||
fn unusable_measurements_are_never_applied() {
|
||
let mut app = test_app("refuse");
|
||
let base = CalibResult {
|
||
offsets_ms: vec![],
|
||
kept: vec![],
|
||
offset_ms: Some(50.0),
|
||
spread_ms: Some(15.0),
|
||
verdict: Verdict::Unstable,
|
||
};
|
||
assert!(app.calib_apply(false).is_err(), "ohne Messung");
|
||
app.calib.result = Some(base.clone());
|
||
assert!(app.calib_apply(false).is_err(), "instabil ohne force");
|
||
assert_eq!(app.config.audio.latency_offset_ms, 0.0);
|
||
assert_eq!(app.calib_apply(true), Ok(50.0), "instabil mit force");
|
||
for verdict in [Verdict::TooFew, Verdict::Implausible] {
|
||
app.config.audio.latency_offset_ms = 0.0;
|
||
app.calib.result = Some(CalibResult {
|
||
verdict,
|
||
..base.clone()
|
||
});
|
||
assert!(app.calib_apply(true).is_err(), "{verdict:?} nie übernehmen");
|
||
assert_eq!(app.config.audio.latency_offset_ms, 0.0);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn calibration_audio_carries_the_click_schedule() {
|
||
let app = test_app("audio");
|
||
let a = app.calib_audio();
|
||
let (clicks, cfg) = a.calibration.unwrap();
|
||
assert_eq!(clicks, calib::schedule(&app.config.calib));
|
||
assert_eq!(cfg, app.config.calib);
|
||
assert!(a.backing.is_none() && a.notes.is_empty());
|
||
}
|
||
}
|