Passagen, Übungsmodus, Stimmfinder-Überarbeitung, Gerätedesign, Metronom und Akkorde

- Passagenwahl, Original-Kurve, Spulen/Üben und Pause
- Startseite, Klartext-Oberfläche, Stimmfinder mit Stimmtyp-Vorschlag
- Gerätedesign (Regler, Schalter, LED) und Metronom (frei/songsynchron, Tap)
- Akkorderkennung aus der Begleitung, Akkordleiste und -karte
- zweiter Song als Chart

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-31 13:38:27 +01:00
parent a5fdab8b49
commit 4112f88e54
29 changed files with 6367 additions and 622 deletions

View File

@ -5,6 +5,7 @@
pub mod align;
pub mod anchors;
pub mod chords;
pub mod lyrics;
use crate::audio::decode;
@ -43,6 +44,48 @@ fn median(v: &mut [f32]) -> f32 {
v[v.len() / 2]
}
fn fnv1a(text: &str) -> u64 {
text.bytes().fold(0xcbf2_9ce4_8422_2325, |h, b| {
(h ^ b as u64).wrapping_mul(0x0100_0000_01b3)
})
}
/// Pitch-Verlauf einer Datei mit Festplatten-Cache: Schlüssel sind Pfad, Größe, Änderungszeit und die
/// Pitch-Einstellungen; ändert sich eins davon, wird neu analysiert.
pub fn cached_frames(
path: &Path,
pitch: &PitchConfig,
cache_dir: &Path,
) -> Result<Vec<PitchFrame>> {
let meta = std::fs::metadata(path)?;
let mtime = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map_or(0, |d| d.as_secs());
let canon = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
let key = fnv1a(&format!(
"v1|{}|{}|{mtime}|{pitch:?}",
canon.display(),
meta.len()
));
let file = cache_dir.join(format!("{key:016x}.json"));
if let Ok(bytes) = std::fs::read(&file)
&& let Ok(frames) = serde_json::from_slice::<Vec<PitchFrame>>(&bytes)
{
return Ok(frames);
}
let frames = analyze_file(path, pitch)?;
// Cache ist nur eine Beschleunigung: Schreibfehler dürfen die Anzeige nicht verhindern.
if std::fs::create_dir_all(cache_dir).is_ok() {
let tmp = file.with_extension("tmp");
if std::fs::write(&tmp, serde_json::to_vec(&frames)?).is_ok() {
let _ = std::fs::rename(&tmp, &file);
}
}
Ok(frames)
}
/// Fasst stimmhafte Frames zu Noten zusammen. Reine Funktion.
pub fn segment_notes(frames: &[PitchFrame], cfg: &ImportConfig) -> Vec<Note> {
let hop = {
@ -149,6 +192,7 @@ pub fn segment_notes(frames: &[PitchFrame], cfg: &ImportConfig) -> Vec<Note> {
/// Ergebnis eines Imports mit Text: Noten plus Prüfbericht.
pub struct TextImport {
pub notes: Vec<Note>,
pub sections: Vec<crate::chart::Section>,
pub report: String,
}
@ -185,7 +229,12 @@ pub fn import_with_lyrics(
Ok(a) => {
align::apply(&mut notes, &a, &syllables);
let report = report(&notes, &a, &syllables, base.len(), dip);
return Ok(TextImport { notes, report });
let sections = sections_from_alignment(&notes, &a, lyrics_text);
return Ok(TextImport {
notes,
sections,
report,
});
}
Err(e) => last_err = format!("dip_db {dip}: {e}"),
}
@ -193,6 +242,41 @@ pub fn import_with_lyrics(
anyhow::bail!("{last_err}")
}
/// Vorlauf vor der ersten Silbe einer Passage (ms).
const SECTION_LEAD_MS: f64 = 400.0;
/// Passagen aus den Textmarken: Beginn = erste Silbe der ersten Zeile (mit kurzem Vorlauf), Ende = Beginn der
/// nächsten Passage bzw. Chartende.
pub fn sections_from_alignment(
notes: &[Note],
a: &align::Alignment,
lyrics_text: &str,
) -> Vec<crate::chart::Section> {
let tags = lyrics::parse_sections(lyrics_text);
let starts: Vec<(String, f64)> = tags
.into_iter()
.filter_map(|(name, line)| {
let first = a.lines.get(line)?.chosen.first().copied()?;
Some((name, notes[first].start_ms))
})
.collect();
let chart_end = notes.last().map_or(0.0, Note::end_ms) + 500.0;
starts
.iter()
.enumerate()
.map(|(i, (name, start))| {
let prev = if i == 0 { 0.0 } else { starts[i - 1].1 };
crate::chart::Section {
name: name.clone(),
start_ms: (start - SECTION_LEAD_MS).max(prev),
end_ms: starts
.get(i + 1)
.map_or(chart_end, |n| n.1 - SECTION_LEAD_MS),
}
})
.collect()
}
fn report(
notes: &[Note],
a: &align::Alignment,
@ -288,6 +372,8 @@ pub fn build_chart(
notes,
backing,
vocals,
sections: Vec::new(),
chords: Vec::new(),
}
}
@ -423,6 +509,59 @@ mod tests {
assert!(summary(&back).contains("Noten"));
}
#[test]
fn cache_is_written_reused_and_invalidated() {
let dir = std::env::temp_dir().join(format!("singtrainer-pcache-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let wav = dir.join("a.wav");
let spec = hound::WavSpec {
channels: 1,
sample_rate: 44_100,
bits_per_sample: 16,
sample_format: hound::SampleFormat::Int,
};
let mut w = hound::WavWriter::create(&wav, spec).unwrap();
for i in 0..44_100 {
w.write_sample(
(0.5 * (std::f32::consts::TAU * 220.0 * i as f32 / 44_100.0).sin() * 32767.0)
as i16,
)
.unwrap();
}
w.finalize().unwrap();
let cache = dir.join("cache");
let first = cached_frames(&wav, &PitchConfig::default(), &cache).unwrap();
assert!(
first
.iter()
.any(|f| f.1.is_some_and(|m| (m - 57.0).abs() < 0.3))
);
let files = std::fs::read_dir(&cache).unwrap().count();
assert_eq!(files, 1);
// Zweiter Aufruf kommt aus dem Cache (identisch, keine neue Datei).
assert_eq!(
cached_frames(&wav, &PitchConfig::default(), &cache).unwrap(),
first
);
assert_eq!(std::fs::read_dir(&cache).unwrap().count(), 1);
// Andere Pitch-Einstellungen → anderer Schlüssel.
let other = PitchConfig {
median_len: 3,
..PitchConfig::default()
};
cached_frames(&wav, &other, &cache).unwrap();
assert_eq!(std::fs::read_dir(&cache).unwrap().count(), 2);
// Defekter Cache wird übergangen.
for e in std::fs::read_dir(&cache).unwrap().flatten() {
std::fs::write(e.path(), "kaputt").unwrap();
}
assert_eq!(
cached_frames(&wav, &PitchConfig::default(), &cache).unwrap(),
first
);
}
#[test]
fn analyze_pcm_finds_a_synthetic_melody() {
// Zwei Sinustöne (220 Hz = A3, 330 Hz = E4) mit Pause.