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>
This commit is contained in:
2026-10-31 00:40:13 +01:00
commit e7e69b7a51
33 changed files with 13845 additions and 0 deletions

425
src/voice/analysis.rs Normal file
View File

@ -0,0 +1,425 @@
//! Auswertung der Stimmfinder-Schritte. Reine Funktionen auf Frame-Listen, ohne Audiogerät testbar.
use crate::config::VoiceConfig;
use crate::pitch::HistoryPoint;
use serde::{Deserialize, Serialize};
/// Ein Messframe: Tonhöhe nur bei stimmhaftem Frame mit ausreichender Konfidenz.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Frame {
pub t: f64,
pub midi: Option<f32>,
pub conf: f32,
}
/// Wandelt den Pitch-Verlauf in Messframes. Überbrückte Aussetzer (`held`) und Frames unter der
/// Mindestkonfidenz zählen als stimmlos, damit Lücken (Legato) sichtbar bleiben.
pub fn frames_from_history<'a>(
points: impl Iterator<Item = &'a HistoryPoint>,
cfg: &VoiceConfig,
) -> Vec<Frame> {
points
.map(|p| match p.est {
Some(e) if !e.held && e.confidence >= cfg.min_confidence => Frame {
t: p.t,
midi: Some(e.midi),
conf: e.confidence,
},
_ => Frame {
t: p.t,
midi: None,
conf: 0.0,
},
})
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct SpeechResult {
pub median_midi: f32,
pub lo_midi: f32,
pub hi_midi: f32,
pub voiced_s: f32,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct LegatoResult {
/// Anteil stimmhafter Frames zwischen erstem und letztem stimmhaften Frame.
pub ratio: f32,
/// Längster Lauf ohne nennenswerte Lücke in Sekunden.
pub longest_run_s: f32,
/// Mediane Streuung (Cent) der Läufe um ihren linearen Trend; `None` ohne ausreichend lange Läufe.
pub stability_cents: Option<f32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TransitionKind {
/// Plötzlicher Tonsprung.
Jump,
/// Unruhige Stelle (Schwanken, Brechen).
Instability,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Transition {
pub midi: f32,
pub kind: TransitionKind,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SirenResult {
pub min_midi: f32,
pub max_midi: f32,
/// Nach Tonhöhe sortiert.
pub transitions: Vec<Transition>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct HoldNote {
pub midi: i32,
pub mean_midi: f32,
pub std_cents: f32,
pub mean_conf: f32,
pub duration_s: f32,
pub voiced_ratio: f32,
pub safe: bool,
}
/// Mittlerer Abstand der Frames in Sekunden (Median), Standard 10 ms.
fn hop(frames: &[Frame]) -> f64 {
let mut d: Vec<f64> = frames
.windows(2)
.map(|w| w[1].t - w[0].t)
.filter(|d| *d > 0.0)
.collect();
if d.is_empty() {
return 0.01;
}
d.sort_by(f64::total_cmp);
d[d.len() / 2]
}
/// Perzentil mit linearer Interpolation; `sorted` muss aufsteigend sortiert und nicht leer sein.
pub fn percentile(sorted: &[f32], p: f32) -> f32 {
let rank = (p / 100.0).clamp(0.0, 1.0) * (sorted.len() - 1) as f32;
let (lo, hi) = (rank.floor() as usize, rank.ceil() as usize);
sorted[lo] + (sorted[hi] - sorted[lo]) * (rank - lo as f32)
}
fn voiced(frames: &[Frame]) -> Vec<(f64, f32, f32)> {
frames
.iter()
.filter_map(|f| f.midi.map(|m| (f.t, m, f.conf)))
.collect()
}
pub fn analyze_speech(frames: &[Frame], cfg: &VoiceConfig) -> Option<SpeechResult> {
let mut v: Vec<f32> = voiced(frames).iter().map(|&(_, m, _)| m).collect();
let voiced_s = v.len() as f32 * hop(frames) as f32;
if v.is_empty() || voiced_s < cfg.speech_min_voiced_s {
return None;
}
v.sort_by(f32::total_cmp);
Some(SpeechResult {
median_midi: percentile(&v, 50.0),
lo_midi: percentile(&v, cfg.speech_percentile_lo),
hi_midi: percentile(&v, cfg.speech_percentile_hi),
voiced_s,
})
}
/// Zerlegt stimmhafte Frames in Läufe; Lücken bis `max_gap_s` halten einen Lauf zusammen.
fn runs(voiced: &[(f64, f32, f32)], max_gap_s: f64, hop: f64) -> Vec<&[(f64, f32, f32)]> {
let mut out = Vec::new();
let mut start = 0;
for i in 1..voiced.len() {
if voiced[i].0 - voiced[i - 1].0 > max_gap_s + hop {
out.push(&voiced[start..i]);
start = i;
}
}
if !voiced.is_empty() {
out.push(&voiced[start..]);
}
out
}
/// Streuung (Cent) um die Regressionsgerade über die Zeit – gewollte Gleitbewegungen zählen nicht.
fn detrended_std_cents(run: &[(f64, f32, f32)]) -> f32 {
let n = run.len() as f64;
let (mt, mm) = (
run.iter().map(|p| p.0).sum::<f64>() / n,
run.iter().map(|p| p.1 as f64 * 100.0).sum::<f64>() / n,
);
let sxx: f64 = run.iter().map(|p| (p.0 - mt).powi(2)).sum();
let sxy: f64 = run
.iter()
.map(|p| (p.0 - mt) * (p.1 as f64 * 100.0 - mm))
.sum();
let slope = if sxx > 0.0 { sxy / sxx } else { 0.0 };
let var = run
.iter()
.map(|p| (p.1 as f64 * 100.0 - (mm + slope * (p.0 - mt))).powi(2))
.sum::<f64>()
/ n;
var.sqrt() as f32
}
pub fn analyze_legato(frames: &[Frame], cfg: &VoiceConfig) -> Option<LegatoResult> {
let h = hop(frames);
let v = voiced(frames);
if v.is_empty() || (v.len() as f64 * h) < cfg.legato_min_voiced_s as f64 {
return None;
}
let first = frames.iter().position(|f| f.midi.is_some())?;
let last = frames.iter().rposition(|f| f.midi.is_some())?;
let span = (last - first + 1) as f32;
let rs = runs(&v, cfg.legato_max_gap_ms / 1000.0, h);
let longest = rs
.iter()
.map(|r| r[r.len() - 1].0 - r[0].0 + h)
.fold(0.0, f64::max) as f32;
let mut stds: Vec<f32> = rs
.iter()
.filter(|r| (r[r.len() - 1].0 - r[0].0 + h) as f32 >= cfg.legato_min_run_s)
.map(|r| detrended_std_cents(r))
.collect();
stds.sort_by(f32::total_cmp);
Some(LegatoResult {
ratio: v.len() as f32 / span,
longest_run_s: longest,
stability_cents: (!stds.is_empty()).then(|| percentile(&stds, 50.0)),
})
}
pub fn analyze_siren(frames: &[Frame], cfg: &VoiceConfig) -> Option<SirenResult> {
let h = hop(frames);
let v = voiced(frames);
if v.is_empty() || (v.len() as f64 * h) < cfg.siren_min_voiced_s as f64 {
return None;
}
let mut sorted: Vec<f32> = v.iter().map(|p| p.1).collect();
sorted.sort_by(f32::total_cmp);
let (min_midi, max_midi) = (
percentile(&sorted, cfg.siren_trim_percent),
percentile(&sorted, 100.0 - cfg.siren_trim_percent),
);
let mut marks: Vec<Transition> = Vec::new();
// Sprünge zwischen unmittelbar aufeinanderfolgenden Frames.
for w in v.windows(2) {
if w[1].0 - w[0].0 <= cfg.siren_jump_max_gap_s
&& (w[1].1 - w[0].1).abs() >= cfg.siren_jump_semitones
{
marks.push(Transition {
midi: (w[0].1 + w[1].1) / 2.0,
kind: TransitionKind::Jump,
});
}
}
// Instabilität: viele Frames weichen vom Medianverlauf (15 Frames, länger als eine Wackelperiode) ab.
// Sprünge und gleichmäßige Rampen erzeugen dabei keine Abweichung.
const SMOOTH: usize = 15;
const WINDOW: usize = 15;
if v.len() >= WINDOW {
let smooth: Vec<f32> = (0..v.len())
.map(|i| {
let lo = i.saturating_sub(SMOOTH / 2);
let hi = (i + SMOOTH / 2 + 1).min(v.len());
let mut w: Vec<f32> = v[lo..hi].iter().map(|p| p.1).collect();
w.sort_by(f32::total_cmp);
w[w.len() / 2]
})
.collect();
let flagged: Vec<bool> = v
.iter()
.zip(&smooth)
.map(|(p, s)| (p.1 - s).abs() >= cfg.siren_instability_semitones)
.collect();
let mut i = 0;
while i + WINDOW <= v.len() {
let n = flagged[i..i + WINDOW].iter().filter(|f| **f).count();
if n >= cfg.siren_instability_frames {
marks.push(Transition {
midi: smooth[i + WINDOW / 2],
kind: TransitionKind::Instability,
});
i += WINDOW;
} else {
i += 1;
}
}
}
// Nahe Marken zusammenfassen; die erste (nach Tonhöhe) bleibt.
marks.sort_by(|a, b| a.midi.total_cmp(&b.midi));
let mut merged: Vec<Transition> = Vec::new();
for m in marks {
if merged
.last()
.is_none_or(|l| m.midi - l.midi >= cfg.transition_merge_semitones)
{
merged.push(m);
}
}
Some(SirenResult {
min_midi,
max_midi,
transitions: merged,
})
}
/// Findet gehaltene Töne: Plateaus mit konstanter Tonhöhe, Zuordnung zum nächsten Halbton.
pub fn analyze_holds(frames: &[Frame], cfg: &VoiceConfig) -> Vec<HoldNote> {
let h = hop(frames);
let v = voiced(frames);
let max_gap = cfg.legato_max_gap_ms / 1000.0 + h;
let mut notes: Vec<HoldNote> = Vec::new();
let mut cur: Vec<(f64, f32, f32)> = Vec::new();
let mut sum = 0.0f64;
let mut close = |seg: &[(f64, f32, f32)]| {
if seg.is_empty() {
return;
}
let (t0, t1) = (seg[0].0, seg[seg.len() - 1].0);
let duration = (t1 - t0 + h) as f32;
if duration < cfg.hold_min_s {
return;
}
let trim = cfg.hold_trim_s as f64;
let core: Vec<&(f64, f32, f32)> = seg
.iter()
.filter(|p| p.0 >= t0 + trim && p.0 <= t1 - trim)
.collect();
let core_s = core.len() as f64 * h;
if core_s < 0.6 {
return;
}
let n = core.len() as f32;
let mean = core.iter().map(|p| p.1).sum::<f32>() / n;
let var = core
.iter()
.map(|p| ((p.1 - mean) * 100.0).powi(2))
.sum::<f32>()
/ n;
let std_cents = var.sqrt();
let mean_conf = core.iter().map(|p| p.2).sum::<f32>() / n;
let span = (t1 - trim) - (t0 + trim) + h;
let voiced_ratio = (core_s / span).min(1.0) as f32;
notes.push(HoldNote {
midi: mean.round() as i32,
mean_midi: mean,
std_cents,
mean_conf,
duration_s: duration,
voiced_ratio,
safe: std_cents < cfg.hold_stable_cents
&& mean_conf >= cfg.hold_min_confidence
&& voiced_ratio >= cfg.hold_min_voiced_ratio,
});
};
for p in &v {
if let Some(last) = cur.last() {
let mean = (sum / cur.len() as f64) as f32;
if p.0 - last.0 > max_gap || (p.1 - mean).abs() > cfg.hold_plateau_semitones {
close(&cur);
cur.clear();
sum = 0.0;
}
}
sum += p.1 as f64;
cur.push(*p);
}
close(&cur);
// Pro Halbton den besten (stabilsten) Versuch behalten.
notes.sort_by(|a, b| {
a.midi
.cmp(&b.midi)
.then(a.std_cents.total_cmp(&b.std_cents))
});
notes.dedup_by_key(|n| n.midi);
notes
}
/// Kleinster und größter als sicher gemessener Ton.
pub fn safe_range(holds: &[HoldNote]) -> Option<(i32, i32)> {
let safe = holds.iter().filter(|n| n.safe).map(|n| n.midi);
Some((safe.clone().min()?, safe.max()?))
}
/// Umfang: tiefster und höchster erreichter Ton aus Sirene und Haltetönen.
pub fn full_range(siren: Option<&SirenResult>, holds: &[HoldNote]) -> Option<(f32, f32)> {
let lows = siren
.map(|s| s.min_midi)
.into_iter()
.chain(holds.iter().map(|n| n.mean_midi));
let highs = siren
.map(|s| s.max_midi)
.into_iter()
.chain(holds.iter().map(|n| n.mean_midi));
let lo = lows.fold(None, |a: Option<f32>, x| Some(a.map_or(x, |a| a.min(x))))?;
let hi = highs.fold(None, |a: Option<f32>, x| Some(a.map_or(x, |a| a.max(x))))?;
Some((lo, hi))
}
/// Schlägt den Bereich mit der besten Stabilität vor (Fenster fester Breite über den sicheren Tönen).
/// Bei gleicher Güte gewinnt das Fenster, dessen Mitte näher an Sprechlage + 5 Halbtönen liegt.
pub fn suggest_tessitura(
holds: &[HoldNote],
speech: Option<&SpeechResult>,
cfg: &VoiceConfig,
) -> Option<(i32, i32)> {
let safe: Vec<&HoldNote> = holds.iter().filter(|n| n.safe).collect();
let first = safe.iter().map(|n| n.midi).min()?;
let last = safe.iter().map(|n| n.midi).max()?;
let width = cfg.tessitura_semitones.max(1);
let prefer = speech.map(|s| s.median_midi + 5.0);
let mut best: Option<(f32, f32, i32)> = None; // (Güte, -Abstand, unterer Ton)
for lo in (first - width + 1)..=last {
let hi = lo + width - 1;
let inside: Vec<&&HoldNote> = safe
.iter()
.filter(|n| (lo..=hi).contains(&n.midi))
.collect();
if inside.len() < cfg.tessitura_min_notes {
continue;
}
let quality: f32 = inside
.iter()
.map(|n| (1.0 - n.std_cents / cfg.hold_stable_cents).max(0.0))
.sum();
let dist = prefer.map_or(0.0, |p| ((lo + hi) as f32 / 2.0 - p).abs());
let cand = (quality, -dist, lo);
if best.is_none_or(|b| (cand.0, cand.1) > (b.0, b.1)) {
best = Some(cand);
}
}
best.map(|(_, _, lo)| (lo, lo + width - 1))
}
/// Hinweis, wenn die Tessitura nicht grob eine Terz bis Quinte über der Sprechlage liegt.
pub fn tessitura_hint(
speech: &SpeechResult,
tess: (i32, i32),
cfg: &VoiceConfig,
) -> Option<String> {
let diff = (tess.0 + tess.1) as f32 / 2.0 - speech.median_midi;
if diff < cfg.hint_min_semitones - cfg.hint_tolerance {
Some(format!(
"Die Tessitura liegt nur {diff:.0} Halbtöne über der Sprechlage (üblich: Terz bis Quinte, \
also {:.0}–{:.0}). Möglicherweise singst du tiefer als nötig; prüfe die Lage mit dem Regler.",
cfg.hint_min_semitones, cfg.hint_max_semitones
))
} else if diff > cfg.hint_max_semitones + cfg.hint_tolerance {
Some(format!(
"Die Tessitura liegt {diff:.0} Halbtöne über der Sprechlage (üblich: Terz bis Quinte, \
also {:.0}–{:.0}). Möglicherweise ist sie zu hoch angesetzt; Anstrengung lässt sich nicht \
messen, achte darauf, ob sich die Lage mühelos anfühlt.",
cfg.hint_min_semitones, cfg.hint_max_semitones
))
} else {
None
}
}

392
src/voice/mod.rs Normal file
View File

@ -0,0 +1,392 @@
//! Stimmfinder: Messung von Sprechlage, Umfang und Tessitura, Profil und Nutzung für Transponierung.
pub mod analysis;
pub mod sim;
mod transpose;
pub use analysis::{
HoldNote, LegatoResult, SirenResult, SpeechResult, TransitionKind, analyze_holds,
analyze_legato, analyze_siren, analyze_speech, frames_from_history, full_range, safe_range,
suggest_tessitura, tessitura_hint,
};
pub use transpose::{out_of_range_passages, suggest_transpose};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
const FORMAT_VERSION: u32 = 1;
/// Ergebnis einer kompletten Messung. Übersprungene Schritte bleiben `None`/leer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VoiceProfile {
pub version: u32,
pub id: String,
/// Lokale Zeit „YYYY-MM-DD HH:MM:SS“.
pub created: String,
pub speech: Option<SpeechResult>,
pub legato: Option<LegatoResult>,
pub siren: Option<SirenResult>,
pub holds: Vec<HoldNote>,
/// Stimmumfang (tiefster, höchster Ton als MIDI).
pub range: Option<(f32, f32)>,
/// Sicherer Bereich: tiefster und höchster Halbton mit stabilem Haltton.
pub safe_range: Option<(i32, i32)>,
/// Vom Nutzer bestätigte (ggf. angepasste) Tessitura.
pub tessitura: Option<(i32, i32)>,
}
impl VoiceProfile {
pub fn assemble(
id: String,
created: String,
speech: Option<SpeechResult>,
legato: Option<LegatoResult>,
siren: Option<SirenResult>,
holds: Vec<HoldNote>,
tessitura: Option<(i32, i32)>,
) -> Self {
Self {
version: FORMAT_VERSION,
id,
created,
range: full_range(siren.as_ref(), &holds),
safe_range: safe_range(&holds),
speech,
legato,
siren,
holds,
tessitura,
}
}
}
pub fn profiles_dir() -> PathBuf {
crate::config::Config::data_dir().join("profiles")
}
pub fn save(root: &Path, profile: &VoiceProfile) -> Result<PathBuf> {
std::fs::create_dir_all(root).with_context(|| format!("Ordner anlegen: {}", root.display()))?;
let path = root.join(format!("{}.json", profile.id));
let tmp = root.join(format!("{}.json.tmp", profile.id));
std::fs::write(&tmp, serde_json::to_vec_pretty(profile)?).context("Profil schreiben")?;
std::fs::rename(&tmp, &path).context("Profil sichern")?;
Ok(path)
}
pub fn load(path: &Path) -> Result<VoiceProfile> {
let bytes = std::fs::read(path).with_context(|| format!("Profil lesen: {}", path.display()))?;
let p: VoiceProfile = serde_json::from_slice(&bytes)
.with_context(|| format!("Profil parsen: {}", path.display()))?;
anyhow::ensure!(
p.version == FORMAT_VERSION,
"Profilformat Version {} wird nicht unterstützt",
p.version
);
Ok(p)
}
/// Alle lesbaren Profile, neueste zuerst. Defekte Dateien werden übersprungen.
pub fn list(root: &Path) -> Vec<VoiceProfile> {
let mut out: Vec<VoiceProfile> = std::fs::read_dir(root)
.into_iter()
.flatten()
.flatten()
.filter(|e| e.path().extension().is_some_and(|x| x == "json"))
.filter_map(|e| load(&e.path()).ok())
.collect();
out.sort_by(|a, b| b.id.cmp(&a.id));
out
}
/// Eindeutige Profil-ID aus der lokalen Zeit; bei Kollision mit Zähler.
pub fn new_id(root: &Path) -> (String, String) {
let now = chrono::Local::now();
let base = now.format("%Y-%m-%d_%H-%M-%S").to_string();
let created = now.format("%Y-%m-%d %H:%M:%S").to_string();
let mut id = base.clone();
let mut n = 2;
while root.join(format!("{id}.json")).exists() {
id = format!("{base}-{n}");
n += 1;
}
(id, created)
}
#[cfg(test)]
mod tests {
use super::analysis::Frame;
use super::sim::{SimStep, frames};
use super::*;
use crate::config::VoiceConfig;
use crate::pitch::{HistoryPoint, PitchEstimate};
fn cfg() -> VoiceConfig {
VoiceConfig::default()
}
/// Kompletter Durchlauf mit simulierter Stimme.
fn run(seed: u64) -> VoiceProfile {
let c = cfg();
let speech = analyze_speech(&frames(SimStep::Speech, seed), &c);
let legato = analyze_legato(&frames(SimStep::Legato, seed), &c);
let siren = analyze_siren(&frames(SimStep::Siren, seed), &c);
let holds = analyze_holds(&frames(SimStep::Holds, seed), &c);
let tess = suggest_tessitura(&holds, speech.as_ref(), &c);
VoiceProfile::assemble(
format!("t{seed}"),
"2026-10-31 20:00:00".into(),
speech,
legato,
siren,
holds,
tess,
)
}
#[test]
fn speech_median_and_percentile_range() {
let s = analyze_speech(&frames(SimStep::Speech, 1), &cfg()).unwrap();
assert!((s.median_midi - 52.0).abs() < 0.8, "{s:?}");
assert!(s.lo_midi < s.median_midi && s.median_midi < s.hi_midi);
assert!((s.hi_midi - s.lo_midi - 4.0).abs() < 1.5, "{s:?}");
assert!(s.voiced_s > 15.0);
}
#[test]
fn speech_needs_enough_voiced_data_and_ignores_unvoiced() {
assert!(analyze_speech(&[], &cfg()).is_none());
let short: Vec<_> = frames(SimStep::Speech, 1).into_iter().take(200).collect();
assert!(
analyze_speech(&short, &cfg()).is_none(),
"2 s reichen nicht"
);
}
#[test]
fn legato_tolerates_short_gap_but_not_pauses() {
let l = analyze_legato(&frames(SimStep::Legato, 1), &cfg()).unwrap();
assert!(l.ratio > 0.97, "{l:?}");
assert!(
l.longest_run_s > 7.5,
"kurze Lücke hält den Lauf zusammen: {l:?}"
);
assert!(l.stability_cents.unwrap() < 60.0, "{l:?}");
// Abgehacktes Sprechen (Wörter mit Pausen) ist kein Legato.
let choppy = analyze_legato(&frames(SimStep::Speech, 1), &cfg()).unwrap();
assert!(choppy.ratio < 0.8, "{choppy:?}");
assert!(choppy.longest_run_s < 1.0, "{choppy:?}");
}
#[test]
fn siren_finds_limits_and_register_breaks() {
let s = analyze_siren(&frames(SimStep::Siren, 1), &cfg()).unwrap();
assert!((s.min_midi - 41.2).abs() < 1.0, "{s:?}");
assert!((s.max_midi - 71.5).abs() < 1.5, "{s:?}");
let jump = s
.transitions
.iter()
.find(|t| t.kind == TransitionKind::Jump)
.expect("Sprung");
assert!((60.0..66.0).contains(&jump.midi), "{jump:?}");
let wobble = s
.transitions
.iter()
.find(|t| t.kind == TransitionKind::Instability)
.expect("Instabilität");
assert!((66.0..71.0).contains(&wobble.midi), "{wobble:?}");
assert!(s.transitions.windows(2).all(|w| w[0].midi <= w[1].midi));
}
#[test]
fn smooth_glide_has_no_transitions() {
let glide: Vec<Frame> = (0..800)
.map(|i| Frame {
t: i as f64 * 0.01,
midi: Some(45.0 + i as f32 * 0.03),
conf: 0.95,
})
.collect();
assert!(
analyze_siren(&glide, &cfg())
.unwrap()
.transitions
.is_empty()
);
}
#[test]
fn holds_are_safe_in_the_middle_only() {
let holds = analyze_holds(&frames(SimStep::Holds, 1), &cfg());
let get = |m: i32| holds.iter().find(|h| h.midi == m);
for m in 50..=60 {
let h = get(m).unwrap_or_else(|| panic!("Ton {m} fehlt"));
assert!(h.safe && h.std_cents < 30.0, "{h:?}");
assert!(h.duration_s > 2.0);
}
for m in [44, 45, 66] {
assert!(
get(m).is_none_or(|h| !h.safe),
"Randton {m} darf nicht sicher sein: {:?}",
get(m)
);
}
assert!(holds.windows(2).all(|w| w[0].midi < w[1].midi));
let (lo, hi) = safe_range(&holds).unwrap();
assert!(
(46..=52).contains(&lo) && (58..=64).contains(&hi),
"{lo}..{hi}"
);
}
#[test]
fn short_or_wobbly_tones_are_not_holds() {
// 0,6 s sind zu kurz.
let short: Vec<Frame> = (0..60)
.map(|i| Frame {
t: i as f64 * 0.01,
midi: Some(50.0),
conf: 0.95,
})
.collect();
assert!(analyze_holds(&short, &cfg()).is_empty());
// Gleiten ist kein Haltton.
let glide: Vec<Frame> = (0..500)
.map(|i| Frame {
t: i as f64 * 0.01,
midi: Some(45.0 + i as f32 * 0.02),
conf: 0.95,
})
.collect();
assert!(analyze_holds(&glide, &cfg()).is_empty());
// Niedrige Konfidenz → nicht sicher.
let weak: Vec<Frame> = (0..300)
.map(|i| Frame {
t: i as f64 * 0.01,
midi: Some(50.0),
conf: 0.6,
})
.collect();
let h = analyze_holds(&weak, &cfg());
assert_eq!(h.len(), 1);
assert!(!h[0].safe);
}
#[test]
fn tessitura_is_a_stable_window_inside_the_safe_range() {
let p = run(1);
let (lo, hi) = p.tessitura.expect("Vorschlag");
let (slo, shi) = p.safe_range.unwrap();
assert_eq!(hi - lo + 1, cfg().tessitura_semitones);
assert!(lo >= slo - 1 && hi <= shi + 1, "{lo}..{hi} vs {slo}..{shi}");
let center = (lo + hi) as f32 / 2.0;
assert!((center - 57.0).abs() <= 3.0, "{center}");
assert!(tessitura_hint(&p.speech.unwrap(), (lo, hi), &cfg()).is_none());
}
#[test]
fn no_suggestion_without_enough_safe_tones() {
let few = vec![HoldNote {
midi: 50,
mean_midi: 50.0,
std_cents: 5.0,
mean_conf: 0.95,
duration_s: 2.0,
voiced_ratio: 1.0,
safe: true,
}];
assert!(suggest_tessitura(&few, None, &cfg()).is_none());
assert!(suggest_tessitura(&[], None, &cfg()).is_none());
}
#[test]
fn hint_when_tessitura_is_far_from_speech_register() {
let sp = SpeechResult {
median_midi: 52.0,
lo_midi: 50.0,
hi_midi: 54.0,
voiced_s: 20.0,
};
assert!(
tessitura_hint(&sp, (53, 61), &cfg()).is_none(),
"Mitte 57 = Quarte darüber"
);
assert!(tessitura_hint(&sp, (50, 56), &cfg()).is_none(), "Terz: ok");
let low = tessitura_hint(&sp, (44, 50), &cfg()).unwrap();
assert!(low.contains("tiefer"), "{low}");
let high = tessitura_hint(&sp, (66, 74), &cfg()).unwrap();
assert!(high.contains("zu hoch"), "{high}");
}
/// Abnahme: Ein Durchlauf erzeugt ein Profil; eine Wiederholung liegt innerhalb weniger Halbtöne.
#[test]
fn repeated_measurement_is_reproducible_within_semitones() {
let (a, b) = (run(1), run(77));
let (sa, sb) = (a.speech.unwrap(), b.speech.unwrap());
assert!((sa.median_midi - sb.median_midi).abs() < 1.0);
let (ra, rb) = (a.range.unwrap(), b.range.unwrap());
assert!(
(ra.0 - rb.0).abs() < 1.0 && (ra.1 - rb.1).abs() < 1.0,
"{ra:?} {rb:?}"
);
let (ta, tb) = (a.tessitura.unwrap(), b.tessitura.unwrap());
assert!(
(ta.0 - tb.0).abs() <= 2 && (ta.1 - tb.1).abs() <= 2,
"{ta:?} {tb:?}"
);
let (fa, fb) = (a.safe_range.unwrap(), b.safe_range.unwrap());
assert!(
(fa.0 - fb.0).abs() <= 3 && (fa.1 - fb.1).abs() <= 3,
"{fa:?} {fb:?}"
);
assert_eq!(
a.siren.unwrap().transitions.len(),
b.siren.unwrap().transitions.len()
);
}
#[test]
fn frames_from_history_drop_held_and_low_confidence() {
let ok = PitchEstimate::from_midi(50.0, 0.95);
let weak = PitchEstimate::from_midi(50.0, 0.5);
let held = PitchEstimate { held: true, ..ok };
let pts: Vec<HistoryPoint> = [Some(ok), Some(weak), Some(held), None]
.into_iter()
.enumerate()
.map(|(i, est)| HistoryPoint {
t: i as f64 * 0.01,
est,
})
.collect();
let f = frames_from_history(pts.iter(), &cfg());
assert_eq!(
f.iter().map(|f| f.midi.is_some()).collect::<Vec<_>>(),
[true, false, false, false]
);
}
#[test]
fn profiles_roundtrip_list_newest_first_and_history_is_kept() {
let root = std::env::temp_dir().join(format!("singtrainer-prof-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let mut a = run(1);
a.id = "2026-01-01_10-00-00".into();
let mut b = run(2);
b.id = "2026-02-01_10-00-00".into();
let path = save(&root, &a).unwrap();
save(&root, &b).unwrap();
assert_eq!(load(&path).unwrap(), a, "identisch nach dem Laden");
let l = list(&root);
assert_eq!(
l.iter().map(|p| p.id.as_str()).collect::<Vec<_>>(),
[b.id.as_str(), a.id.as_str()]
);
// Wiederholung überschreibt nichts: neue ID bei Kollision.
let (id1, _) = new_id(&root);
std::fs::write(root.join(format!("{id1}.json")), "{}").unwrap();
assert_ne!(new_id(&root).0, id1);
std::fs::write(root.join("kaputt.json"), "{ nope").unwrap();
assert_eq!(list(&root).len(), 2, "defekte Dateien werden übersprungen");
}
}

103
src/voice/sim.rs Normal file
View File

@ -0,0 +1,103 @@
//! Deterministische simulierte Stimme für Tests und `--sim`: ein Sänger mit Sprechlage um D3,
//! Registerbruch beim Aufwärtsgleiten und stabiler Mitte (nur am Rand schwankende Haltetöne).
#[cfg(test)]
use super::analysis::Frame;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SimStep {
Speech,
Legato,
Siren,
Holds,
}
pub const HOLD_LOWEST: i32 = 44;
pub const HOLD_COUNT: i32 = 23;
const HOLD_PERIOD_S: f64 = 2.9;
impl SimStep {
/// Dauer der simulierten Aufnahme in Sekunden.
#[cfg(test)]
pub fn duration_s(self) -> f64 {
match self {
SimStep::Speech => 30.0,
SimStep::Legato => 8.0,
SimStep::Siren => 12.0,
SimStep::Holds => HOLD_COUNT as f64 * HOLD_PERIOD_S,
}
}
}
/// Pseudozufall in -1..1, abhängig von Zeitindex und Seed.
fn noise(i: u64, seed: u64) -> f32 {
let mut x = i.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ seed.wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
x ^= x >> 29;
x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
x ^= x >> 32;
(x % 20_001) as f32 / 10_000.0 - 1.0
}
/// Tonhöhe (MIDI) zur Zeit `t` des Schritts oder `None` bei Pause.
pub fn sim_voice(step: SimStep, t: f64, seed: u64) -> Option<f32> {
let i = (t * 100.0).round() as u64;
let n = noise(i, seed);
match step {
SimStep::Speech => {
// Wörter von 0,45 s mit 0,2 s Pause.
if t % 0.65 > 0.45 {
return None;
}
Some(52.0 + 2.2 * (t as f32 * 1.7).sin() + 0.5 * n)
}
SimStep::Legato => {
if (3.0..3.08).contains(&t) {
return None; // kurze Lücke, unter der Legato-Toleranz
}
Some(53.0 + 0.4 * (t as f32 * 0.9).sin() + 0.12 * n)
}
SimStep::Siren => {
let m = if t < 6.0 {
55.0 - (t as f32 / 6.0) * 14.0
} else {
41.0 + ((t as f32 - 6.0) / 6.0) * 29.0
};
let mut p = m;
if t >= 6.0 && m > 62.0 {
p += 2.0; // Registerbruch
}
if t >= 6.0 && (66.0..67.2).contains(&m) {
p += 0.9 * (t as f32 * 60.0).sin(); // unruhige Stelle
}
Some(p + 0.05 * n)
}
SimStep::Holds => {
let k = (t / HOLD_PERIOD_S).floor() as i32;
let within = t - k as f64 * HOLD_PERIOD_S;
if k >= HOLD_COUNT || within > 2.5 {
return None;
}
// Streuung: mittig ca. 8 Cent, an den Rändern deutlich über 30 Cent.
let mid = (HOLD_COUNT - 1) as f32 / 2.0;
let edge = ((k as f32 - mid).abs() / mid).powi(3);
let amp = 0.12 + 1.1 * edge;
Some((HOLD_LOWEST + k) as f32 + amp * n)
}
}
}
/// Frames mit 100 Hz für den ganzen Schritt.
#[cfg(test)]
pub fn frames(step: SimStep, seed: u64) -> Vec<Frame> {
(0..(step.duration_s() * 100.0) as usize)
.map(|i| {
let t = i as f64 * 0.01;
let midi = sim_voice(step, t, seed);
Frame {
t,
midi,
conf: if midi.is_some() { 0.95 } else { 0.0 },
}
})
.collect()
}

67
src/voice/transpose.rs Normal file
View File

@ -0,0 +1,67 @@
//! Nutzung des Profils für Charts: Transponierungsvorschlag und Warnung außerhalb des sicheren Bereichs.
use super::VoiceProfile;
use crate::chart::{NoteChart, NoteKind};
/// Verschiebung in Halbtönen, die den Median der Melodie in die Mitte der Tessitura legt.
/// `None` ohne Tessitura im Profil oder ohne Melodienoten.
pub fn suggest_transpose(chart: &NoteChart, profile: &VoiceProfile) -> Option<i32> {
let (lo, hi) = profile.tessitura?;
let median = chart.median_pitch()?;
Some(((lo + hi) as f32 / 2.0 - median).round() as i32)
}
/// Zusammenhängende Zeitabschnitte (ms), in denen Noten außerhalb des sicheren Bereichs liegen.
/// Direkt aufeinanderfolgende Noten werden zu einem Abschnitt vereint.
pub fn out_of_range_passages(chart: &NoteChart, safe: (i32, i32)) -> Vec<(f64, f64)> {
let mut out: Vec<(f64, f64)> = Vec::new();
for n in chart.notes.iter().filter(|n| n.typ != NoteKind::Frei) {
if n.midi_pitch < safe.0 || n.midi_pitch > safe.1 {
match out.last_mut() {
Some(last) if n.start_ms - last.1 < 1.0 => last.1 = n.end_ms(),
_ => out.push((n.start_ms, n.end_ms())),
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::voice::VoiceProfile;
fn chart(pitches: &[i32]) -> NoteChart {
let mut s = String::from("title=\"t\"\n");
for (i, p) in pitches.iter().enumerate() {
s += &format!(
"[[notes]]\nstart_ms={}\ndauer_ms=500\nmidi_pitch={p}\n",
i * 500
);
}
NoteChart::from_toml_str(&s, None).unwrap()
}
fn profile(tess: Option<(i32, i32)>) -> VoiceProfile {
VoiceProfile::assemble("x".into(), "y".into(), None, None, None, vec![], tess)
}
#[test]
fn suggestion_centers_melody_median_in_tessitura() {
let c = chart(&[60, 62, 64, 65, 67]); // Median 64
// Tessitura 50..58 → Mitte 54 → Verschiebung -10.
assert_eq!(suggest_transpose(&c, &profile(Some((50, 58)))), Some(-10));
assert_eq!(suggest_transpose(&c, &profile(Some((60, 68)))), Some(0));
assert_eq!(suggest_transpose(&c, &profile(None)), None);
let shifted = c.transposed(-10);
assert_eq!(shifted.median_pitch(), Some(54.0));
}
#[test]
fn passages_merge_adjacent_out_of_range_notes() {
let c = chart(&[60, 72, 74, 60, 60, 75]);
let p = out_of_range_passages(&c, (55, 70));
assert_eq!(p, vec![(500.0, 1500.0), (2500.0, 3000.0)]);
assert!(out_of_range_passages(&c, (55, 80)).is_empty());
}
}