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:
345
src/chart/mod.rs
Normal file
345
src/chart/mod.rs
Normal file
@ -0,0 +1,345 @@
|
||||
//! NoteChart: Datenmodell für Songs und Übungen, unabhängig von der Quelle.
|
||||
//! Zeit intern in Millisekunden relativ zum Audiostart.
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::ops::Range;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum NoteKind {
|
||||
#[default]
|
||||
Normal,
|
||||
Golden,
|
||||
/// Freestyle: nur Stimmhaftigkeit zählt, nicht die Tonhöhe.
|
||||
Frei,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Note {
|
||||
pub start_ms: f64,
|
||||
pub dauer_ms: f64,
|
||||
pub midi_pitch: i32,
|
||||
pub silbe: Option<String>,
|
||||
pub typ: NoteKind,
|
||||
/// Beginnt eine neue Textzeile.
|
||||
pub zeile: bool,
|
||||
}
|
||||
|
||||
impl Note {
|
||||
pub fn end_ms(&self) -> f64 {
|
||||
self.start_ms + self.dauer_ms
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct NoteChart {
|
||||
pub title: String,
|
||||
pub bpm: Option<f64>,
|
||||
/// Nach Startzeit sortiert, ohne Überlappungen.
|
||||
pub notes: Vec<Note>,
|
||||
pub backing: Option<PathBuf>,
|
||||
pub vocals: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct RawChart {
|
||||
title: String,
|
||||
bpm: Option<f64>,
|
||||
backing: Option<String>,
|
||||
vocals: Option<String>,
|
||||
notes: Vec<RawNote>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct RawNote {
|
||||
start_ms: Option<f64>,
|
||||
dauer_ms: Option<f64>,
|
||||
start_beat: Option<f64>,
|
||||
laenge_beats: Option<f64>,
|
||||
midi_pitch: i32,
|
||||
silbe: Option<String>,
|
||||
#[serde(default)]
|
||||
typ: NoteKind,
|
||||
#[serde(default)]
|
||||
zeile: bool,
|
||||
}
|
||||
|
||||
impl NoteChart {
|
||||
/// Lädt ein Chart aus TOML; relative Audiopfade gelten ab dem Verzeichnis der Datei.
|
||||
pub fn load(path: &Path) -> Result<Self> {
|
||||
let text = std::fs::read_to_string(path)
|
||||
.with_context(|| format!("Chart lesen: {}", path.display()))?;
|
||||
Self::from_toml_str(&text, path.parent())
|
||||
.with_context(|| format!("Chart {}", path.display()))
|
||||
}
|
||||
|
||||
pub fn from_toml_str(text: &str, base_dir: Option<&Path>) -> Result<Self> {
|
||||
let raw: RawChart = toml::from_str(text)?;
|
||||
let beat_ms = raw.bpm.map(|b| 60_000.0 / b);
|
||||
let mut notes = Vec::with_capacity(raw.notes.len());
|
||||
for (i, n) in raw.notes.iter().enumerate() {
|
||||
let n_no = i + 1;
|
||||
let (start_ms, dauer_ms) = match (n.start_ms, n.dauer_ms, n.start_beat, n.laenge_beats)
|
||||
{
|
||||
(Some(s), Some(d), None, None) => (s, d),
|
||||
(None, None, Some(s), Some(l)) => {
|
||||
let Some(b) = beat_ms else {
|
||||
bail!("Note {n_no}: Beat-Angaben brauchen `bpm`");
|
||||
};
|
||||
(s * b, l * b)
|
||||
}
|
||||
_ => bail!(
|
||||
"Note {n_no}: entweder start_ms+dauer_ms oder start_beat+laenge_beats angeben"
|
||||
),
|
||||
};
|
||||
if !(0.0..).contains(&start_ms) || dauer_ms <= 0.0 {
|
||||
bail!("Note {n_no}: Start muss ≥ 0 und Dauer > 0 sein");
|
||||
}
|
||||
if !(0..=127).contains(&n.midi_pitch) {
|
||||
bail!("Note {n_no}: midi_pitch {} außerhalb 0..127", n.midi_pitch);
|
||||
}
|
||||
notes.push(Note {
|
||||
start_ms,
|
||||
dauer_ms,
|
||||
midi_pitch: n.midi_pitch,
|
||||
silbe: n.silbe.clone(),
|
||||
typ: n.typ,
|
||||
zeile: n.zeile,
|
||||
});
|
||||
}
|
||||
if notes.is_empty() {
|
||||
bail!("Chart enthält keine Noten");
|
||||
}
|
||||
notes.sort_by(|a, b| a.start_ms.total_cmp(&b.start_ms));
|
||||
for w in notes.windows(2) {
|
||||
if w[1].start_ms < w[0].end_ms() - 0.5 {
|
||||
bail!(
|
||||
"Noten überlappen bei {:.0} ms ({} / {})",
|
||||
w[1].start_ms,
|
||||
w[0].silbe.as_deref().unwrap_or("?"),
|
||||
w[1].silbe.as_deref().unwrap_or("?")
|
||||
);
|
||||
}
|
||||
}
|
||||
let resolve = |p: Option<String>| {
|
||||
p.map(|p| match base_dir {
|
||||
Some(d) => d.join(p),
|
||||
None => PathBuf::from(p),
|
||||
})
|
||||
};
|
||||
Ok(Self {
|
||||
title: raw.title,
|
||||
bpm: raw.bpm,
|
||||
notes,
|
||||
backing: resolve(raw.backing),
|
||||
vocals: resolve(raw.vocals),
|
||||
})
|
||||
}
|
||||
|
||||
/// Kopie um `semitones` Halbtöne verschoben (auf 0..=127 begrenzt); der Titel nennt die Verschiebung.
|
||||
pub fn transposed(&self, semitones: i32) -> NoteChart {
|
||||
if semitones == 0 {
|
||||
return self.clone();
|
||||
}
|
||||
let mut c = self.clone();
|
||||
for n in &mut c.notes {
|
||||
n.midi_pitch = (n.midi_pitch + semitones).clamp(0, 127);
|
||||
}
|
||||
c.title = format!("{} ({semitones:+} HT)", self.title);
|
||||
c
|
||||
}
|
||||
|
||||
/// Dauergewichteter Median der Tonhöhen (ohne Frei-Noten) als Schwerpunkt der Melodie.
|
||||
pub fn median_pitch(&self) -> Option<f32> {
|
||||
let mut v: Vec<(i32, f64)> = self
|
||||
.notes
|
||||
.iter()
|
||||
.filter(|n| n.typ != NoteKind::Frei)
|
||||
.map(|n| (n.midi_pitch, n.dauer_ms))
|
||||
.collect();
|
||||
if v.is_empty() {
|
||||
return None;
|
||||
}
|
||||
v.sort_by_key(|&(p, _)| p);
|
||||
let half = v.iter().map(|&(_, d)| d).sum::<f64>() / 2.0;
|
||||
let mut acc = 0.0;
|
||||
for (p, d) in v {
|
||||
acc += d;
|
||||
if acc >= half {
|
||||
return Some(p as f32);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn end_ms(&self) -> f64 {
|
||||
self.notes.last().map_or(0.0, Note::end_ms)
|
||||
}
|
||||
|
||||
/// Tiefste und höchste Notenhöhe (MIDI).
|
||||
pub fn pitch_range(&self) -> (i32, i32) {
|
||||
let lo = self.notes.iter().map(|n| n.midi_pitch).min().unwrap_or(60);
|
||||
let hi = self.notes.iter().map(|n| n.midi_pitch).max().unwrap_or(60);
|
||||
(lo, hi)
|
||||
}
|
||||
|
||||
/// Index der Note, die zum Zeitpunkt `ms` klingt.
|
||||
pub fn note_at(&self, ms: f64) -> Option<usize> {
|
||||
let i = self.notes.partition_point(|n| n.start_ms <= ms);
|
||||
i.checked_sub(1).filter(|&i| ms < self.notes[i].end_ms())
|
||||
}
|
||||
|
||||
/// Textzeile, die zum Zeitpunkt `ms` gerade dran ist: die der klingenden oder nächsten Note,
|
||||
/// nach dem Ende die letzte Zeile.
|
||||
pub fn lyric_line_at(&self, ms: f64) -> Range<usize> {
|
||||
let lines = self.lyric_lines();
|
||||
let idx = self
|
||||
.note_at(ms)
|
||||
.unwrap_or_else(|| self.notes.partition_point(|n| n.start_ms <= ms))
|
||||
.min(self.notes.len() - 1);
|
||||
lines
|
||||
.into_iter()
|
||||
.find(|l| l.contains(&idx))
|
||||
.unwrap_or(0..self.notes.len())
|
||||
}
|
||||
|
||||
/// Notenindex-Bereiche der Textzeilen (neue Zeile bei `zeile = true`; die erste Note beginnt immer eine).
|
||||
pub fn lyric_lines(&self) -> Vec<Range<usize>> {
|
||||
let mut lines = Vec::new();
|
||||
let mut start = 0;
|
||||
for (i, n) in self.notes.iter().enumerate() {
|
||||
if i > 0 && n.zeile {
|
||||
lines.push(start..i);
|
||||
start = i;
|
||||
}
|
||||
}
|
||||
lines.push(start..self.notes.len());
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const BEATS: &str = r#"
|
||||
title = "T"
|
||||
bpm = 120.0
|
||||
[[notes]]
|
||||
start_beat = 0.0
|
||||
laenge_beats = 1.0
|
||||
midi_pitch = 60
|
||||
silbe = "do"
|
||||
[[notes]]
|
||||
start_beat = 2.0
|
||||
laenge_beats = 2.0
|
||||
midi_pitch = 64
|
||||
typ = "golden"
|
||||
zeile = true
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn beats_convert_to_ms() {
|
||||
let c = NoteChart::from_toml_str(BEATS, None).unwrap();
|
||||
assert_eq!(c.notes[0].dauer_ms, 500.0);
|
||||
assert_eq!(c.notes[1].start_ms, 1000.0);
|
||||
assert_eq!(c.notes[1].typ, NoteKind::Golden);
|
||||
assert_eq!(c.end_ms(), 2000.0);
|
||||
assert_eq!(c.pitch_range(), (60, 64));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_based_and_lookup() {
|
||||
let c = NoteChart::from_toml_str(
|
||||
"title=\"x\"\n[[notes]]\nstart_ms=100\ndauer_ms=200\nmidi_pitch=60\n[[notes]]\nstart_ms=400\ndauer_ms=100\nmidi_pitch=62\n",
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(c.note_at(50.0), None);
|
||||
assert_eq!(c.note_at(100.0), Some(0));
|
||||
assert_eq!(c.note_at(299.9), Some(0));
|
||||
assert_eq!(c.note_at(300.0), None);
|
||||
assert_eq!(c.note_at(450.0), Some(1));
|
||||
assert_eq!(c.note_at(500.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lyric_lines_split_on_flag() {
|
||||
let c = NoteChart::from_toml_str(BEATS, None).unwrap();
|
||||
assert_eq!(c.lyric_lines(), vec![0..1, 1..2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transposition_shifts_notes_and_clamps() {
|
||||
let c = NoteChart::from_toml_str(BEATS, None).unwrap();
|
||||
let t = c.transposed(-5);
|
||||
assert_eq!(t.notes[0].midi_pitch, 55);
|
||||
assert_eq!(t.notes[1].midi_pitch, 59);
|
||||
assert!(t.title.ends_with("(-5 HT)"));
|
||||
assert_eq!(c.transposed(0), c);
|
||||
assert_eq!(c.transposed(100).notes[1].midi_pitch, 127);
|
||||
assert_eq!(c.transposed(-100).notes[0].midi_pitch, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn median_pitch_is_duration_weighted() {
|
||||
// 60 (500 ms) und 64 (1000 ms): die längere Note bestimmt den Median.
|
||||
let c = NoteChart::from_toml_str(BEATS, None).unwrap();
|
||||
assert_eq!(c.median_pitch(), Some(64.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lyric_line_follows_time() {
|
||||
let c = NoteChart::from_toml_str(BEATS, None).unwrap();
|
||||
assert_eq!(c.lyric_line_at(100.0), 0..1);
|
||||
assert_eq!(c.lyric_line_at(600.0), 1..2, "Pause → nächste Zeile");
|
||||
assert_eq!(c.lyric_line_at(1500.0), 1..2);
|
||||
assert_eq!(
|
||||
c.lyric_line_at(9999.0),
|
||||
1..2,
|
||||
"nach dem Ende → letzte Zeile"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_charts() {
|
||||
let bad = |s: &str| NoteChart::from_toml_str(s, None).unwrap_err().to_string();
|
||||
assert!(bad("title=\"x\"\nnotes=[]").contains("keine Noten"));
|
||||
assert!(
|
||||
bad("title=\"x\"\n[[notes]]\nstart_beat=0.0\nlaenge_beats=1.0\nmidi_pitch=60")
|
||||
.contains("bpm")
|
||||
);
|
||||
assert!(bad("title=\"x\"\n[[notes]]\nstart_ms=0\nmidi_pitch=60").contains("entweder"));
|
||||
assert!(
|
||||
bad("title=\"x\"\n[[notes]]\nstart_ms=0\ndauer_ms=10\nmidi_pitch=200")
|
||||
.contains("midi_pitch")
|
||||
);
|
||||
let overlap = "title=\"x\"\n[[notes]]\nstart_ms=0\ndauer_ms=300\nmidi_pitch=60\n[[notes]]\nstart_ms=200\ndauer_ms=100\nmidi_pitch=62";
|
||||
assert!(bad(overlap).contains("überlappen"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_paths_resolve_relative_to_chart() {
|
||||
let c = NoteChart::from_toml_str(
|
||||
"title=\"x\"\nbacking=\"a.ogg\"\n[[notes]]\nstart_ms=0\ndauer_ms=10\nmidi_pitch=60",
|
||||
Some(Path::new("/songs/x")),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(c.backing, Some(PathBuf::from("/songs/x/a.ogg")));
|
||||
assert_eq!(c.vocals, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shipped_test_chart_is_valid() {
|
||||
let c = NoteChart::load(
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("charts/test.toml")
|
||||
.as_path(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(c.notes.len() > 20);
|
||||
assert!(c.lyric_lines().len() >= 5);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user