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