forked from wlkns-dev/stimmwerk
Stimmfinder: automatisch speichern, Songliste mit Begründung; Sänger-Regler; README
- Profil wird beim Ergebnis automatisch gespeichert (und bei jeder Anpassung erneut); Verwerfen löscht es - Ergebnisseite mit „Deine Songs“: Passung je Song mit ausführlicher Begründung (Melodie, Stimme, zu tief/zu hoch, Verschiebung, betroffene Stellen) - Mischpult: eigener Lautstärkeregler für den Original-Sänger - README: Kopf aktualisiert, Übersicht über Ordner und Werkzeuge Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@ -1459,13 +1459,15 @@ impl App {
|
||||
bar(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
knob_sized(ui, &mut self.gain_backing, (0.0, 1.0), 0.8, "Musik", pct, chart.backing.is_some(), K);
|
||||
knob_sized(ui, &mut self.gain_original, (0.0, 1.0), 0.6, "Sänger", pct, chart.vocals.is_some(), K)
|
||||
.on_hover_text("Lautstärke des Original-Sängers (Schalter „Original-Sänger“ rechts). Ganz herunter = nur die Musik.");
|
||||
knob_sized(ui, &mut self.gain_guide, (0.0, 1.0), default_guide, "Zieltöne", pct, true, K)
|
||||
.on_hover_text("Spielt die Zieltöne als Piepton mit – hilfreich zum Üben.");
|
||||
knob_sized(ui, &mut self.metro.volume, (0.0, 1.0), 0.5, "Metronom", pct, true, K)
|
||||
.on_hover_text("Lautstärke des Metronoms (Schalter rechts)");
|
||||
knob_sized(ui, &mut self.gain_monitor, (0.0, 1.0), 0.0, "Eigene Stimme", pct, true, K)
|
||||
.on_hover_text("Hört dich selbst im Kopfhörer. Besser am Audiogerät einstellen (geringere Verzögerung).");
|
||||
ui.add_space(14.0);
|
||||
knob_sized(ui, &mut self.gain_monitor, (0.0, 1.0), 0.0, "Stimme", pct, true, K)
|
||||
.on_hover_text("Eigene Stimme: hört dich selbst im Kopfhörer. Besser am Audiogerät einstellen (geringere Verzögerung).");
|
||||
ui.add_space(6.0);
|
||||
ui.vertical(|ui| {
|
||||
toggle(ui, &mut self.original_on, "Original-Sänger", chart.vocals.is_some())
|
||||
.on_hover_text("Den Original-Gesang zur Musik mithören");
|
||||
@ -1474,7 +1476,7 @@ impl App {
|
||||
toggle(ui, &mut self.show_grid, "Taktstriche", chart.effective_grid().is_some())
|
||||
.on_hover_text("Taktstriche und Zählzeiten im Notenfeld zeigen");
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
ui.add_space(4.0);
|
||||
ui.vertical(|ui| {
|
||||
toggle(ui, &mut self.show_chords, "Akkorde", !chart.chords.is_empty())
|
||||
.on_hover_text("Akkorde der Begleitung über dem Notenfeld und als Karte zeigen");
|
||||
@ -1499,7 +1501,7 @@ impl App {
|
||||
store_f32(
|
||||
&s.gain_vocals,
|
||||
if self.original_on {
|
||||
self.gain_backing.max(0.5)
|
||||
self.gain_original
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
|
||||
@ -89,6 +89,8 @@ pub struct App {
|
||||
session_sim_t0: f64,
|
||||
gain_backing: f32,
|
||||
original_on: bool,
|
||||
/// Lautstärke des Original-Sängers (wirkt, solange „Original-Sänger“ eingeschaltet ist).
|
||||
gain_original: f32,
|
||||
gain_guide: f32,
|
||||
gain_monitor: f32,
|
||||
/// Laufende, noch nicht gespeicherte Session (Ordner, ID).
|
||||
@ -129,6 +131,10 @@ pub struct App {
|
||||
grid_dirty: bool,
|
||||
/// Fenster „Mehr“ (Song laden, Takt-Raster) offen.
|
||||
tools_open: bool,
|
||||
/// Geladene Charts für die Songliste im Stimmfinder (einmal geladen, dann zwischengespeichert).
|
||||
voice_songs: Option<Vec<(String, std::path::PathBuf, Arc<NoteChart>)>>,
|
||||
/// Berechnete Song-Passungen zum zuletzt gezeigten Profil (Schlüssel: Profil und Lage).
|
||||
voice_fits: Option<(String, Vec<voice_view::SongRow>)>,
|
||||
/// Ergebnisfenster nach dem Singen offen.
|
||||
result_open: bool,
|
||||
calib_wav: std::path::PathBuf,
|
||||
@ -179,6 +185,7 @@ impl App {
|
||||
session_sim_t0: 0.0,
|
||||
gain_backing: 0.8,
|
||||
original_on: false,
|
||||
gain_original: 0.6,
|
||||
gain_monitor: 0.0,
|
||||
pending_save: None,
|
||||
sessions_root: crate::review::sessions_dir(),
|
||||
@ -203,6 +210,8 @@ impl App {
|
||||
show_grid: true,
|
||||
grid_dirty: false,
|
||||
tools_open: false,
|
||||
voice_songs: None,
|
||||
voice_fits: None,
|
||||
result_open: true,
|
||||
calib_wav: calib_view::default_wav_path(),
|
||||
config_path: Config::path(),
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
//! 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;
|
||||
use super::{App, Mode};
|
||||
use crate::chart::NoteChart;
|
||||
use crate::config::VoiceConfig;
|
||||
use crate::pitch::note_name;
|
||||
use crate::voice::classify::{Classification, Confidence, classify};
|
||||
@ -12,6 +13,7 @@ use crate::voice::{
|
||||
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 {
|
||||
@ -184,6 +186,8 @@ pub(super) struct Wizard {
|
||||
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 {
|
||||
@ -202,6 +206,7 @@ impl Wizard {
|
||||
auto_ref: true,
|
||||
ref_driven: false,
|
||||
seed: 0,
|
||||
saved: None,
|
||||
}
|
||||
}
|
||||
|
||||
@ -369,6 +374,13 @@ impl App {
|
||||
});
|
||||
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).
|
||||
@ -387,26 +399,158 @@ impl App {
|
||||
w.tess = (lo, hi.max(lo + 1));
|
||||
w.preview = Some(w.profile_preview());
|
||||
}
|
||||
self.wizard_autosave();
|
||||
}
|
||||
|
||||
/// Speichert die Messung als neues Profil; frühere bleiben erhalten.
|
||||
pub(super) fn wizard_save(&mut self) -> Result<(), String> {
|
||||
/// 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 Ok(());
|
||||
return;
|
||||
};
|
||||
let Some(mut p) = w.preview.clone() else {
|
||||
return Ok(());
|
||||
return;
|
||||
};
|
||||
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:#}"))?;
|
||||
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("Hinweis: Beim Transponieren bleibt die Musik in der Originaltonart; verschoben werden die Zieltöne und die Wertung.");
|
||||
});
|
||||
});
|
||||
});
|
||||
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()?;
|
||||
@ -705,9 +849,12 @@ impl App {
|
||||
""
|
||||
}
|
||||
));
|
||||
draw_results(ui, &p, &self.config.voice);
|
||||
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;
|
||||
@ -1019,7 +1166,11 @@ impl App {
|
||||
let Some(p) = self.wizard.as_ref().and_then(|w| w.preview.clone()) else {
|
||||
return;
|
||||
};
|
||||
draw_results(ui, &p, &cfg);
|
||||
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.");
|
||||
@ -1043,16 +1194,59 @@ impl App {
|
||||
if ui.button("◀ Zurück").clicked() {
|
||||
self.wizard_back();
|
||||
}
|
||||
if primary_button(ui, "✔ Profil speichern", true).clicked() {
|
||||
self.messages = match self.wizard_save() {
|
||||
Ok(()) => vec!["Stimmprofil gespeichert".into()],
|
||||
Err(e) => vec![format!("Profil speichern fehlgeschlagen: {e}")],
|
||||
};
|
||||
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("Verwerfen").clicked() {
|
||||
self.wizard = None;
|
||||
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,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -10,7 +10,7 @@ pub use analysis::{
|
||||
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};
|
||||
pub use transpose::{SongFit, explain, out_of_range_passages, song_fit, suggest_transpose};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@ -14,9 +14,15 @@ pub fn suggest_transpose(chart: &NoteChart, profile: &VoiceProfile) -> Option<i3
|
||||
/// 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)> {
|
||||
passages_shifted(chart, safe, 0)
|
||||
}
|
||||
|
||||
/// Wie [`out_of_range_passages`], nachdem der Song um `shift` Halbtöne verschoben wurde.
|
||||
pub fn passages_shifted(chart: &NoteChart, safe: (i32, i32), shift: 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 {
|
||||
let m = n.midi_pitch + shift;
|
||||
if m < safe.0 || m > 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())),
|
||||
@ -26,6 +32,210 @@ pub fn out_of_range_passages(chart: &NoteChart, safe: (i32, i32)) -> Vec<(f64, f
|
||||
out
|
||||
}
|
||||
|
||||
/// Wie gut ein Song zu einem Profil passt, mit allen Zahlen, die für eine Begründung nötig sind.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct SongFit {
|
||||
/// Empfohlene Verschiebung in Halbtönen (Melodie-Median in die Mitte der Wohlfühllage).
|
||||
pub shift: i32,
|
||||
/// Tiefster und höchster Melodieton und Median (dauergewichtet).
|
||||
pub lowest: i32,
|
||||
pub highest: i32,
|
||||
pub median: f32,
|
||||
/// Anteil der Notendauer (0–1) zu tief bzw. zu hoch für den sicheren Bereich, ohne und mit Verschiebung.
|
||||
pub low_now: f32,
|
||||
pub high_now: f32,
|
||||
pub low_shifted: f32,
|
||||
pub high_shifted: f32,
|
||||
pub safe: (i32, i32),
|
||||
pub tess: (i32, i32),
|
||||
/// Zeitabschnitte außerhalb des sicheren Bereichs nach der Verschiebung.
|
||||
pub passages_shifted: Vec<(f64, f64)>,
|
||||
}
|
||||
|
||||
impl SongFit {
|
||||
pub fn outside_now(&self) -> f32 {
|
||||
self.low_now + self.high_now
|
||||
}
|
||||
|
||||
pub fn outside_shifted(&self) -> f32 {
|
||||
self.low_shifted + self.high_shifted
|
||||
}
|
||||
}
|
||||
|
||||
/// Anteil der Notendauer, der nach `shift` Halbtönen zu tief bzw. zu hoch für `safe` liegt (Freestyle zählt nicht).
|
||||
pub fn outside_sides(chart: &NoteChart, safe: (i32, i32), shift: i32) -> (f32, f32) {
|
||||
let (mut low, mut high, mut total) = (0.0f64, 0.0f64, 0.0f64);
|
||||
for n in chart.notes.iter().filter(|n| n.typ != NoteKind::Frei) {
|
||||
total += n.dauer_ms;
|
||||
let m = n.midi_pitch + shift;
|
||||
if m < safe.0 {
|
||||
low += n.dauer_ms;
|
||||
} else if m > safe.1 {
|
||||
high += n.dauer_ms;
|
||||
}
|
||||
}
|
||||
if total > 0.0 {
|
||||
((low / total) as f32, (high / total) as f32)
|
||||
} else {
|
||||
(0.0, 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Anteil der Notendauer außerhalb des sicheren Bereichs (zu tief + zu hoch).
|
||||
#[cfg(test)]
|
||||
pub fn outside_share(chart: &NoteChart, safe: (i32, i32), shift: i32) -> f32 {
|
||||
let (l, h) = outside_sides(chart, safe, shift);
|
||||
l + h
|
||||
}
|
||||
|
||||
/// Passung eines Songs zum Profil; `None`, wenn Wohlfühllage, sicherer Bereich oder Melodienoten fehlen.
|
||||
pub fn song_fit(chart: &NoteChart, profile: &VoiceProfile) -> Option<SongFit> {
|
||||
let shift = suggest_transpose(chart, profile)?;
|
||||
let safe = profile.safe_range?;
|
||||
let tess = profile.tessitura?;
|
||||
let (lowest, highest) = chart
|
||||
.notes
|
||||
.iter()
|
||||
.filter(|n| n.typ != NoteKind::Frei)
|
||||
.fold((i32::MAX, i32::MIN), |(lo, hi), n| {
|
||||
(lo.min(n.midi_pitch), hi.max(n.midi_pitch))
|
||||
});
|
||||
if lowest > highest {
|
||||
return None;
|
||||
}
|
||||
let (low_now, high_now) = outside_sides(chart, safe, 0);
|
||||
let (low_shifted, high_shifted) = outside_sides(chart, safe, shift);
|
||||
Some(SongFit {
|
||||
shift,
|
||||
lowest,
|
||||
highest,
|
||||
median: chart.median_pitch()?,
|
||||
low_now,
|
||||
high_now,
|
||||
low_shifted,
|
||||
high_shifted,
|
||||
safe,
|
||||
tess,
|
||||
passages_shifted: passages_shifted(chart, safe, shift),
|
||||
})
|
||||
}
|
||||
|
||||
fn clock(ms: f64) -> String {
|
||||
format!("{}:{:02.0}", (ms / 60_000.0) as i32, (ms / 1000.0) % 60.0)
|
||||
}
|
||||
|
||||
fn pct(x: f32) -> i32 {
|
||||
(x * 100.0).round() as i32
|
||||
}
|
||||
|
||||
/// Begründung in einfachen Sätzen: Melodie, Stimme, Lage ohne und mit Verschiebung, betroffene Stellen.
|
||||
pub fn explain(f: &SongFit) -> Vec<String> {
|
||||
use crate::pitch::note_name as nn;
|
||||
let span = f.highest - f.lowest;
|
||||
let safe_w = f.safe.1 - f.safe.0;
|
||||
let mut out = vec![
|
||||
format!(
|
||||
"Die Melodie reicht von {} bis {} ({} Halbtöne), meist um {}.",
|
||||
nn(f.lowest),
|
||||
nn(f.highest),
|
||||
span,
|
||||
nn(f.median.round() as i32)
|
||||
),
|
||||
format!(
|
||||
"Dein sicherer Bereich: {} bis {} ({} Halbtöne), deine Wohlfühllage {} bis {}.",
|
||||
nn(f.safe.0),
|
||||
nn(f.safe.1),
|
||||
safe_w,
|
||||
nn(f.tess.0),
|
||||
nn(f.tess.1)
|
||||
),
|
||||
];
|
||||
// Ohne Verschiebung.
|
||||
if f.outside_now() <= 0.005 {
|
||||
out.push("So wie er ist, liegt die ganze Melodie in deinem sicheren Bereich.".into());
|
||||
} else {
|
||||
let mut parts = Vec::new();
|
||||
if f.low_now > 0.005 {
|
||||
parts.push(format!(
|
||||
"{} % zu tief (tiefster Ton {}, {} Halbtöne unter deiner Grenze)",
|
||||
pct(f.low_now),
|
||||
nn(f.lowest),
|
||||
f.safe.0 - f.lowest
|
||||
));
|
||||
}
|
||||
if f.high_now > 0.005 {
|
||||
parts.push(format!(
|
||||
"{} % zu hoch (höchster Ton {}, {} Halbtöne über deiner Grenze)",
|
||||
pct(f.high_now),
|
||||
nn(f.highest),
|
||||
f.highest - f.safe.1
|
||||
));
|
||||
}
|
||||
out.push(format!("So wie er ist: {}.", parts.join(" und ")));
|
||||
}
|
||||
// Mit empfohlener Verschiebung.
|
||||
if f.shift != 0 {
|
||||
let dir = if f.shift < 0 { "tiefer" } else { "höher" };
|
||||
let mut line = format!(
|
||||
"Mit {} Halbtönen {dir} liegt der Schwerpunkt der Melodie ({}) in deiner Wohlfühllage",
|
||||
f.shift.abs(),
|
||||
nn((f.median + f.shift as f32).round() as i32)
|
||||
);
|
||||
if f.outside_shifted() <= 0.005 {
|
||||
line += "; dann liegt alles im sicheren Bereich.";
|
||||
} else {
|
||||
let mut parts = Vec::new();
|
||||
if f.low_shifted > 0.005 {
|
||||
parts.push(format!("{} % zu tief", pct(f.low_shifted)));
|
||||
}
|
||||
if f.high_shifted > 0.005 {
|
||||
parts.push(format!("{} % zu hoch", pct(f.high_shifted)));
|
||||
}
|
||||
line += &format!("; trotzdem bleiben {}.", parts.join(" und "));
|
||||
}
|
||||
out.push(line);
|
||||
}
|
||||
// Warum es nicht ganz passt und welche Stellen betroffen sind.
|
||||
if f.outside_shifted() > 0.005 {
|
||||
if span > safe_w {
|
||||
out.push(format!(
|
||||
"Der Song ist {} Halbtöne breit, dein sicherer Bereich nur {}: Ganz passend lässt er sich nicht machen.",
|
||||
span, safe_w
|
||||
));
|
||||
}
|
||||
// Stellen, die weniger als 3 s auseinanderliegen, gelten als eine; genannt werden die längsten.
|
||||
let mut merged: Vec<(f64, f64)> = Vec::new();
|
||||
for &(a, b) in &f.passages_shifted {
|
||||
match merged.last_mut() {
|
||||
Some(last) if a - last.1 < 3000.0 => last.1 = b,
|
||||
_ => merged.push((a, b)),
|
||||
}
|
||||
}
|
||||
if !merged.is_empty() {
|
||||
let mut longest = merged.clone();
|
||||
longest.sort_by(|x, y| (y.1 - y.0).total_cmp(&(x.1 - x.0)));
|
||||
longest.truncate(3);
|
||||
longest.sort_by(|x, y| x.0.total_cmp(&y.0));
|
||||
let list: Vec<String> = longest
|
||||
.iter()
|
||||
.map(|(a, b)| format!("{}–{}", clock(*a), clock(*b)))
|
||||
.collect();
|
||||
let n = merged.len();
|
||||
out.push(format!(
|
||||
"Betroffen {}: {}{}.",
|
||||
if n == 1 {
|
||||
"ist 1 Stelle".to_string()
|
||||
} else {
|
||||
format!("sind {n} Stellen")
|
||||
},
|
||||
if n > longest.len() { "vor allem " } else { "" }.to_string() + &list.join(", "),
|
||||
""
|
||||
));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@ -46,6 +256,82 @@ mod tests {
|
||||
VoiceProfile::assemble("x".into(), "y".into(), None, None, None, vec![], tess)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn song_fit_reports_shift_and_share_outside_the_safe_range() {
|
||||
let c = chart(&[60, 62, 64, 65, 67]); // je 500 ms
|
||||
let mut p = profile(Some((50, 58))); // Mitte 54 → Verschiebung −10
|
||||
p.safe_range = Some((48, 60));
|
||||
let fit = song_fit(&c, &p).unwrap();
|
||||
assert_eq!(fit.shift, -10);
|
||||
assert!(
|
||||
(fit.outside_now() - 0.8).abs() < 1e-6,
|
||||
"4 von 5 Noten über 60: {fit:?}"
|
||||
);
|
||||
assert_eq!(fit.outside_shifted(), 0.0);
|
||||
// Ohne sicheren Bereich oder ohne Wohlfühllage gibt es kein Urteil.
|
||||
assert!(song_fit(&c, &profile(Some((50, 58)))).is_none());
|
||||
let mut q = profile(None);
|
||||
q.safe_range = Some((48, 60));
|
||||
assert!(song_fit(&c, &q).is_none());
|
||||
// Nur Freestyle-Noten: nichts zu bewerten, kein Teilen durch null.
|
||||
let free = NoteChart::from_toml_str(
|
||||
"title=\"f\"\n[[notes]]\nstart_ms=0\ndauer_ms=500\nmidi_pitch=90\ntyp=\"frei\"\n",
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(outside_share(&free, (48, 60), 0), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explanation_names_numbers_sides_and_affected_passages() {
|
||||
// Melodie 60–67 (je 500 ms); sicherer Bereich 48–62: hoch zu viel, tief nichts.
|
||||
let c = chart(&[60, 62, 64, 65, 67]);
|
||||
let mut p = profile(Some((50, 58)));
|
||||
p.safe_range = Some((48, 62));
|
||||
let fit = song_fit(&c, &p).unwrap();
|
||||
let text = explain(&fit).join("\n");
|
||||
assert!(text.contains("reicht von C4 bis G4 (7 Halbtöne)"), "{text}");
|
||||
assert!(
|
||||
text.contains("sicherer Bereich: C3 bis D4 (14 Halbtöne)"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(
|
||||
text.contains("60 % zu hoch (höchster Ton G4, 5 Halbtöne über deiner Grenze)"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(!text.contains("zu tief"), "{text}");
|
||||
assert!(text.contains("Mit 10 Halbtönen tiefer"), "{text}");
|
||||
assert!(
|
||||
text.contains("dann liegt alles im sicheren Bereich"),
|
||||
"{text}"
|
||||
);
|
||||
// Ein Song, der zu breit ist: Begründung nennt Breite, Seite und Zeiten.
|
||||
let wide = chart(&[40, 60, 80]);
|
||||
let mut q = profile(Some((55, 60)));
|
||||
q.safe_range = Some((52, 64));
|
||||
let f = song_fit(&wide, &q).unwrap();
|
||||
let t = explain(&f).join("\n");
|
||||
assert!(
|
||||
t.contains("Der Song ist 40 Halbtöne breit, dein sicherer Bereich nur 12"),
|
||||
"{t}"
|
||||
);
|
||||
assert!(t.contains("trotzdem bleiben"), "{t}");
|
||||
assert!(t.contains("Betroffen"), "{t}");
|
||||
// Passt ohne Verschiebung: kurzer Text ohne Warnungen.
|
||||
let ok = chart(&[56, 58, 60]);
|
||||
let mut r = profile(Some((54, 62)));
|
||||
r.safe_range = Some((52, 64));
|
||||
let line = explain(&song_fit(&ok, &r).unwrap()).join("\n");
|
||||
assert!(
|
||||
line.contains("ganze Melodie in deinem sicheren Bereich"),
|
||||
"{line}"
|
||||
);
|
||||
assert!(
|
||||
!line.contains("Betroffen") && !line.contains("trotzdem"),
|
||||
"{line}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggestion_centers_melody_median_in_tessitura() {
|
||||
let c = chart(&[60, 62, 64, 65, 67]); // Median 64
|
||||
|
||||
Reference in New Issue
Block a user