diff --git a/docs/format.md b/docs/format.md index 5d080bc..b25bc93 100644 --- a/docs/format.md +++ b/docs/format.md @@ -270,8 +270,9 @@ Anschlagereignisse und Rhythmusmuster für Begleitinstrumente. --- ### 3.6 `song.txt` (UltraStar Deluxe) -Exportformat für Karaoke-Software: -- Header: `#TITLE`, `#ARTIST`, `#MP3`, `#BPM` ($4 \times$ Viertelnoten-BPM), `#GAP` (Offset in ms), `#LANGUAGE`. +Exportformat für Karaoke-Software (UltraStar Deluxe / USDX): +- Header: `#TITLE`, `#ARTIST`, `#MP3` (Audiodatei), `#BPM` (Viertelnoten-BPM), `#GAP` (Audio-Offset in Millisekunden vor Beat 0), `#LANGUAGE`. +- Zeitachse: 1 Beat entspricht $\frac{15}{\text{BPM}}$ Sekunden (4 Ticks pro Viertelnote: $t = \frac{\text{GAP}}{1000} + \text{Beat} \times \frac{15}{\text{BPM}}$). - Notenzeilen: `: ` - Pausen/Umbruch: `- ` - Ende: `E` diff --git a/src/unmix/export/ultrastar.py b/src/unmix/export/ultrastar.py index 1ab18c6..b02b9c5 100644 --- a/src/unmix/export/ultrastar.py +++ b/src/unmix/export/ultrastar.py @@ -19,10 +19,26 @@ from pathlib import Path from unmix.schema.meta import MetaDocument from unmix.schema.tempo import TempoDocument from unmix.schema.vocals import VocalsDocument -from unmix.tempo import sec_to_beat + +LANG_MAP = { + "de": "German", + "en": "English", + "es": "Spanish", + "fr": "French", + "it": "Italian", + "ja": "Japanese", + "ko": "Korean", + "zh": "Chinese", +} -def export_ultrastar(song_dir: Path) -> Path: +def export_ultrastar( + song_dir: Path, + title: str | None = None, + artist: str | None = None, + language: str | None = None, + audio_filename: str | None = None, +) -> Path: """Export song package directory to UltraStar song.txt. Reads meta.json, vocals.json, and tempo.json if present. @@ -49,9 +65,10 @@ def export_ultrastar(song_dir: Path) -> Path: with open(tempo_file, encoding="utf-8") as f: tempo = TempoDocument.model_validate(json.load(f)) - title = meta.title if meta and meta.title else song_dir.name - artist = meta.artist if meta and meta.artist else "Unknown Artist" - language = meta.language if meta and meta.language else "German" + final_title = title or (meta.title if meta and meta.title else song_dir.name) + final_artist = artist or (meta.artist if meta and meta.artist else "Unknown Artist") + raw_lang = language or (meta.language if meta and meta.language else "German") + final_language = LANG_MAP.get(raw_lang.lower(), raw_lang) # Find earliest vocal syllable for GAP first_syllable_sec = 0.0 @@ -60,26 +77,44 @@ def export_ultrastar(song_dir: Path) -> Path: first_syllable_sec = line.syllables[0].start break - # Determine reference BPM + # Determine reference BPM (standard quarter-note BPM) if tempo and tempo.anchors: - base_bpm = tempo.anchors[0].bpm + base_bpm = float(tempo.anchors[0].bpm) else: base_bpm = 120.0 - # In UltraStar, #BPM is 4x standard BPM (4 beats per quarter note) - ultrastar_bpm = base_bpm * 4.0 gap_ms = int(max(0.0, first_syllable_sec) * 1000.0) + gap_sec = gap_ms / 1000.0 - # Audio reference file: vocals.wav if present, else original file - mp3_name = "stems/vocals.wav" if (song_dir / "stems" / "vocals.wav").exists() else "extracted.wav" + # Determine audio reference filename (#MP3) + mp3_name = audio_filename + if not mp3_name and meta: + src = getattr(meta, "source", None) or getattr(meta, "source_file", None) + if src and hasattr(src, "filename") and src.filename: + mp3_name = src.filename + elif src and hasattr(src, "path") and src.path: + mp3_name = Path(src.path).name + if not mp3_name: + for ext in [".mp3", ".ogg", ".flac", ".m4a", ".wav"]: + candidates = [p for p in song_dir.glob(f"*{ext}") if p.name not in ["vocals.wav", "instrumental.wav"]] + if candidates: + mp3_name = candidates[0].name + break + if not mp3_name: + if (song_dir / "extracted.wav").exists(): + mp3_name = "extracted.wav" + elif (song_dir / ".cache" / "extracted.wav").exists(): + mp3_name = "extracted.wav" + else: + mp3_name = "audio.mp3" out_lines = [ - f"#TITLE:{title}", - f"#ARTIST:{artist}", + f"#TITLE:{final_title}", + f"#ARTIST:{final_artist}", f"#MP3:{mp3_name}", - f"#BPM:{ultrastar_bpm:.2f}", + f"#BPM:{base_bpm:.2f}", f"#GAP:{gap_ms}", - f"#LANGUAGE:{language}", + f"#LANGUAGE:{final_language}", ] # Pass through additional header fields from meta.ultrastar @@ -88,14 +123,15 @@ def export_ultrastar(song_dir: Path) -> Path: if k.upper() not in ["TITLE", "ARTIST", "MP3", "BPM", "GAP", "LANGUAGE"]: out_lines.append(f"#{k.upper()}:{v}") + # UltraStar timing: 1 tick = 15.0 / BPM seconds -> beats = rel_sec * (BPM / 15.0) + ticks_per_sec = base_bpm / 15.0 + def sec_to_ultrastar_beat(sec: float) -> int: - rel_sec = max(0.0, sec - (gap_ms / 1000.0)) - if tempo and tempo.anchors: - quarter_beats = sec_to_beat(rel_sec, tempo) - return max(0, int(round(quarter_beats * 4.0))) - else: - beats_per_sec = base_bpm / 60.0 - return max(0, int(round(rel_sec * beats_per_sec * 4.0))) + rel_sec = max(0.0, sec - gap_sec) + return max(0, int(round(rel_sec * ticks_per_sec))) + + def duration_to_ultrastar_beats(dur: float) -> int: + return max(1, int(round(dur * ticks_per_sec))) tag_map = {"normal": ":", "golden": "*", "freestyle": "F", "rap": "R"} @@ -106,8 +142,7 @@ def export_ultrastar(song_dir: Path) -> Path: for syl_idx, syl in enumerate(line.syllables): syl_start_beat = sec_to_ultrastar_beat(syl.start) - syl_end_beat = sec_to_ultrastar_beat(syl.end) - duration_beats = max(1, syl_end_beat - syl_start_beat) + duration_beats = duration_to_ultrastar_beats(syl.end - syl.start) # Prevent overlap with previous syllable in same line if syl_start_beat < current_beat: @@ -129,7 +164,15 @@ def export_ultrastar(song_dir: Path) -> Path: # Add line break if not the last line if line_idx < len(vocals.lines) - 1: - line_break_beat = current_beat + 2 + next_line_start = None + for next_l in vocals.lines[line_idx + 1 :]: + if next_l.syllables: + next_line_start = sec_to_ultrastar_beat(next_l.syllables[0].start) + break + if next_line_start is not None and next_line_start > current_beat + 1: + line_break_beat = current_beat + (next_line_start - current_beat) // 2 + else: + line_break_beat = current_beat + 1 out_lines.append(f"- {line_break_beat}") current_beat = line_break_beat + 1 @@ -193,8 +236,8 @@ class UltraStarSong: @property def bpm(self) -> float: - # Standard quarter-note BPM - return float(self.headers.get("BPM", "480").replace(",", ".")) / 4.0 + # Standard quarter-note BPM from header + return float(self.headers.get("BPM", "120").replace(",", ".")) @property def gap_ms(self) -> float: @@ -256,11 +299,11 @@ def parse_ultrastar(file_path: Path) -> UltraStarSong: lines.append(current_line) # Calculate absolute timings in seconds for each note - raw_bpm = float(headers.get("BPM", "480").replace(",", ".")) + raw_bpm = float(headers.get("BPM", "120").replace(",", ".")) gap_sec = float(headers.get("GAP", "0").replace(",", ".")) / 1000.0 - # UltraStar tick duration in seconds = 60.0 / BPM - sec_per_tick = 60.0 / raw_bpm if raw_bpm > 0 else 0.125 + # UltraStar tick duration in seconds = 15.0 / BPM (4 ticks per quarter note) + sec_per_tick = 15.0 / raw_bpm if raw_bpm > 0 else 0.03125 for line_notes in lines: for note in line_notes: diff --git a/tests/test_ultrastar.py b/tests/test_ultrastar.py index d989567..ac69e65 100644 --- a/tests/test_ultrastar.py +++ b/tests/test_ultrastar.py @@ -2,6 +2,8 @@ from pathlib import Path +import pytest + from unmix.export.ultrastar import export_ultrastar, parse_ultrastar from unmix.schema.meta import MetaDocument, SourceFileInfo from unmix.schema.tempo import TempoAnchor, TempoDocument @@ -56,8 +58,10 @@ def test_ultrastar_writer_and_reader(tmp_path: Path): content = txt_path.read_text(encoding="utf-8") assert "#TITLE:Test Song" in content assert "#ARTIST:Test Artist" in content - assert "#BPM:480.00" in content # 120 * 4 = 480 + assert "#BPM:120.00" in content assert "#GAP:500" in content # 0.5s = 500 ms + assert "#LANGUAGE:German" in content + assert "stems/vocals.wav" not in content assert "E" in content # 5. Parse back using parse_ultrastar @@ -72,10 +76,82 @@ def test_ultrastar_writer_and_reader(tmp_path: Path): assert len(line1) == 2 assert line1[0].text == "Hal-" assert line1[0].midi == 60.0 + assert line1[0].start_sec == pytest.approx(0.5, abs=0.02) + assert line1[0].end_sec == pytest.approx(1.0, abs=0.02) + assert line1[1].text == "lo " assert line1[1].midi == 62.0 + assert line1[1].start_sec == pytest.approx(1.0, abs=0.02) + assert line1[1].end_sec == pytest.approx(2.0, abs=0.02) line2 = parsed.lines[1] assert len(line2) == 1 assert line2[0].text == "Welt" assert line2[0].midi == 64.0 + assert line2[0].start_sec == pytest.approx(3.0, abs=0.02) + assert line2[0].end_sec == pytest.approx(4.5, abs=0.02) + + +def test_ultrastar_metadata_and_language_english(tmp_path: Path): + song_dir = tmp_path / "song_pkg" + song_dir.mkdir(parents=True, exist_ok=True) + + meta = MetaDocument( + title="Chasing Cars", + artist="Snow Patrol", + language="en", + duration_sec=269.0, + source_file=SourceFileInfo( + filename="Chasing_Cars.mp3", path="/tmp/Chasing_Cars.mp3", sha256="abc", size_bytes=100 + ), + created_at="2026-11-02T10:00:00Z", + ) + (song_dir / "meta.json").write_text(meta.model_dump_json(indent=2)) + + # Tempo anchor starting at 65.34s (reproducing Chasing Cars test scenario) + tempo = TempoDocument(anchors=[TempoAnchor(sec=65.34, beat=0.0, bpm=104.0)]) + (song_dir / "tempo.json").write_text(tempo.model_dump_json(indent=2)) + + # Vocals starting at 7.08s, ending at 258.7s + vocals = VocalsDocument( + lines=[ + VocalLine( + start=7.08, + end=10.0, + syllables=[ + VocalSyllable(text="I'll ", start=7.08, end=8.0, midi=52.0), + VocalSyllable(text="do ", start=8.0, end=9.0, midi=52.0), + VocalSyllable(text="it ", start=9.0, end=10.0, midi=52.0), + ], + ), + VocalLine( + start=250.0, + end=258.7, + syllables=[ + VocalSyllable(text="cars", start=250.0, end=258.7, midi=50.0), + ], + ), + ] + ) + (song_dir / "vocals.json").write_text(vocals.model_dump_json(indent=2)) + + txt_path = export_ultrastar(song_dir) + content = txt_path.read_text(encoding="utf-8") + + assert "#TITLE:Chasing Cars" in content + assert "#ARTIST:Snow Patrol" in content + assert "#LANGUAGE:English" in content + assert "#MP3:Chasing_Cars.mp3" in content + assert "#GAP:7080" in content + assert "#BPM:104.00" in content + + parsed = parse_ultrastar(txt_path) + assert parsed.bpm == 104.0 + assert parsed.gap_ms == 7080.0 + # First note must be at 7.08s + assert parsed.lines[0][0].start_sec == pytest.approx(7.08, abs=0.05) + # Last note must be around 250.0s to 258.7s (NOT compressed to 52s!) + # Quantization resolution at 104 BPM is 15 / 104 = 0.144s per tick + last_note = parsed.lines[1][0] + assert last_note.start_sec == pytest.approx(250.0, abs=0.15) + assert last_note.end_sec == pytest.approx(258.7, abs=0.15)