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

998
src/ui/voice_view.rs Normal file
View File

@ -0,0 +1,998 @@
//! Stimmfinder: geführter Assistent (Sprechlage → Legato → Sirene → Haltetöne → Tessitura → Übersicht)
//! und Klaviatur-Übersicht des Profils. Die Schrittlogik (`wizard_*`) kommt ohne egui aus.
use super::App;
use crate::pitch::note_name;
use crate::voice::sim::{SimStep, sim_voice};
use crate::voice::{
self, HoldNote, LegatoResult, SirenResult, SpeechResult, TransitionKind, VoiceProfile,
analyze_holds, analyze_legato, analyze_siren, analyze_speech, frames_from_history,
suggest_tessitura, tessitura_hint,
};
use eframe::egui::{self, Align2, Color32, FontId, Rect, Stroke, pos2, vec2};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Step {
Speech,
Legato,
Siren,
Holds,
Tessitura,
Overview,
}
impl Step {
fn number(self) -> usize {
self as usize + 1
}
fn title(self) -> &'static str {
match self {
Step::Speech => "Sprechlage",
Step::Legato => "Gebundenes Sprechen",
Step::Siren => "Sirene",
Step::Holds => "Haltetöne",
Step::Tessitura => "Tessitura",
Step::Overview => "Übersicht",
}
}
fn instructions(self) -> &'static str {
match self {
Step::Speech => {
"Sprich etwa 30 Sekunden in normaler Lautstärke und Sprechweise: neutrale Wörter und \
Sätze, z. B. Zahlen, Wochentage, Alltagssätze. Nicht singen, nicht flüstern."
}
Step::Legato => {
"Dehne die Vokale ohne Pause, z. B. „Mmmaaa-weeeiii-geeehhhtt-ooosss“, alles in einem \
Atem und ohne Absetzen. Das zeigt, wie gebunden deine Stimme trägt."
}
Step::Siren => {
"Gleite wie eine Sirene aus der Mitte langsam nach unten bis zum tiefsten bequemen Ton, \
dann gleichmäßig nach oben bis zum höchsten Ton (Kopfstimme erlaubt). Nicht pressen."
}
Step::Holds => {
"Halte Töne Halbton für Halbton jeweils 2–3 Sekunden, von tief nach hoch, mit kurzer \
Pause dazwischen. Der Referenzton hilft beim Treffen. Ein Ton gilt als „sicher“, wenn \
er stabil und eindeutig erkannt wird."
}
Step::Tessitura => {
"Das ist der Bereich mit der besten Stabilität. Anstrengung lässt sich nicht messen: \
verschiebe ihn mit den Reglern dorthin, wo du mühelos und gern singst."
}
Step::Overview => {
"So sieht dein Profil aus. Speichern legt eine neue Messung im Verlauf ab."
}
}
}
fn next(self) -> Step {
match self {
Step::Speech => Step::Legato,
Step::Legato => Step::Siren,
Step::Siren => Step::Holds,
Step::Holds => Step::Tessitura,
Step::Tessitura | Step::Overview => Step::Overview,
}
}
fn records(self) -> bool {
matches!(
self,
Step::Speech | Step::Legato | Step::Siren | Step::Holds
)
}
fn sim(self) -> Option<SimStep> {
match self {
Step::Speech => Some(SimStep::Speech),
Step::Legato => Some(SimStep::Legato),
Step::Siren => Some(SimStep::Siren),
Step::Holds => Some(SimStep::Holds),
_ => None,
}
}
}
pub(super) struct Wizard {
pub step: Step,
/// Eingangszeit des Aufnahmestarts, solange eine Aufnahme läuft.
pub rec_t0: Option<f64>,
pub speech: Option<SpeechResult>,
pub legato: Option<LegatoResult>,
pub siren: Option<SirenResult>,
pub holds: Vec<HoldNote>,
pub tess: (i32, i32),
pub tess_suggested: Option<(i32, i32)>,
pub preview: Option<VoiceProfile>,
pub message: Option<String>,
/// Seed der simulierten Stimme; wechselt mit jeder Aufnahme.
pub seed: u64,
}
impl Wizard {
pub fn new() -> Self {
Self {
step: Step::Speech,
rec_t0: None,
speech: None,
legato: None,
siren: None,
holds: Vec::new(),
tess: (55, 63),
tess_suggested: None,
preview: None,
message: None,
seed: 0,
}
}
fn has_result(&self) -> bool {
match self.step {
Step::Speech => self.speech.is_some(),
Step::Legato => self.legato.is_some(),
Step::Siren => self.siren.is_some(),
Step::Holds => !self.holds.is_empty(),
_ => false,
}
}
fn clear_result(&mut self) {
match self.step {
Step::Speech => self.speech = None,
Step::Legato => self.legato = None,
Step::Siren => self.siren = None,
Step::Holds => self.holds.clear(),
_ => {}
}
}
}
impl App {
pub(super) fn refresh_profiles(&mut self) {
self.profiles = voice::list(&self.profiles_root);
}
/// Das aktive Profil ist die neueste Messung.
pub(super) fn active_profile(&self) -> Option<&VoiceProfile> {
self.profiles.first()
}
pub(super) fn wizard_begin(&mut self) {
self.wizard = Some(Wizard::new());
}
pub(super) fn wizard_record_start(&mut self) {
let t0 = self.input_now_s();
if let Ok(mut h) = self.history.lock() {
// Sirene und Haltetöne dauern länger als die Standardaufbewahrung des Verlaufs.
h.ensure_retention(self.config.voice.speech_duration_s.max(120.0) + 30.0);
}
if let Some(w) = self.wizard.as_mut() {
w.rec_t0 = Some(t0);
w.message = None;
w.seed = w.seed.wrapping_add(1);
}
}
/// Sekunden seit Aufnahmestart.
pub(super) fn wizard_elapsed(&self) -> Option<f64> {
let t0 = self.wizard.as_ref()?.rec_t0?;
Some(self.input_now_s() - t0)
}
pub(super) fn wizard_record_finish(&mut self) {
let cfg = self.config.voice.clone();
let Some(w) = self.wizard.as_mut() else {
return;
};
let Some(t0) = w.rec_t0.take() else { return };
let frames = match self.history.lock() {
Ok(h) => frames_from_history(h.since(t0), &cfg),
Err(_) => return,
};
let ok = match w.step {
Step::Speech => {
w.speech = analyze_speech(&frames, &cfg);
w.speech.is_some()
}
Step::Legato => {
w.legato = analyze_legato(&frames, &cfg);
w.legato.is_some()
}
Step::Siren => {
w.siren = analyze_siren(&frames, &cfg);
w.siren.is_some()
}
Step::Holds => {
w.holds = analyze_holds(&frames, &cfg);
!w.holds.is_empty()
}
_ => true,
};
w.message = (!ok).then(|| {
"Zu wenige stimmhafte Daten erkannt. Prüfe den Pegel, singe/sprich etwas lauter und wiederhole."
.to_string()
});
}
/// Geht zum nächsten Schritt (auch per „Überspringen“).
pub(super) fn wizard_next(&mut self) {
let cfg = self.config.voice.clone();
let Some(w) = self.wizard.as_mut() else {
return;
};
w.message = None;
w.rec_t0 = None;
w.step = w.step.next();
match w.step {
Step::Tessitura => {
w.tess_suggested = suggest_tessitura(&w.holds, w.speech.as_ref(), &cfg);
let width = cfg.tessitura_semitones.max(1);
w.tess = w.tess_suggested.unwrap_or_else(|| {
// Ohne sichere Haltetöne: grober Startwert aus Sprechlage oder Sirene.
let lo = match (&w.speech, &w.siren) {
(Some(s), _) => s.median_midi.round() as i32 + 3,
(None, Some(s)) => {
((s.min_midi + s.max_midi) / 2.0).round() as i32 - width / 2
}
_ => 55,
};
(lo, lo + width - 1)
});
}
Step::Overview => {
w.preview = Some(VoiceProfile::assemble(
String::new(),
String::new(),
w.speech,
w.legato,
w.siren.clone(),
w.holds.clone(),
Some(w.tess),
));
}
_ => {}
}
}
/// Speichert die Messung als neues Profil; frühere bleiben erhalten.
pub(super) fn wizard_save(&mut self) -> Result<(), String> {
let Some(w) = self.wizard.as_mut() else {
return Ok(());
};
let Some(mut p) = w.preview.clone() else {
return Ok(());
};
let (id, created) = voice::new_id(&self.profiles_root);
p.id = id;
p.created = created;
voice::save(&self.profiles_root, &p).map_err(|e| format!("{e:#}"))?;
self.wizard = None;
self.refresh_profiles();
self.shown_profile = 0;
Ok(())
}
/// Simulierte Stimme, solange im Simulationsmodus ein Schritt aufnimmt.
pub(super) fn sim_voice_pitch(&self, t: f64) -> Option<Option<f32>> {
let w = self.wizard.as_ref()?;
let step = w.step.sim()?;
Some(sim_voice(step, t - w.rec_t0?, w.seed))
}
pub(super) fn voice_ui(&mut self, ui: &mut egui::Ui) {
if self.wizard.is_some() {
self.wizard_ui(ui);
} else {
self.profile_ui(ui);
}
}
fn profile_ui(&mut self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
ui.heading("Stimmfinder");
if ui.button("Neue Messung starten").clicked() {
self.wizard_begin();
}
});
let Some(p) = self.profiles.get(self.shown_profile).cloned() else {
ui.label(
"Noch kein Stimmprofil. Der Assistent misst Sprechlage, Stimmumfang und Tessitura \
und speichert das Ergebnis; Songs lassen sich damit in deine Lage transponieren.",
);
return;
};
ui.label(format!(
"Profil vom {}{}",
p.created,
if self.shown_profile == 0 {
" (aktiv)"
} else {
""
}
));
draw_profile(ui, &p, &self.config.voice);
ui.separator();
ui.strong("Verlauf der Messungen");
let mut show = None;
egui::Grid::new("profiles").striped(true).show(ui, |ui| {
for h in ["Datum", "Sprechlage", "Umfang", "Sicher", "Tessitura", ""] {
ui.strong(h);
}
ui.end_row();
for (i, q) in self.profiles.iter().enumerate() {
ui.label(&q.created);
ui.label(
q.speech
.map_or("–".into(), |s| note_name(s.median_midi.round() as i32)),
);
ui.label(q.range.map_or("–".into(), |(a, b)| {
format!(
"{}–{}",
note_name(a.round() as i32),
note_name(b.round() as i32)
)
}));
ui.label(q.safe_range.map_or("–".into(), |(a, b)| {
format!("{}–{}", note_name(a), note_name(b))
}));
ui.label(q.tessitura.map_or("–".into(), |(a, b)| {
format!("{}–{}", note_name(a), note_name(b))
}));
if ui.button("Anzeigen").clicked() {
show = Some(i);
}
ui.end_row();
}
});
if let Some(i) = show {
self.shown_profile = i;
}
}
fn wizard_ui(&mut self, ui: &mut egui::Ui) {
let (step, recording, has_result, message) = {
let w = self.wizard.as_ref().expect("Assistent aktiv");
(
w.step,
w.rec_t0.is_some(),
w.has_result(),
w.message.clone(),
)
};
ui.horizontal(|ui| {
ui.heading(format!("Schritt {} von 6: {}", step.number(), step.title()));
if ui.button("Abbrechen").clicked() {
self.wizard = None;
}
});
ui.label(step.instructions());
if self.wizard.is_none() {
return;
}
if step.records() {
self.roll_view(ui, 360.0);
let elapsed = self.wizard_elapsed();
// Sprechlage endet automatisch nach der Zielzeit.
if step == Step::Speech
&& elapsed.is_some_and(|e| e >= self.config.voice.speech_duration_s)
{
self.wizard_record_finish();
}
if step == Step::Holds {
self.reference_controls(ui);
}
ui.horizontal(|ui| {
if recording {
if ui.button("■ Fertig").clicked() {
self.wizard_record_finish();
}
ui.label(format!("läuft … {:.0} s", elapsed.unwrap_or(0.0)));
} else if has_result {
if ui.button("↻ Wiederholen").clicked()
&& let Some(w) = self.wizard.as_mut()
{
w.clear_result();
}
if ui.button("Weiter ▶").clicked() {
self.wizard_next();
}
} else {
if ui.button("● Aufnahme starten").clicked() {
self.wizard_record_start();
}
if ui.button("Überspringen").clicked() {
self.wizard_next();
}
}
});
if let Some(m) = message {
ui.colored_label(Color32::from_rgb(230, 120, 60), m);
}
if let Some(w) = &self.wizard {
show_step_result(ui, w, &self.config.voice);
}
} else if step == Step::Tessitura {
self.tessitura_step(ui);
} else {
let Some(p) = self.wizard.as_ref().and_then(|w| w.preview.clone()) else {
return;
};
draw_profile(ui, &p, &self.config.voice);
ui.horizontal(|ui| {
if ui.button("Profil speichern").clicked() {
self.messages = match self.wizard_save() {
Ok(()) => vec!["Stimmprofil gespeichert".into()],
Err(e) => vec![format!("Profil speichern fehlgeschlagen: {e}")],
};
}
if ui.button("Verwerfen").clicked() {
self.wizard = None;
}
});
}
}
fn tessitura_step(&mut self, ui: &mut egui::Ui) {
let cfg = self.config.voice.clone();
let Some(w) = self.wizard.as_mut() else {
return;
};
match w.tess_suggested {
Some((a, b)) => ui.label(format!(
"Vorschlag: {}–{} (beste Stabilität der sicheren Haltetöne).",
note_name(a),
note_name(b)
)),
None => ui.label(
"Kein Vorschlag möglich (zu wenige sichere Töne); Startwert aus der Sprechlage.",
),
};
let (mut lo, mut hi) = w.tess;
ui.horizontal(|ui| {
ui.label("Von");
ui.add(
egui::Slider::new(&mut lo, 24..=96).custom_formatter(|v, _| note_name(v as i32)),
);
ui.label("bis");
ui.add(
egui::Slider::new(&mut hi, 24..=96).custom_formatter(|v, _| note_name(v as i32)),
);
});
hi = hi.max(lo + 1);
w.tess = (lo, hi);
if let Some(s) = &w.speech {
ui.label(format!(
"Mitte {} · Sprechlage {}: {:+.0} Halbtöne",
note_name((lo + hi) / 2),
note_name(s.median_midi.round() as i32),
(lo + hi) as f32 / 2.0 - s.median_midi
));
if let Some(h) = tessitura_hint(s, (lo, hi), &cfg) {
ui.colored_label(Color32::from_rgb(230, 170, 60), format!("Hinweis: {h}"));
}
}
if ui.button("Bestätigen ▶").clicked() {
self.wizard_next();
}
}
}
fn show_step_result(ui: &mut egui::Ui, w: &Wizard, cfg: &crate::config::VoiceConfig) {
let n = |m: f32| note_name(m.round() as i32);
match w.step {
Step::Speech => {
if let Some(s) = &w.speech {
ui.label(format!(
"Sprechlage: Median {} ({:.0} Hz), Bereich {}–{} (Perzentil {:.0}–{:.0}), {:.0} s stimmhaft",
n(s.median_midi),
440.0 * 2f32.powf((s.median_midi - 69.0) / 12.0),
n(s.lo_midi),
n(s.hi_midi),
cfg.speech_percentile_lo,
cfg.speech_percentile_hi,
s.voiced_s
));
}
}
Step::Legato => {
if let Some(l) = &w.legato {
ui.label(format!(
"Legato: {:.0} % stimmhaft ohne Lücke, längster Lauf {:.1} s, Stabilität {}",
l.ratio * 100.0,
l.longest_run_s,
l.stability_cents
.map_or("–".into(), |c| format!("±{c:.0} Cent"))
));
}
}
Step::Siren => {
if let Some(s) = &w.siren {
ui.label(format!("Umfang: {}–{}", n(s.min_midi), n(s.max_midi)));
if s.transitions.is_empty() {
ui.label("Keine Registerübergänge erkannt.");
} else {
let list: Vec<String> = s
.transitions
.iter()
.map(|t| {
format!(
"{} ({})",
n(t.midi),
match t.kind {
TransitionKind::Jump => "Sprung",
TransitionKind::Instability => "instabil",
}
)
})
.collect();
ui.label(format!("Registerübergänge: {}", list.join(", ")));
}
}
}
Step::Holds if !w.holds.is_empty() => {
let safe = w.holds.iter().filter(|h| h.safe).count();
ui.label(format!(
"{} Töne gemessen, davon {safe} sicher.",
w.holds.len()
));
egui::ScrollArea::vertical()
.max_height(110.0)
.show(ui, |ui| {
egui::Grid::new("holds").striped(true).show(ui, |ui| {
for h in ["Ton", "Streuung", "Konfidenz", "Dauer", "sicher"] {
ui.strong(h);
}
ui.end_row();
for h in &w.holds {
ui.label(note_name(h.midi));
ui.label(format!("{:.0} Cent", h.std_cents));
ui.label(format!("{:.2}", h.mean_conf));
ui.label(format!("{:.1} s", h.duration_s));
ui.label(if h.safe { "✓" } else { "–" });
ui.end_row();
}
});
});
}
_ => {}
}
}
/// x-Position eines (kontinuierlichen) MIDI-Werts auf der chromatischen Klaviatur:
/// jeder Halbton eine Zelle, Zelle `lo` beginnt bei `left`.
pub(super) fn semitone_x(midi: f32, lo: i32, cell_w: f32, left: f32) -> f32 {
left + (midi - (lo as f32 - 0.5)) * cell_w
}
/// Darstellbarer Bereich der Klaviatur: Profilwerte plus Rand, mindestens drei Oktaven, an C/B ausgerichtet.
pub(super) fn keyboard_span(p: &VoiceProfile) -> (i32, i32) {
let mut vals: Vec<f32> = Vec::new();
if let Some(s) = &p.speech {
vals.extend([s.lo_midi, s.hi_midi]);
}
if let Some((a, b)) = p.range {
vals.extend([a, b]);
}
if let Some((a, b)) = p.tessitura.or(p.safe_range) {
vals.extend([a as f32, b as f32]);
}
let (lo, hi) = match (
vals.iter()
.copied()
.fold(None, |a: Option<f32>, x| Some(a.map_or(x, |a| a.min(x)))),
vals.iter()
.copied()
.fold(None, |a: Option<f32>, x| Some(a.map_or(x, |a| a.max(x)))),
) {
(Some(l), Some(h)) => (l.floor() as i32 - 2, h.ceil() as i32 + 2),
_ => (48, 72),
};
// Auf volle Oktaven (C bis B) erweitern, mindestens 36 Halbtöne.
let mut lo = lo.div_euclid(12) * 12;
let mut hi = (hi.div_euclid(12) + 1) * 12 - 1;
while hi - lo + 1 < 36 {
if lo > 24 {
lo -= 12;
} else {
hi += 12;
}
}
(lo.max(0), hi.min(127))
}
/// Klaviatur mit Lanes für Umfang, sicheren Bereich, Tessitura, Sprechlage und Übergänge, plus Werte.
fn draw_profile(ui: &mut egui::Ui, p: &VoiceProfile, cfg: &crate::config::VoiceConfig) {
let (lo, hi) = keyboard_span(p);
let n = (hi - lo + 1) as f32;
const LANE_H: f32 = 18.0;
const KEY_H: f32 = 46.0;
const LANES: usize = 5;
let h = LANE_H * LANES as f32 + KEY_H + 18.0;
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), h), egui::Sense::hover());
let label_w = 96.0;
let (left, width) = (rect.left() + label_w, rect.width() - label_w);
let cell = width / n;
let painter = ui.painter_at(rect);
painter.rect_filled(rect, 4.0, Color32::from_rgb(24, 26, 32));
let x = |m: f32| semitone_x(m, lo, cell, left);
let lane = |i: usize| {
let top = rect.top() + i as f32 * LANE_H;
Rect::from_min_max(
pos2(left, top + 2.0),
pos2(left + width, top + LANE_H - 2.0),
)
};
let bar = |i: usize, a: f32, b: f32, color: Color32, label: &str| {
let l = lane(i);
painter.text(
pos2(rect.left() + 6.0, l.center().y),
Align2::LEFT_CENTER,
label,
FontId::proportional(12.0),
Color32::from_gray(170),
);
painter.rect_filled(
Rect::from_min_max(pos2(x(a), l.top()), pos2(x(b), l.bottom())),
3.0,
color,
);
};
if let Some((a, b)) = p.range {
bar(
0,
a - 0.5,
b + 0.5,
Color32::from_rgb(70, 110, 190),
"Umfang",
);
}
if let Some((a, b)) = p.safe_range {
bar(
1,
a as f32 - 0.5,
b as f32 + 0.5,
Color32::from_rgb(70, 170, 120),
"Sicher",
);
}
if let Some((a, b)) = p.tessitura {
bar(
2,
a as f32 - 0.5,
b as f32 + 0.5,
Color32::from_rgb(220, 170, 50),
"Tessitura",
);
}
if let Some(s) = &p.speech {
bar(
3,
s.lo_midi,
s.hi_midi,
Color32::from_rgb(170, 110, 200),
"Sprechlage",
);
let l = lane(3);
painter.line_segment(
[
pos2(x(s.median_midi), l.top()),
pos2(x(s.median_midi), l.bottom()),
],
Stroke::new(2.5, Color32::WHITE),
);
}
painter.text(
pos2(rect.left() + 6.0, lane(4).center().y),
Align2::LEFT_CENTER,
"Übergänge",
FontId::proportional(12.0),
Color32::from_gray(170),
);
for t in p.siren.iter().flat_map(|s| &s.transitions) {
let c = lane(4).center();
let color = match t.kind {
TransitionKind::Jump => Color32::from_rgb(235, 90, 90),
TransitionKind::Instability => Color32::from_rgb(240, 150, 60),
};
painter.circle_filled(pos2(x(t.midi), c.y), 5.0, color);
}
// Klaviatur.
let key_top = rect.top() + LANE_H * LANES as f32 + 4.0;
for m in lo..=hi {
let black = super::roll::is_black_key(m);
let cell_rect = Rect::from_min_max(
pos2(x(m as f32 - 0.5), key_top),
pos2(x(m as f32 + 0.5), key_top + KEY_H),
);
painter.rect_filled(
cell_rect.shrink2(vec2(0.5, 0.0)),
1.0,
if black {
Color32::from_gray(35)
} else {
Color32::from_gray(225)
},
);
if m.rem_euclid(12) == 0 {
painter.text(
pos2(cell_rect.center().x, cell_rect.bottom() + 8.0),
Align2::CENTER_CENTER,
note_name(m),
FontId::monospace(11.0),
Color32::from_gray(190),
);
}
}
// Werte als Text.
let n = |m: f32| note_name(m.round() as i32);
if let Some(s) = &p.speech {
ui.label(format!(
"Sprechlage: Median {} ({:.0} Hz), Bereich {}–{}",
n(s.median_midi),
440.0 * 2f32.powf((s.median_midi - 69.0) / 12.0),
n(s.lo_midi),
n(s.hi_midi)
));
}
if let Some((a, b)) = p.range {
ui.label(format!(
"Stimmumfang: {}–{} ({:.0} Halbtöne)",
n(a),
n(b),
b - a
));
}
if let Some((a, b)) = p.safe_range {
ui.label(format!(
"Sicherer Bereich: {}–{}",
note_name(a),
note_name(b)
));
}
if let Some((a, b)) = p.tessitura {
ui.label(format!("Tessitura: {}–{}", note_name(a), note_name(b)));
}
if let Some(l) = &p.legato {
ui.label(format!(
"Legato: {:.0} % ohne Lücke, längster Lauf {:.1} s, Stabilität {}",
l.ratio * 100.0,
l.longest_run_s,
l.stability_cents
.map_or("–".into(), |c| format!("±{c:.0} Cent"))
));
}
if let (Some(s), Some(t)) = (&p.speech, p.tessitura)
&& let Some(hint) = tessitura_hint(s, t, cfg)
{
ui.colored_label(Color32::from_rgb(230, 170, 60), format!("Hinweis: {hint}"));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn semitone_mapping_is_cell_centered() {
// Zelle 48 beginnt bei 100, Breite 10: Mitte von 48 bei 105, Rand zwischen 48 und 49 bei 110.
assert_eq!(semitone_x(48.0, 48, 10.0, 100.0), 105.0);
assert_eq!(semitone_x(48.5, 48, 10.0, 100.0), 110.0);
assert_eq!(semitone_x(47.5, 48, 10.0, 100.0), 100.0);
}
#[test]
fn keyboard_span_covers_profile_in_full_octaves() {
let p = VoiceProfile::assemble(
"x".into(),
"y".into(),
Some(SpeechResult {
median_midi: 52.0,
lo_midi: 50.0,
hi_midi: 54.0,
voiced_s: 10.0,
}),
None,
Some(SirenResult {
min_midi: 41.0,
max_midi: 72.0,
transitions: vec![],
}),
vec![],
Some((53, 61)),
);
let (lo, hi) = keyboard_span(&p);
assert_eq!(lo.rem_euclid(12), 0, "beginnt bei C");
assert_eq!(hi.rem_euclid(12), 11, "endet bei B");
assert!(lo <= 39 && hi >= 74 && hi - lo + 1 >= 36, "{lo}..{hi}");
// Leeres Profil bekommt einen Standardausschnitt.
let empty = VoiceProfile::assemble("x".into(), "y".into(), None, None, None, vec![], None);
let (lo, hi) = keyboard_span(&empty);
assert!(hi - lo + 1 >= 36 && lo <= 48 && hi >= 72, "{lo}..{hi}");
}
use crate::chart::NoteChart;
use crate::pitch::PitchEstimate;
use std::path::Path;
use std::sync::Arc;
fn test_app(name: &str) -> App {
let mut app = App::new(true, false, false);
let root =
std::env::temp_dir().join(format!("singtrainer-voice-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
app.profiles_root = root;
app.profiles.clear();
app
}
/// Nimmt einen Schritt mit der simulierten Stimme auf; die Sim-Uhr läuft danach weiter.
fn feed(app: &mut App, step: SimStep) {
app.wizard_record_start();
let (t0, seed) = {
let w = app.wizard.as_ref().unwrap();
(w.rec_t0.unwrap(), w.seed)
};
let n = (step.duration_s() * 100.0) as usize;
{
let mut h = app.history.lock().unwrap();
for i in 0..n {
let t = i as f64 * 0.01;
h.push(
t0 + t,
sim_voice(step, t, seed).map(|m| PitchEstimate::from_midi(m, 0.95)),
);
}
}
app.sim_t = t0 + step.duration_s() + 1.0;
app.wizard_record_finish();
}
/// Kompletter Durchlauf; `seed` variiert das Rauschen der simulierten Stimme.
fn full_run(app: &mut App, seed: u64) {
app.wizard_begin();
app.wizard.as_mut().unwrap().seed = seed;
for step in [
SimStep::Speech,
SimStep::Legato,
SimStep::Siren,
SimStep::Holds,
] {
feed(app, step);
assert!(
app.wizard.as_ref().unwrap().has_result(),
"{step:?} ohne Ergebnis"
);
app.wizard_next();
}
assert_eq!(app.wizard.as_ref().unwrap().step, Step::Tessitura);
assert!(app.wizard.as_ref().unwrap().tess_suggested.is_some());
app.wizard_next(); // Vorschlag bestätigen
assert_eq!(app.wizard.as_ref().unwrap().step, Step::Overview);
app.wizard_save().unwrap();
assert!(app.wizard.is_none());
}
#[test]
fn complete_run_creates_profile_and_repeat_is_reproducible() {
let mut app = test_app("full");
full_run(&mut app, 0);
assert_eq!(app.profiles.len(), 1);
let first = app.profiles[0].clone();
assert!(first.speech.is_some() && first.legato.is_some() && first.siren.is_some());
assert!(first.range.is_some() && first.safe_range.is_some() && first.tessitura.is_some());
assert!(!first.siren.as_ref().unwrap().transitions.is_empty());
assert!(!first.holds.is_empty());
// Wiederholung: zweites Profil, das erste bleibt im Verlauf erhalten.
full_run(&mut app, 1000);
assert_eq!(app.profiles.len(), 2);
assert_ne!(app.profiles[0].id, app.profiles[1].id);
assert!(app.profiles[0].id > app.profiles[1].id, "neueste zuerst");
assert_eq!(app.profiles[1], first, "alte Messung unverändert");
assert_ne!(
app.profiles[0].holds, first.holds,
"anderes Rauschen, andere Rohwerte"
);
let (a, b) = (&app.profiles[0], &first);
let (sa, sb) = (a.speech.unwrap(), b.speech.unwrap());
assert!((sa.median_midi - sb.median_midi).abs() < 1.0);
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 (ra, rb) = (a.range.unwrap(), b.range.unwrap());
assert!((ra.0 - rb.0).abs() < 1.5 && (ra.1 - rb.1).abs() < 1.5);
// Von der Platte neu laden → identisch.
let mut reloaded = test_app("full-reload");
reloaded.profiles_root = app.profiles_root.clone();
reloaded.refresh_profiles();
assert_eq!(reloaded.profiles, app.profiles);
}
#[test]
fn user_adjusted_tessitura_is_what_gets_saved() {
let mut app = test_app("adjust");
app.wizard_begin();
for step in [SimStep::Speech, SimStep::Holds] {
while app.wizard.as_ref().unwrap().step.sim() != Some(step) {
app.wizard_next(); // Zwischenschritte überspringen
}
feed(&mut app, step);
}
app.wizard_next();
app.wizard.as_mut().unwrap().tess = (50, 58); // per Regler angepasst
app.wizard_next();
app.wizard_save().unwrap();
assert_eq!(app.profiles[0].tessitura, Some((50, 58)));
assert!(app.profiles[0].legato.is_none() && app.profiles[0].siren.is_none());
}
#[test]
fn skipping_everything_and_empty_recordings_are_handled() {
let mut app = test_app("skip");
app.wizard_begin();
// Aufnahme ohne Daten → Meldung, kein Ergebnis, Schritt bleibt.
app.wizard_record_start();
app.wizard_record_finish();
let w = app.wizard.as_ref().unwrap();
assert!(w.speech.is_none() && w.message.is_some() && w.step == Step::Speech);
for _ in 0..4 {
app.wizard_next();
}
assert_eq!(app.wizard.as_ref().unwrap().step, Step::Tessitura);
assert_eq!(app.wizard.as_ref().unwrap().tess_suggested, None);
app.wizard_next();
app.wizard_save().unwrap();
let p = &app.profiles[0];
assert!(p.speech.is_none() && p.range.is_none() && p.safe_range.is_none());
}
#[test]
fn profile_drives_chart_transposition_and_warning() {
let mut app = test_app("transpose");
full_run(&mut app, 0);
let base = Arc::new(
NoteChart::load(&Path::new(env!("CARGO_MANIFEST_DIR")).join("charts/test.toml"))
.unwrap(),
);
app.chart_base = Some(base.clone());
app.chart = Some(base.clone());
let profile = app.active_profile().unwrap().clone();
let k = crate::voice::suggest_transpose(&base, &profile).unwrap();
app.set_transpose(k);
let (lo, hi) = profile.tessitura.unwrap();
let median = app.chart.as_ref().unwrap().median_pitch().unwrap();
assert!(
(median - (lo + hi) as f32 / 2.0).abs() <= 0.5,
"{median} vs {lo}..{hi}"
);
assert!(app.chart.as_ref().unwrap().title.contains("HT"));
assert_eq!(
app.chart_base.as_ref().unwrap().title,
base.title,
"Original unverändert"
);
// Warnpassagen: Auf die Spitze getriebene Transponierung liegt außerhalb des sicheren Bereichs.
let safe = profile.safe_range.unwrap();
let shifted = app.chart.clone().unwrap();
let passages = crate::voice::out_of_range_passages(&shifted, safe);
assert!(
passages.len() <= 1,
"nach dem Vorschlag höchstens Randpassagen: {passages:?}"
);
app.set_transpose(20);
let high = crate::voice::out_of_range_passages(app.chart.as_ref().unwrap(), safe);
assert!(!high.is_empty());
app.set_transpose(0);
assert_eq!(app.chart.as_ref().unwrap().notes, base.notes);
}
}