//! UltraStar-/SingStar-Textcharts (`.txt`) einlesen und in ein Chart umwandeln. //! //! Format: Kopfzeilen `#KEY:Wert`, danach Notenzeilen `: Start Länge Tonhöhe Text` (`*` golden, `F` Freestyle, //! `R` Rap), `- Beat` für einen Zeilenwechsel und `E` als Ende. Zeiten sind in Beats; ein Beat dauert //! `15000 / BPM` ms (die BPM-Angabe ist vierfach), der Ursprung liegt bei `#GAP` ms. Tonhöhe 0 ist C4, die //! Oktavlage der Dateien ist aber nicht einheitlich – [`auto_sync`] prüft sie gegen die Gesangsspur. use super::PitchFrame; use crate::chart::{Grid, Note, NoteKind}; use anyhow::{Context, Result, bail}; #[derive(Debug, Clone, PartialEq)] pub struct UsNote { pub kind: NoteKind, pub start_beat: i64, pub len_beats: i64, pub pitch: i32, /// Text wie in der Datei (Leerzeichen am Ende = Wortende). pub text: String, /// Beginnt eine neue Textzeile. pub new_line: bool, } #[derive(Debug, Clone, PartialEq)] pub struct UltraStar { pub artist: String, pub title: String, /// BPM-Angabe der Datei (Viertel-Auflösung). pub bpm: f64, pub gap_ms: f64, pub notes: Vec, } impl UltraStar { /// Dauer eines Beats in ms. pub fn beat_ms(&self) -> f64 { 15_000.0 / self.bpm } /// Tempo in Schlägen pro Minute, wie man es mitklopft. pub fn real_bpm(&self) -> f64 { self.bpm / 4.0 } } pub fn parse(text: &str) -> Result { let (mut artist, mut title) = (String::new(), String::new()); let (mut bpm, mut gap) = (None, 0.0); let mut notes: Vec = Vec::new(); let mut pending_break = false; let num = |s: &str| s.trim().replace(',', ".").parse::(); for (no, raw) in text.lines().enumerate() { let line = raw.trim_end_matches(['\r', '\n']); let no = no + 1; if let Some(h) = line.strip_prefix('#') { let Some((k, v)) = h.split_once(':') else { continue; }; match k.trim().to_ascii_uppercase().as_str() { "ARTIST" => artist = v.trim().into(), "TITLE" => title = v.trim().into(), "BPM" => bpm = Some(num(v).with_context(|| format!("Zeile {no}: BPM"))?), "GAP" => gap = num(v).with_context(|| format!("Zeile {no}: GAP"))?, _ => {} } continue; } let mut chars = line.chars(); let Some(tag) = chars.next() else { continue }; match tag { 'E' => break, '-' => pending_break = true, ':' | '*' | 'F' | 'R' | 'G' => { let rest = chars.as_str().strip_prefix(' ').unwrap_or(chars.as_str()); let mut it = rest.splitn(4, ' '); let mut field = |name: &str| -> Result { it.next() .and_then(|f| f.trim().parse().ok()) .with_context(|| format!("Zeile {no}: {name} fehlt oder ist keine Zahl")) }; let (start, len, pitch) = (field("Start")?, field("Länge")?, field("Tonhöhe")?); let text = it.next().unwrap_or("").to_string(); let kind = match tag { '*' | 'G' => NoteKind::Golden, 'F' | 'R' => NoteKind::Frei, _ => NoteKind::Normal, }; notes.push(UsNote { kind, start_beat: start, len_beats: len.max(1), pitch: pitch as i32, text, new_line: std::mem::take(&mut pending_break), }); } _ => {} } } let bpm = bpm .filter(|b| *b > 0.0) .context("#BPM fehlt oder ist ungültig")?; if notes.is_empty() { bail!("keine Noten gefunden"); } Ok(UltraStar { artist, title, bpm, gap_ms: gap, notes, }) } /// Umwandlung in Chart-Noten: `octave_shift` in Halbtönen (Vielfache von 12), `offset_ms` wird zur Zeit addiert. pub fn to_notes(us: &UltraStar, octave_shift: i32, offset_ms: f64) -> Vec { let beat = us.beat_ms(); let mut notes: Vec = Vec::new(); let mut first = true; for n in &us.notes { let start = us.gap_ms + offset_ms + n.start_beat as f64 * beat; let word_end = n.text.ends_with(' '); let body = n.text.trim().trim_start_matches('~').trim(); let silbe = (!body.is_empty()).then(|| { if word_end { body.to_string() } else { format!("{body}-") } }); notes.push(Note { start_ms: start.max(0.0), dauer_ms: n.len_beats as f64 * beat, midi_pitch: 60 + n.pitch + octave_shift, silbe, typ: n.kind, zeile: n.new_line && !first, }); first = false; } // Das Chart verlangt sortierte, überlappungsfreie Noten. notes.sort_by(|a, b| a.start_ms.total_cmp(&b.start_ms)); for i in 1..notes.len() { let next = notes[i].start_ms; let p = &mut notes[i - 1]; if p.end_ms() > next { p.dauer_ms = (next - p.start_ms).max(1.0); } } // Wortendes „-“ am Zeilenende ist sinnlos: letzte Silbe jeder Zeile schließt das Wort ab. for i in 0..notes.len() { let last_in_line = i + 1 == notes.len() || notes[i + 1].zeile; if last_in_line && let Some(s) = notes[i].silbe.as_mut() && let Some(stem) = s.strip_suffix('-') { *s = stem.to_string(); } } notes } /// Taktraster: Schlagtempo und Zeit des Beats 0 (Annahme: dort beginnt ein Takt). pub fn grid(us: &UltraStar, offset_ms: f64) -> Grid { Grid { bpm: us.real_bpm(), first_bar_ms: us.gap_ms + offset_ms, beats_per_bar: 4, } } /// Ergebnis der Prüfung gegen die Gesangsspur. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Sync { /// Zeitversatz in ms, der zu den Notenzeiten addiert werden muss. pub offset_ms: f64, /// Oktavverschiebung in Halbtönen (Vielfaches von 12). pub octave_shift: i32, /// Anteil der Notenframes, in denen die Gesangsspur die erwartete Tonklasse (±1 Halbton) singt. pub score: f64, /// Wert ohne Versatz zum Vergleich: wie viel besser ist das gefundene Ergebnis? pub score_without_offset: f64, } fn fold(d: f32) -> f32 { let m = d.rem_euclid(12.0); m.min(12.0 - m) } /// Anteil der Frames innerhalb der Noten, die zur Note passen (Oktav-gefaltet), bei Zeitversatz `offset_ms`. fn match_score(us: &UltraStar, frames: &[PitchFrame], offset_ms: f64) -> f64 { let beat = us.beat_ms(); let (mut ok, mut total) = (0usize, 0usize); for n in us.notes.iter().filter(|n| n.kind != NoteKind::Frei) { let a = (us.gap_ms + offset_ms + n.start_beat as f64 * beat) / 1000.0; let b = a + n.len_beats as f64 * beat / 1000.0; // Rand der Note auslassen (Einsatz/Ausklang ungenau). let (a, b) = (a + 0.04, b - 0.04); let i0 = frames.partition_point(|f| f.0 < a); for f in frames[i0..].iter().take_while(|f| f.0 <= b) { total += 1; if let Some(m) = f.1 && fold(m - (60 + n.pitch) as f32) < 1.0 { ok += 1; } } } if total == 0 { 0.0 } else { ok as f64 / total as f64 } } /// Sucht Zeitversatz (±`max_offset_ms`) und Oktavlage, bei denen die Noten am besten zur Gesangsspur passen. pub fn auto_sync(us: &UltraStar, frames: &[PitchFrame], max_offset_ms: f64) -> Option { if frames.is_empty() { return None; } let mut best = (f64::MIN, 0.0); let mut o = -max_offset_ms; while o <= max_offset_ms { let s = match_score(us, frames, o); if s > best.0 { best = (s, o); } o += 20.0; } // Feinsuche ±100 ms in 5-ms-Schritten; bei einem Plateau gleich guter Werte gilt dessen Mitte. let coarse = best.1; let fine: Vec<(f64, f64)> = (-20..=20) .map(|k| { let o = coarse + f64::from(k) * 5.0; (o, match_score(us, frames, o)) }) .collect(); let top = fine.iter().map(|x| x.1).fold(best.0, f64::max); let plateau: Vec = fine .iter() .filter(|x| x.1 >= top - 0.002) .map(|x| x.0) .collect(); best = ( top, (plateau.first().copied().unwrap_or(coarse) + plateau.last().copied().unwrap_or(coarse)) / 2.0, ); // Oktave: Median der Abweichung (Gesang − Note) bei den passenden Frames. let beat = us.beat_ms(); let mut diffs: Vec = Vec::new(); for n in us.notes.iter().filter(|n| n.kind != NoteKind::Frei) { let a = (us.gap_ms + best.1 + n.start_beat as f64 * beat) / 1000.0 + 0.04; let b = a + n.len_beats as f64 * beat / 1000.0 - 0.08; let i0 = frames.partition_point(|f| f.0 < a); for f in frames[i0..].iter().take_while(|f| f.0 <= b) { if let Some(m) = f.1 { let d = m - (60 + n.pitch) as f32; if fold(d) < 1.0 { diffs.push(d); } } } } if diffs.is_empty() { return None; } diffs.sort_by(f32::total_cmp); let med = diffs[diffs.len() / 2]; Some(Sync { offset_ms: best.1, octave_shift: ((med / 12.0).round() as i32) * 12, score: best.0, score_without_offset: match_score(us, frames, 0.0), }) } #[cfg(test)] mod tests { use super::*; const SAMPLE: &str = "#ARTIST:Test Band\n#TITLE:Demo\n#BPM:240,0\n#GAP:1000\n\ : 0 4 0 Hel\n: 4 4 2 lo \n- 10\n: 12 8 4 world \n* 20 4 4 ~ \nF 24 2 0 ah\nE\n"; #[test] fn parses_header_notes_lines_and_kinds() { let us = parse(SAMPLE).unwrap(); assert_eq!( (us.artist.as_str(), us.title.as_str()), ("Test Band", "Demo") ); assert_eq!((us.bpm, us.gap_ms), (240.0, 1000.0)); assert_eq!(us.notes.len(), 5); assert_eq!(us.notes[3].kind, NoteKind::Golden); assert_eq!(us.notes[4].kind, NoteKind::Frei); assert!(us.notes[2].new_line && !us.notes[1].new_line); assert_eq!( us.notes[1].text, "lo ", "Wortende-Leerzeichen bleibt erhalten" ); assert_eq!(us.real_bpm(), 60.0); assert_eq!(us.beat_ms(), 62.5); } #[test] fn rejects_files_without_bpm_or_notes() { assert!(parse("#TITLE:x\n: 0 1 0 a\nE\n").is_err()); assert!(parse("#BPM:100\nE\n").is_err()); assert!(parse("#BPM:100\n: 0 x 0 a\n").is_err_and(|e| e.to_string().contains("Länge"))); } #[test] fn converts_timing_pitch_syllables_and_lines() { let us = parse(SAMPLE).unwrap(); let notes = to_notes(&us, -12, 0.0); assert_eq!(notes[0].start_ms, 1000.0); assert_eq!(notes[0].dauer_ms, 250.0); assert_eq!(notes[1].start_ms, 1250.0); assert_eq!(notes[0].midi_pitch, 48, "C4 − eine Oktave"); assert_eq!(notes[1].midi_pitch, 50); assert_eq!(notes[0].silbe.as_deref(), Some("Hel-"), "Wort geht weiter"); assert_eq!(notes[1].silbe.as_deref(), Some("lo"), "Wortende"); assert_eq!(notes[2].silbe.as_deref(), Some("world")); assert!(notes[3].silbe.is_none(), "reine Haltenote hat keinen Text"); assert!(notes[2].zeile && !notes[0].zeile && !notes[1].zeile); assert_eq!(notes[3].typ, NoteKind::Golden); let shifted = to_notes(&us, 0, 500.0); assert_eq!(shifted[0].start_ms, 1500.0); // Ergebnis ist ein gültiges Chart. let chart = super::super::build_chart("Demo", notes, None, None); let toml = toml::to_string_pretty(&chart).unwrap(); assert!(crate::chart::NoteChart::from_toml_str(&toml, None).is_ok()); } #[test] fn grid_uses_quarter_tempo_and_gap() { let us = parse(SAMPLE).unwrap(); let g = grid(&us, 20.0); assert_eq!((g.bpm, g.first_bar_ms, g.beats_per_bar), (60.0, 1020.0, 4)); } /// Sängerin singt die Noten zwei Oktaven tiefer und 1,3 s später als im Chart. fn vocal_frames(us: &UltraStar, delay_ms: f64, octave: i32) -> Vec { let beat = us.beat_ms(); let end = us .notes .iter() .map(|n| us.gap_ms + (n.start_beat + n.len_beats) as f64 * beat) .fold(0.0, f64::max); let mut out = Vec::new(); let mut t = 0.0; while t < end + delay_ms + 2000.0 { let m = us.notes.iter().find_map(|n| { let a = us.gap_ms + delay_ms + n.start_beat as f64 * beat; (t >= a && t < a + n.len_beats as f64 * beat && n.kind != NoteKind::Frei) .then(|| (60 + n.pitch + octave) as f32) }); out.push((t / 1000.0, m)); t += 11.6; } out } fn long_song() -> UltraStar { // 40 Noten über einen Tonumfang von 7 Halbtönen, unregelmäßige Längen. let mut s = String::from("#BPM:240\n#GAP:2000\n"); let mut beat = 0; for i in 0..40 { let len = 3 + (i * 7) % 5; s += &format!(": {beat} {len} {} la \n", (i * 5) % 8); beat += len + 2 + (i % 3); } s += "E\n"; parse(&s).unwrap() } #[test] fn auto_sync_finds_delay_and_octave() { let us = long_song(); let frames = vocal_frames(&us, 1300.0, -24); let s = auto_sync(&us, &frames, 5000.0).unwrap(); assert!((s.offset_ms - 1300.0).abs() <= 25.0, "{s:?}"); assert_eq!(s.octave_shift, -24, "{s:?}"); assert!(s.score > 0.9 && s.score_without_offset < 0.5, "{s:?}"); // Ohne Versatz und ohne Oktavunterschied bleibt alles beim Alten. let s0 = auto_sync(&us, &vocal_frames(&us, 0.0, 0), 5000.0).unwrap(); assert!(s0.offset_ms.abs() <= 25.0 && s0.octave_shift == 0, "{s0:?}"); assert!(auto_sync(&us, &[], 1000.0).is_none()); } }