Files
stimmwerk/src/ui/voice_view.rs
wlkns-dev 2d1cae5064 Transponieren verschiebt Musik und Original-Gesang mit
- src/audio/shift.rs: ffmpeg/rubberband rechnet die Tonhöhe um ganze Halbtöne (Dauer bleibt), Ergebnis als FLAC im
  Zwischenspeicher mit Aufräumen bei 3 GB; Gesang mit erhaltenem Klangcharakter
- Hintergrundauftrag mit Entprellung; während des Rechnens sind Singen und Üben gesperrt („Musik wird angepasst …“)
- Auswertung nutzt die verschobene Musik, falls sie noch im Zwischenspeicher liegt
- Tests: Rechnen mit echtem ffmpeg (Länge, Oktave), Schlüssel, Aufräumen, Ersetzen der Pfade, Sperre

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:48:04 +01:00

1952 lines
68 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.

//! Stimmfinder: geführter Assistent (Willkommen → Sprechlage → Legato → Sirene → Haltetöne → Ergebnis) mit
//! Stimmtyp-Einschätzung und Empfehlung. Die Schrittlogik (`wizard_*`) kommt ohne egui aus.
use super::{App, Mode};
use crate::chart::NoteChart;
use crate::config::VoiceConfig;
use crate::pitch::note_name;
use crate::voice::classify::{Classification, Confidence, classify};
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, RichText, Stroke, pos2, vec2};
use std::sync::Arc;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub(super) enum Step {
Intro,
Speech,
Legato,
Siren,
Holds,
Overview,
}
/// Die vier Messschritte in Reihenfolge.
const MEASURE_STEPS: [Step; 4] = [Step::Speech, Step::Legato, Step::Siren, Step::Holds];
impl Step {
fn title(self) -> &'static str {
match self {
Step::Intro => "Willkommen",
Step::Speech => "Sprechstimme",
Step::Legato => "Lange Vokale",
Step::Siren => "Sirene",
Step::Holds => "Einzelne Töne",
Step::Overview => "Ergebnis",
}
}
/// Nummer unter den Messschritten (1–4).
fn measure_number(self) -> Option<usize> {
MEASURE_STEPS.iter().position(|&s| s == self).map(|i| i + 1)
}
fn headline(self) -> &'static str {
match self {
Step::Speech => "Sprich ganz normal",
Step::Legato => "Zieh die Vokale lang",
Step::Siren => "Gleite wie eine Sirene",
Step::Holds => "Halte einzelne Töne",
Step::Intro => "Finde deine Stimme",
Step::Overview => "Dein Ergebnis",
}
}
/// Was zu tun ist, in einfachen Worten.
fn how(self) -> &'static str {
match self {
Step::Speech => {
"Sprich etwa 30 Sekunden so wie im Alltag: zähle bis 20, nenne die Wochentage oder erzähle, \
was du heute gemacht hast. Nicht singen, nicht flüstern."
}
Step::Legato => {
"Sag langsam und ohne abzusetzen „Mmmaaa – weeeiii – geeehhhtt – ooosss“, alles in einem \
Atemzug. Wiederhole es zwei- bis dreimal."
}
Step::Siren => {
"Starte in deiner Mitte und gleite langsam so tief, wie es bequem geht. Dann ganz gleichmäßig \
nach oben bis zum höchsten Ton (Kopfstimme ist erlaubt). Nichts pressen."
}
Step::Holds => {
"Die App spielt dir Halbton für Halbton einen Ton vor. Singe ihn 2–3 Sekunden lang mit, \
mach eine kurze Pause, dann kommt der nächste – von tief nach hoch. Hör auf, sobald es \
anstrengend wird."
}
Step::Intro | Step::Overview => "",
}
}
/// Dauer und Zweck.
fn why(self) -> &'static str {
match self {
Step::Speech => {
"Dauer ca. 30 s (endet von selbst). Daraus lese ich deine natürliche Sprechlage ab."
}
Step::Legato => "Dauer ca. 10 s. Zeigt, wie ruhig und gebunden deine Stimme trägt.",
Step::Siren => {
"Dauer ca. 20 s. Zeigt deinen Stimmumfang und wo die Stimme „umschaltet“."
}
Step::Holds => {
"Dauer ca. 1–2 Minuten. Daraus ergeben sich dein sicherer Bereich und deine Wohlfühllage."
}
Step::Intro | Step::Overview => "",
}
}
/// Was beim Überspringen fehlt.
fn skip_effect(self) -> &'static str {
match self {
Step::Speech => "ohne Sprechlage gibt es keinen Abgleich der Wohlfühllage",
Step::Legato => "ohne Legato-Wert fehlt nur die Bewertung der Bindung",
Step::Siren => "ohne Sirene fehlen Umfang und Registerwechsel",
Step::Holds => "ohne Einzeltöne gibt es keine genaue Wohlfühllage",
Step::Intro | Step::Overview => "",
}
}
fn next(self) -> Step {
match self {
Step::Intro => Step::Speech,
Step::Speech => Step::Legato,
Step::Legato => Step::Siren,
Step::Siren => Step::Holds,
Step::Holds | Step::Overview => Step::Overview,
}
}
fn prev(self) -> Step {
match self {
Step::Intro | Step::Speech => Step::Intro,
Step::Legato => Step::Speech,
Step::Siren => Step::Legato,
Step::Holds => Step::Siren,
Step::Overview => 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,
}
}
}
/// Mindestmenge stimmhafter Daten (Sekunden) für einen Messschritt; `None` = keine Mindestmenge.
pub(super) fn min_voiced_s(step: Step, cfg: &VoiceConfig) -> Option<f32> {
match step {
Step::Speech => Some(cfg.speech_min_voiced_s),
Step::Legato => Some(cfg.legato_min_voiced_s),
Step::Siren => Some(cfg.siren_min_voiced_s),
_ => None,
}
}
/// Erster Zielton der Haltetöne: ein Stück unter der Sprechlage (bequem tief), ohne Sprechlage C3.
pub(super) fn first_hold_target(speech: Option<&SpeechResult>) -> i32 {
speech
.map_or(48, |s| s.median_midi.round() as i32 - 3)
.clamp(36, 72)
}
/// Nächster vorzuspielender Ton: einen Halbton über dem höchsten bisher sicher gehaltenen Ton.
pub(super) fn next_hold_target(holds: &[HoldNote], first: i32) -> i32 {
holds
.iter()
.filter(|h| h.safe)
.map(|h| h.midi + 1)
.max()
.map_or(first, |m| m.max(first))
.min(96)
}
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>,
/// Empfohlene bzw. angepasste Wohlfühllage.
pub tess: (i32, i32),
pub tess_suggested: Option<(i32, i32)>,
pub preview: Option<VoiceProfile>,
pub message: Option<String>,
/// Referenzton spielt bei den Haltetönen automatisch den nächsten Halbton.
pub auto_ref: bool,
/// Der Assistent hat den Referenzton eingeschaltet (und schaltet ihn wieder aus).
pub ref_driven: bool,
/// Seed der simulierten Stimme; wechselt mit jeder Aufnahme.
pub seed: u64,
/// (ID, Zeitstempel) des automatisch gespeicherten Profils dieser Messung.
pub saved: Option<(String, String)>,
}
impl Wizard {
pub fn new() -> Self {
Self {
step: Step::Intro,
rec_t0: None,
speech: None,
legato: None,
siren: None,
holds: Vec::new(),
tess: (55, 63),
tess_suggested: None,
preview: None,
message: None,
auto_ref: true,
ref_driven: false,
seed: 0,
saved: None,
}
}
fn has_result_for(&self, step: Step) -> bool {
match 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 has_result(&self) -> bool {
self.has_result_for(self.step)
}
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(),
_ => {}
}
}
fn profile_preview(&self) -> VoiceProfile {
VoiceProfile::assemble(
String::new(),
String::new(),
self.speech,
self.legato,
self.siren.clone(),
self.holds.clone(),
Some(self.tess),
)
}
}
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()
}
/// Öffnet den Assistenten auf der Willkommensseite.
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);
}
let first = self
.wizard
.as_ref()
.map(|w| first_hold_target(w.speech.as_ref()));
if let Some(w) = self.wizard.as_mut() {
w.rec_t0 = Some(t0);
w.message = None;
w.seed = w.seed.wrapping_add(1);
// Haltetöne: der Referenzton beginnt am ersten Zielton.
if w.step == Step::Holds && w.auto_ref {
w.ref_driven = true;
if let Some(f) = first {
self.ref_midi = f;
}
self.ref_on = true;
}
}
}
/// Schaltet den vom Assistenten gestarteten Referenzton wieder aus.
fn wizard_stop_ref(&mut self) {
if let Some(w) = self.wizard.as_mut()
&& std::mem::take(&mut w.ref_driven)
{
self.ref_on = false;
}
self.apply_reference();
}
/// 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)
}
/// Frames der laufenden Aufnahme (seit Start).
fn wizard_frames(&self) -> Vec<crate::voice::analysis::Frame> {
let Some(t0) = self.wizard.as_ref().and_then(|w| w.rec_t0) else {
return Vec::new();
};
match self.history.lock() {
Ok(h) => frames_from_history(h.since(t0), &self.config.voice),
Err(_) => Vec::new(),
}
}
pub(super) fn wizard_record_finish(&mut self) {
let cfg = self.config.voice.clone();
let frames = self.wizard_frames();
let Some(w) = self.wizard.as_mut() else {
return;
};
if w.rec_t0.take().is_none() {
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(|| {
"Ich habe zu wenig von deiner Stimme gehört. Sprich oder singe etwas lauter, geh näher ans \
Mikrofon und versuch es noch einmal."
.to_string()
});
self.wizard_stop_ref();
}
/// Geht zum nächsten Schritt (auch per „Überspringen“). Nach den Messungen entsteht direkt die Empfehlung.
pub(super) fn wizard_next(&mut self) {
self.wizard_stop_ref();
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();
if w.step == Step::Overview {
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)
});
w.preview = Some(w.profile_preview());
}
if self
.wizard
.as_ref()
.is_some_and(|w| w.step == Step::Overview)
{
self.wizard_autosave();
}
}
/// Einen Schritt zurück (die bisherigen Ergebnisse bleiben erhalten).
pub(super) fn wizard_back(&mut self) {
self.wizard_stop_ref();
if let Some(w) = self.wizard.as_mut() {
w.message = None;
w.rec_t0 = None;
w.step = w.step.prev();
}
}
/// Übernimmt eine angepasste Wohlfühllage in die Vorschau.
pub(super) fn wizard_set_tessitura(&mut self, lo: i32, hi: i32) {
if let Some(w) = self.wizard.as_mut() {
w.tess = (lo, hi.max(lo + 1));
w.preview = Some(w.profile_preview());
}
self.wizard_autosave();
}
/// Speichert die Messung als Profil, sobald das Ergebnis steht, und danach bei jeder Anpassung der Wohlfühllage
/// erneut unter derselben ID. So geht eine fünfminütige Messung nie verloren, auch wenn man den Assistenten
/// einfach verlässt. Frühere Profile bleiben erhalten.
fn wizard_autosave(&mut self) {
let Some(w) = self.wizard.as_mut() else {
return;
};
let Some(mut p) = w.preview.clone() else {
return;
};
let (id, created) = w
.saved
.clone()
.unwrap_or_else(|| voice::new_id(&self.profiles_root));
p.id = id.clone();
p.created = created.clone();
match voice::save(&self.profiles_root, &p) {
Ok(_) => {
w.saved = Some((id, created));
self.refresh_profiles();
self.shown_profile = 0;
}
Err(e) => self.messages = vec![format!("Profil speichern fehlgeschlagen: {e:#}")],
}
}
/// Schließt den Assistenten; das Profil ist bereits gespeichert (Notfalls wird es jetzt gespeichert).
pub(super) fn wizard_save(&mut self) -> Result<(), String> {
if self.wizard.as_ref().is_some_and(|w| w.saved.is_none()) {
self.wizard_autosave();
}
self.wizard = None;
self.refresh_profiles();
self.shown_profile = 0;
Ok(())
}
/// Verwirft die Messung: das automatisch gespeicherte Profil wird wieder gelöscht.
pub(super) fn wizard_discard(&mut self) {
if let Some((id, _)) = self.wizard.as_ref().and_then(|w| w.saved.clone()) {
let _ = std::fs::remove_file(self.profiles_root.join(format!("{id}.json")));
}
self.wizard = None;
self.refresh_profiles();
self.shown_profile = 0;
}
/// Lädt die Charts für die Songliste (einmal; danach aus dem Zwischenspeicher).
fn voice_songs(&mut self) -> &[(String, std::path::PathBuf, Arc<NoteChart>)] {
if self.voice_songs.is_none() {
let list = self
.charts
.iter()
.filter_map(|e| {
NoteChart::load(&e.path)
.ok()
.map(|c| (e.title.clone(), e.path.clone(), Arc::new(c)))
})
.collect();
self.voice_songs = Some(list);
}
self.voice_songs.as_deref().unwrap_or(&[])
}
/// Öffnet einen Song im Reiter „Singen“.
fn open_song(&mut self, path: &std::path::Path) {
self.wizard = None;
self.chart_path_text = path.display().to_string();
self.load_chart();
self.mode = Mode::Chart;
}
/// Ergebnisse links, rechts eine Liste der Songs mit Passung und ausführlicher Begründung. Liefert den Song, der
/// geöffnet werden soll.
fn results_with_songs(
&mut self,
ui: &mut egui::Ui,
p: &VoiceProfile,
) -> Option<std::path::PathBuf> {
let cfg = self.config.voice.clone();
let total = ui.available_width();
let mut open = None;
// Passungen nur neu berechnen, wenn sich Profil oder Lage ändern.
let key = format!("{}|{:?}|{:?}", p.id, p.tessitura, p.safe_range);
let mut cache = self.voice_fits.take().filter(|(k, _)| *k == key);
if cache.is_none() {
let rows = self
.voice_songs()
.iter()
.map(|(title, path, c)| {
let fit = crate::voice::song_fit(c, p);
let lines = fit.as_ref().map(crate::voice::explain).unwrap_or_default();
SongRow {
title: title.clone(),
path: path.clone(),
fit,
lines,
}
})
.collect();
cache = Some((key, rows));
}
let rows: &[SongRow] = cache.as_ref().map_or(&[], |(_, r)| r.as_slice());
// Unter den Spalten stehen noch zwei Einklappbereiche und die Knöpfe: dafür Platz lassen.
let height = (ui.ctx().content_rect().bottom() - ui.next_widget_position().y - 270.0)
.clamp(180.0, 430.0);
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(total * 0.50);
draw_results(ui, p, &cfg);
});
ui.add_space(12.0);
ui.vertical(|ui| {
ui.set_width(total * 0.46);
ui.add_space(4.0);
ui.label(egui::RichText::new("Deine Songs").size(20.0).color(egui::Color32::from_rgb(255, 176, 48)));
ui.weak("So gut passt jeder Song zu deiner Stimme – und warum:");
egui::ScrollArea::vertical().max_height(height).auto_shrink([false, false]).show(ui, |ui| {
if rows.is_empty() {
ui.weak("Keine Songs gefunden.");
}
for row in rows {
ui.add_space(6.0);
ui.label(egui::RichText::new(&row.title).strong().size(16.0));
match &row.fit {
Some(f) => {
let (text, color) = fit_verdict(f);
ui.colored_label(color, egui::RichText::new(text).strong());
for line in &row.lines {
ui.label(egui::RichText::new(line).size(12.5).color(egui::Color32::from_gray(180)));
}
}
None => {
ui.weak("Noch keine Aussage möglich: Es fehlen Haltetöne (Schritt 4), aus denen dein sicherer Bereich bestimmt wird.");
}
}
if ui.small_button("Öffnen ▶").clicked() {
open = Some(row.path.clone());
}
ui.separator();
}
ui.weak("Beim Singen in einer anderen Tonlage wird die Musik mit verschoben (beim ersten Mal einige Sekunden Rechenzeit, danach gespeichert).");
});
});
});
self.voice_fits = cache;
open
}
/// 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);
}
}
}
/// Frequenz einer (kontinuierlichen) MIDI-Zahl.
fn hz_of(m: f32) -> f32 {
440.0 * 2f32.powf((m - 69.0) / 12.0)
}
/// Überschrift und Unterzeile der Stimmtyp-Aussage in einfacher Sprache.
pub(super) fn type_headline(c: &Classification) -> (String, String) {
let head = match (c.confidence, c.runner_up) {
(Confidence::Niedrig, Some(r)) => {
format!("Du liegst zwischen {} und {}", c.best.name(), r.name())
}
(Confidence::Niedrig, None) => format!("Du bist wahrscheinlich ein {}", c.best.name()),
(Confidence::Mittel, _) => format!("Du bist eher ein {}", c.best.name()),
(Confidence::Hoch, _) => format!("Du bist ein {}", c.best.name()),
};
let how_sure = match c.confidence {
Confidence::Hoch => "Die Messung ist eindeutig.",
Confidence::Mittel => "Die Messung deutet klar in diese Richtung.",
Confidence::Niedrig => {
"Das ist eine grobe Einschätzung; die Messung liegt zwischen zwei Typen."
}
};
(
head,
format!("{} ({}). {how_sure}", c.best.name(), c.best.description()),
)
}
/// Ergebnis eines Messschritts in einfacher Sprache.
pub(super) fn step_summary(w: &Wizard, step: Step, cfg: &VoiceConfig) -> Vec<String> {
let n = |m: f32| note_name(m.round() as i32);
match step {
Step::Speech => w
.speech
.iter()
.map(|s| {
format!(
"Deine Sprechstimme liegt bei {} ({:.0} Hz), meist zwischen {} und {}.",
n(s.median_midi),
hz_of(s.median_midi),
n(s.lo_midi),
n(s.hi_midi)
)
})
.collect(),
Step::Legato => w
.legato
.iter()
.flat_map(|l| {
let quality = if l.ratio >= 0.9 {
"sehr gut gebunden"
} else if l.ratio >= 0.75 {
"gut gebunden"
} else {
"eher abgehackt – das ist normal, wenn du zwischendurch absetzt"
};
[
format!(
"{:.0} % deiner Stimme waren ohne Lücke: {quality}.",
l.ratio * 100.0
),
format!("Längster Zug: {:.1} Sekunden.", l.longest_run_s),
]
})
.collect(),
Step::Siren => w
.siren
.iter()
.flat_map(|s| {
let mut v = vec![format!(
"Dein Umfang reicht von {} bis {} (etwa {:.0} Halbtöne).",
n(s.min_midi),
n(s.max_midi),
s.max_midi - s.min_midi
)];
if s.transitions.is_empty() {
v.push("Kein deutlicher Registerwechsel erkannt – sehr gleichmäßig.".into());
} else {
let list: Vec<String> = s
.transitions
.iter()
.map(|t| {
format!(
"{} ({})",
n(t.midi),
match t.kind {
TransitionKind::Jump => "Sprung",
TransitionKind::Instability => "unruhig",
}
)
})
.collect();
v.push(format!("Die Stimme schaltet um bei: {}.", list.join(", ")));
}
v
})
.collect(),
Step::Holds => {
if w.holds.is_empty() {
return Vec::new();
}
let safe: Vec<&HoldNote> = w.holds.iter().filter(|h| h.safe).collect();
let mut v = vec![format!(
"{} Töne gehört, davon {} stabil.",
w.holds.len(),
safe.len()
)];
if let (Some(lo), Some(hi)) = (
safe.iter().map(|h| h.midi).min(),
safe.iter().map(|h| h.midi).max(),
) {
v.push(format!(
"Stabil klingst du von {} bis {}.",
note_name(lo),
note_name(hi)
));
} else {
v.push(format!(
"Kein Ton war stabil genug (unter {:.0} Cent Schwankung) – versuch es ruhiger.",
cfg.hold_stable_cents
));
}
v
}
_ => Vec::new(),
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum StepState {
Current,
Done,
Skipped,
Pending,
}
fn step_state(w: &Wizard, s: Step) -> StepState {
if w.step == s {
StepState::Current
} else if w.has_result_for(s) {
StepState::Done
} else if s < w.step {
StepState::Skipped
} else {
StepState::Pending
}
}
/// Fortschrittsband: ein Kreis je Schritt (✓ erledigt, Zahl = aktuell/offen, – übersprungen).
fn draw_stepper(ui: &mut egui::Ui, w: &Wizard) {
const STEPS: [Step; 5] = [
Step::Speech,
Step::Legato,
Step::Siren,
Step::Holds,
Step::Overview,
];
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 54.0), egui::Sense::hover());
let painter = ui.painter_at(rect);
let cell = rect.width() / STEPS.len() as f32;
let cy = rect.top() + 18.0;
for i in 0..STEPS.len() - 1 {
let (a, b) = (
rect.left() + (i as f32 + 0.5) * cell,
rect.left() + (i as f32 + 1.5) * cell,
);
painter.line_segment(
[pos2(a + 16.0, cy), pos2(b - 16.0, cy)],
Stroke::new(2.0, Color32::from_gray(70)),
);
}
for (i, &s) in STEPS.iter().enumerate() {
let cx = rect.left() + (i as f32 + 0.5) * cell;
let (fill, text, color) = match step_state(w, s) {
StepState::Done => (
Color32::from_rgb(70, 170, 110),
"✓".to_string(),
Color32::WHITE,
),
StepState::Current => (
Color32::from_rgb(70, 130, 230),
format!("{}", i + 1),
Color32::WHITE,
),
StepState::Skipped => (
Color32::from_gray(75),
"–".to_string(),
Color32::from_gray(200),
),
StepState::Pending => (
Color32::from_gray(45),
format!("{}", i + 1),
Color32::from_gray(150),
),
};
painter.circle_filled(pos2(cx, cy), 15.0, fill);
painter.text(
pos2(cx, cy),
Align2::CENTER_CENTER,
text,
FontId::proportional(15.0),
color,
);
painter.text(
pos2(cx, cy + 27.0),
Align2::CENTER_CENTER,
s.title(),
FontId::proportional(13.0),
if w.step == s {
Color32::WHITE
} else {
Color32::from_gray(160)
},
);
}
}
/// Große Hauptschaltfläche.
fn primary_button(ui: &mut egui::Ui, text: &str, enabled: bool) -> egui::Response {
super::gear::accent_button(ui, text, 17.0, enabled)
}
fn intro_card(ui: &mut egui::Ui) {
ui.label(
RichText::new("Finde heraus, wo deine Stimme zu Hause ist")
.size(20.0)
.strong(),
);
ui.add_space(4.0);
ui.label(
RichText::new(
"In etwa 5 Minuten messe ich vier Dinge und sage dir am Ende, welcher Stimmtyp du bist (Bass, Bariton, \
Tenor, Alt, Mezzosopran oder Sopran) und in welchem Bereich du am bequemsten singst. Songs lassen sich \
danach passend für dich anpassen.",
)
.size(16.0)
.color(Color32::from_gray(225)),
);
ui.add_space(6.0);
ui.label("So läuft es ab:");
for l in [
"1 Sprechstimme – du sprichst kurz ganz normal",
"2 Lange Vokale – du ziehst Laute in einem Atemzug",
"3 Sirene – du gleitest tief und hoch",
"4 Einzelne Töne – du singst vorgespielte Töne mit",
] {
ui.label(format!(" {l}"));
}
ui.add_space(6.0);
ui.label(
RichText::new("Du brauchst: ein funktionierendes Mikrofon, Kopfhörer (damit der vorgespielte Ton nicht ins Mikro läuft) und einen ruhigen Raum.")
.color(Color32::from_gray(190)),
);
}
impl App {
fn profile_ui(&mut self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
ui.heading("Stimmfinder");
let label = if self.profiles.is_empty() {
"▶ Messung starten"
} else {
"▶ Neue Messung starten"
};
if primary_button(ui, label, true).clicked() {
self.wizard_begin();
}
});
let Some(p) = self.profiles.get(self.shown_profile).cloned() else {
ui.add_space(6.0);
intro_card(ui);
return;
};
ui.label(format!(
"Messung vom {}{}",
p.created,
if self.shown_profile == 0 {
" (aktiv)"
} else {
""
}
));
let open = self.results_with_songs(ui, &p);
egui::CollapsingHeader::new("Alle Messwerte")
.show(ui, |ui| profile_details(ui, &p, &self.config.voice));
if let Some(path) = open {
self.open_song(&path);
}
ui.separator();
ui.strong("Verlauf der Messungen");
let mut show = None;
egui::Grid::new("profiles").striped(true).show(ui, |ui| {
for h in [
"Datum",
"Stimmtyp",
"Sprechlage",
"Umfang",
"Wohlfühllage",
"",
] {
ui.strong(h);
}
ui.end_row();
for (i, q) in self.profiles.iter().enumerate() {
ui.label(&q.created);
ui.label(classify(q).map_or("–", |c| c.best.name()));
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.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 Some(w) = self.wizard.as_ref() else {
return;
};
let step = w.step;
ui.horizontal(|ui| {
ui.heading("Stimmfinder");
if ui
.button("✕ Abbrechen")
.on_hover_text("Verwirft diese Messung")
.clicked()
{
self.wizard_stop_ref();
self.wizard = None;
}
});
if self.wizard.is_none() {
return;
}
if let Some(w) = self.wizard.as_ref() {
draw_stepper(ui, w);
}
ui.add_space(4.0);
match step {
Step::Intro => {
intro_card(ui);
ui.add_space(8.0);
if primary_button(ui, "Los geht’s ▶", true).clicked() {
self.wizard_next();
}
}
Step::Overview => self.wizard_overview(ui),
_ => self.wizard_measure(ui, step),
}
}
/// Ein Messschritt: Anleitung, Live-Rückmeldung, Bedienung, Ergebnis in einfacher Sprache.
fn wizard_measure(&mut self, ui: &mut egui::Ui, step: Step) {
let cfg = self.config.voice.clone();
let (recording, has_result, message, auto_ref) = {
let w = self.wizard.as_ref().expect("Assistent aktiv");
(
w.rec_t0.is_some(),
w.has_result(),
w.message.clone(),
w.auto_ref,
)
};
let n = step.measure_number().unwrap_or(0);
ui.label(
RichText::new(format!("Schritt {n} von 4: {}", step.headline()))
.size(20.0)
.strong(),
);
ui.label(
RichText::new(step.how())
.size(17.0)
.color(Color32::from_gray(230)),
);
ui.label(RichText::new(step.why()).color(Color32::from_gray(170)));
ui.add_space(4.0);
// Live-Kurve und Rückmeldung, ob das Mikrofon dich hört.
let est = self.roll_view(ui, 340.0);
let level_ok = self.peak_db > -48.0 || self.sim_start.is_some();
let hearing = est.is_some();
{
use super::roll::{PitchCard, USER_COLOR, draw_pitch_cards};
let gray = Color32::from_gray(170);
let du = PitchCard {
title: "Du (live)".into(),
color: USER_COLOR,
midi: est.map(|e| e.midi),
big: None,
lines: est.map_or_else(Vec::new, |e| {
vec![
(format!("{:.1} Hz", e.freq_hz), gray),
(format!("{:+.0} Cent", e.cents), gray),
]
}),
level: None,
meter: est.map(|e| e.cents),
};
let (status, color) = if !level_ok {
("leise", Color32::from_rgb(240, 130, 60))
} else if hearing {
("✓ ich höre dich", Color32::from_rgb(90, 210, 120))
} else {
("bereit", Color32::from_gray(200))
};
let mic = PitchCard {
title: "Mikrofon".into(),
color,
midi: Some(60.0),
big: Some(status.to_string()),
lines: vec![(format!("Pegel {:.0} dB", self.peak_db.max(-60.0)), gray)],
level: Some(((self.peak_db + 60.0) / 60.0).clamp(0.0, 1.0)),
meter: None,
};
draw_pitch_cards(ui, &[du, mic]);
if !level_ok && recording {
ui.colored_label(
Color32::from_rgb(240, 130, 60),
"Ich höre dich kaum: sprich oder singe lauter, geh näher ans Mikrofon oder prüfe in den Audio-Einstellungen den Eingang.",
);
}
}
if recording {
self.wizard_recording_panel(ui, step, &cfg, auto_ref);
} else if has_result {
let lines = self
.wizard
.as_ref()
.map(|w| step_summary(w, step, &cfg))
.unwrap_or_default();
ui.add_space(4.0);
ui.group(|ui| {
ui.label(RichText::new("Das habe ich gehört:").strong());
for l in &lines {
ui.label(format!("• {l}"));
}
});
ui.horizontal(|ui| {
if ui.button("◀ Zurück").clicked() {
self.wizard_back();
}
if ui.button("↻ Nochmal").clicked()
&& let Some(w) = self.wizard.as_mut()
{
w.clear_result();
}
if primary_button(ui, "Weiter ▶", true).clicked() {
self.wizard_next();
}
});
} else {
ui.add_space(4.0);
ui.horizontal(|ui| {
if ui.button("◀ Zurück").clicked() {
self.wizard_back();
}
if primary_button(ui, "● Aufnahme starten", true).clicked() {
self.wizard_record_start();
}
if ui
.button("Überspringen")
.on_hover_text(format!("Wenn du überspringst: {}.", step.skip_effect()))
.clicked()
{
self.wizard_next();
}
});
}
if let Some(m) = message {
ui.colored_label(Color32::from_rgb(240, 130, 60), m);
}
}
/// Während der Aufnahme: Fortschritt, Mindestmenge, bei Haltetönen Zielton und erkannte Töne.
fn wizard_recording_panel(
&mut self,
ui: &mut egui::Ui,
step: Step,
cfg: &VoiceConfig,
auto_ref: bool,
) {
let elapsed = self.wizard_elapsed().unwrap_or(0.0);
let frames = self.wizard_frames();
let hop = 0.01;
let voiced_s = frames.iter().filter(|f| f.midi.is_some()).count() as f32 * hop;
let need = min_voiced_s(step, cfg);
let enough = need.is_none_or(|n| voiced_s >= n);
ui.add_space(4.0);
if step == Step::Speech {
let total = cfg.speech_duration_s;
ui.add(
egui::ProgressBar::new((elapsed / total).clamp(0.0, 1.0) as f32)
.desired_width(ui.available_width())
.text(format!("{:.0} s von {:.0} s", elapsed, total)),
);
if elapsed >= total {
self.wizard_record_finish();
return;
}
} else {
ui.label(format!("Aufnahme läuft … {elapsed:.0} s"));
}
if let Some(n) = need {
let color = if enough {
Color32::from_rgb(90, 210, 120)
} else {
Color32::from_gray(200)
};
ui.colored_label(
color,
format!(
"{} Gehört: {voiced_s:.1} s (mindestens {n:.0} s nötig)",
if enough { "✓" } else { "…" }
),
);
}
if step == Step::Holds {
let live = analyze_holds(&frames, cfg);
let first = first_hold_target(self.wizard.as_ref().and_then(|w| w.speech.as_ref()));
let target = next_hold_target(&live, first);
if auto_ref {
self.ref_midi = target;
self.ref_on = true;
}
ui.label(
RichText::new(format!("Jetzt singen: {}", note_name(target)))
.size(22.0)
.strong(),
);
ui.horizontal_wrapped(|ui| {
ui.label("Erkannt:");
if live.is_empty() {
ui.weak("noch nichts – halte einen Ton 2–3 Sekunden");
}
for h in &live {
let text = format!("{} {}", note_name(h.midi), if h.safe { "✓" } else { "✗" });
let rt = RichText::new(text).monospace();
ui.label(if h.safe {
rt.color(Color32::from_rgb(90, 210, 120))
} else {
rt.color(Color32::from_rgb(240, 150, 60))
})
.on_hover_text(if h.safe {
format!("stabil (±{:.0} Cent)", h.std_cents)
} else {
format!("zu unruhig (±{:.0} Cent) – ruhiger halten", h.std_cents)
});
}
});
let mut auto = auto_ref;
if ui
.checkbox(&mut auto, "Nächsten Ton automatisch vorspielen")
.changed()
{
if let Some(w) = self.wizard.as_mut() {
w.auto_ref = auto;
}
if !auto {
self.ref_on = false;
}
}
self.apply_reference();
}
ui.add_space(4.0);
ui.horizontal(|ui| {
if primary_button(ui, "■ Fertig", enough).clicked() {
self.wizard_record_finish();
}
if !enough {
ui.weak("Sobald genug Stimme erkannt ist, kannst du beenden.");
}
});
}
/// Ergebnis: Stimmtyp, Empfehlung, Klaviatur; Anpassen und Details einklappbar.
fn wizard_overview(&mut self, ui: &mut egui::Ui) {
let cfg = self.config.voice.clone();
let Some(p) = self.wizard.as_ref().and_then(|w| w.preview.clone()) else {
return;
};
ui.colored_label(
egui::Color32::from_rgb(110, 200, 130),
"✓ Dein Profil ist gespeichert – auch wenn du den Assistenten jetzt verlässt.",
);
let open = self.results_with_songs(ui, &p);
let (mut lo, mut hi) = self.wizard.as_ref().map_or((55, 63), |w| w.tess);
egui::CollapsingHeader::new("Wohlfühllage anpassen (optional)").show(ui, |ui| {
ui.weak("Die Empfehlung kommt aus deinen stabilsten Tönen. Ändere sie nur, wenn du dich woanders wohler fühlst.");
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)));
});
});
if self
.wizard
.as_ref()
.is_some_and(|w| w.tess != (lo, hi.max(lo + 1)))
{
self.wizard_set_tessitura(lo, hi);
}
egui::CollapsingHeader::new("Alle Messwerte").show(ui, |ui| profile_details(ui, &p, &cfg));
ui.add_space(8.0);
ui.horizontal(|ui| {
if ui.button("◀ Zurück").clicked() {
self.wizard_back();
}
if primary_button(ui, "✔ Fertig – weiter zu den Songs ▶", true).clicked() {
let _ = self.wizard_save();
self.messages = vec!["Stimmprofil gespeichert".into()];
self.mode = Mode::Chart;
}
if ui.button("Neu messen").clicked() {
self.wizard = Some(Wizard::new());
}
if ui
.button("Verwerfen")
.on_hover_text("Löscht diese Messung wieder")
.clicked()
{
self.wizard_discard();
}
});
if let Some(path) = open {
let _ = self.wizard_save();
self.open_song(&path);
}
}
}
/// Ein Song mit Passung zum Profil und fertig formulierter Begründung.
pub(super) struct SongRow {
title: String,
path: std::path::PathBuf,
fit: Option<crate::voice::SongFit>,
lines: Vec<String>,
}
/// Kurzurteil zur Passung eines Songs in einfachen Worten.
fn fit_verdict(f: &crate::voice::SongFit) -> (String, egui::Color32) {
let green = egui::Color32::from_rgb(110, 200, 130);
let amber = egui::Color32::from_rgb(255, 176, 48);
let red = egui::Color32::from_rgb(230, 120, 60);
let pct = |x: f32| (x * 100.0).round() as i32;
if f.shift.abs() <= 1 && f.outside_now() <= 0.05 {
("✓ passt so, wie er ist".into(), green)
} else if f.outside_shifted() <= 0.05 {
let dir = if f.shift < 0 { "tiefer" } else { "höher" };
(
format!("passt mit {} Halbtönen {dir}", f.shift.abs()),
amber,
)
} else {
(
format!(
"schwierig: auch angepasst {} % außerhalb deines sicheren Bereichs",
pct(f.outside_shifted())
),
red,
)
}
}
/// Stimmtyp-Aussage, Wohlfühllage-Empfehlung und Klaviatur.
fn draw_results(ui: &mut egui::Ui, p: &VoiceProfile, cfg: &VoiceConfig) {
ui.add_space(4.0);
match classify(p) {
Some(c) => {
let (head, sub) = type_headline(&c);
ui.label(
RichText::new(head)
.size(30.0)
.strong()
.color(Color32::from_rgb(120, 190, 255)),
);
ui.label(RichText::new(sub).size(15.0));
ui.weak(&c.explanation);
}
None => {
ui.label(
RichText::new("Für eine Einschätzung fehlen Messwerte")
.size(20.0)
.strong(),
);
ui.weak("Wiederhole die Messung und löse mindestens die Sirene oder die Einzeltöne.");
}
}
ui.add_space(6.0);
if let Some((a, b)) = p.tessitura {
ui.label(
RichText::new(format!(
"Deine Wohlfühllage: {} bis {}",
note_name(a),
note_name(b)
))
.size(20.0)
.strong()
.color(Color32::from_rgb(240, 190, 80)),
);
ui.label(
"Hier klingt deine Stimme am stabilsten. Songs transponiere ich so, dass die Melodie in diesem Bereich liegt.",
);
}
if let Some((a, b)) = p.range {
ui.label(format!(
"Dein Stimmumfang: {} bis {} (etwa {:.0} Halbtöne, {:.1} Oktaven).",
note_name(a.round() as i32),
note_name(b.round() as i32),
b - a,
(b - a) / 12.0
));
}
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}"));
}
ui.add_space(4.0);
draw_keyboard(ui, p);
ui.weak("Gelb = Wohlfühllage, Grün = sichere Töne, Blau = Umfang, Lila = Sprechlage, Punkte = Registerwechsel.");
}
/// Alle Messwerte als Text (für Neugierige).
fn profile_details(ui: &mut egui::Ui, p: &VoiceProfile, cfg: &VoiceConfig) {
let _ = cfg;
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),
hz_of(s.median_midi),
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!(
"Wohlfühllage (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 !p.holds.is_empty() {
egui::ScrollArea::vertical()
.max_height(140.0)
.show(ui, |ui| {
egui::Grid::new("holds_detail")
.striped(true)
.show(ui, |ui| {
for h in ["Ton", "Schwankung", "Konfidenz", "Dauer", "stabil"] {
ui.strong(h);
}
ui.end_row();
for h in &p.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, Wohlfühllage, Sprechlage und Übergänge.
fn draw_keyboard(ui: &mut egui::Ui, p: &VoiceProfile) {
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),
"Wohlfühllage",
);
}
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),
);
}
}
}
#[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, None);
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();
assert_eq!(
app.wizard.as_ref().unwrap().step,
Step::Intro,
"Start mit der Willkommensseite"
);
app.wizard_next();
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();
}
// Nach dem letzten Messschritt steht die Empfehlung direkt im Ergebnis – keine Auswahl nötig.
let w = app.wizard.as_ref().unwrap();
assert_eq!(w.step, Step::Overview);
assert!(w.tess_suggested.is_some());
assert_eq!(
Some(w.tess),
w.tess_suggested,
"Empfehlung ist vorausgewählt"
);
assert_eq!(w.preview.as_ref().unwrap().tessitura, Some(w.tess));
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();
app.wizard_next();
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(); // → Ergebnis mit Empfehlung
assert_eq!(app.wizard.as_ref().unwrap().step, Step::Overview);
app.wizard_set_tessitura(50, 58); // optional per Regler angepasst
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();
app.wizard_next();
// 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::Overview);
assert_eq!(app.wizard.as_ref().unwrap().tess_suggested, None);
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);
}
#[test]
fn back_keeps_results_and_never_leaves_the_intro() {
let mut app = test_app("back");
app.wizard_begin();
app.wizard_back();
assert_eq!(
app.wizard.as_ref().unwrap().step,
Step::Intro,
"vor dem Start gibt es nichts zurück"
);
app.wizard_next();
feed(&mut app, SimStep::Speech);
app.wizard_next();
assert_eq!(app.wizard.as_ref().unwrap().step, Step::Legato);
app.wizard_back();
let w = app.wizard.as_ref().unwrap();
assert_eq!(w.step, Step::Speech);
assert!(
w.speech.is_some(),
"Ergebnis bleibt beim Zurückgehen erhalten"
);
assert!(step_summary(w, Step::Speech, &VoiceConfig::default())[0].contains("Sprechstimme"));
}
#[test]
fn stepper_states_reflect_progress() {
let mut app = test_app("stepper");
app.wizard_begin();
app.wizard_next();
feed(&mut app, SimStep::Speech);
app.wizard_next(); // Legato übersprungen:
app.wizard_next();
let w = app.wizard.as_ref().unwrap();
assert_eq!(w.step, Step::Siren);
assert!(step_state(w, Step::Speech) == StepState::Done);
assert!(step_state(w, Step::Legato) == StepState::Skipped);
assert!(step_state(w, Step::Siren) == StepState::Current);
assert!(step_state(w, Step::Holds) == StepState::Pending);
}
#[test]
fn plain_language_summaries_and_type_headline() {
let mut app = test_app("texts");
full_run(&mut app, 0);
let p = app.profiles[0].clone();
let c = classify(&p).expect("Stimmtyp");
let (head, sub) = type_headline(&c);
assert!(
head.starts_with("Du ") && head.contains(c.best.name()),
"{head}"
);
assert!(sub.contains(c.best.description()), "{sub}");
// Alle Messschritte liefern verständliche Sätze.
let mut w = Wizard::new();
w.speech = p.speech;
w.legato = p.legato;
w.siren = p.siren.clone();
w.holds = p.holds.clone();
let cfg = VoiceConfig::default();
for step in MEASURE_STEPS {
let lines = step_summary(&w, step, &cfg);
assert!(!lines.is_empty(), "{step:?}");
assert!(lines.iter().all(|l| l.len() > 15), "{lines:?}");
}
assert!(step_summary(&w, Step::Legato, &cfg)[0].contains("gebunden"));
assert!(
step_summary(&w, Step::Siren, &cfg)
.iter()
.any(|l| l.contains("schaltet um"))
);
// Ohne Daten keine Sätze.
assert!(step_summary(&Wizard::new(), Step::Holds, &cfg).is_empty());
}
#[test]
fn headline_wording_follows_confidence() {
use crate::voice::classify::VoiceType;
let mk = |confidence, runner_up| Classification {
best: VoiceType::Bariton,
runner_up,
confidence,
center: 55.0,
explanation: String::new(),
};
assert_eq!(
type_headline(&mk(Confidence::Hoch, None)).0,
"Du bist ein Bariton"
);
assert_eq!(
type_headline(&mk(Confidence::Mittel, None)).0,
"Du bist eher ein Bariton"
);
assert_eq!(
type_headline(&mk(Confidence::Niedrig, Some(VoiceType::Tenor))).0,
"Du liegst zwischen Bariton und Tenor"
);
assert_eq!(
type_headline(&mk(Confidence::Niedrig, None)).0,
"Du bist wahrscheinlich ein Bariton"
);
}
#[test]
fn hold_targets_climb_semitone_by_semitone() {
let hold = |midi, safe| HoldNote {
midi,
mean_midi: midi as f32,
std_cents: 10.0,
mean_conf: 0.95,
duration_s: 2.5,
voiced_ratio: 1.0,
safe,
};
assert_eq!(first_hold_target(None), 48);
let sp = SpeechResult {
median_midi: 52.0,
lo_midi: 50.0,
hi_midi: 54.0,
voiced_s: 20.0,
};
assert_eq!(
first_hold_target(Some(&sp)),
49,
"ein Stück unter der Sprechlage"
);
assert_eq!(next_hold_target(&[], 49), 49);
assert_eq!(next_hold_target(&[hold(49, true), hold(50, true)], 49), 51);
assert_eq!(
next_hold_target(&[hold(49, true), hold(50, false)], 49),
50,
"unsichere Töne zählen nicht"
);
assert_eq!(
next_hold_target(&[hold(30, true)], 49),
49,
"nie unter den Start"
);
let cfg = VoiceConfig::default();
assert_eq!(
min_voiced_s(Step::Speech, &cfg),
Some(cfg.speech_min_voiced_s)
);
assert_eq!(min_voiced_s(Step::Holds, &cfg), None);
}
#[test]
fn recording_holds_starts_and_stops_the_reference_tone() {
let mut app = test_app("reftone");
app.wizard_begin();
app.wizard_next();
while app.wizard.as_ref().unwrap().step != Step::Holds {
app.wizard_next();
}
app.wizard_record_start();
assert!(app.ref_on, "Referenzton läuft während der Haltetöne");
assert!(app.wizard.as_ref().unwrap().ref_driven);
app.wizard_record_finish();
assert!(!app.ref_on, "danach wieder aus");
// Wer den Ton selbst eingeschaltet hat, behält ihn.
app.ref_on = true;
app.wizard.as_mut().unwrap().auto_ref = false;
app.wizard_record_start();
app.wizard_record_finish();
assert!(app.ref_on);
}
}