From 1b6921af9443690b33be654b8541b72b96ab0c4f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 19:20:43 +0000 Subject: [PATCH] feat: Custom Music dialog on the Patches page A "Custom Music" button on the Patches page opens a dialog with the music you can replace, on Races, Battle and Menus tabs: the Retro Rewind tracks plus the original courses, arenas and menus. Choosing or dropping a song converts it to BRSTM and saves it in a normal "Custom Music" patch, so it goes through the existing patch system and can be turned off or deleted there like any other patch. Clicking that patch opens the dialog. The dialog can sort, search and play each track's current music (the custom song, Retro Rewind's file or the original from the game disc). Its settings choose the final lap style (faster like Retro Rewind, faster at the same pitch, or unchanged), turn volume matching on or off and open the music folder. Songs loop at their own loop points (BRSTM, LOOPSTART tags) or where the music repeats; otherwise the ending crossfades into the opening. New songs are matched to the loudness of the music they replace. The audio work uses existing libraries: NAudio (WAV, AIFF, resampling and playback), NLayer (MP3), NVorbis (Ogg Vorbis), FLAKE (FLAC), NWaves (FFT and same-pitch tempo change), VGAudio (BRSTM) and TagLib# (tags). The game disc is read with RVZSharp through the existing disc image service. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VhnFEntEAoknsP4NCnn73y --- .../CustomMusic/CustomMusicCatalogTests.cs | 174 ++++++++ .../CustomMusic/CustomMusicServiceTests.cs | 241 +++++++++++ .../CustomMusic/MusicConverterTests.cs | 227 ++++++++++ .../CustomMusic/PulsarConfigBuilder.cs | 134 ++++++ WheelWizard.UI.Test/CustomMusicWindowTests.cs | 146 +++++++ .../CustomMusic/Catalog/GameMusicCatalog.cs | 164 +++++++ .../Catalog/MusicCatalogService.cs | 217 ++++++++++ .../Features/CustomMusic/Catalog/MusicSlot.cs | 51 +++ .../CustomMusic/Catalog/PulsarConfigReader.cs | 252 +++++++++++ .../CustomMusic/CustomMusicExtensions.cs | 14 + .../CustomMusic/CustomMusicService.cs | 333 +++++++++++++++ .../Features/CustomMusic/LoopFinder.cs | 156 +++++++ WheelWizard/Features/CustomMusic/Loudness.cs | 84 ++++ .../Features/CustomMusic/MusicConverter.cs | 399 ++++++++++++++++++ .../Features/CustomMusic/MusicPlayer.cs | 66 +++ .../CustomMusic/Views/CustomMusicRow.cs | 106 +++++ .../CustomMusic/Views/CustomMusicWindow.axaml | 131 ++++++ .../Views/CustomMusicWindow.axaml.cs | 234 ++++++++++ .../Features/DiscImages/DiscImageService.cs | 73 +++- .../Features/Mods/Views/ModsPage.axaml | 24 +- .../Features/Mods/Views/ModsPage.axaml.cs | 15 + WheelWizard/Resources/Languages/en.yml | 41 ++ WheelWizard/SetupExtensions.cs | 2 + .../Views/Styles/Resources/Icons.axaml | 5 + WheelWizard/WheelWizard.csproj | 13 + 25 files changed, 3272 insertions(+), 30 deletions(-) create mode 100644 WheelWizard.Test/Features/CustomMusic/CustomMusicCatalogTests.cs create mode 100644 WheelWizard.Test/Features/CustomMusic/CustomMusicServiceTests.cs create mode 100644 WheelWizard.Test/Features/CustomMusic/MusicConverterTests.cs create mode 100644 WheelWizard.Test/Features/CustomMusic/PulsarConfigBuilder.cs create mode 100644 WheelWizard.UI.Test/CustomMusicWindowTests.cs create mode 100644 WheelWizard/Features/CustomMusic/Catalog/GameMusicCatalog.cs create mode 100644 WheelWizard/Features/CustomMusic/Catalog/MusicCatalogService.cs create mode 100644 WheelWizard/Features/CustomMusic/Catalog/MusicSlot.cs create mode 100644 WheelWizard/Features/CustomMusic/Catalog/PulsarConfigReader.cs create mode 100644 WheelWizard/Features/CustomMusic/CustomMusicExtensions.cs create mode 100644 WheelWizard/Features/CustomMusic/CustomMusicService.cs create mode 100644 WheelWizard/Features/CustomMusic/LoopFinder.cs create mode 100644 WheelWizard/Features/CustomMusic/Loudness.cs create mode 100644 WheelWizard/Features/CustomMusic/MusicConverter.cs create mode 100644 WheelWizard/Features/CustomMusic/MusicPlayer.cs create mode 100644 WheelWizard/Features/CustomMusic/Views/CustomMusicRow.cs create mode 100644 WheelWizard/Features/CustomMusic/Views/CustomMusicWindow.axaml create mode 100644 WheelWizard/Features/CustomMusic/Views/CustomMusicWindow.axaml.cs diff --git a/WheelWizard.Test/Features/CustomMusic/CustomMusicCatalogTests.cs b/WheelWizard.Test/Features/CustomMusic/CustomMusicCatalogTests.cs new file mode 100644 index 00000000..4ea2270a --- /dev/null +++ b/WheelWizard.Test/Features/CustomMusic/CustomMusicCatalogTests.cs @@ -0,0 +1,174 @@ +using System.Text; +using Microsoft.Extensions.Logging.Abstractions; +using Testably.Abstractions.Testing; +using WheelWizard.CustomDistributions; +using WheelWizard.CustomMusic.Catalog; + +namespace WheelWizard.Test.Features.CustomMusic; + +public class CustomMusicCatalogTests +{ + [Fact] + public void GameCatalog_ListsEveryCourseArenaAndMenuOnce() + { + var slots = GameMusicCatalog.Build(); + + Assert.Equal(slots.Count, slots.Select(slot => slot.Key).Distinct().Count()); + // 32 courses where Luigi Circuit and Mario Circuit share music, plus Galaxy Colosseum. + Assert.Equal(32, slots.Count(slot => slot.Category == MusicCategory.Course)); + Assert.Equal(10, slots.Count(slot => slot.Category == MusicCategory.Arena)); + Assert.Equal(7, slots.Count(slot => slot.Category == MusicCategory.Menu)); + Assert.Equal(41, slots.Count(slot => slot.HasFinalLap)); // every course and arena but Galaxy Colosseum + } + + [Fact] + public void GameCatalog_UsesTheGamesExactFileNames() + { + var slots = GameMusicCatalog.Build().ToDictionary(slot => slot.Key); + + var luigi = slots["game:n_circuit32"]; + Assert.Equal("Luigi Circuit / Mario Circuit", luigi.Name); + Assert.Equal(["n_Circuit32_n.brstm"], luigi.FileNames); + Assert.Equal(["n_Circuit32_f.brstm"], luigi.FinalLapFileNames); + Assert.Equal("n_Circuit32_n.brstm", luigi.GameFile); + Assert.Equal("n_BossMI_32.brstm", slots["game:n_bossmi_32"].GameFile); + Assert.Equal(["n_Kinoko_F.brstm"], slots["game:n_kinoko"].FinalLapFileNames); + Assert.False(slots["game:n_bossmi_32"].HasFinalLap); + + var waiting = slots["game:o_wi-fi_waiting32"]; + Assert.Equal(MusicCategory.Menu, waiting.Category); + Assert.Equal(["o_Wi-Fi_waiting32.brstm"], waiting.FileNames); + Assert.Equal(["wifi_lobby_bg.brstm"], slots["menu:wifi_lobby_bg"].FileNames); + Assert.Null(slots["menu:wifi_lobby_bg"].GameFile); // Retro Rewind's own menu music, not on the game disc + } + + [Theory] + [InlineData("n_Circuit32_n", "n_Circuit32")] + [InlineData("STRM_N_KOOPA_F", "STRM_N_KOOPA")] + [InlineData("title_bg", "title_bg")] + public void GameCatalog_StripsLapSuffixes(string name, string expected) => + Assert.Equal(expected, GameMusicCatalog.StripLapSuffix(name)); + + [Fact] + public async Task CatalogService_ListsRetroRewindTracksFirst_UnderTheFileNamesRetroRewindLoads() + { + var fs = new MockFileSystem(); + var root = fs.Path.Combine(Path.GetTempPath(), "custom-music-tests", Guid.NewGuid().ToString("N")); + var retroRewind = fs.Path.Combine(root, "RetroRewind6"); + fs.Directory.CreateDirectory(fs.Path.Combine(retroRewind, "Binaries")); + fs.Directory.CreateDirectory(fs.Path.Combine(retroRewind, "strm")); + var config = new PulsarConfigBuilder() + .Cup("3DS Cup") + .Track(0x08, 0x08, "3DS") + .Track(0x01, 0x01, "3DS") + .Track(0x02, 0x1A, "Ghost Valley", variants: [(0x02, 0x1A, "Ghost Valley (Night)")]) + .Track(0x03, 0x03, "Unique Track") + .File(0, "dsA") + .File(1, "dsB") + .File(2, "gv") + .File((1 << 12) + 2, "gvNight") + .Build(); + fs.File.WriteAllBytes(fs.Path.Combine(retroRewind, "Binaries", "ConfigRT.pul"), config); + fs.File.WriteAllText(fs.Path.Combine(retroRewind, "strm", "dsA_n.brstm"), ""); + fs.File.WriteAllText(fs.Path.Combine(retroRewind, "strm", "dsA_n2.brstm"), ""); + var paths = Substitute.For(); + paths.RootFolderPath.Returns(root); + paths.RetroRewindFolderPath.Returns(retroRewind); + paths.XmlFilePath.Returns(fs.Path.Combine(root, "riivolution", "RetroRewind6.xml")); + + var slots = await new MusicCatalogService(fs, paths, NullLogger.Instance).LoadAsync(); + + var tracks = slots.TakeWhile(slot => slot.Category == MusicCategory.RetroRewindTrack).ToList(); + Assert.Equal(["3DS (dsA)", "3DS (dsB)", "Ghost Valley (all versions)", "Unique Track"], tracks.Select(slot => slot.Name)); + Assert.Equal(["dsA_n.brstm", "dsA_n2.brstm"], tracks[0].FileNames); + Assert.Equal(["dsA_final.brstm"], tracks[0].FinalLapFileNames); + Assert.Equal("Retro Rewind music · dsA", tracks[0].Detail); + Assert.Equal((fs.Path.Combine(retroRewind, "strm", "dsA_n.brstm"), null), (tracks[0].RetroRewindFile, tracks[0].GameFile)); + Assert.Equal("Uses Moo Moo Meadows music · dsB", tracks[1].Detail); + Assert.Equal((null, "n_Farm_n.brstm"), (tracks[1].RetroRewindFile, tracks[1].GameFile)); + Assert.Equal(["gv_n.brstm", "gvNight_n.brstm"], tracks[2].FileNames); + Assert.Equal(["Unique Track_n.brstm"], tracks[3].FileNames); // no file name, so Retro Rewind looks for the track name + Assert.Equal("3DS Cup", tracks[3].Group); + Assert.Equal(GameMusicCatalog.Build().Count, slots.Count - tracks.Count); + } + + [Fact] + public void PulsarConfigReader_ReadsCupsTracksVariantsAndFileNames() + { + var config = new PulsarConfigBuilder() + .Cup("SNES Cup") + .Track(0x08, 0x18, "SNES Mario Circuit 1", version: "v2") + .Track(0x01, 0x08, "SNES Donut Plains 1") + .Track(0x02, 0x1A, "SNES Ghost Valley 1", variants: [(0x02, 0x1A, "SNES Ghost Valley 1 (Night)")]) + .Track(0x04, 0x0F, "SNES Bowser Castle 1") + .Cup("N64 Cup") // an odd cup count is stored rounded up to an even number + .Track(0x00, 0x1C, "N64 Luigi Raceway") + .Track(0x05, 0x05, "N64 Moo Moo Farm") + .Track(0x06, 0x06, "N64 Koopa Troopa Beach") + .Track(0x07, 0x07, "N64 Kalimari Desert") + .Cup("GBA Cup") + .Track(0x08, 0x08, "GBA Peach Circuit") + .Track(0x09, 0x09, "GBA Riverside Park") + .Track(0x0A, 0x0A, "GBA Cheese Land") + .Track(0x0B, 0x0B, "GBA Sky Garden") + .File(0, "rMC1") + .File(2, "rGV1") + .File((1 << 12) + 2, "rGV1Night") + .File(4, "nLR") + .Build(); + + var result = PulsarConfigReader.Read(config); + + Assert.Equal(["SNES Cup", "N64 Cup", "GBA Cup"], result.CupNames); + Assert.Equal(12, result.Tracks.Count); + + var mc1 = result.Tracks[0]; + Assert.Equal("SNES Mario Circuit 1 v2", mc1.Name); // text around colour codes is kept, the codes themselves are dropped + Assert.Equal("rMC1", mc1.FileName); + Assert.Equal(0x18, mc1.MusicSlot); + Assert.Null(result.Tracks[1].FileName); + + var ghostValley = result.Tracks[2]; + Assert.Equal("SNES Ghost Valley 1 (all versions)", ghostValley.Name); + var night = Assert.Single(ghostValley.Variants); + Assert.Equal("SNES Ghost Valley 1 (Night)", night.Name); + Assert.Equal("rGV1Night", night.FileName); + Assert.Equal(0x1A, night.MusicSlot); + + Assert.Equal(1, result.Tracks[4].CupIndex); + Assert.Equal("GBA Sky Garden", result.Tracks[11].Name); + Assert.Empty(result.Tracks[11].Variants); + } + + [Fact] + public void PulsarConfigReader_KeepsNamesThatAreSplitByColourCodes() + { + var config = new PulsarConfigBuilder() + .Cup("3DS Cup") + .Track(0x08, 0x08, "\u00013DS\u0001 Toad Circuit") + .Track(0x01, 0x01, "\u00013DS\u0001 Rainbow Road") + .Track(0x02, 0x02, "3DS Music Park") + .Track(0x03, 0x03, "3DS Piranha Plant Slide") + .Build(); + + var names = PulsarConfigReader.Read(config).Tracks.Select(track => track.Name); + + Assert.Equal(["3DS Toad Circuit", "3DS Rainbow Road", "3DS Music Park", "3DS Piranha Plant Slide"], names); + } + + [Fact] + public void PulsarConfigReader_RejectsOtherFiles() => + Assert.Throws(() => PulsarConfigReader.Read(Encoding.ASCII.GetBytes("RSTM and some more bytes here...."))); + + [Fact] + public void PulsarConfigReader_FileSectionKeepsOnlyTheFileName() + { + var files = PulsarConfigReader.ReadFileSection( + Encoding.UTF8.GetBytes("FILE\n1A=uMKS|expert1|expert2\n1001A=uMKSv2|a\nbroken line\n0?cupicon\n") + ); + + Assert.Equal("uMKS", files[0x1A]); + Assert.Equal("uMKSv2", files[0x1001A]); + Assert.Equal(2, files.Count); + } +} diff --git a/WheelWizard.Test/Features/CustomMusic/CustomMusicServiceTests.cs b/WheelWizard.Test/Features/CustomMusic/CustomMusicServiceTests.cs new file mode 100644 index 00000000..75a642bc --- /dev/null +++ b/WheelWizard.Test/Features/CustomMusic/CustomMusicServiceTests.cs @@ -0,0 +1,241 @@ +using System.Collections.ObjectModel; +using Microsoft.Extensions.Logging.Abstractions; +using Testably.Abstractions.Testing; +using WheelWizard.ApplicationData; +using WheelWizard.CustomMusic; +using WheelWizard.CustomMusic.Catalog; +using WheelWizard.DiscImages; +using WheelWizard.Models.Mods; +using WheelWizard.Mods; +using WheelWizard.Settings; +using WheelWizard.Settings.Types; +using static WheelWizard.Localization.TranslationFunctions; + +namespace WheelWizard.Test.Features.CustomMusic; + +public class CustomMusicServiceTests +{ + private static readonly Dictionary Slots = GameMusicCatalog.Build().ToDictionary(slot => slot.Key); + + private readonly MockFileSystem _fs = new(); + private readonly IModManager _mods = Substitute.For(); + private readonly IDiscImageService _discs = Substitute.For(); + private string _gamePath = ""; + private readonly ObservableCollection _modList = []; + private readonly string _songFolder; + private readonly string _modFolder; + private readonly Func _createService; + private readonly CustomMusicService _service; + + public CustomMusicServiceTests() + { + var location = Substitute.For(); + location.DirectoryPath.Returns(_fs.Path.Combine(Path.GetTempPath(), "custom-music-tests", Guid.NewGuid().ToString("N"))); + var paths = new ModPaths(location, _fs); + _modFolder = paths.GetModDirectoryPath(CustomMusicService.ModTitle); + _songFolder = _fs.Path.Combine(location.DirectoryPath, "Songs"); + _fs.Directory.CreateDirectory(_songFolder); + + _mods.Mods.Returns(_modList); + _mods.ReloadAsync().Returns(Ok()); + _mods.SaveModsAsync().Returns(Ok()); + _mods.GetLowestActivePriority().Returns(_ => _modList.Count == 0 ? 0 : _modList.Min(mod => mod.Priority)); + _mods + .AddModAsync(Arg.Any()) + .Returns(call => + { + _modList.Add(call.Arg()); + return Ok(); + }); + _mods + .DeleteModAsync(Arg.Any()) + .Returns(call => + { + _fs.Directory.Delete(_modFolder, recursive: true); + _modList.Remove(call.Arg()); + return Ok(); + }); + + var settings = Substitute.For(); + var gameLocation = new WhWzSetting("GameLocation", ""); + settings.GAME_LOCATION.Returns(gameLocation); + settings.Get(gameLocation).Returns(_ => _gamePath); + + _createService = () => + new CustomMusicService( + Substitute.For(), + _mods, + paths, + location, + _discs, + settings, + _fs, + NullLogger.Instance + ); + _service = _createService(); + } + + [Fact] + public async Task SetSong_InstallsBothLapsInAnEnabledTopPriorityPatch() + { + _modList.Add( + new Mod + { + Title = "Music Pack", + Priority = 3, + IsEnabled = true, + } + ); + + var result = await _service.SetSongAsync(Slots["game:n_circuit32"], Song("My Song.wav")); + + Assert.True(result.IsSuccess); + Assert.Equal(new CustomSong("My Song", null), result.Value); // the file name stands in for a missing title tag + var mod = Assert.Single(_modList, m => m.Title == CustomMusicService.ModTitle); + Assert.True(mod.IsEnabled); + Assert.Equal(2, mod.Priority); // beats the music pack (lower number wins) + var normal = _fs.File.ReadAllBytes(_fs.Path.Combine(_modFolder, "n_Circuit32_n.brstm")); + var finalLap = _fs.File.ReadAllBytes(_fs.Path.Combine(_modFolder, "n_Circuit32_f.brstm")); + Assert.True(finalLap.Length < normal.Length); // the final lap plays faster, so it is shorter + Assert.Equal(new CustomSong("My Song", null), _service.LoadSongs(Slots.Values)["game:n_circuit32"]); + } + + [Fact] + public async Task SetSong_ForMenuMusic_WritesOneFile() + { + await _service.SetSongAsync(Slots["menu:title_bg"], Song("Menu.wav")); + + Assert.Equal(["title_bg.brstm"], _fs.Directory.EnumerateFiles(_modFolder, "*.brstm").Select(_fs.Path.GetFileName)); + } + + [Fact] + public async Task SetSong_LeavesEverythingAsItWas_WhenTheSongCannotBeUsed() + { + var broken = _fs.Path.Combine(_songFolder, "broken.mp3"); + _fs.File.WriteAllBytes(broken, new byte[50_000]); + var slot = Slots["game:n_circuit32"]; + + Assert.Equal(t("custom_music.error.unsupported"), (await _service.SetSongAsync(slot, Song("song.wav", ".wma"))).Error?.Message); + Assert.Equal( + t("custom_music.error.missing"), + (await _service.SetSongAsync(slot, _fs.Path.Combine(_songFolder, "gone.wav"))).Error?.Message + ); + Assert.Equal(t("custom_music.error.unreadable"), (await _service.SetSongAsync(slot, broken)).Error?.Message); + + Assert.Empty(_modList); + Assert.False(_fs.Directory.Exists(_modFolder)); + Assert.Empty(_service.LoadSongs(Slots.Values)); + } + + [Fact] + public async Task SetSong_ReplacesTheOldSong_AndTurnsADisabledPatchBackOn() + { + var slot = Slots["game:n_circuit32"]; + await _service.SetSongAsync(slot, Song("First.wav")); + var mod = _modList.Single(); + mod.IsEnabled = false; + + await _service.SetSongAsync(slot, Song("Second.wav")); + + Assert.True(mod.IsEnabled); + await _mods.Received(1).SaveModsAsync(); + Assert.Equal("Second", Assert.Single(_service.LoadSongs(Slots.Values)).Value.Title); + } + + [Fact] + public async Task Reset_RemovesTheSong_AndThePatchWithTheLastSong() + { + await _service.SetSongAsync(Slots["game:n_circuit32"], Song("One.wav")); + await _service.SetSongAsync(Slots["menu:title_bg"], Song("Two.wav")); + + Assert.True((await _service.ResetAsync(Slots["game:n_circuit32"])).IsSuccess); + + Assert.False(_fs.File.Exists(_fs.Path.Combine(_modFolder, "n_Circuit32_n.brstm"))); + Assert.False(_fs.File.Exists(_fs.Path.Combine(_modFolder, "n_Circuit32_f.brstm"))); + Assert.Single(_modList); + Assert.Equal(["menu:title_bg"], _service.LoadSongs(Slots.Values).Keys); + + Assert.True((await _service.ResetAsync(Slots["menu:title_bg"])).IsSuccess); + + Assert.Empty(_modList); + Assert.Empty(_service.LoadSongs(Slots.Values)); + } + + [Fact] + public async Task DeletingThePatch_ForgetsItsSongs() + { + await _service.SetSongAsync(Slots["game:n_circuit32"], Song("Song.wav")); + + await _mods.DeleteModAsync(_modList.Single()); + + Assert.Empty(_service.LoadSongs(Slots.Values)); + } + + [Fact] + public void MusicInThePatchFolder_CountsAsCustom_EvenWithoutAName() + { + _fs.Directory.CreateDirectory(_modFolder); + _fs.File.WriteAllBytes(_fs.Path.Combine(_modFolder, "n_Circuit32_n.brstm"), [1, 2, 3]); + + Assert.Equal(new CustomSong(t("custom_music.unknown_song"), null), Assert.Single(_service.LoadSongs(Slots.Values)).Value); + } + + [Fact] + public async Task Settings_AreSaved_AndUsedForNewSongs() + { + var settings = new CustomMusicSettings(FinalLapStyle.Unchanged, MatchVolume: false); + + _service.SaveSettings(settings); + await _service.SetSongAsync(Slots["game:n_circuit32"], Song("Song.wav")); + + Assert.Equal(settings, _createService().LoadSettings()); + Assert.Equal( + _fs.File.ReadAllBytes(_fs.Path.Combine(_modFolder, "n_Circuit32_n.brstm")), + _fs.File.ReadAllBytes(_fs.Path.Combine(_modFolder, "n_Circuit32_f.brstm")) + ); + } + + [Fact] + public async Task NewSongs_MatchTheVolumeOfTheOriginalMusic() + { + var original = _fs.Path.Combine(_songFolder, "original.brstm"); + var quiet = MusicConverter.Convert(MusicConverterTests.Wav(32000, 2, 10, amplitude: 0.1), ".wav", new ConvertOptions(false)).Normal; + _fs.File.WriteAllBytes(original, quiet); + var slot = Slots["menu:title_bg"] with { RetroRewindFile = original }; + + await _service.SetSongAsync(slot, Song("Loud.wav")); + + var installed = MusicConverterTests.ReadBrstm(_fs.File.ReadAllBytes(_fs.Path.Combine(_modFolder, "title_bg.brstm"))); + Assert.InRange( + MusicConverterTests.LoudnessOf(installed), + MusicConverter.MeasureLoudness(quiet, ".brstm") - 0.5, + MusicConverter.MeasureLoudness(quiet, ".brstm") + 0.5 + ); + } + + [Fact] + public async Task ReadMusic_GivesTheCustomSong_OrElseTheOriginalMusic() + { + var slot = Slots["game:n_circuit32"]; + Assert.Equal(t("custom_music.error.no_game"), (await _service.ReadMusicAsync(slot)).Error?.Message); + Assert.Equal(t("custom_music.error.no_original"), (await _service.ReadMusicAsync(slot with { GameFile = null })).Error?.Message); + + _gamePath = "/games/mkwii.rvz"; + byte[] disc = [1, 2, 3]; + _discs.ReadFile("/games/mkwii.rvz", "sound/strm/n_Circuit32_n.brstm").Returns(Ok(disc)); + Assert.Equal(disc, (await _service.ReadMusicAsync(slot)).Value); + + await _service.SetSongAsync(slot, Song("Song.wav")); + Assert.Equal( + _fs.File.ReadAllBytes(_fs.Path.Combine(_modFolder, "n_Circuit32_n.brstm")), + (await _service.ReadMusicAsync(slot)).Value + ); + } + + private string Song(string name, string? extension = null) + { + var path = _fs.Path.Combine(_songFolder, extension == null ? name : _fs.Path.ChangeExtension(name, extension)); + _fs.File.WriteAllBytes(path, MusicConverterTests.Wav(32000, channels: 2, seconds: 2)); + return path; + } +} diff --git a/WheelWizard.Test/Features/CustomMusic/MusicConverterTests.cs b/WheelWizard.Test/Features/CustomMusic/MusicConverterTests.cs new file mode 100644 index 00000000..bc6d6d2b --- /dev/null +++ b/WheelWizard.Test/Features/CustomMusic/MusicConverterTests.cs @@ -0,0 +1,227 @@ +using System.Text; +using CUETools.Codecs.FLAKE; +using NAudio.Wave; +using VGAudio.Containers.NintendoWare; +using VGAudio.Formats.Pcm16; +using WheelWizard.CustomMusic; + +namespace WheelWizard.Test.Features.CustomMusic; + +public class MusicConverterTests +{ + [Fact] + public void Wav_BecomesALoopingStereoBrstm() + { + var music = MusicConverter.Convert(Wav(48000, channels: 1, seconds: 3), ".WAV", new ConvertOptions(WithFinalLap: false)); + + var normal = ReadBrstm(music.Normal); + Assert.Null(music.FinalLap); + Assert.Equal((MusicConverter.SampleRate, 2), (normal.SampleRate, normal.ChannelCount)); + Assert.True(normal.Channels[1].Max() > 10_000); // the mono song plays on both sides + Assert.InRange(Frequency(normal), 437, 443); + // Without a repeat in the music, the ending crossfades into the opening and the loop continues after it. + Assert.True(normal.Looping); + Assert.True(normal.LoopStart > 0); + Assert.Equal(normal.SampleCount, normal.LoopEnd); + } + + [Fact] + public void FinalLap_FollowsTheChosenStyle() + { + var song = Wav(32000, channels: 2, seconds: 4); + var normal = ReadBrstm(MusicConverter.Convert(song, ".wav", new ConvertOptions(false)).Normal); + + var faster = ReadBrstm(MusicConverter.Convert(song, ".wav", new ConvertOptions(true, FinalLapStyle.Faster)).FinalLap!); + Assert.InRange(LoopLength(faster) * MusicConverter.FinalLapSpeed, LoopLength(normal) * 0.995, LoopLength(normal) * 1.005); + Assert.InRange(Frequency(faster), 463, 470); + + var samePitch = ReadBrstm(MusicConverter.Convert(song, ".wav", new ConvertOptions(true, FinalLapStyle.FasterSamePitch)).FinalLap!); + Assert.InRange(LoopLength(samePitch) * MusicConverter.FinalLapTempo, LoopLength(normal) * 0.995, LoopLength(normal) * 1.005); + Assert.InRange(Frequency(samePitch), 436, 444); + + var unchanged = MusicConverter.Convert(song, ".wav", new ConvertOptions(true, FinalLapStyle.Unchanged)); + Assert.Same(unchanged.Normal, unchanged.FinalLap); + } + + [Fact] + public void RepeatingMusic_LoopsAtTheRepeat() + { + var music = MusicConverter.Convert(StructuredSong(), ".wav", new ConvertOptions(false)); + + // The verse and chorus (31 s together) play twice; the loop jumps from the second time back to the first. + Assert.InRange(LoopLength(ReadBrstm(music.Normal)) / (double)MusicConverter.SampleRate, 30.9, 31.1); + } + + [Fact] + public void Brstm_KeepsItsLoop() + { + var channel = Tone(32000 * 4, 32000, 0.5); + var song = new BrstmWriter().GetFile(new Pcm16Format([channel, channel], 32000).WithLoop(true, 32000, 96000)); + + var normal = ReadBrstm(MusicConverter.Convert(song, ".brstm", new ConvertOptions(false)).Normal); + + Assert.True(normal.Looping); + Assert.Equal(64000, LoopLength(normal)); + } + + [Fact] + public void Flac_IsDecoded() + { + var normal = ReadBrstm(MusicConverter.Convert(Flac(44100, seconds: 2), ".flac", new ConvertOptions(false)).Normal); + + Assert.Equal((MusicConverter.SampleRate, 2), (normal.SampleRate, normal.ChannelCount)); + Assert.InRange(Frequency(normal), 437, 443); + } + + [Fact] + public void Volume_MatchesTheTarget_AsFarAsThePeaksAllow() + { + var quiet = Wav(32000, channels: 2, seconds: 10, amplitude: 0.1); + Assert.InRange(MusicConverter.MeasureLoudness(quiet, ".wav"), -21, -20); // a sine at -20 dBFS, lowered a bit by K-weighting + + var matched = ReadBrstm(MusicConverter.Convert(quiet, ".wav", new ConvertOptions(false, TargetLoudness: -16)).Normal); + Assert.InRange(LoudnessOf(matched), -16.5, -15.5); + + // A sine at 0 LUFS would have to peak at full scale; the volume stops short of that. + var limited = ReadBrstm(MusicConverter.Convert(quiet, ".wav", new ConvertOptions(false, TargetLoudness: 0)).Normal); + Assert.True(limited.Channels[0].Max(sample => Math.Abs((int)sample)) < short.MaxValue); + Assert.True(LoudnessOf(limited) < -1); + } + + [Fact] + public void Tags_GiveTheTitleAndArtist() + { + var music = MusicConverter.Convert( + WithInfo(Wav(32000, channels: 2, seconds: 1), title: "Test Song", artist: "Wii Bands"), + ".wav", + new ConvertOptions(false) + ); + + Assert.Equal(("Test Song", "Wii Bands"), (music.Title, music.Artist)); + } + + [Theory] + [InlineData(".m4a")] + [InlineData(".wma")] + public void OtherFileTypes_AreNotSupported(string extension) + { + Assert.False(MusicConverter.IsSupported(extension)); + Assert.Throws(() => MusicConverter.Convert(Wav(32000, 2, 1), extension, new ConvertOptions(false))); + } + + [Fact] + public void SongsShorterThanASecond_AreRejected() => + Assert.Throws(() => MusicConverter.Convert(Wav(32000, 2, 0.5), ".wav", new ConvertOptions(false))); + + [Fact] + public void SongsLongerThanTheLimit_AreRejected() => + Assert.Throws( + () => MusicConverter.Convert(Wav(32000, 1, MusicConverter.MaxSeconds + 1), ".wav", new ConvertOptions(false)) + ); + + /// A 440 Hz tone. + internal static byte[] Wav(int sampleRate, int channels, double seconds, double amplitude = 0.5) => + Wav(sampleRate, channels, Tone((int)(sampleRate * seconds), sampleRate, amplitude)); + + private static byte[] Wav(int sampleRate, int channels, short[] mono) + { + var samples = mono.SelectMany(sample => Enumerable.Repeat(sample, channels)).ToArray(); + using var stream = new MemoryStream(); + using (var writer = new WaveFileWriter(stream, new WaveFormat(sampleRate, 16, channels))) + writer.WriteSamples(samples, 0, samples.Length); + + return stream.ToArray(); + } + + private static short[] Tone(int length, int sampleRate, double amplitude) => + Enumerable + .Range(0, length) + .Select(i => (short)(amplitude * short.MaxValue * Math.Sin(2 * Math.PI * 440 * i / sampleRate))) + .ToArray(); + + /// Intro, verse, chorus, verse, chorus, outro: random notes, but each verse and chorus is played identically twice. + private static byte[] StructuredSong() + { + const int rate = 32000; + short[] Section(int seed, int beats) + { + var random = new Random(seed); + var notes = new List(); + for (var beat = 0; beat < beats; beat++) + { + var frequency = 220 * Math.Pow(2, random.Next(12) / 12.0); + var volume = 0.15 + 0.15 * random.NextDouble(); + for (var i = 0; i < rate / 2; i++) + { + var t = i / (double)rate; + var envelope = Math.Min(1, t / 0.01) * Math.Exp(-3 * t); + notes.Add( + (short)( + short.MaxValue + * volume + * envelope + * (Math.Sin(2 * Math.PI * frequency * t) + 0.5 * Math.Sin(4 * Math.PI * frequency * t)) + ) + ); + } + } + + return notes.ToArray(); + } + + var verse = Section(2, 30); + var chorus = Section(3, 32); + return Wav(rate, 2, [.. Section(1, 16), .. verse, .. chorus, .. verse, .. chorus, .. Section(4, 10)]); + } + + private static byte[] Flac(int sampleRate, double seconds) + { + var mono = Tone((int)(sampleRate * seconds), sampleRate, 0.5); + var pcm = new AudioPCMConfig(16, 2, sampleRate); + var bytes = mono.SelectMany(sample => BitConverter.GetBytes(sample).Concat(BitConverter.GetBytes(sample))).ToArray(); + using var stream = new MemoryStream(); + var writer = new FlakeWriter(null, stream, new FlakeWriterSettings { PCM = pcm, EncoderMode = "5" }); + writer.Write(new AudioBuffer(pcm, bytes, mono.Length)); + writer.Close(); + return stream.ToArray(); + } + + // Adds a RIFF INFO chunk, where WAV files keep their tags. + private static byte[] WithInfo(byte[] wav, string title, string artist) + { + byte[] info = [.. "INFO"u8, .. Item("INAM", title), .. Item("IART", artist)]; + byte[] file = [.. wav, .. "LIST"u8, .. BitConverter.GetBytes(info.Length), .. info]; + BitConverter.GetBytes(file.Length - 8).CopyTo(file, 4); + return file; + + static byte[] Item(string id, string text) => + [.. Encoding.ASCII.GetBytes(id), .. BitConverter.GetBytes(text.Length + 1), .. Encoding.ASCII.GetBytes(text), 0]; + } + + internal static Pcm16Format ReadBrstm(byte[] file) => new BrstmReader().Read(file).GetFormat(); + + private static int LoopLength(Pcm16Format pcm) => pcm.LoopEnd - pcm.LoopStart; + + // Zero crossings of the left channel, away from the crossfaded edges. + private static double Frequency(Pcm16Format pcm) + { + var samples = pcm.Channels[0]; + int from = pcm.SampleRate / 10, + to = pcm.LoopEnd - pcm.SampleRate / 2, + crossings = 0; + for (var i = from + 1; i < to; i++) + { + if (samples[i - 1] < 0 && samples[i] >= 0) + crossings++; + } + + return crossings / ((to - from) / (double)pcm.SampleRate); + } + + internal static double LoudnessOf(Pcm16Format pcm) => + WheelWizard.CustomMusic.Loudness.Measure( + pcm.Channels.Select(channel => channel.Select(sample => sample / 32768f).ToArray()).ToArray(), + pcm.SampleRate, + pcm.LoopEnd + ); +} diff --git a/WheelWizard.Test/Features/CustomMusic/PulsarConfigBuilder.cs b/WheelWizard.Test/Features/CustomMusic/PulsarConfigBuilder.cs new file mode 100644 index 00000000..3f2ed6df --- /dev/null +++ b/WheelWizard.Test/Features/CustomMusic/PulsarConfigBuilder.cs @@ -0,0 +1,134 @@ +using System.Buffers.Binary; +using System.Text; + +namespace WheelWizard.Test.Features.CustomMusic; + +/// Writes a minimal Pulsar config (PULS header, CUPS, BMG names and FILE block) like Pulsar's creator tool. +internal sealed class PulsarConfigBuilder +{ + private readonly List _cups = []; + private readonly List<(byte Slot, byte Music, string Name, string? Version, (byte Slot, byte Music, string Name)[] Variants)> _tracks = + []; + private readonly Dictionary _files = []; + + public PulsarConfigBuilder Cup(string name) + { + _cups.Add(name); + return this; + } + + public PulsarConfigBuilder Track(byte slot, byte music, string name, string? version = null, (byte, byte, string)[]? variants = null) + { + _tracks.Add((slot, music, name, version, variants ?? [])); + return this; + } + + public PulsarConfigBuilder File(int id, string fileName) + { + _files[id] = fileName; + return this; + } + + public byte[] Build() + { + var storedCups = _cups.Count + _cups.Count % 2; + var trackTable = new List(); + for (var i = 0; i < storedCups * 4; i++) + { + var track = _tracks[i % _tracks.Count]; + trackTable.AddRange([track.Slot, track.Music, .. U16(i < _tracks.Count ? track.Variants.Length : 0), .. U32(0x1234)]); + } + + var variants = _tracks.SelectMany(track => track.Variants).SelectMany(v => new[] { v.Slot, v.Music }).ToArray(); + byte[] cupsBody = + [ + .. U16(_cups.Count), + 2, + 0, + .. new byte[8], + .. S32(variants.Length / 2), + .. trackTable, + .. variants, + .. new byte[storedCups * 8], + ]; + byte[] cups = [.. "CUPS"u8, .. U32(3), .. U32(12 + cupsBody.Length), .. cupsBody]; + + var messages = new List<(uint Id, byte[] Text)>(); + for (var i = 0; i < _cups.Count; i++) + messages.Add((0x10000u + (uint)i, Utf16(_cups[i]))); + for (var i = 0; i < _tracks.Count; i++) + { + var track = _tracks[i]; + messages.Add( + ( + 0x20000u + (uint)i, + track.Version == null + ? Utf16(track.Name) + : [.. Utf16(track.Name), .. ColourEscape, .. Utf16(" " + track.Version), .. ColourEscape] + ) + ); + if (track.Variants.Length == 0) + continue; + messages.Add((0x20000u + (8u << 12) + (uint)i, Utf16(track.Name + " (all versions)"))); + for (var v = 0; v < track.Variants.Length; v++) + messages.Add((0x20000u + ((uint)(v + 1) << 12) + (uint)i, Utf16(track.Variants[v].Name))); + } + + var fileText = "FILE\n" + string.Concat(_files.Select(file => $"{file.Key:X}={file.Value}|e1|e2|e3|e4\n")) + "0?cupicon\n"; + + const int headerLength = 0x24; + byte[] info = [.. "INFO"u8, .. U32(1), .. U32(12 + 0x30), .. new byte[0x30]]; + var cupsOffset = headerLength + info.Length; + var bmgOffset = cupsOffset + cups.Length; + var header = new byte[headerLength]; + "PULS"u8.CopyTo(header); + BinaryPrimitives.WriteInt32BigEndian(header.AsSpan(4), 3); + BinaryPrimitives.WriteInt32BigEndian(header.AsSpan(8), headerLength); + BinaryPrimitives.WriteInt32BigEndian(header.AsSpan(0x0C), cupsOffset); + BinaryPrimitives.WriteInt32BigEndian(header.AsSpan(0x10), bmgOffset); + return [.. header, .. info, .. cups, .. Bmg(messages), .. Encoding.UTF8.GetBytes(fileText)]; + } + + private static readonly byte[] ColourEscape = [0, 0x1A, 8, 0, 0, 3, 0, 0]; + + private static byte[] Bmg(List<(uint Id, byte[] Text)> messages) + { + var text = new List { 0, 0 }; + var offsets = new List(); + foreach (var message in messages) + { + offsets.Add(text.Count); + text.AddRange([.. message.Text, 0, 0]); + } + + var inf = Block( + "INF1", + [.. U16(messages.Count), .. U16(8), .. U32(0), .. offsets.SelectMany(offset => U32(offset).Concat(U32(0)))] + ); + var dat = Block("DAT1", [.. text]); + var mid = Block("MID1", [.. U16(messages.Count), 0x10, 0, .. U32(0), .. messages.SelectMany(message => U32((int)message.Id))]); + byte[] body = [.. inf, .. dat, .. mid]; + byte[] header = [.. "MESGbmg1"u8, .. U32(0x20 + body.Length), .. U32(3), 2, .. new byte[15]]; + return [.. header, .. body]; + } + + private static byte[] Block(string magic, byte[] body) + { + var length = (8 + body.Length + 0x1F) & ~0x1F; + var block = new byte[length]; + Encoding.ASCII.GetBytes(magic, block.AsSpan(0, 4)); + BinaryPrimitives.WriteInt32BigEndian(block.AsSpan(4), length); + body.CopyTo(block, 8); + return block; + } + + /// UTF-16 text; a \u0001 in the text becomes a colour escape code. + private static byte[] Utf16(string text) => + text.Split('\u0001').Select(part => Encoding.BigEndianUnicode.GetBytes(part)).Aggregate((a, b) => [.. a, .. ColourEscape, .. b]); + + private static byte[] U16(int value) => [(byte)(value >> 8), (byte)value]; + + private static byte[] U32(int value) => [(byte)(value >> 24), (byte)(value >> 16), (byte)(value >> 8), (byte)value]; + + private static byte[] S32(int value) => U32(value); +} diff --git a/WheelWizard.UI.Test/CustomMusicWindowTests.cs b/WheelWizard.UI.Test/CustomMusicWindowTests.cs new file mode 100644 index 00000000..9914860f --- /dev/null +++ b/WheelWizard.UI.Test/CustomMusicWindowTests.cs @@ -0,0 +1,146 @@ +using Avalonia.Controls; +using Avalonia.Headless.XUnit; +using Avalonia.Interactivity; +using Avalonia.Platform.Storage; +using Avalonia.Threading; +using Avalonia.VisualTree; +using NSubstitute; +using WheelWizard.CustomMusic; +using WheelWizard.CustomMusic.Catalog; +using WheelWizard.CustomMusic.Views; +using WheelWizard.Shared; +using WheelWizard.Shared.Desktop.Storage; +using WheelWizard.Views.Components; + +namespace WheelWizard.UI.Test; + +public class CustomMusicWindowTests +{ + private static readonly MusicSlot Luigi = Slot("game:n_circuit32", "Luigi Circuit", MusicCategory.Course); + private static readonly MusicSlot Coconut = Slot("game:n_shopping32", "Coconut Mall", MusicCategory.Course); + private static readonly MusicSlot Block = Slot("game:n_block", "Block Plaza", MusicCategory.Arena); + private static readonly MusicSlot Title = Slot("menu:title_bg", "Title screen", MusicCategory.Menu); + + private readonly ICustomMusicService _music = Substitute.For(); + private readonly IFilePickerService _picker = Substitute.For(); + private readonly IMusicPlayer _player = Substitute.For(); + + public CustomMusicWindowTests() + { + IReadOnlyList slots = [Luigi, Coconut, Block, Title]; + _music.LoadSlotsAsync(Arg.Any()).Returns(slots); + _music + .LoadSongs(Arg.Any>()) + .Returns(new Dictionary { [Coconut.Key] = new("Theme", "Band"), [Title.Key] = new("Intro", null) }); + _music.LoadSettings().Returns(new CustomMusicSettings()); + } + + [AvaloniaFact] + public void Window_ShowsEachTab_SortsAndSearches_AndChangesSongs() + { + _music.SetSongAsync(Luigi, "/songs/new.mp3", Arg.Any()).Returns(OperationResult.Ok(new CustomSong("New", null))); + _music.ResetAsync(Coconut).Returns(OperationResult.Ok()); + _picker.OpenSingleFileAsync(Arg.Any(), Arg.Any>()).Returns("/songs/new.mp3"); + using var owner = new UiTestHost(); + var window = Open(owner); + var list = window.FindControl("MusicList")!; + var tabs = window.FindControl("Tabs")!; + var sort = window.FindControl("SortBox")!; + + Assert.False(window.FindControl("LoadingSpinner")!.IsVisible); + Assert.Equal(["Luigi Circuit", "Coconut Mall"], Names(list)); + Assert.Equal("Theme · Band", Rows(list)[1].Subtitle); + sort.SelectedIndex = 1; + Assert.Equal(["Coconut Mall", "Luigi Circuit"], Names(list)); + sort.SelectedIndex = 2; + Assert.Equal(["Coconut Mall", "Luigi Circuit"], Names(list)); + sort.SelectedIndex = 0; + window.FindControl("SearchInput")!.Text = "band"; + Layout(owner); + Assert.Equal(["Coconut Mall"], Names(list)); + window.FindControl("SearchInput")!.Text = ""; + tabs.SelectedIndex = 1; + Assert.Equal(["Block Plaza"], Names(list)); + tabs.SelectedIndex = 2; + Assert.Equal(["Title screen"], Names(list)); + tabs.SelectedIndex = 0; + Layout(owner); + + // Each row has a play button, a reset button shown only for custom songs, and a choose button. + Assert.False(Buttons(list, 0)[1].IsVisible); + Click(Buttons(list, 0)[2]); + Click(Buttons(list, 1)[1]); + Assert.Equal("New", Rows(list)[0].Subtitle); + Assert.True(Buttons(list, 0)[1].IsVisible); + Assert.False(Rows(list)[1].IsCustom); + } + + [AvaloniaFact] + public void Window_PlaysTheMusic_AndSavesTheSettings() + { + byte[] brstm = [1, 2, 3]; + _music.ReadMusicAsync(Luigi).Returns(OperationResult.Ok(brstm)); + _music.FolderPath.Returns("/patches/Custom Music"); + using var owner = new UiTestHost(); + var window = Open(owner); + var list = window.FindControl("MusicList")!; + + Click(Buttons(list, 0)[0]); + _player.Received(1).Play(brstm); + Assert.True(Rows(list)[0].IsPlaying); + _player.Finished += Raise.Event(); + Dispatcher.UIThread.RunJobs(); + Assert.False(Rows(list)[0].IsPlaying); + + Click(window.FindControl("SettingsButton")!); + Assert.True(window.FindControl("SettingsPanel")!.IsVisible); + Assert.False(list.IsVisible); + var matchVolume = window.FindControl("MatchVolumeToggle")!; + Assert.True(matchVolume.IsChecked); + matchVolume.IsChecked = false; + Click(matchVolume); + _music.Received().SaveSettings(new CustomMusicSettings(FinalLapStyle.Faster, MatchVolume: false)); + window.FindControl("FinalLapBox")!.SelectedIndex = 1; + _music.Received().SaveSettings(new CustomMusicSettings(FinalLapStyle.FasterSamePitch, MatchVolume: false)); + } + + private CustomMusicWindow Open(UiTestHost owner) + { + owner.Show(); + var window = new CustomMusicWindow(_music, _picker, _player); + window.SetModalOwner(owner); + window.Show(); + Layout(owner); + return window; + } + + private static MusicSlot Slot(string key, string name, MusicCategory category) => + new() + { + Key = key, + Name = name, + Category = category, + Group = "Cup", + FileNames = [key + ".brstm"], + }; + + private static List Rows(ListBox list) => list.ItemsSource!.Cast().ToList(); + + private static IEnumerable Names(ListBox list) => Rows(list).Select(row => row.Name); + + private static ActionButton[] Buttons(ListBox list, int index) => + list.ContainerFromIndex(index)!.GetVisualDescendants().OfType().ToArray(); + + private static void Click(Button button) + { + button.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + Dispatcher.UIThread.RunJobs(); + } + + private static void Layout(Window owner) + { + owner.UpdateLayout(); + Dispatcher.UIThread.RunJobs(); + owner.UpdateLayout(); + } +} diff --git a/WheelWizard/Features/CustomMusic/Catalog/GameMusicCatalog.cs b/WheelWizard/Features/CustomMusic/Catalog/GameMusicCatalog.cs new file mode 100644 index 00000000..d1b9d51c --- /dev/null +++ b/WheelWizard/Features/CustomMusic/Catalog/GameMusicCatalog.cs @@ -0,0 +1,164 @@ +namespace WheelWizard.CustomMusic.Catalog; + +/// Mario Kart Wii's course, arena and menu music, with the exact file names from the retail revo_kart.brsar. +public static class GameMusicCatalog +{ + private sealed record CourseMusic(string Name, string Cup, int CourseId, string Normal, string Final, string? AlsoUsedBy = null); + + private static readonly CourseMusic[] Courses = + [ + new("Luigi Circuit", "Mushroom Cup", 0x08, "n_Circuit32_n", "n_Circuit32_f", "Mario Circuit"), + new("Moo Moo Meadows", "Mushroom Cup", 0x01, "n_Farm_n", "n_Farm_F"), + new("Mushroom Gorge", "Mushroom Cup", 0x02, "n_Kinoko_n", "n_Kinoko_F"), + new("Toad's Factory", "Mushroom Cup", 0x04, "STRM_N_FACTORY_N", "STRM_N_FACTORY_F"), + new("Coconut Mall", "Flower Cup", 0x05, "n_Shopping32_n", "n_Shopping32_f"), + new("DK Summit", "Flower Cup", 0x06, "n_Snowboard32_n", "n_Snowboard32_f"), + new("Wario's Gold Mine", "Flower Cup", 0x07, "STRM_N_TRUCK_N", "STRM_N_TRUCK_F"), + new("Daisy Circuit", "Star Cup", 0x09, "n_Daisy32_n", "n_Daisy32_f"), + new("Koopa Cape", "Star Cup", 0x0F, "STRM_N_WATER_N", "STRM_N_WATER_F"), + new("Maple Treeway", "Star Cup", 0x0B, "n_maple_n", "n_maple_F"), + new("Grumble Volcano", "Star Cup", 0x03, "n_Volcano32_n", "n_Volcano32_f"), + new("Dry Dry Ruins", "Special Cup", 0x0E, "STRM_N_DESERT_N", "STRM_N_DESERT_F"), + new("Moonview Highway", "Special Cup", 0x0A, "STRM_N_RIDGEHIGHWAY_N", "STRM_N_RIDGEHIGHWAY_F"), + new("Bowser's Castle", "Special Cup", 0x0C, "STRM_N_KOOPA_N", "STRM_N_KOOPA_F"), + new("Rainbow Road", "Special Cup", 0x0D, "n_Rainbow32_n", "n_Rainbow32_f"), + new("GCN Peach Beach", "Shell Cup", 0x10, "r_GC_Beach32_n", "r_GC_Beach32_f"), + new("DS Yoshi Falls", "Shell Cup", 0x14, "r_DS_Jungle32_n", "r_DS_Jungle32_f"), + new("SNES Ghost Valley 2", "Shell Cup", 0x19, "r_SFC_Obake32_n", "r_SFC_Obake32_f"), + new("N64 Mario Raceway", "Shell Cup", 0x1A, "r_64_Circuit32_n", "r_64_Circuit32_f"), + new("N64 Sherbet Land", "Banana Cup", 0x1B, "r_64_Sherbet32_n", "r_64_Sherbet32_f"), + new("GBA Shy Guy Beach", "Banana Cup", 0x1F, "r_AGB_Beach32_n", "r_AGB_Beach32_f"), + new("DS Delfino Square", "Banana Cup", 0x17, "r_DS_Town32_n", "r_DS_Town32_f"), + new("GCN Waluigi Stadium", "Banana Cup", 0x12, "r_GC_Stadium32_n", "r_GC_Stadium32_f"), + new("DS Desert Hills", "Leaf Cup", 0x15, "r_DS_Desert32_n", "r_DS_Desert32_f"), + new("GBA Bowser Castle 3", "Leaf Cup", 0x1E, "r_AGB_Kuppa32_n", "r_AGB_Kuppa32_f"), + new("N64 DK's Jungle Parkway", "Leaf Cup", 0x1D, "r_64_Jungle32_n", "r_64_Jungle32_f"), + new("GCN Mario Circuit", "Leaf Cup", 0x11, "r_GC_Circuit32_n", "r_GC_Circuit32_f"), + new("SNES Mario Circuit 3", "Lightning Cup", 0x18, "r_SFC_Circuit32_n", "r_SFC_Circuit32_f"), + new("DS Peach Gardens", "Lightning Cup", 0x16, "r_DS_Garden32_n", "r_DS_Garden32_f"), + new("GCN DK Mountain", "Lightning Cup", 0x13, "r_GC_Mountain32_n", "r_GC_Mountain32_f"), + new("N64 Bowser's Castle", "Lightning Cup", 0x1C, "r_64_Kuppa32_n", "r_64_Kuppa32_f"), + ]; + + private static readonly CourseMusic[] Arenas = + [ + new("Block Plaza", "Wii Arenas", 0x21, "n_block_n", "n_block_F"), + new("Delfino Pier", "Wii Arenas", 0x20, "n_venice_n", "n_venice_F"), + new("Chain Chomp Roulette", "Wii Arenas", 0x22, "n_casino_n", "n_casino_F"), + new("Funky Stadium", "Wii Arenas", 0x23, "n_skate_n", "n_skate_F"), + new("Thwomp Desert", "Wii Arenas", 0x24, "n_ryuusa_n", "n_ryuusa_F"), + new("GCN Cookie Land", "Retro Arenas", 0x25, "r_GC_Battle32_n", "r_GC_Battle32_F"), + new("DS Twilight House", "Retro Arenas", 0x26, "r_ds_battle_n", "r_ds_battle_F"), + new("SNES Battle Course 4", "Retro Arenas", 0x27, "r_sfc_battle_n", "r_sfc_battle_F"), + new("GBA Battle Course 3", "Retro Arenas", 0x28, "r_agb_battle_n", "r_agb_battle_F"), + new("N64 Skyscraper", "Retro Arenas", 0x29, "r_64_battle_n", "r_64_battle_F"), + ]; + + /// Course id of Galaxy Colosseum, whose music has no final lap file. + public const int GalaxyColosseumCourseId = 0x36; + + private sealed record SingleMusic(string Key, string Name, string File, string? Detail = null, bool IsGameFile = true); + + private static readonly SingleMusic[] Menus = + [ + new("title_bg", "Title screen", "title_bg", "Retro Rewind title screen music", IsGameFile: false), + new("offline_bg", "Offline menus", "offline_bg", "Single player and local multiplayer menus", IsGameFile: false), + new("wifi_globe_bg", "Online menus", "wifi_globe_bg", "Online menu and globe screens", IsGameFile: false), + new("wifi_lobby_bg", "Online lobby", "wifi_lobby_bg", "Online rooms and track voting", IsGameFile: false), + new("o_Wi-Fi_waiting32", "Waiting to join a race", "o_Wi-Fi_waiting32", "Also plays while watching ghost replays"), + new("o_Option_32", "Options menu", "o_Option_32"), + new("o_Ending_PartA_32", "Credits", "o_Ending_PartA_32"), + ]; + + public static string KeyForGameFile(string baseName) => "game:" + baseName.ToLowerInvariant(); + + /// Display name of the original course with the given id. + public static string? CourseName(int courseId) + { + if (courseId == 0x00) + return "Mario Circuit"; + if (courseId == GalaxyColosseumCourseId) + return "Galaxy Colosseum"; + return Courses.Concat(Arenas).FirstOrDefault(c => c.CourseId == courseId)?.Name; + } + + /// The game disc's music file of the original course with the given id. + public static string? GameFile(int courseId) + { + if (courseId == 0x00) + return "n_Circuit32_n.brstm"; + if (courseId == GalaxyColosseumCourseId) + return "n_BossMI_32.brstm"; + return Courses.Concat(Arenas).FirstOrDefault(c => c.CourseId == courseId) is { } course ? course.Normal + ".brstm" : null; + } + + public static IReadOnlyList Build() + { + var slots = new List(); + foreach (var course in Courses) + { + var name = course.AlsoUsedBy == null ? course.Name : $"{course.Name} / {course.AlsoUsedBy}"; + slots.Add( + CourseSlot( + course, + name, + MusicCategory.Course, + course.AlsoUsedBy == null ? null : $"Shared by {course.Name} and {course.AlsoUsedBy}" + ) + ); + } + + slots.Add( + new MusicSlot + { + Key = KeyForGameFile("n_BossMI_32"), + Name = "Galaxy Colosseum", + Category = MusicCategory.Course, + Group = "Other courses", + FileNames = ["n_BossMI_32.brstm"], + Detail = "Its final lap always speeds up instead of switching files", + GameFile = "n_BossMI_32.brstm", + } + ); + + foreach (var arena in Arenas) + slots.Add(CourseSlot(arena, arena.Name, MusicCategory.Arena, null)); + + foreach (var menu in Menus) + { + slots.Add( + new MusicSlot + { + Key = menu.IsGameFile ? KeyForGameFile(menu.File) : "menu:" + menu.Key.ToLowerInvariant(), + Name = menu.Name, + Category = MusicCategory.Menu, + Group = "Menus", + FileNames = [menu.File + ".brstm"], + Detail = menu.Detail, + GameFile = menu.IsGameFile ? menu.File + ".brstm" : null, + } + ); + } + + return slots; + } + + private static MusicSlot CourseSlot(CourseMusic course, string name, MusicCategory category, string? detail) => + new() + { + Key = KeyForGameFile(StripLapSuffix(course.Normal)), + Name = name, + Category = category, + Group = course.Cup, + FileNames = [course.Normal + ".brstm"], + FinalLapFileNames = [course.Final + ".brstm"], + Detail = detail, + GameFile = course.Normal + ".brstm", + }; + + /// "n_Circuit32_n" -> "n_Circuit32", "STRM_N_KOOPA_N" -> "STRM_N_KOOPA". + public static string StripLapSuffix(string name) => + name.EndsWith("_n", StringComparison.OrdinalIgnoreCase) || name.EndsWith("_f", StringComparison.OrdinalIgnoreCase) + ? name[..^2] + : name; +} diff --git a/WheelWizard/Features/CustomMusic/Catalog/MusicCatalogService.cs b/WheelWizard/Features/CustomMusic/Catalog/MusicCatalogService.cs new file mode 100644 index 00000000..3963eecb --- /dev/null +++ b/WheelWizard/Features/CustomMusic/Catalog/MusicCatalogService.cs @@ -0,0 +1,217 @@ +using System.IO.Abstractions; +using System.Xml.Linq; +using Microsoft.Extensions.Logging; +using WheelWizard.CustomDistributions; + +namespace WheelWizard.CustomMusic.Catalog; + +public interface IMusicCatalogService +{ + /// Builds the list of replaceable music: the installed Retro Rewind tracks plus the original game's music. + Task> LoadAsync(CancellationToken cancellationToken = default); +} + +public sealed class MusicCatalogService(IFileSystem fileSystem, ICustomDistributionPaths paths, ILogger logger) + : IMusicCatalogService +{ + private static readonly string[] ConfigFiles = ["ConfigRT.pul", "ConfigCT.pul", "ConfigBT.pul"]; + + public Task> LoadAsync(CancellationToken cancellationToken = default) => + Task.Run(() => Load(cancellationToken), cancellationToken); + + private IReadOnlyList Load(CancellationToken cancellationToken) + { + var shippedMusic = new Dictionary(); + var retroRewindSlots = new List(); + try + { + if (fileSystem.Directory.Exists(paths.RetroRewindFolderPath)) + { + shippedMusic = IndexRetroRewindMusic(); + retroRewindSlots = BuildRetroRewindSlots(shippedMusic, cancellationToken); + } + } + // A damaged config can also make the binary readers run off the end of the data. + catch (Exception exception) + when (exception + is IOException + or InvalidDataException + or UnauthorizedAccessException + or ArgumentException + or IndexOutOfRangeException + ) + { + logger.LogWarning(exception, "Could not read the Retro Rewind track list for custom music."); + } + + var gameSlots = GameMusicCatalog + .Build() + .Select(slot => slot with { RetroRewindFile = shippedMusic.GetValueOrDefault(slot.FileNames[0]) }); + return retroRewindSlots.Concat(gameSlots).ToList(); + } + + private List BuildRetroRewindSlots(Dictionary shippedMusic, CancellationToken cancellationToken) + { + var binaries = fileSystem.Path.Combine(paths.RetroRewindFolderPath, "Binaries"); + var configs = ConfigFiles.Select(name => fileSystem.Path.Combine(binaries, name)).Where(fileSystem.File.Exists).ToList(); + if (configs.Count == 0) + { + var single = fileSystem.Path.Combine(binaries, "Config.pul"); + if (fileSystem.File.Exists(single)) + configs.Add(single); + } + + var slots = new List(); + var globalOffset = 0; + foreach (var configPath in configs) + { + cancellationToken.ThrowIfCancellationRequested(); + var config = PulsarConfigReader.Read(fileSystem.File.ReadAllBytes(configPath)); + var isBattle = fileSystem.Path.GetFileName(configPath).Equals("ConfigBT.pul", StringComparison.OrdinalIgnoreCase); + var configKey = fileSystem.Path.GetFileNameWithoutExtension(configPath).ToLowerInvariant(); + + foreach (var track in config.Tracks) + { + var globalIndex = globalOffset + track.LocalIndex; + var slot = BuildTrackSlot(track, config, globalIndex, isBattle, configKey, shippedMusic); + if (slot != null) + slots.Add(slot); + } + + globalOffset += config.CupCount * 4; + } + + // Keys must be unique; duplicated creator names would otherwise collide. + var unique = slots.GroupBy(slot => slot.Key).Select(group => group.First()).ToList(); + + // Tracks that share a name get their file name appended so they can be told apart. + var duplicated = unique + .GroupBy(slot => slot.Name, StringComparer.OrdinalIgnoreCase) + .Where(group => group.Count() > 1) + .Select(group => group.Key) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + return unique + .Select(slot => duplicated.Contains(slot.Name) ? slot with { Name = $"{slot.Name} ({StripSuffix(slot.FileNames[0])})" } : slot) + .ToList(); + } + + private MusicSlot? BuildTrackSlot( + PulsarTrack track, + PulsarConfig config, + int globalIndex, + bool isBattle, + string configKey, + Dictionary shippedMusic + ) + { + // Retro Rewind tries strm/_n.brstm with the file name, the track name, then the index (BRSTMExpansion.cpp). + var candidates = new[] { track.FileName, track.Name, globalIndex.ToString() } + .Where(name => !string.IsNullOrWhiteSpace(name)) + .Select(name => name!.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + var baseName = candidates.FirstOrDefault(IsUsableFileName); + if (baseName == null) + return null; + + var shipped = candidates.Select(name => shippedMusic.GetValueOrDefault($"{name}_n.brstm")).FirstOrDefault(path => path != null); + + var normalNames = new List { $"{baseName}_n.brstm" }; + var finalNames = new List { $"{baseName}_final.brstm" }; + foreach (var variant in track.Variants.Where(v => v.FileName != null && IsUsableFileName(v.FileName))) + { + normalNames.Add($"{variant.FileName}_n.brstm"); + finalNames.Add($"{variant.FileName}_final.brstm"); + } + + // Some tracks switch to new music at checkpoints (name_n2, name_n3, ...); replace those parts too. + for (var part = 2; part <= 9; part++) + { + if (candidates.Any(name => shippedMusic.ContainsKey($"{name}_n{part}.brstm"))) + normalNames.Add($"{baseName}_n{part}.brstm"); + } + + var name = track.Name ?? track.FileName ?? $"Track {globalIndex}"; + var cupName = track.CupIndex < config.CupNames.Count ? config.CupNames[track.CupIndex] : $"Cup {track.CupIndex + 1}"; + var musicCourse = GameMusicCatalog.CourseName(track.MusicSlot); + var detail = + shipped != null ? "Retro Rewind music" + : musicCourse != null ? $"Uses {musicCourse} music" + : null; + + // The file name tells apart tracks whose names look alike. + detail = detail == null ? baseName : $"{detail} · {baseName}"; + + return new MusicSlot + { + Key = "rr:" + (track.FileName ?? $"{configKey}:{track.LocalIndex}").ToLowerInvariant(), + Name = name, + Category = isBattle ? MusicCategory.RetroRewindArena : MusicCategory.RetroRewindTrack, + Group = cupName, + FileNames = normalNames.Distinct(StringComparer.OrdinalIgnoreCase).ToList(), + FinalLapFileNames = finalNames.Distinct(StringComparer.OrdinalIgnoreCase).ToList(), + Detail = detail, + RetroRewindFile = shipped, + GameFile = shipped == null ? GameMusicCatalog.GameFile(track.MusicSlot) : null, + }; + } + + private static string StripSuffix(string fileName) => + fileName.EndsWith("_n.brstm", StringComparison.OrdinalIgnoreCase) ? fileName[..^8] : fileName; + + // The music is written as _n.brstm, so the name must be a valid file name everywhere. + private static bool IsUsableFileName(string name) => + name.Length is > 0 and <= 48 + && name.IndexOfAny(['<', '>', ':', '"', '/', '\\', '|', '?', '*']) < 0 + && name.All(c => c >= ' ') + && !name.EndsWith(' ') + && !name.EndsWith('.'); + + /// Every BRSTM Retro Rewind maps onto /sound/strm, indexed by file name. + private Dictionary IndexRetroRewindMusic() + { + var folders = new List + { + fileSystem.Path.Combine(paths.RetroRewindFolderPath, "strm"), + fileSystem.Path.Combine(paths.RetroRewindFolderPath, "CTBRSTM"), + }; + + try + { + if (fileSystem.File.Exists(paths.XmlFilePath)) + { + var document = XDocument.Parse(fileSystem.File.ReadAllText(paths.XmlFilePath)); + foreach (var folder in document.Descendants().Where(element => element.Name.LocalName == "folder")) + { + var disc = folder.Attribute("disc")?.Value.Trim('/') ?? string.Empty; + var external = folder.Attribute("external")?.Value; + if (external == null || !disc.Equals("sound/strm", StringComparison.OrdinalIgnoreCase)) + continue; + + var relative = external + .Replace("{$pack}", "RetroRewind6") + .TrimStart('/', '\\') + .Replace('/', fileSystem.Path.DirectorySeparatorChar); + folders.Add(fileSystem.Path.Combine(paths.RootFolderPath, relative)); + } + } + } + catch (Exception exception) when (exception is System.Xml.XmlException or IOException) + { + logger.LogDebug(exception, "Could not read the Retro Rewind XML while looking for music folders."); + } + + var index = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var folder in folders.Distinct(StringComparer.OrdinalIgnoreCase).Where(fileSystem.Directory.Exists)) + { + // Match the extension ourselves: wildcard patterns are case sensitive on Linux. + foreach (var file in fileSystem.Directory.EnumerateFiles(folder, "*", SearchOption.TopDirectoryOnly)) + { + if (file.EndsWith(".brstm", StringComparison.OrdinalIgnoreCase)) + index.TryAdd(fileSystem.Path.GetFileName(file), file); + } + } + + return index; + } +} diff --git a/WheelWizard/Features/CustomMusic/Catalog/MusicSlot.cs b/WheelWizard/Features/CustomMusic/Catalog/MusicSlot.cs new file mode 100644 index 00000000..e544f03c --- /dev/null +++ b/WheelWizard/Features/CustomMusic/Catalog/MusicSlot.cs @@ -0,0 +1,51 @@ +namespace WheelWizard.CustomMusic.Catalog; + +public enum MusicCategory +{ + /// A Retro Rewind race track (retro and custom tracks from ConfigRT/ConfigCT). + RetroRewindTrack, + + /// A Retro Rewind battle arena (ConfigBT). + RetroRewindArena, + + /// One of the original 32 courses (or Galaxy Colosseum). + Course, + + /// One of the original 10 battle arenas. + Arena, + + /// Menu background music. + Menu, +} + +/// One piece of music the player can replace, and the files the game loads for it. +public sealed record MusicSlot +{ + /// Stable identifier, used to remember songs between sessions and Retro Rewind updates. + public required string Key { get; init; } + + public required string Name { get; init; } + public required MusicCategory Category { get; init; } + + /// Section the music belongs to, e.g. "Mushroom Cup". + public required string Group { get; init; } + + /// File names (no folders) that receive the normal version. + public required IReadOnlyList FileNames { get; init; } + + /// File names that receive the final lap version; empty when the music has no final lap. + public IReadOnlyList FinalLapFileNames { get; init; } = []; + + /// Short explanation of what currently plays here (e.g. "Uses Luigi Circuit music"). + public string? Detail { get; init; } + + /// Full path of the music Retro Rewind itself plays here, when it ships a file for it. + public string? RetroRewindFile { get; init; } + + /// The file in the game disc's sound/strm folder whose music plays here otherwise. + public string? GameFile { get; init; } + + public bool HasFinalLap => FinalLapFileNames.Count > 0; + + public IEnumerable AllFileNames => FileNames.Concat(FinalLapFileNames); +} diff --git a/WheelWizard/Features/CustomMusic/Catalog/PulsarConfigReader.cs b/WheelWizard/Features/CustomMusic/Catalog/PulsarConfigReader.cs new file mode 100644 index 00000000..2d6b9f3d --- /dev/null +++ b/WheelWizard/Features/CustomMusic/Catalog/PulsarConfigReader.cs @@ -0,0 +1,252 @@ +using System.Buffers.Binary; +using System.Text; + +namespace WheelWizard.CustomMusic.Catalog; + +/// A track defined in a Pulsar config file. +public sealed record PulsarTrack( + int LocalIndex, + int CupIndex, + byte Slot, + byte MusicSlot, + string? Name, + string? FileName, + IReadOnlyList Variants +); + +public sealed record PulsarVariant(int VariantIndex, byte Slot, byte MusicSlot, string? Name, string? FileName); + +public sealed record PulsarConfig(IReadOnlyList CupNames, IReadOnlyList Tracks) +{ + public int CupCount => CupNames.Count; +} + +/// Reads Pulsar's Binaries/Config*.pul: the cups and tracks, their names (BMG) and their music file names (FILE). +public static class PulsarConfigReader +{ + private const uint PulsMagic = 0x50554C53; // "PULS" + private const uint CupsMagic = 0x43555053; // "CUPS" + private const int BmgCups = 0x10000; + private const int BmgTracks = 0x20000; + + public static PulsarConfig Read(byte[] file) + { + if (file.Length < 0x20 || BinaryPrimitives.ReadUInt32BigEndian(file) != PulsMagic) + throw new InvalidDataException("This is not a Pulsar config file."); + + var cupsOffset = BinaryPrimitives.ReadInt32BigEndian(file.AsSpan(0x0C)); + var bmgOffset = BinaryPrimitives.ReadInt32BigEndian(file.AsSpan(0x10)); + if (cupsOffset <= 0 || cupsOffset + 0x1C > file.Length) + throw new InvalidDataException("The Pulsar config has no CUPS section."); + if (BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(cupsOffset)) != CupsMagic) + throw new InvalidDataException("The Pulsar CUPS section is invalid."); + + var cupCount = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(cupsOffset + 0x0C)); + var totalVariants = BinaryPrimitives.ReadInt32BigEndian(file.AsSpan(cupsOffset + 0x18)); + var storedCups = cupCount % 2 == 1 ? cupCount + 1 : cupCount; + var trackCount = cupCount * 4; + var tracksStart = cupsOffset + 0x1C; + var variantsStart = tracksStart + storedCups * 4 * 8; + if (variantsStart + Math.Max(0, totalVariants) * 2 > file.Length) + throw new InvalidDataException("The Pulsar track table is truncated."); + + var messages = new Dictionary(); + var fileNames = new Dictionary(); + if (bmgOffset > 0 && bmgOffset + 0x20 <= file.Length && BmgReader.IsBmg(file.AsSpan(bmgOffset))) + { + var bmgLength = (int) + Math.Min(BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(bmgOffset + 8)), (uint)(file.Length - bmgOffset)); + messages = BmgReader.Read(file.AsSpan(bmgOffset, bmgLength)); + fileNames = ReadFileSection(file.AsSpan(bmgOffset + bmgLength)); + } + + var cupNames = new List(cupCount); + for (var cup = 0; cup < cupCount; cup++) + cupNames.Add(messages.TryGetValue((uint)(BmgCups + cup), out var cupName) ? CleanName(cupName) : $"Cup {cup + 1}"); + + var tracks = new List(trackCount); + var variantCursor = 0; + for (var i = 0; i < trackCount; i++) + { + var entry = tracksStart + i * 8; + var slot = file[entry]; + var musicSlot = file[entry + 1]; + var variantCount = BinaryPrimitives.ReadUInt16BigEndian(file.AsSpan(entry + 2)); + + var variants = new List(variantCount); + for (var v = 1; v <= variantCount && variantCursor < totalVariants; v++, variantCursor++) + { + var variantEntry = variantsStart + variantCursor * 2; + variants.Add( + new PulsarVariant( + v, + file[variantEntry], + file[variantEntry + 1], + messages.TryGetValue((uint)(BmgTracks + (v << 12) + i), out var variantName) ? CleanName(variantName) : null, + fileNames.GetValueOrDefault((v << 12) + i) + ) + ); + } + + // Tracks with variants have a shared "common name" at variant index 8. + string? name = null; + if (variantCount > 0 && messages.TryGetValue((uint)(BmgTracks + (8 << 12) + i), out var common)) + name = CleanName(common); + if (string.IsNullOrWhiteSpace(name) && messages.TryGetValue((uint)(BmgTracks + i), out var trackName)) + name = CleanName(trackName); + + tracks.Add( + new PulsarTrack( + i, + i / 4, + slot, + musicSlot, + string.IsNullOrWhiteSpace(name) ? null : name, + fileNames.GetValueOrDefault(i), + variants + ) + ); + } + + return new PulsarConfig(cupNames, tracks); + } + + /// "FILE" followed by lines like "1A=uMKS|expert1|expert2..."; keys are (variant << 12) | track. + public static Dictionary ReadFileSection(ReadOnlySpan data) + { + var result = new Dictionary(); + if (data.Length < 4) + return result; + + var text = Encoding.UTF8.GetString(data).TrimStart('', '\0'); + if (!text.StartsWith("FILE", StringComparison.Ordinal)) + return result; + + foreach (var rawLine in text.Split('\n').Skip(1)) + { + var line = rawLine.Trim('\r', ' ', '\t', '\0'); + var equals = line.IndexOf('='); + if (equals <= 0) + continue; + + var key = line[..equals].Trim(); + var value = line[(equals + 1)..]; + var pipe = value.IndexOf('|'); + if (pipe < 0) + continue; + value = value[..pipe].Trim(); + if (value.Length == 0) + continue; + + if (int.TryParse(key, System.Globalization.NumberStyles.HexNumber, null, out var id)) + result[id] = value; + } + + return result; + } + + private static string CleanName(string name) => name.Trim(); +} + +/// Minimal reader for Nintendo BMG message files (UTF-16 with INF1/DAT1/MID1 blocks). +public static class BmgReader +{ + public static bool IsBmg(ReadOnlySpan data) => data.Length >= 8 && Encoding.ASCII.GetString(data[..8]) == "MESGbmg1"; + + /// Returns message id -> text, with escape sequences (colours, icons) removed. + public static Dictionary Read(ReadOnlySpan data) + { + var result = new Dictionary(); + if (!IsBmg(data)) + return result; + + var encoding = data[0x10]; + var blockCount = BinaryPrimitives.ReadUInt32BigEndian(data[0x0C..]); + int inf = -1, + dat = -1, + mid = -1; + var position = 0x20; + for (var block = 0; block < blockCount && position + 8 <= data.Length; block++) + { + var magic = Encoding.ASCII.GetString(data.Slice(position, 4)); + var size = (int)BinaryPrimitives.ReadUInt32BigEndian(data[(position + 4)..]); + if (size < 8) + break; + switch (magic) + { + case "INF1": + inf = position; + break; + case "DAT1": + dat = position; + break; + case "MID1": + mid = position; + break; + } + + position += size; + } + + if (inf < 0 || dat < 0) + return result; + + var count = BinaryPrimitives.ReadUInt16BigEndian(data[(inf + 8)..]); + var entrySize = BinaryPrimitives.ReadUInt16BigEndian(data[(inf + 10)..]); + var midCount = mid >= 0 ? BinaryPrimitives.ReadUInt16BigEndian(data[(mid + 8)..]) : 0; + var textStart = dat + 8; + + for (var i = 0; i < count; i++) + { + var entry = inf + 0x10 + i * entrySize; + if (entry + 4 > data.Length) + break; + var offset = (int)BinaryPrimitives.ReadUInt32BigEndian(data[entry..]); + var id = mid >= 0 && i < midCount ? BinaryPrimitives.ReadUInt32BigEndian(data[(mid + 0x10 + i * 4)..]) : (uint)i; + var text = ReadString(data, textStart + offset, encoding); + if (text != null) + result[id] = text; + } + + return result; + } + + private static string? ReadString(ReadOnlySpan data, int start, byte encoding) + { + if (start < 0 || start >= data.Length) + return null; + + var builder = new StringBuilder(); + if (encoding is 2 or 0) + { + var position = start; + while (position + 1 < data.Length) + { + var c = (char)BinaryPrimitives.ReadUInt16BigEndian(data[position..]); + if (c == '\0') + break; + if (c == '\u001A') + { + // Escape: 0x1A, then the total escape length in bytes (including the 0x1A and length byte). + if (position + 2 >= data.Length) + break; + var length = data[position + 2]; + // Colour and icon escapes are dropped, keeping the text around them ("3DS Toad Circuit"). + position += Math.Max(4, length + (length % 2)); + continue; + } + + builder.Append(c); + position += 2; + } + } + else + { + var end = data[start..].IndexOf((byte)0); + var slice = end < 0 ? data[start..] : data.Slice(start, end); + builder.Append(encoding == 4 ? Encoding.UTF8.GetString(slice) : Encoding.Latin1.GetString(slice)); + } + + return System.Text.RegularExpressions.Regex.Replace(builder.ToString(), @"\s+", " ").Trim(); + } +} diff --git a/WheelWizard/Features/CustomMusic/CustomMusicExtensions.cs b/WheelWizard/Features/CustomMusic/CustomMusicExtensions.cs new file mode 100644 index 00000000..5166475e --- /dev/null +++ b/WheelWizard/Features/CustomMusic/CustomMusicExtensions.cs @@ -0,0 +1,14 @@ +using WheelWizard.CustomMusic.Catalog; + +namespace WheelWizard.CustomMusic; + +public static class CustomMusicExtensions +{ + public static IServiceCollection AddCustomMusic(this IServiceCollection services) + { + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + return services; + } +} diff --git a/WheelWizard/Features/CustomMusic/CustomMusicService.cs b/WheelWizard/Features/CustomMusic/CustomMusicService.cs new file mode 100644 index 00000000..482ed241 --- /dev/null +++ b/WheelWizard/Features/CustomMusic/CustomMusicService.cs @@ -0,0 +1,333 @@ +using System.IO.Abstractions; +using System.Text.Json; +using Microsoft.Extensions.Logging; +using WheelWizard.ApplicationData; +using WheelWizard.CustomMusic.Catalog; +using WheelWizard.DiscImages; +using WheelWizard.Models.Mods; +using WheelWizard.Mods; +using WheelWizard.Settings; + +namespace WheelWizard.CustomMusic; + +/// A song the player put on a music slot. +public sealed record CustomSong(string Title, string? Artist); + +/// How new songs are converted. +public sealed record CustomMusicSettings(FinalLapStyle FinalLap = FinalLapStyle.Faster, bool MatchVolume = true); + +public interface ICustomMusicService +{ + /// The "Custom Music" patch folder with the converted music, or the folder it will go in until there is any. + string FolderPath { get; } + + Task> LoadSlotsAsync(CancellationToken cancellationToken = default); + + /// The slots that have custom music in the patch, by slot key. + IReadOnlyDictionary LoadSongs(IEnumerable slots); + + CustomMusicSettings LoadSettings(); + + void SaveSettings(CustomMusicSettings settings); + + /// Converts the song and installs it for the slot, in the "Custom Music" patch. + Task> SetSongAsync(MusicSlot slot, string songPath, CancellationToken cancellationToken = default); + + /// Puts the slot back to its original music, removing the patch when no songs are left. + Task ResetAsync(MusicSlot slot); + + /// The music that plays for the slot: its custom song, or else the original music. + Task> ReadMusicAsync(MusicSlot slot); +} + +/// Installs songs as a normal patch, which Wheel Wizard copies into Retro Rewind's Patches folder at launch. +public sealed class CustomMusicService( + IMusicCatalogService catalog, + IModManager mods, + IModPaths modPaths, + IApplicationDataLocation applicationData, + IDiscImageService discImages, + ISettingsManager settings, + IFileSystem fileSystem, + ILogger logger +) : ICustomMusicService +{ + public const string ModTitle = "Custom Music"; + private const long MaxFileBytes = 300L * 1024 * 1024; + + // The song names, by slot key, and the files written for each. The patch folder holds the music itself. + private sealed record SavedSong(string Title, string? Artist, string[] Files); + + private sealed record SavedState(CustomMusicSettings Settings, Dictionary Songs); + + private readonly SemaphoreSlim _lock = new(1, 1); + + public string FolderPath => fileSystem.Directory.Exists(ModFolder) ? ModFolder : fileSystem.Path.GetDirectoryName(ModFolder)!; + private string ModFolder => modPaths.GetModDirectoryPath(ModTitle); + private string StateFile => fileSystem.Path.Combine(applicationData.DirectoryPath, "CustomMusic.json"); + + public Task> LoadSlotsAsync(CancellationToken cancellationToken = default) => + catalog.LoadAsync(cancellationToken); + + // Music in the patch folder counts even without a saved name, e.g. files put there by hand. + public IReadOnlyDictionary LoadSongs(IEnumerable slots) + { + var saved = ReadState().Songs; + return slots + .Where(slot => fileSystem.File.Exists(fileSystem.Path.Combine(ModFolder, slot.FileNames[0]))) + .ToDictionary( + slot => slot.Key, + slot => + saved.TryGetValue(slot.Key, out var song) + ? new CustomSong(song.Title, song.Artist) + : new CustomSong(t("custom_music.unknown_song"), null) + ); + } + + public CustomMusicSettings LoadSettings() => ReadState().Settings; + + public void SaveSettings(CustomMusicSettings newSettings) + { + _lock.Wait(); + try + { + WriteState(ReadState() with { Settings = newSettings }); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + logger.LogWarning(exception, "Could not save the custom music settings."); + } + finally + { + _lock.Release(); + } + } + + public async Task> SetSongAsync( + MusicSlot slot, + string songPath, + CancellationToken cancellationToken = default + ) + { + var extension = fileSystem.Path.GetExtension(songPath); + if (!MusicConverter.IsSupported(extension)) + return Fail(t("custom_music.error.unsupported")); + if (!fileSystem.File.Exists(songPath)) + return Fail(t("custom_music.error.missing")); + if (fileSystem.FileInfo.New(songPath).Length > MaxFileBytes) + return Fail(t("custom_music.error.too_long")); + + var options = LoadSettings(); + ConvertedMusic music; + try + { + var file = await fileSystem.File.ReadAllBytesAsync(songPath, cancellationToken); + music = await Task.Run( + () => + { + double? target = options.MatchVolume ? OriginalLoudness(slot) : null; + return MusicConverter.Convert( + file, + extension, + new ConvertOptions(slot.HasFinalLap, options.FinalLap, target), + cancellationToken + ); + }, + cancellationToken + ); + } + catch (SongTooLongException) + { + return Fail(t("custom_music.error.too_long")); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + // The decoders throw many kinds of exceptions on damaged files. + logger.LogWarning(exception, "Could not convert {Song} for custom music.", songPath); + return Fail(t("custom_music.error.unreadable")); + } + + var song = new CustomSong(music.Title ?? fileSystem.Path.GetFileNameWithoutExtension(songPath), music.Artist); + await _lock.WaitAsync(cancellationToken); + try + { + var modResult = await EnsureModAsync(); + if (modResult.IsFailure) + return modResult.Error; + + fileSystem.Directory.CreateDirectory(ModFolder); + var state = ReadState(); + if (state.Songs.TryGetValue(slot.Key, out var previous)) + DeleteFiles(previous.Files); + foreach (var name in slot.FileNames) + await fileSystem.File.WriteAllBytesAsync(fileSystem.Path.Combine(ModFolder, name), music.Normal, CancellationToken.None); + foreach (var name in slot.FinalLapFileNames) + await fileSystem.File.WriteAllBytesAsync( + fileSystem.Path.Combine(ModFolder, name), + music.FinalLap ?? music.Normal, + CancellationToken.None + ); + + state.Songs[slot.Key] = new SavedSong(song.Title, song.Artist, slot.AllFileNames.ToArray()); + WriteState(state); + return song; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + logger.LogError(exception, "Could not install custom music for {Slot}.", slot.Key); + return new OperationError + { + Message = t("custom_music.error.write", new { message = exception.Message }), + Exception = exception, + }; + } + finally + { + _lock.Release(); + } + } + + public async Task ResetAsync(MusicSlot slot) + { + await _lock.WaitAsync(); + try + { + var state = ReadState(); + DeleteFiles(state.Songs.Remove(slot.Key, out var song) ? song.Files.Union(slot.AllFileNames) : slot.AllFileNames); + WriteState(state); + + var mod = FindMod(); + var hasMusic = fileSystem.Directory.Exists(ModFolder) && fileSystem.Directory.EnumerateFiles(ModFolder, "*.brstm").Any(); + return mod != null && !hasMusic ? await mods.DeleteModAsync(mod) : Ok(); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + logger.LogError(exception, "Could not remove custom music for {Slot}.", slot.Key); + return new OperationError + { + Message = t("custom_music.error.write", new { message = exception.Message }), + Exception = exception, + }; + } + finally + { + _lock.Release(); + } + } + + public Task> ReadMusicAsync(MusicSlot slot) + { + var custom = fileSystem.Path.Combine(ModFolder, slot.FileNames[0]); + return Task.Run(() => fileSystem.File.Exists(custom) ? ReadFile(custom) : ReadOriginal(slot)); + } + + /// The original music: Retro Rewind's own file, or the file on the player's game disc. + private OperationResult ReadOriginal(MusicSlot slot) + { + if (slot.RetroRewindFile != null) + return ReadFile(slot.RetroRewindFile); + if (slot.GameFile == null) + return Fail(t("custom_music.error.no_original")); + + var gamePath = settings.Get(settings.GAME_LOCATION); + if (string.IsNullOrWhiteSpace(gamePath)) + return Fail(t("custom_music.error.no_game")); + return discImages.ReadFile(gamePath, "sound/strm/" + slot.GameFile); + } + + private OperationResult ReadFile(string path) + { + try + { + return fileSystem.File.ReadAllBytes(path); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return new OperationError { Message = exception.Message, Exception = exception }; + } + } + + /// How loud the music being replaced is, so the new song can match it. + private double OriginalLoudness(MusicSlot slot) + { + try + { + var original = ReadOriginal(slot); + var loudness = original.IsSuccess ? MusicConverter.MeasureLoudness(original.Value, ".brstm") : double.NaN; + if (double.IsFinite(loudness)) + return loudness; + } + // The original is only a measuring stick; a typical volume stands in when it cannot be read. + catch (Exception exception) + { + logger.LogDebug(exception, "Could not measure the original music of {Slot}.", slot.Key); + } + + return MusicConverter.DefaultLoudness; + } + + /// Creates the patch with the highest priority, so the songs chosen here beat music packs, and keeps it on. + private async Task EnsureModAsync() + { + // The Patches page loads the list in the background; never add a second "Custom Music" next to an unloaded one. + if (FindMod() == null && await mods.ReloadAsync() is { IsFailure: true } reload) + return reload; + + var mod = FindMod(); + if (mod == null) + { + return await mods.AddModAsync( + new Mod + { + Title = ModTitle, + Author = "Wheel Wizard", + ModID = -1, + IsEnabled = true, + // Lowest number = highest priority. + Priority = mods.Mods.Count == 0 ? 0 : mods.GetLowestActivePriority() - 1, + } + ); + } + + if (mod.IsEnabled) + return Ok(); + mod.IsEnabled = true; + return await mods.SaveModsAsync(); + } + + private Mod? FindMod() => mods.Mods.FirstOrDefault(mod => mod.Title.Equals(ModTitle, StringComparison.OrdinalIgnoreCase)); + + private void DeleteFiles(IEnumerable names) + { + foreach (var name in names) + { + var path = fileSystem.Path.Combine(ModFolder, name); + if (fileSystem.File.Exists(path)) + fileSystem.File.Delete(path); + } + } + + private SavedState ReadState() + { + try + { + if ( + fileSystem.File.Exists(StateFile) + && JsonSerializer.Deserialize(fileSystem.File.ReadAllText(StateFile)) is { } state + ) + return state with { Settings = state.Settings ?? new(), Songs = state.Songs ?? [] }; + } + catch (Exception exception) when (exception is JsonException or IOException or UnauthorizedAccessException) + { + logger.LogWarning( + exception, + "Could not read {File}; the default settings are used and custom songs show without a name.", + StateFile + ); + } + + return new SavedState(new(), []); + } + + private void WriteState(SavedState state) => fileSystem.File.WriteAllText(StateFile, JsonSerializer.Serialize(state)); +} diff --git a/WheelWizard/Features/CustomMusic/LoopFinder.cs b/WheelWizard/Features/CustomMusic/LoopFinder.cs new file mode 100644 index 00000000..dcb2050f --- /dev/null +++ b/WheelWizard/Features/CustomMusic/LoopFinder.cs @@ -0,0 +1,156 @@ +using NWaves.Transforms; +using NWaves.Windows; + +namespace WheelWizard.CustomMusic; + +/// Finds where a song repeats itself, comparing the spectra of 64 ms frames, so it loops without an audible cut. +public static class LoopFinder +{ + private const int FrameSize = 2048; + private const int BandCount = 24; + private const double MinLoopSeconds = 12; + private const double MatchSeconds = 6; + + // Average similarity (cosine of the band spectra) the music must reach on both sides of the jump. + private const double MinSimilarity = 0.95; + + // Frames quieter than this (silence, the tail of a fade) carry no usable shape. + private const float SilenceDb = -50; + + // Similarity lost per dB of level difference, so a fade-out or a quieter repeat does not pass for the same music. + private const float LevelCostPerDb = 0.03f; + + /// The loop, or null when the song does not repeat cleanly enough. + public static (int Start, int End)? Find(float[][] channels, int sampleRate, CancellationToken cancellationToken = default) + { + var mono = new float[channels[0].Length]; + foreach (var channel in channels) + { + for (var i = 0; i < mono.Length; i++) + mono[i] += channel[i] / channels.Length; + } + + var (frames, levels) = Features(mono); + var half = Math.Max(2, (int)(MatchSeconds * sampleRate / FrameSize / 2)); + var window = 2 * half; + var minLag = Math.Max(window, (int)(MinLoopSeconds * sampleRate / FrameSize)); + if (frames.Length < minLag + window) + return null; + + var similarity = new float[frames.Length]; + var bestScore = double.NegativeInfinity; + int bestEnd = 0, + bestLag = 0; + for (var lag = minLag; lag + half < frames.Length - half; lag++) + { + cancellationToken.ThrowIfCancellationRequested(); + for (var t = lag; t < frames.Length; t++) + similarity[t] = Similarity(frames, levels, t, t - lag); + + // The jump needs matching music before it and after it: what follows the jump is what the earlier section has to sound like. + double sum = 0; + for (var t = lag; t < lag + window; t++) + sum += similarity[t]; + for (var end = lag + half; end + half <= frames.Length; end++) + { + if (end > lag + half) + sum += similarity[end + half - 1] - similarity[end - half - 1]; + var mean = sum / window; + var score = mean + 0.04 * lag / frames.Length + 0.02 * end / frames.Length; + if (mean >= MinSimilarity && score > bestScore) + (bestScore, bestEnd, bestLag) = (score, end, lag); + } + } + + if (bestLag == 0) + return null; + + var loopEnd = bestEnd * FrameSize; + return Refine(mono, loopEnd, (bestEnd - bestLag) * FrameSize) is { } start && loopEnd - start >= MinLoopSeconds * sampleRate * 0.9 + ? (start, loopEnd) + : null; + } + + /// Per frame: the log energy in bands evenly spaced in log frequency, centred and normalised to unit length. + private static (float[][] Frames, float[] Levels) Features(float[] mono) + { + var count = mono.Length / FrameSize; + var frames = new float[count][]; + var levels = new float[count]; + + // Band edges in FFT bins, from about 60 Hz to the top of the spectrum. + var bins = FrameSize / 2; + var edges = Enumerable + .Range(0, BandCount + 1) + .Select(band => Math.Clamp((int)Math.Round(4 * Math.Pow(bins / 4.0, band / (double)BandCount)), 1, bins)) + .ToArray(); + + var fft = new RealFft(FrameSize); + var hann = Window.OfType(WindowType.Hann, FrameSize); + var frame = new float[FrameSize]; + var spectrum = new float[bins + 1]; + var bands = new double[BandCount]; + for (var f = 0; f < count; f++) + { + Array.Copy(mono, f * FrameSize, frame, 0, FrameSize); + levels[f] = (float)(10 * Math.Log10(frame.Average(x => x * x) + 1e-12)); + frame.ApplyWindow(hann); + fft.PowerSpectrum(frame, spectrum, normalize: false); + + for (var b = 0; b < BandCount; b++) + { + double sum = 0; + for (var k = edges[b]; k < Math.Max(edges[b] + 1, edges[b + 1]); k++) + sum += spectrum[k]; + bands[b] = Math.Log10(sum + 1e-10); + } + + var mean = bands.Average(); + var norm = Math.Sqrt(bands.Sum(band => (band - mean) * (band - mean))); + frames[f] = bands.Select(band => norm > 1e-9 ? (float)((band - mean) / norm) : 0f).ToArray(); + } + + return (frames, levels); + } + + private static float Similarity(float[][] frames, float[] levels, int a, int b) + { + if (levels[a] < SilenceDb || levels[b] < SilenceDb) + return 0f; + var dot = 0f; + for (var i = 0; i < BandCount; i++) + dot += frames[a][i] * frames[b][i]; + return dot - LevelCostPerDb * Math.Abs(levels[a] - levels[b]); + } + + /// The loop start near that best matches the waveform at . + private static int? Refine(float[] mono, int end, int roughStart) + { + const int span = 1024; + if (end - span < 0 || end + span > mono.Length) + return null; + + double targetEnergy = 0; + for (var i = -span; i < span; i++) + targetEnergy += (double)mono[end + i] * mono[end + i]; + + var best = double.NegativeInfinity; + int? bestStart = null; + for (var candidate = Math.Max(span, roughStart - FrameSize); candidate <= roughStart + FrameSize && candidate < end; candidate++) + { + double cross = 0, + energy = 0; + for (var i = -span; i < span; i++) + { + cross += mono[candidate + i] * mono[end + i]; + energy += mono[candidate + i] * mono[candidate + i]; + } + + var correlation = cross / Math.Sqrt(Math.Max(energy * targetEnergy, 1e-20)); + if (correlation > best) + (best, bestStart) = (correlation, candidate); + } + + return bestStart; + } +} diff --git a/WheelWizard/Features/CustomMusic/Loudness.cs b/WheelWizard/Features/CustomMusic/Loudness.cs new file mode 100644 index 00000000..f9bfdbf6 --- /dev/null +++ b/WheelWizard/Features/CustomMusic/Loudness.cs @@ -0,0 +1,84 @@ +namespace WheelWizard.CustomMusic; + +/// Integrated loudness in LUFS (ITU-R BS.1770 / EBU R128): K-weighted, in gated 400 ms blocks. +public static class Loudness +{ + /// The loudness of the first samples, or negative infinity for silence. + public static double Measure(float[][] channels, int sampleRate, int length) + { + var block = sampleRate * 4 / 10; + var step = block / 4; + if (length < block) + return double.NegativeInfinity; + + // Per channel, the K-weighted energy of every 100 ms step; a block is four steps. + var steps = new double[length / step]; + foreach (var channel in channels) + { + var filter = new KWeighting(sampleRate); + for (var i = 0; i < steps.Length * step; i++) + { + var y = filter.Process(channel[i]); + steps[i / step] += y * y; + } + } + + var blocks = Enumerable + .Range(0, steps.Length - 3) + .Select(i => (steps[i] + steps[i + 1] + steps[i + 2] + steps[i + 3]) / block) + .ToArray(); + var absolute = blocks.Where(power => Lufs(power) > -70).ToArray(); + if (absolute.Length == 0) + return double.NegativeInfinity; + + var relative = Lufs(absolute.Average()) - 10; + return Lufs(absolute.Where(power => Lufs(power) > relative).Average()); + } + + private static double Lufs(double power) => -0.691 + 10 * Math.Log10(power); + + /// The two-stage K-weighting filter (a high shelf, then a high pass), with coefficients for any sample rate. + private sealed class KWeighting + { + private readonly Biquad _shelf; + private readonly Biquad _highPass; + + public KWeighting(int sampleRate) + { + var k = Math.Tan(Math.PI * 1681.974450955533 / sampleRate); + var q = 0.7071752369554196; + var vh = Math.Pow(10, 3.999843853973347 / 20); + var vb = Math.Pow(vh, 0.4996667741545416); + var a0 = 1 + k / q + k * k; + _shelf = new Biquad( + (vh + vb * k / q + k * k) / a0, + 2 * (k * k - vh) / a0, + (vh - vb * k / q + k * k) / a0, + 2 * (k * k - 1) / a0, + (1 - k / q + k * k) / a0 + ); + + k = Math.Tan(Math.PI * 38.13547087602444 / sampleRate); + q = 0.5003270373238773; + a0 = 1 + k / q + k * k; + _highPass = new Biquad(1, -2, 1, 2 * (k * k - 1) / a0, (1 - k / q + k * k) / a0); + } + + public double Process(double x) => _highPass.Process(_shelf.Process(x)); + } + + private sealed class Biquad(double b0, double b1, double b2, double a1, double a2) + { + private double _x1, + _x2, + _y1, + _y2; + + public double Process(double x) + { + var y = b0 * x + b1 * _x1 + b2 * _x2 - a1 * _y1 - a2 * _y2; + (_x2, _x1, _y2, _y1) = (_x1, x, _y1, y); + return y; + } + } +} diff --git a/WheelWizard/Features/CustomMusic/MusicConverter.cs b/WheelWizard/Features/CustomMusic/MusicConverter.cs new file mode 100644 index 00000000..d2fbfd07 --- /dev/null +++ b/WheelWizard/Features/CustomMusic/MusicConverter.cs @@ -0,0 +1,399 @@ +using System.Buffers.Binary; +using NAudio.Vorbis; +using NAudio.Wave; +using NAudio.Wave.SampleProviders; +using NLayer.NAudioSupport; +using NWaves.Operations; +using NWaves.Signals; +using VGAudio.Containers.NintendoWare; +using VGAudio.Formats.Pcm16; +using Flac = CUETools.Codecs.FLAKE; + +namespace WheelWizard.CustomMusic; + +public enum FinalLapStyle +{ + /// Faster and higher, like Retro Rewind's own speed-up. + Faster, + + /// Faster at the same pitch, closest to the original game's final lap music. + FasterSamePitch, + + /// The same as laps 1 and 2. + Unchanged, +} + +/// Loudness (LUFS) to match, or null to keep the song's own volume. +public sealed record ConvertOptions(bool WithFinalLap, FinalLapStyle FinalLap = FinalLapStyle.Faster, double? TargetLoudness = null); + +/// A song converted into the BRSTM files the game streams, plus the tags shown in the list. +public sealed record ConvertedMusic(byte[] Normal, byte[]? FinalLap, string? Title, string? Artist); + +public sealed class SongTooLongException() : Exception($"Songs can be at most {MusicConverter.MaxSeconds / 60} minutes long."); + +/// Converts a song into looping 32 kHz stereo BRSTMs with NAudio, NLayer, NVorbis, FLAKE, NWaves, VGAudio and TagLib#. +public static class MusicConverter +{ + public const int SampleRate = 32000; + + /// Retro Rewind plays a track's music this much faster (and higher) on the final lap. + public const double FinalLapSpeed = 1.06; + + /// Tempo of the same-pitch final lap version, closest to the original game's final lap music. + public const double FinalLapTempo = 1.08; + + /// A typical loudness of the game's music, used when the original music cannot be measured. + public const double DefaultLoudness = -16; + + public const int MaxSeconds = 10 * 60; + + // -1 dBFS, which leaves room for DSP-ADPCM's small overshoots. + private const float PeakCeiling = 0.891f; + + public static readonly string[] Extensions = [".mp3", ".ogg", ".flac", ".wav", ".aif", ".aiff", ".brstm", ".bcstm", ".bfstm"]; + + public static bool IsSupported(string extension) => Extensions.Contains(extension.ToLowerInvariant()); + + public static ConvertedMusic Convert( + byte[] file, + string extension, + ConvertOptions options, + CancellationToken cancellationToken = default + ) + { + extension = extension.ToLowerInvariant(); + var tags = ReadTags(file, extension); + var song = MakeLoop(Render(file, extension, tags.Loop, cancellationToken), cancellationToken); + if (options.TargetLoudness is { } target) + MatchLoudness(song, target); + + var normal = Encode(song); + var finalLap = !options.WithFinalLap + ? null + : options.FinalLap switch + { + FinalLapStyle.Faster => Encode(Speed(song, (int)Math.Round(SampleRate / FinalLapSpeed))), + FinalLapStyle.FasterSamePitch => Encode(Stretch(song, 1 / FinalLapTempo)), + _ => normal, + }; + return new ConvertedMusic(normal, finalLap, tags.Title, tags.Artist); + } + + /// How loud a song file plays, in LUFS. + public static double MeasureLoudness(byte[] file, string extension) + { + var song = Render(file, extension.ToLowerInvariant(), null, CancellationToken.None); + return Loudness.Measure(song.Channels, SampleRate, song.End); + } + + /// The song as stereo audio, for playing it. + public static ISampleProvider Decode(byte[] file, string extension) => ToStereo(Open(file, extension.ToLowerInvariant()).Audio); + + /// Stereo 32 kHz audio; playback runs to and, once looped, jumps back to . + private sealed record Song(float[][] Channels, int LoopStart, int End, bool HasLoop); + + private static Song Render(byte[] file, string extension, (long Start, long End)? tagLoop, CancellationToken cancellationToken) + { + using var source = Open(file, extension); + var sourceRate = source.Audio.WaveFormat.SampleRate; + var stereo = ToStereo(source.Audio); + var output = sourceRate == SampleRate ? stereo : new WdlResamplingSampleProvider(stereo, SampleRate); + + var left = new List(SampleRate * 60); + var right = new List(SampleRate * 60); + var buffer = new float[16384]; + int read; + while ((read = output.Read(buffer)) > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + for (var i = 0; i + 1 < read; i += 2) + { + left.Add(float.IsFinite(buffer[i]) ? buffer[i] : 0); + right.Add(float.IsFinite(buffer[i + 1]) ? buffer[i + 1] : 0); + } + + if (left.Count > MaxSeconds * SampleRate) + throw new SongTooLongException(); + } + + // Damaged or mislabelled files (an M4A renamed to .mp3) can decode to a few milliseconds of noise. + if (left.Count < SampleRate) + throw new InvalidDataException("The file contains less than a second of audio."); + + float[][] channels = [left.ToArray(), right.ToArray()]; + if ((source.Loop ?? tagLoop) is { } loop) + { + var start = (int)(loop.Start * SampleRate / sourceRate); + var end = (int)Math.Min(channels[0].Length, loop.End * SampleRate / sourceRate); + if (start >= 0 && end - start >= SampleRate) + return new Song(channels, start, end, HasLoop: true); + } + + return TrimSilence(channels); + } + + private static ISampleProvider ToStereo(ISampleProvider audio) => + audio.WaveFormat.Channels switch + { + 1 => new MonoToStereoSampleProvider(audio), + 2 => audio, + // The first two channels: the first track of a multi-track BRSTM, the front of surround sound. + _ => new MultiplexingSampleProvider([audio], 2), + }; + + /// Drops silence at the start and the end, which would otherwise leave a gap in the loop. + private static Song TrimSilence(float[][] channels) + { + const float threshold = 0.001f; + var length = channels[0].Length; + bool Audible(int i) => Math.Abs(channels[0][i]) > threshold || Math.Abs(channels[1][i]) > threshold; + var first = 0; + while (first < length - 1 && !Audible(first)) + first++; + var last = length - 1; + while (last > first && !Audible(last)) + last--; + + var keep = SampleRate / 100; + first = Math.Max(0, first - keep); + last = Math.Min(length - 1, last + keep); + if (last - first < SampleRate) + return new Song(channels, 0, length, HasLoop: false); + return new Song([channels[0][first..(last + 1)], channels[1][first..(last + 1)]], 0, last + 1 - first, HasLoop: false); + } + + /// Loops the song where the music repeats, or else by crossfading the ending into the opening. + private static Song MakeLoop(Song song, CancellationToken cancellationToken) + { + if (song.HasLoop) + return song; + + if (LoopFinder.Find(song.Channels, SampleRate, cancellationToken) is { } found) + return Blend(song with { LoopStart = found.Start, End = found.End, HasLoop = true }); + + var fade = Math.Min(SampleRate * 5 / 2, song.End / 4); + var channels = song.Channels.Select(channel => channel[..song.End]).ToArray(); + foreach (var channel in channels) + { + for (var i = 0; i < fade; i++) + { + // Equal power keeps the level steady across unrelated music. + var t = (i + 0.5) / fade * Math.PI / 2; + var at = song.End - fade + i; + channel[at] = (float)(channel[at] * Math.Cos(t) + channel[i] * Math.Sin(t)); + } + } + + // The opening already played its first part during the crossfade, so the loop continues from there. + return new Song(channels, fade, song.End, HasLoop: true); + } + + /// Blends the last milliseconds before the loop end into the audio before the loop start, so the jump has no click. + private static Song Blend(Song song) + { + var blend = Math.Min(SampleRate * 3 / 100, song.LoopStart); + var channels = song.Channels.Select(channel => channel[..song.End]).ToArray(); + foreach (var channel in channels) + { + for (var i = 0; i < blend; i++) + { + var weight = (i + 0.5f) / blend; + var at = song.End - blend + i; + channel[at] = channel[at] * (1 - weight) + channel[song.LoopStart - blend + i] * weight; + } + } + + return song with + { + Channels = channels, + }; + } + + /// Changes the volume to LUFS, as far as the peaks allow without distorting. + private static void MatchLoudness(Song song, double target) + { + var loudness = Loudness.Measure(song.Channels, SampleRate, song.End); + if (double.IsNegativeInfinity(loudness)) + return; + + var peak = 0f; + foreach (var channel in song.Channels) + { + for (var i = 0; i < song.End; i++) + peak = Math.Max(peak, Math.Abs(channel[i])); + } + + var gain = (float)Math.Min(Math.Pow(10, (target - loudness) / 20), PeakCeiling / Math.Max(peak, 1e-6f)); + foreach (var channel in song.Channels) + { + for (var i = 0; i < channel.Length; i++) + channel[i] *= gain; + } + } + + /// Plays the song faster and higher: resampled to but stored as 32 kHz. + private static Song Speed(Song song, int rate) => + Retime( + song, + (double)rate / SampleRate, + channels => channels.Select(channel => ReadAll(new WdlResamplingSampleProvider(new Samples(channel), rate))).ToArray() + ); + + /// Plays the song faster at the same pitch: is the new length relative to the old one. + private static Song Stretch(Song song, double stretch) => + Retime( + song, + stretch, + channels => + channels.Select(channel => Operation.TimeStretch(new DiscreteSignal(SampleRate, channel), stretch).Samples).ToArray() + ); + + /// Changes the speed with , given the music past the loop start so the jump stays smooth. + private static Song Retime(Song song, double ratio, Func process) + { + var tail = Math.Min(SampleRate / 2, song.End - song.LoopStart); + var processed = process( + song.Channels.Select(channel => channel[..song.End].Concat(channel[song.LoopStart..(song.LoopStart + tail)]).ToArray()) + .ToArray() + ); + var end = Math.Min((int)Math.Round(song.End * ratio), processed.Min(channel => channel.Length)); + return Blend(new Song(processed, (int)Math.Round(song.LoopStart * ratio), end, HasLoop: true)); + } + + private static float[] ReadAll(ISampleProvider audio) + { + var samples = new List(); + var buffer = new float[16384]; + int read; + while ((read = audio.Read(buffer)) > 0) + samples.AddRange(buffer.AsSpan(0, read)); + return samples.ToArray(); + } + + private sealed class Samples(float[] samples) : ISampleProvider + { + private int _position; + + public WaveFormat WaveFormat { get; } = WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, 1); + + public int Read(Span buffer) + { + var count = Math.Min(buffer.Length, samples.Length - _position); + samples.AsSpan(_position, count).CopyTo(buffer); + _position += count; + return count; + } + } + + private static byte[] Encode(Song song) + { + var channels = song.Channels.Select(channel => new short[song.End]).ToArray(); + for (var c = 0; c < channels.Length; c++) + { + for (var i = 0; i < song.End; i++) + channels[c][i] = (short)Math.Clamp(MathF.Round(song.Channels[c][i] * short.MaxValue), short.MinValue, short.MaxValue); + } + + return new BrstmWriter().GetFile(new Pcm16Format(channels, SampleRate).WithLoop(true, song.LoopStart, song.End)); + } + + private sealed record Source(ISampleProvider Audio, IDisposable Owner, (long Start, long End)? Loop = null) : IDisposable + { + public void Dispose() => Owner.Dispose(); + } + + private static Source Open(byte[] file, string extension) + { + var stream = new MemoryStream(file, writable: false); + switch (extension) + { + case ".mp3": + var mp3 = new ManagedMpegStream(stream); + return new(mp3.ToSampleProvider(), mp3); + case ".ogg": + var ogg = new VorbisSampleProvider(stream); + return new(ogg, ogg); + case ".flac": + var flac = new Flac.FlakeReader(null, stream); + var decoded = new MemoryStream(); + var block = new Flac.AudioBuffer(flac, 16384); + while (flac.Read(block, -1) > 0) + decoded.Write(block.Bytes, 0, block.ByteLength); + flac.Close(); + return Raw(decoded.ToArray(), flac.PCM.SampleRate, flac.PCM.BitsPerSample, flac.PCM.ChannelCount, null); + case ".wav": + var wav = new WaveFileReader(stream); + return new(wav.ToSampleProvider(), wav); + case ".aif" + or ".aiff": + var aiff = new AiffFileReader(stream); + return new(aiff.ToSampleProvider(), aiff); + case ".brstm" + or ".bcstm" + or ".bfstm": + var audio = extension == ".brstm" ? new BrstmReader().Read(file) : new BCFstmReader().Read(file); + var pcm = audio.GetFormat(); + var interleaved = new byte[pcm.SampleCount * pcm.ChannelCount * 2]; + for (var i = 0; i < pcm.SampleCount; i++) + { + for (var channel = 0; channel < pcm.ChannelCount; channel++) + BinaryPrimitives.WriteInt16LittleEndian( + interleaved.AsSpan((i * pcm.ChannelCount + channel) * 2), + pcm.Channels[channel][i] + ); + } + + return Raw(interleaved, pcm.SampleRate, 16, pcm.ChannelCount, pcm.Looping ? (pcm.LoopStart, pcm.LoopEnd) : null); + default: + throw new NotSupportedException($"{extension} files are not supported."); + } + } + + private static Source Raw(byte[] pcm, int sampleRate, int bits, int channels, (long Start, long End)? loop) + { + var raw = new RawSourceWaveStream(pcm, 0, pcm.Length, new WaveFormat(sampleRate, bits, channels)); + return new(raw.ToSampleProvider(), raw, loop); + } + + private sealed record Tags(string? Title, string? Artist, (long Start, long End)? Loop); + + private static Tags ReadTags(byte[] file, string extension) + { + try + { + using var tags = TagLib.File.Create(new TagSource("song" + extension, file), TagLib.ReadStyle.None); + return new Tags(Clean(tags.Tag.Title), Clean(tags.Tag.FirstPerformer ?? tags.Tag.FirstAlbumArtist), LoopTags(tags)); + } + // Tags are optional, and TagLib# throws many kinds of exceptions on files it cannot read (BRSTMs have none). + catch (Exception) + { + return new Tags(null, null, null); + } + } + + /// The LOOPSTART and LOOPLENGTH (or LOOPEND) tags, in samples, that game music rips often carry. + private static (long Start, long End)? LoopTags(TagLib.File tags) + { + if ( + tags.GetTag(TagLib.TagTypes.Xiph) is not TagLib.Ogg.XiphComment comment + || !long.TryParse(comment.GetFirstField("LOOPSTART"), out var start) + ) + return null; + if (long.TryParse(comment.GetFirstField("LOOPLENGTH"), out var length)) + return (start, start + length); + return long.TryParse(comment.GetFirstField("LOOPEND"), out var end) ? (start, end) : null; + } + + private static string? Clean(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim(); + + private sealed class TagSource(string name, byte[] file) : TagLib.File.IFileAbstraction + { + private readonly MemoryStream _stream = new(file, writable: false); + + public string Name => name; + public Stream ReadStream => _stream; + public Stream WriteStream => _stream; + + public void CloseStream(Stream stream) { } + } +} diff --git a/WheelWizard/Features/CustomMusic/MusicPlayer.cs b/WheelWizard/Features/CustomMusic/MusicPlayer.cs new file mode 100644 index 00000000..9559d1b9 --- /dev/null +++ b/WheelWizard/Features/CustomMusic/MusicPlayer.cs @@ -0,0 +1,66 @@ +using NAudio.Wave; +using NAudio.Wave.SampleProviders; + +namespace WheelWizard.CustomMusic; + +public interface IMusicPlayer +{ + /// Plays a BRSTM from the start, replacing whatever was playing. + void Play(byte[] brstm); + + void Stop(); + + /// Raised, on any thread, when the music finishes playing on its own. + event EventHandler? Finished; +} + +/// Plays music through NAudio's output for each system: WinMM on Windows, ALSA on Linux and Core Audio on macOS. +public sealed class MusicPlayer : IMusicPlayer +{ + private IWavePlayer? _output; + + public event EventHandler? Finished; + + public void Play(byte[] brstm) + { + Stop(); + var audio = new SampleToWaveProvider16(MusicConverter.Decode(brstm, ".brstm")); + var output = CreateOutput(); + try + { + output.Init(audio); + output.PlaybackStopped += (_, _) => + { + if (output == _output) + Finished?.Invoke(this, EventArgs.Empty); + }; + _output = output; + output.Play(); + } + catch + { + _output = null; + output.Dispose(); + throw; + } + } + + public void Stop() + { + var output = _output; + _output = null; + output?.Stop(); + output?.Dispose(); + } + + private static IWavePlayer CreateOutput() + { + if (OperatingSystem.IsWindows()) + return new WaveOut(); + if (OperatingSystem.IsMacOS()) + return new CoreAudioPlayer(); + if (OperatingSystem.IsLinux()) + return new NAudio.Wave.Alsa.AlsaOut(); + throw new PlatformNotSupportedException(); + } +} diff --git a/WheelWizard/Features/CustomMusic/Views/CustomMusicRow.cs b/WheelWizard/Features/CustomMusic/Views/CustomMusicRow.cs new file mode 100644 index 00000000..669f82a4 --- /dev/null +++ b/WheelWizard/Features/CustomMusic/Views/CustomMusicRow.cs @@ -0,0 +1,106 @@ +using System.ComponentModel; +using WheelWizard.CustomMusic.Catalog; + +namespace WheelWizard.CustomMusic.Views; + +/// One row of the Custom Music list. +public sealed class CustomMusicRow(MusicSlot slot, CustomSong? song) : INotifyPropertyChanged +{ + private CustomSong? _song = song; + private bool _isBusy; + private bool _isPlaying; + private bool _isLoadingMusic; + private string? _error; + + public MusicSlot Slot { get; } = slot; + + public string Name => Slot.Name; + public bool IsCustom => _song != null; + public bool HasError => _error != null; + + public bool IsBusy + { + get => _isBusy; + set + { + _isBusy = value; + if (value) + _error = null; + Changed(); + } + } + + public bool IsPlaying + { + get => _isPlaying; + set + { + _isPlaying = value; + Changed(); + } + } + + public bool IsLoadingMusic + { + get => _isLoadingMusic; + set + { + _isLoadingMusic = value; + if (value) + _error = null; + Changed(); + } + } + + public string? Error + { + get => _error; + set + { + _error = value; + Changed(); + } + } + + public string Subtitle => + _error + ?? ( + _isBusy ? t("custom_music.converting") + : _song is { } current ? (current.Artist == null ? current.Title : $"{current.Title} · {current.Artist}") + : Slot.Detail == null ? Slot.Group + : $"{Slot.Group} · {Slot.Detail}" + ); + + public void SetSong(CustomSong? song) + { + _song = song; + _error = null; + Changed(); + } + + public bool Matches(string search) => + search.Length == 0 + || Name.Contains(search, StringComparison.OrdinalIgnoreCase) + || Slot.Group.Contains(search, StringComparison.OrdinalIgnoreCase) + || (_song?.Title.Contains(search, StringComparison.OrdinalIgnoreCase) ?? false) + || (_song?.Artist?.Contains(search, StringComparison.OrdinalIgnoreCase) ?? false); + + public event PropertyChangedEventHandler? PropertyChanged; + + private void Changed() + { + foreach ( + var name in new[] + { + nameof(IsBusy), + nameof(IsPlaying), + nameof(IsLoadingMusic), + nameof(Error), + nameof(HasError), + nameof(IsCustom), + nameof(Subtitle), + } + ) + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); + } +} diff --git a/WheelWizard/Features/CustomMusic/Views/CustomMusicWindow.axaml b/WheelWizard/Features/CustomMusic/Views/CustomMusicWindow.axaml new file mode 100644 index 00000000..d149f3b7 --- /dev/null +++ b/WheelWizard/Features/CustomMusic/Views/CustomMusicWindow.axaml @@ -0,0 +1,131 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/WheelWizard/Features/CustomMusic/Views/CustomMusicWindow.axaml.cs b/WheelWizard/Features/CustomMusic/Views/CustomMusicWindow.axaml.cs new file mode 100644 index 00000000..1d0ba8e9 --- /dev/null +++ b/WheelWizard/Features/CustomMusic/Views/CustomMusicWindow.axaml.cs @@ -0,0 +1,234 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Platform.Storage; +using Avalonia.Threading; +using WheelWizard.CustomMusic.Catalog; +using WheelWizard.Shared.Desktop.Storage; +using WheelWizard.Views.Dialogs.Base; + +namespace WheelWizard.CustomMusic.Views; + +/// Lists the replaceable music; choosing or dropping a song converts and installs it right away. +public partial class CustomMusicWindow : ModalContent +{ + // The categories shown on each tab: races, battle arenas, menus. + private static readonly MusicCategory[][] TabCategories = + [ + [MusicCategory.RetroRewindTrack, MusicCategory.Course], + [MusicCategory.RetroRewindArena, MusicCategory.Arena], + [MusicCategory.Menu], + ]; + + private readonly ICustomMusicService _music; + private readonly IFilePickerService _filePicker; + private readonly IMusicPlayer _player; + private List _rows = []; + private CustomMusicRow? _playing; + private int _playRequest; + private bool _settingsLoaded; + + private static FilePickerFileType SongFiles => + new(t("custom_music.file_type")) + { + Patterns = MusicConverter.Extensions.Select(extension => "*" + extension).ToArray(), + AppleUniformTypeIdentifiers = ["public.audio"], + MimeTypes = ["audio/*"], + }; + + public CustomMusicWindow(ICustomMusicService music, IFilePickerService filePicker, IMusicPlayer player) + : base(t("custom_music.title")) + { + _music = music; + _filePicker = filePicker; + _player = player; + InitializeComponent(); + IsDismissible = true; + + SortBox.ItemsSource = new[] + { + t("custom_music.sort.track_order"), + t("custom_music.sort.name"), + t("custom_music.sort.changed_first"), + }; + SortBox.SelectedIndex = 0; + FinalLapBox.ItemsSource = new[] + { + t("custom_music.final_lap.faster"), + t("custom_music.final_lap.faster_same_pitch"), + t("custom_music.final_lap.unchanged"), + }; + Tabs.SelectedIndex = 0; + MusicList.AddHandler(DragDrop.DragOverEvent, Music_DragOver); + MusicList.AddHandler(DragDrop.DropEvent, Music_Drop); + _player.Finished += Player_Finished; + } + + protected override async void BeforeOpen() + { + var settings = _music.LoadSettings(); + MatchVolumeToggle.IsChecked = settings.MatchVolume; + FinalLapBox.SelectedIndex = (int)settings.FinalLap; + _settingsLoaded = true; + try + { + var slots = await _music.LoadSlotsAsync(); + var songs = _music.LoadSongs(slots); + _rows = slots.Select(slot => new CustomMusicRow(slot, songs.GetValueOrDefault(slot.Key))).ToList(); + ShowRows(); + } + finally + { + LoadingSpinner.IsVisible = false; + } + } + + protected override void BeforeClose() + { + _player.Finished -= Player_Finished; + StopPlaying(); + } + + private void ShowRows() + { + var categories = TabCategories[Math.Max(0, Tabs.SelectedIndex)]; + var search = SearchInput.Text?.Trim() ?? string.Empty; + var rows = _rows.Where(row => categories.Contains(row.Slot.Category) && row.Matches(search)); + rows = SortBox.SelectedIndex switch + { + 1 => rows.OrderBy(row => row.Name, StringComparer.CurrentCultureIgnoreCase), + 2 => rows.OrderByDescending(row => row.IsCustom), + _ => rows, + }; + MusicList.ItemsSource = rows.ToList(); + } + + private void Filter_Changed(object? sender, SelectionChangedEventArgs e) => ShowRows(); + + private void Search_TextChanged(object? sender, TextChangedEventArgs e) => ShowRows(); + + private void Settings_Click(object? sender, RoutedEventArgs e) + { + SettingsPanel.IsVisible = !SettingsPanel.IsVisible; + MusicList.IsVisible = !SettingsPanel.IsVisible; + } + + private void FinalLap_Changed(object? sender, SelectionChangedEventArgs e) => SaveSettings(); + + private void MatchVolume_Click(object? sender, RoutedEventArgs e) => SaveSettings(); + + private void SaveSettings() + { + if (_settingsLoaded) + _music.SaveSettings( + new CustomMusicSettings((FinalLapStyle)Math.Max(0, FinalLapBox.SelectedIndex), MatchVolumeToggle.IsChecked == true) + ); + } + + private void OpenFolder_Click(object? sender, RoutedEventArgs e) => _filePicker.OpenFolderInFileManager(_music.FolderPath); + + private async void Choose_Click(object? sender, RoutedEventArgs e) + { + if ((sender as Control)?.DataContext is not CustomMusicRow { IsBusy: false } row) + return; + + var path = await _filePicker.OpenSingleFileAsync(t("custom_music.pick_title", new { name = row.Name }), [SongFiles]); + if (path != null) + await SetSongAsync(row, path); + } + + private async void Reset_Click(object? sender, RoutedEventArgs e) + { + if ((sender as Control)?.DataContext is not CustomMusicRow { IsBusy: false } row) + return; + + StopPlaying(); + row.IsBusy = true; + var result = await _music.ResetAsync(row.Slot); + row.IsBusy = false; + if (result.IsSuccess) + row.SetSong(null); + else + row.Error = result.Error.Message; + } + + private async Task SetSongAsync(CustomMusicRow row, string path) + { + StopPlaying(); + row.IsBusy = true; + var result = await _music.SetSongAsync(row.Slot, path); + row.IsBusy = false; + if (result.IsSuccess) + row.SetSong(result.Value); + else + row.Error = result.Error.Message; + } + + private async void Play_Click(object? sender, RoutedEventArgs e) + { + if ((sender as Control)?.DataContext is not CustomMusicRow row) + return; + + var wasPlaying = row.IsPlaying; + StopPlaying(); + if (wasPlaying) + return; + + // Only the last row asked for plays, however long reading each one takes. + var request = ++_playRequest; + row.IsLoadingMusic = true; + var music = await _music.ReadMusicAsync(row.Slot); + row.IsLoadingMusic = false; + if (request != _playRequest) + return; + if (music.IsFailure) + { + row.Error = music.Error.Message; + return; + } + + try + { + _player.Play(music.Value); + } + // Damaged files and missing or busy audio devices fail in many different ways. + catch (Exception exception) + { + row.Error = t("custom_music.error.play", new { message = exception.Message }); + return; + } + + _playing = row; + row.IsPlaying = true; + } + + private void StopPlaying() + { + _playRequest++; + _player.Stop(); + if (_playing != null) + _playing.IsPlaying = false; + _playing = null; + } + + private void Player_Finished(object? sender, EventArgs e) => + Dispatcher.UIThread.Post(() => + { + if (_playing != null) + _playing.IsPlaying = false; + _playing = null; + }); + + private static CustomMusicRow? RowAt(DragEventArgs e) => (e.Source as StyledElement)?.DataContext as CustomMusicRow; + + private void Music_DragOver(object? sender, DragEventArgs e) => + e.DragEffects = + RowAt(e) is { IsBusy: false } && e.DataTransfer.Contains(DataFormat.File) ? DragDropEffects.Copy : DragDropEffects.None; + + private async void Music_Drop(object? sender, DragEventArgs e) + { + if (RowAt(e) is { IsBusy: false } row && e.DataTransfer.TryGetFile()?.TryGetLocalPath() is { } path) + await SetSongAsync(row, path); + } +} diff --git a/WheelWizard/Features/DiscImages/DiscImageService.cs b/WheelWizard/Features/DiscImages/DiscImageService.cs index 00be285d..103223ad 100644 --- a/WheelWizard/Features/DiscImages/DiscImageService.cs +++ b/WheelWizard/Features/DiscImages/DiscImageService.cs @@ -1,7 +1,9 @@ using System.IO.Abstractions; using RVZSharp.Blobs; +using RVZSharp.Files; using RVZSharp.Interfaces; using RVZSharp.Models; +using RVZSharp.Wii; using WheelWizard.DiscImages.Domain; namespace WheelWizard.DiscImages; @@ -13,6 +15,9 @@ public interface IDiscImageService /// Reads the disc header of a game file in any supported format. OperationResult ReadInfo(string path); + + /// Reads a file from the game's data partition, e.g. "sound/strm/n_Circuit32_n.brstm". + OperationResult ReadFile(string path, string filePath); } public sealed class DiscImageService(IFileSystem fileSystem) : IDiscImageService @@ -73,31 +78,44 @@ _cache is { } cached } } - private OperationResult Read(string path) + public OperationResult ReadFile(string path, string filePath) { + if (string.IsNullOrWhiteSpace(path)) + return Fail("No game file is set."); + try { - var stream = fileSystem.File.OpenRead(path); - IBlobReader reader; - try - { - reader = Blob.Open(stream, path, leaveOpen: false); - } - catch - { - // Blob.Open only takes ownership of the stream once it succeeds. - stream.Dispose(); - throw; - } + using var reader = Open(path); + var partitions = WiiVolume.GetPartitions(reader); + // Wii discs keep their files in the data partition (type 0); GameCube discs have no partitions. + using var files = + partitions.Count == 0 + ? DiscFileSystem.Open(reader) + : DiscFileSystem.Open(reader, partitions.FirstOrDefault(partition => partition.Type == 0, partitions[0])); + var file = files.Find(filePath); + if (file is not { IsDirectory: false, Size: > 0 and <= 64 * 1024 * 1024 }) + return Fail($"The game file has no {filePath}."); - using (reader) - { - var info = DiscInfo.TryRead(reader); - if (info == null) - return Fail("This file is not a GameCube or Wii disc image."); + using var output = new MemoryStream((int)file.Size); + files.CopyFileTo(file, output); + return output.ToArray(); + } + catch (Exception ex) + { + return new OperationError { Message = $"Failed to read game file: {ex.Message}", Exception = ex }; + } + } - return new DiscImageInfo(info.GameId, info.InternalName, info.Revision, ToFormat(reader.Type)); - } + private OperationResult Read(string path) + { + try + { + using var reader = Open(path); + var info = DiscInfo.TryRead(reader); + if (info == null) + return Fail("This file is not a GameCube or Wii disc image."); + + return new DiscImageInfo(info.GameId, info.InternalName, info.Revision, ToFormat(reader.Type)); } catch (Exception ex) { @@ -105,6 +123,21 @@ private OperationResult Read(string path) } } + private IBlobReader Open(string path) + { + var stream = fileSystem.File.OpenRead(path); + try + { + return Blob.Open(stream, path, leaveOpen: false); + } + catch + { + // Blob.Open only takes ownership of the stream once it succeeds. + stream.Dispose(); + throw; + } + } + private static DiscImageFormat ToFormat(BlobType type) => type switch { diff --git a/WheelWizard/Features/Mods/Views/ModsPage.axaml b/WheelWizard/Features/Mods/Views/ModsPage.axaml index 5aad4220..83fd6b40 100644 --- a/WheelWizard/Features/Mods/Views/ModsPage.axaml +++ b/WheelWizard/Features/Mods/Views/ModsPage.axaml @@ -56,7 +56,7 @@ - + @@ -65,15 +65,19 @@ - - - - - - - - + + + + + + + + + + + diff --git a/WheelWizard/Features/Mods/Views/ModsPage.axaml.cs b/WheelWizard/Features/Mods/Views/ModsPage.axaml.cs index 6007889d..df8c026c 100644 --- a/WheelWizard/Features/Mods/Views/ModsPage.axaml.cs +++ b/WheelWizard/Features/Mods/Views/ModsPage.axaml.cs @@ -9,6 +9,8 @@ using Avalonia.Layout; using Avalonia.Media; using Avalonia.VisualTree; +using WheelWizard.CustomMusic; +using WheelWizard.CustomMusic.Views; using WheelWizard.Features.Patches; using WheelWizard.Models.Mods; using WheelWizard.Mods; @@ -255,6 +257,13 @@ private void BrowseMod_Click(object sender, RoutedEventArgs e) _navigation.NavigateTo(); } + private void CustomMusic_Click(object sender, RoutedEventArgs e) + { + var popup = Popups.Create(); + popup.SetModalOwner(this); + popup.Show(); + } + private async Task ReloadModsAndShowErrorsAsync() { var reloadResult = await ModManager.ReloadAsync(); @@ -418,6 +427,12 @@ private void ViewMod_Click(object sender, RoutedEventArgs e) return; } + if (selectedMod.Mod.Title.Equals(CustomMusicService.ModTitle, StringComparison.OrdinalIgnoreCase)) + { + CustomMusic_Click(sender, e); + return; + } + if (selectedMod.Mod.ModID == -1) { MessageTranslationHelper.ShowMessage(MessageTranslation.Warning_CantViewMod_NotFromBrowser); diff --git a/WheelWizard/Resources/Languages/en.yml b/WheelWizard/Resources/Languages/en.yml index 1b5da973..ab2948f8 100644 --- a/WheelWizard/Resources/Languages/en.yml +++ b/WheelWizard/Resources/Languages/en.yml @@ -183,6 +183,47 @@ en: search_placeholder: Search... input: invalid_number: Enter a number + custom_music: + choose: Choose music + converting: Converting... + error: + missing: The song file could not be found. + no_game: Set your Mario Kart Wii game file in Wheel Wizard's settings to play the original music. + no_original: The original music here isn't a file Wheel Wizard can play. + play: 'Could not play the music: %{message}' + too_long: Songs can be at most 10 minutes long. + unreadable: This song could not be read. The file may be damaged. + unsupported: This file type is not supported. Use an MP3, OGG, FLAC, WAV, AIFF or BRSTM file. + write: 'Could not save the custom music: %{message}' + file_type: Music files + final_lap: + faster: Faster (Retro Rewind style) + faster_same_pitch: Faster, same pitch + help: Used for songs you add from now on. + label: Final lap music + unchanged: Same as laps 1 and 2 + help: Choose or drop an MP3, OGG, FLAC, WAV, AIFF or BRSTM file onto a track. Songs loop where the music repeats, or at their own loop points. Changes are saved right away in the Custom Music patch. + match_volume: + help: New songs are made as loud as the music they replace, measured from Retro Rewind's files or your game file. + label: Match the volume of the original music + open_folder: Open the music folder + pick_title: Choose music for %{name} + play: Play the music + reset: Use the original music + search: Search tracks and menus + settings: Settings + sort: + changed_first: Changed first + label: Sort + name: A to Z + track_order: Track order + stop: Stop + tab: + battle: Battle + menus: Menus + races: Races + title: Custom Music + unknown_song: Custom music empty_content: no_friends: You can add friends in-game no_friends_title: No friends yet! diff --git a/WheelWizard/SetupExtensions.cs b/WheelWizard/SetupExtensions.cs index 5538e46f..4c47d8b5 100644 --- a/WheelWizard/SetupExtensions.cs +++ b/WheelWizard/SetupExtensions.cs @@ -5,6 +5,7 @@ using WheelWizard.Branding; using WheelWizard.CustomCharacters; using WheelWizard.CustomDistributions; +using WheelWizard.CustomMusic; using WheelWizard.DiscImages; using WheelWizard.DolphinInstaller; using WheelWizard.Features.Archives; @@ -53,6 +54,7 @@ public static void AddWheelWizardServices(this IServiceCollection services, IApp services.AddArchives(); services.AddPatches(); services.AddMods(); + services.AddCustomMusic(); services.AddRecomp(); services.AddPresentation(); } diff --git a/WheelWizard/Views/Styles/Resources/Icons.axaml b/WheelWizard/Views/Styles/Resources/Icons.axaml index 94e6dfb4..f43242ab 100644 --- a/WheelWizard/Views/Styles/Resources/Icons.axaml +++ b/WheelWizard/Views/Styles/Resources/Icons.axaml @@ -92,6 +92,8 @@ + + @@ -188,4 +190,7 @@ M160 0a48 48 0 1 1 0 96 48 48 0 1 1 0-96zM88 384l-17.8 0c-10.9 0-18.6-10.7-15.2-21.1L93.3 248.1 59.4 304.5c-9.1 15.1-28.8 20-43.9 10.9s-20-28.8-10.9-43.9l53.6-89.2c20.3-33.7 56.7-54.3 96-54.3l11.6 0c39.3 0 75.7 20.6 96 54.3l53.6 89.2c9.1 15.1 4.2 34.8-10.9 43.9s-34.8 4.2-43.9-10.9l-33.9-56.3L265 362.9c3.5 10.4-4.3 21.1-15.2 21.1L232 384l0 96c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-96-16 0 0 96c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-96z M23 23v466h466v-18H41v-82.184l85.854-57.234 70.023 70.022 65.133-260.536L387.28 203.7l67.79-107.97 19.317 11.858 6.102-71.1-60.644 37.616 19.884 12.207-59.01 93.99-130.732-65.366-62.865 251.462-57.98-57.978L41 367.184V23H23z M352 160C352 142.3 366.3 128 384 128C401.7 128 416 142.3 416 160C416 177.7 430.3 192 448 192C465.7 192 480 177.7 480 160C480 107 437 64 384 64C331 64 288 107 288 160L288 352L224 352L224 312C224 281.1 198.9 256 168 256L120 256C106.7 256 96 266.7 96 280C96 293.3 106.7 304 120 304L168 304C172.4 304 176 307.6 176 312L176 352L96 352C78.3 352 64 366.3 64 384C64 401.7 78.3 416 96 416L96 480C96 533 139 576 192 576L448 576C501 576 544 533 544 480L544 416C561.7 416 576 401.7 576 384C576 366.3 561.7 352 544 352L464 352L464 312C464 307.6 467.6 304 472 304L528 304C541.3 304 552 293.3 552 280C552 266.7 541.3 256 528 256L472 256C441.1 256 416 281.1 416 312L416 352L352 352L352 160z + + F1 M176,80 L464,16 L464,72 L176,136 Z M176,96 L208,96 L208,400 L176,400 Z M432,32 L464,32 L464,336 L432,336 Z M80,400 A64,48 0 1,1 208,400 A64,48 0 1,1 80,400 Z M336,336 A64,48 0 1,1 464,336 A64,48 0 1,1 336,336 Z + M0 128C0 92.7 28.7 64 64 64H320c35.3 0 64 28.7 64 64V384c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V128z diff --git a/WheelWizard/WheelWizard.csproj b/WheelWizard/WheelWizard.csproj index e2420601..0f10c348 100644 --- a/WheelWizard/WheelWizard.csproj +++ b/WheelWizard/WheelWizard.csproj @@ -72,6 +72,19 @@ + + + + + + + + + + + + +