diff --git a/README.md b/README.md index fefa814..1100379 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,6 @@ A .NET 10 C# library for reading and writing Rhythia replay and map files. -Currently only `.rhr` replay files are supported, but `.rhm` map files are easy to implement and will be implemented in the coming days. - This library is designed for the Steam version of Rhythia, but it may work with the open-source one as well if they end up using the same formats. As of now (July 2026) the open-source version supports `.rhm` maps. ## Installation @@ -22,15 +20,17 @@ dotnet add reference path/to/RhythiaLib/RhythiaLib/RhythiaLib.csproj ## Supported Formats -| Extension | Status | Description | -| --------- | --------- | --------------------------- | -| .rhr | Supported | Rhythia replay file | -| .rhm | Planned | Rhythia map file/archive | -| .sspm | Possibly | Legacy/SoundSpace+ map file | +| Extension | Status | Description | +| --------- | --------- | ------------------------ | +| .rhr | Supported | Rhythia replay file | +| .rhm | Supported | Rhythia map file/archive | +| .sspm | Possibly | SoundSpace+ map file | +| .ssre | Possibly | SoundSpace+ replay file | ## Usage - [RHR Files](./RhythiaLib/Rhr/USAGE.MD) +- [RHM Files](./RhythiaLib/Rhm/USAGE.MD) ## Testing @@ -43,6 +43,7 @@ dotnet test ## Credits - [yoru](https://github.com/yo-ru) - Their [rhrParse](https://github.com/yo-ru/rhrParse) repo was used as reference for unknown fields and backwards compatibility. +- [FOSS Rhythia](https://github.com/Rhythia/Client) - Their map [parser](https://github.com/Rhythia/Client/blob/d931b419853387ef6d2ecd1b378e409f6de6f630/scripts/map/MapParser.cs)/[model](https://github.com/Rhythia/Client/blob/d931b419853387ef6d2ecd1b378e409f6de6f630/scripts/map/Map.cs) was used as reference. ## License diff --git a/RhythiaLib.Tests/Rhm/Fixtures/no-quantum.rhm b/RhythiaLib.Tests/Rhm/Fixtures/no-quantum.rhm new file mode 100644 index 0000000..0addca1 Binary files /dev/null and b/RhythiaLib.Tests/Rhm/Fixtures/no-quantum.rhm differ diff --git a/RhythiaLib.Tests/Rhm/Fixtures/quantum.rhm b/RhythiaLib.Tests/Rhm/Fixtures/quantum.rhm new file mode 100644 index 0000000..6ca8684 Binary files /dev/null and b/RhythiaLib.Tests/Rhm/Fixtures/quantum.rhm differ diff --git a/RhythiaLib.Tests/Rhm/RhmCorruptionTests.cs b/RhythiaLib.Tests/Rhm/RhmCorruptionTests.cs new file mode 100644 index 0000000..6c2bd50 --- /dev/null +++ b/RhythiaLib.Tests/Rhm/RhmCorruptionTests.cs @@ -0,0 +1,165 @@ +using System.Text.Json; +using RhythiaLib.Maps; +using RhythiaLib.Rhm; + +namespace RhythiaLib.Tests.Rhm +{ + public sealed class RhmCorruptionTests + { + [Fact] + public void Decode_NonZip_Throws() + { + Assert.Throws(() => RhmFile.Decode("not a zip"u8)); + } + + [Fact] + public void Decode_MissingMap_Throws() + { + Assert.Throws(() => + RhmFile.Decode(RhmFixtureData.CreateArchive("", includeMap: false)) + ); + } + + [Fact] + public void Decode_InvalidMapJson_Throws() + { + Assert.Throws(() => + RhmFile.Decode(RhmFixtureData.CreateArchive("{")) + ); + } + + [Fact] + public void Decode_MissingAudio_Throws() + { + Assert.Throws(() => + RhmFile.Decode( + RhmFixtureData.CreateArchive(RhmFixtureData.ValidMapJson, includeAudio: false) + ) + ); + } + + [Fact] + public void Decode_MissingCover_Throws() + { + Assert.Throws(() => + RhmFile.Decode( + RhmFixtureData.CreateArchive(RhmFixtureData.ValidMapJson, includeCover: false) + ) + ); + } + + [Fact] + public void Decode_MapOverLimit_Throws() + { + Assert.Throws(() => + RhmFile.Decode( + RhmFixtureData.CreateArchive(RhmFixtureData.ValidMapJson), + new RhmReadOptions { MaximumMapSize = 1 } + ) + ); + } + + [Theory] + [InlineData(0)] + [InlineData(6)] + public void Decode_InvalidDifficulty_Throws(int difficulty) + { + string json = Replace("Difficulty", difficulty); + Assert.Throws(() => + RhmFile.Decode(RhmFixtureData.CreateArchive(json)) + ); + } + + [Fact] + public void Decode_NegativeDuration_Throws() + { + string json = Replace("Duration", -1); + Assert.Throws(() => + RhmFile.Decode(RhmFixtureData.CreateArchive(json)) + ); + } + + [Fact] + public void Decode_ExcessiveNoteCount_Throws() + { + Assert.Throws(() => + RhmFile.Decode( + RhmFixtureData.CreateArchive(RhmFixtureData.ValidMapJson), + new RhmReadOptions { MaximumNoteCount = 0 } + ) + ); + } + + [Fact] + public void Decode_NegativeNoteTime_Throws() + { + string json = RhmFixtureData.ValidMapJson.Replace( + "\"Time\":10", + "\"Time\":-1", + StringComparison.Ordinal + ); + Assert.Throws(() => + RhmFile.Decode(RhmFixtureData.CreateArchive(json)) + ); + } + + [Fact] + public void Decode_NonFiniteNoteCoordinate_Throws() + { + string json = RhmFixtureData.ValidMapJson.Replace( + "\"X\":1", + "\"X\":1e100", + StringComparison.Ordinal + ); + Assert.Throws(() => + RhmFile.Decode(RhmFixtureData.CreateArchive(json)) + ); + } + + [Fact] + public void Read_UnreadableStream_Throws() + { + using var stream = new UnreadableStream(); + Assert.Throws(() => RhmFile.Read(stream)); + } + + [Fact] + public void Write_UnwritableStream_Throws() + { + using var stream = new MemoryStream([], writable: false); + Assert.Throws(() => + RhmFile.Write(stream, RhmFixtureData.CreateMap()) + ); + } + + [Fact] + public void Encode_MissingRequiredMedia_Throws() + { + RhythiaMap map = RhmFixtureData.CreateMap(); + map.Audio = null; + Assert.Throws(() => RhmFile.Encode(map)); + + map.Audio = []; + map.Cover = null; + Assert.Throws(() => RhmFile.Encode(map)); + } + + private static string Replace(string propertyName, int value) + { + using JsonDocument document = JsonDocument.Parse(RhmFixtureData.ValidMapJson); + var values = new Dictionary(); + foreach (JsonProperty property in document.RootElement.EnumerateObject()) + { + values[property.Name] = + property.Name == propertyName ? value : property.Value.Clone(); + } + + return JsonSerializer.Serialize(values); + } + + private sealed class UnreadableStream : MemoryStream + { + public override bool CanRead => false; + } + } +} diff --git a/RhythiaLib.Tests/Rhm/RhmFileReadTests.cs b/RhythiaLib.Tests/Rhm/RhmFileReadTests.cs new file mode 100644 index 0000000..1ffa276 --- /dev/null +++ b/RhythiaLib.Tests/Rhm/RhmFileReadTests.cs @@ -0,0 +1,59 @@ +using RhythiaLib.Maps; +using RhythiaLib.Rhm; + +namespace RhythiaLib.Tests.Rhm +{ + public sealed class RhmFileReadTests + { + [Theory] + [MemberData(nameof(RhmFixtureData.FixturePaths), MemberType = typeof(RhmFixtureData))] + public void Read_GameFixture_ReturnsValidMap(string path) + { + RhythiaMap map = RhmFile.Read(path); + + Assert.False(string.IsNullOrWhiteSpace(map.Title)); + Assert.InRange(map.Difficulty, 1, 5); + Assert.NotEmpty(map.Notes); + Assert.NotNull(map.Audio); + Assert.NotEmpty(map.Audio); + Assert.NotNull(map.Cover); + Assert.NotEmpty(map.Cover); + + for (int index = 0; index < map.Notes.Count; index++) + { + RhythiaNote note = map.Notes[index]; + Assert.Equal(index, note.Index); + Assert.True(float.IsFinite(note.X)); + Assert.True(float.IsFinite(note.Y)); + if (index > 0) + Assert.True(map.Notes[index - 1].TimeMilliseconds <= note.TimeMilliseconds); + } + } + + [Fact] + public void Read_KnownFixture_ReturnsKnownMetadata() + { + string path = Path.Combine(AppContext.BaseDirectory, "Rhm", "Fixtures", "quantum.rhm"); + + RhythiaMap map = RhmFile.Read(path); + + Assert.Equal("5860246058480dfb", map.Id); + Assert.Equal("nature", map.Artist); + Assert.Equal("chirp", map.Title); + Assert.Equal(465, map.LengthMilliseconds); + Assert.Equal(1, map.Difficulty); + Assert.Equal(["whip"], map.Mappers); + } + + [Fact] + public void Read_LeavesCallerStreamOpen() + { + byte[] data = RhmFixtureData.CreateArchive(RhmFixtureData.ValidMapJson); + using var stream = new MemoryStream(data); + + _ = RhmFile.Read(stream); + + Assert.True(stream.CanRead); + } + } +} diff --git a/RhythiaLib.Tests/Rhm/RhmFileWriteTests.cs b/RhythiaLib.Tests/Rhm/RhmFileWriteTests.cs new file mode 100644 index 0000000..b20da90 --- /dev/null +++ b/RhythiaLib.Tests/Rhm/RhmFileWriteTests.cs @@ -0,0 +1,92 @@ +using System.IO.Compression; +using System.Text.Json; +using RhythiaLib.Maps; +using RhythiaLib.Rhm; + +namespace RhythiaLib.Tests.Rhm +{ + public sealed class RhmFileWriteTests + { + [Fact] + public void Encode_WritesExpectedArchiveLayout() + { + byte[] data = RhmFile.Encode(RhmFixtureData.CreateMap()); + + using var stream = new MemoryStream(data); + using var archive = new ZipArchive(stream, ZipArchiveMode.Read); + ZipArchiveEntry mapEntry = Assert.Single( + archive.Entries, + entry => entry.FullName == "map" + ); + Assert.NotNull(archive.GetEntry("audio.mp3")); + Assert.NotNull(archive.GetEntry("cover.png")); + + using Stream mapStream = mapEntry.Open(); + using JsonDocument json = JsonDocument.Parse(mapStream); + Assert.Equal("audio.mp3", json.RootElement.GetProperty("AudioFileName").GetString()); + Assert.Equal("cover.png", json.RootElement.GetProperty("ImagePath").GetString()); + Assert.Equal( + JsonValueKind.Number, + json.RootElement.GetProperty("Difficulty").ValueKind + ); + } + + [Fact] + public void Encode_ConvertsCoordinatesAndDecodeRestoresThem() + { + RhythiaMap map = RhmFixtureData.CreateMap(); + map.Notes = + [ + new RhythiaNote + { + TimeMilliseconds = 0, + X = 0, + Y = 0, + }, + new RhythiaNote + { + TimeMilliseconds = 1, + X = -1, + Y = 1, + }, + new RhythiaNote + { + TimeMilliseconds = 2, + X = 1, + Y = -1, + }, + ]; + + byte[] data = RhmFile.Encode(map); + using (var stream = new MemoryStream(data)) + using (var archive = new ZipArchive(stream, ZipArchiveMode.Read)) + using (Stream mapStream = archive.GetEntry("map")!.Open()) + using (JsonDocument json = JsonDocument.Parse(mapStream)) + { + JsonElement notes = json.RootElement.GetProperty("Notes"); + AssertStored(notes[0], 1, 1); + AssertStored(notes[1], 0, 0); + AssertStored(notes[2], 2, 2); + } + + RhythiaMap decoded = RhmFile.Decode(data); + Assert.Equal((0f, 0f), (decoded.Notes[0].X, decoded.Notes[0].Y)); + Assert.Equal((-1f, 1f), (decoded.Notes[1].X, decoded.Notes[1].Y)); + Assert.Equal((1f, -1f), (decoded.Notes[2].X, decoded.Notes[2].Y)); + } + + [Fact] + public void Write_LeavesCallerStreamOpen() + { + using var stream = new MemoryStream(); + RhmFile.Write(stream, RhmFixtureData.CreateMap()); + Assert.True(stream.CanWrite); + } + + private static void AssertStored(JsonElement note, float x, float y) + { + Assert.Equal(x, note.GetProperty("X").GetSingle()); + Assert.Equal(y, note.GetProperty("Y").GetSingle()); + } + } +} diff --git a/RhythiaLib.Tests/Rhm/RhmFixtureData.cs b/RhythiaLib.Tests/Rhm/RhmFixtureData.cs new file mode 100644 index 0000000..d836acd --- /dev/null +++ b/RhythiaLib.Tests/Rhm/RhmFixtureData.cs @@ -0,0 +1,92 @@ +using System.IO.Compression; +using System.Text; +using RhythiaLib.Maps; + +namespace RhythiaLib.Tests.Rhm +{ + internal static class RhmFixtureData + { + public const string ValidMapJson = """ + {"OnlineId":null,"OnlineStatus":null,"LegacyId":"test-id","SongName":"Artist - Song","Mappers":["Mapper"],"Title":"Artist - Song","Duration":1000,"Difficulty":3,"CustomDifficultyName":"Test","StarRating":4.5,"Notes":[{"Time":10,"X":1,"Y":1}],"ImagePath":"cover","AudioFileName":"song.mp3"} + """; + + public static TheoryData FixturePaths() + { + var data = new TheoryData(); + + string directory = Path.Combine(AppContext.BaseDirectory, "Rhm", "Fixtures"); + + if (!Directory.Exists(directory)) + return data; + + foreach ( + string path in Directory.EnumerateFiles( + directory, + "*.rhm", + SearchOption.AllDirectories + ) + ) + { + data.Add(path); + } + + return data; + } + + public static RhythiaMap CreateMap() + { + return new RhythiaMap + { + Id = "test-id", + Artist = "Artist", + Title = "Artist - Song", + Rating = 4.5f, + Mappers = ["Mapper"], + Difficulty = 3, + DifficultyName = "Test", + LengthMilliseconds = 1000, + Notes = + [ + new RhythiaNote + { + Index = 0, + TimeMilliseconds = 10, + X = 0, + Y = 0, + }, + ], + Audio = [1, 2, 3], + AudioExtension = ".mp3", + Cover = [4, 5, 6], + }; + } + + public static byte[] CreateArchive( + string mapJson, + bool includeMap = true, + bool includeAudio = true, + bool includeCover = true + ) + { + using var stream = new MemoryStream(); + using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) + { + if (includeMap) + WriteEntry(archive, "map", Encoding.UTF8.GetBytes(mapJson)); + if (includeAudio) + WriteEntry(archive, "audio", [1, 2, 3]); + if (includeCover) + WriteEntry(archive, "cover", [4, 5, 6]); + } + + return stream.ToArray(); + } + + private static void WriteEntry(ZipArchive archive, string name, byte[] data) + { + ZipArchiveEntry entry = archive.CreateEntry(name); + using Stream stream = entry.Open(); + stream.Write(data); + } + } +} diff --git a/RhythiaLib.Tests/Rhm/RhmRoundTripTests.cs b/RhythiaLib.Tests/Rhm/RhmRoundTripTests.cs new file mode 100644 index 0000000..0051549 --- /dev/null +++ b/RhythiaLib.Tests/Rhm/RhmRoundTripTests.cs @@ -0,0 +1,38 @@ +using RhythiaLib.Maps; +using RhythiaLib.Rhm; + +namespace RhythiaLib.Tests.Rhm +{ + public sealed class RhmRoundTripTests + { + [Theory] + [MemberData(nameof(RhmFixtureData.FixturePaths), MemberType = typeof(RhmFixtureData))] + public void Fixture_LogicalRoundTripPreservesData(string path) + { + RhythiaMap original = RhmFile.Read(path); + RhythiaMap decoded = RhmFile.Decode(RhmFile.Encode(original)); + + Assert.Equal(original.Id, decoded.Id); + Assert.Equal(original.Artist, decoded.Artist); + Assert.Equal(original.Title, decoded.Title); + Assert.Equal(original.Rating, decoded.Rating); + Assert.Equal(original.Mappers, decoded.Mappers); + Assert.Equal(original.Difficulty, decoded.Difficulty); + Assert.Equal(original.DifficultyName, decoded.DifficultyName); + Assert.Equal(original.LengthMilliseconds, decoded.LengthMilliseconds); + Assert.Equal(original.Audio, decoded.Audio); + Assert.Equal(original.Cover, decoded.Cover); + Assert.Equal(original.Notes.Count, decoded.Notes.Count); + + for (int index = 0; index < original.Notes.Count; index++) + { + RhythiaNote expected = original.Notes[index]; + RhythiaNote actual = decoded.Notes[index]; + Assert.Equal(expected.Index, actual.Index); + Assert.Equal(expected.TimeMilliseconds, actual.TimeMilliseconds); + Assert.Equal(expected.X, actual.X); + Assert.Equal(expected.Y, actual.Y); + } + } + } +} diff --git a/RhythiaLib.Tests/RhythiaLib.Tests.csproj b/RhythiaLib.Tests/RhythiaLib.Tests.csproj index e07d8e2..d680851 100644 --- a/RhythiaLib.Tests/RhythiaLib.Tests.csproj +++ b/RhythiaLib.Tests/RhythiaLib.Tests.csproj @@ -25,5 +25,8 @@ PreserveNewest + + PreserveNewest + diff --git a/RhythiaLib/Maps/RhythiaMap.cs b/RhythiaLib/Maps/RhythiaMap.cs new file mode 100644 index 0000000..e3a4103 --- /dev/null +++ b/RhythiaLib/Maps/RhythiaMap.cs @@ -0,0 +1,21 @@ +namespace RhythiaLib.Maps +{ + public sealed class RhythiaMap + { + public string Id { get; set; } = string.Empty; + public string Artist { get; set; } = string.Empty; + public string ArtistLink { get; set; } = string.Empty; + public string ArtistPlatform { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public float Rating { get; set; } + public List Mappers { get; set; } = []; + public int Difficulty { get; set; } + public string DifficultyName { get; set; } = string.Empty; + public int LengthMilliseconds { get; set; } + public List Notes { get; set; } = []; + public byte[]? Audio { get; set; } + public string? AudioExtension { get; set; } + public byte[]? Cover { get; set; } + public byte[]? Video { get; set; } + } +} diff --git a/RhythiaLib/Maps/RhythiaNote.cs b/RhythiaLib/Maps/RhythiaNote.cs new file mode 100644 index 0000000..fcb5e7c --- /dev/null +++ b/RhythiaLib/Maps/RhythiaNote.cs @@ -0,0 +1,10 @@ +namespace RhythiaLib.Maps +{ + public sealed class RhythiaNote + { + public int Index { get; set; } + public int TimeMilliseconds { get; set; } + public float X { get; set; } + public float Y { get; set; } + } +} diff --git a/RhythiaLib/Rhm/Internal/RhmArchiveCodec.cs b/RhythiaLib/Rhm/Internal/RhmArchiveCodec.cs new file mode 100644 index 0000000..5963a62 --- /dev/null +++ b/RhythiaLib/Rhm/Internal/RhmArchiveCodec.cs @@ -0,0 +1,147 @@ +using System.IO.Compression; +using RhythiaLib.Maps; + +namespace RhythiaLib.Rhm.Internal +{ + internal static class RhmArchiveCodec + { + private const string MapEntryName = "map"; + private const string DefaultCoverEntryName = "cover.png"; + + public static RhythiaMap Read(Stream stream, RhmReadOptions options) + { + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(options); + + if (!stream.CanRead) + throw new ArgumentException("The stream must be readable.", nameof(stream)); + + RhmValidation.ValidateReadOptions(options); + + try + { + using var archive = new ZipArchive(stream, ZipArchiveMode.Read, leaveOpen: true); + + ZipArchiveEntry mapEntry = + archive.GetEntry(MapEntryName) + ?? throw new InvalidRhmFormatException( + "The RHM archive is missing its map entry." + ); + RhmValidation.ValidateEntrySize(mapEntry, options.MaximumMapSize, "map"); + + RhmMapDto dto; + using (Stream mapStream = mapEntry.Open()) + dto = RhmMapCodec.Read(mapStream); + + RhmValidation.ValidateDto(dto, options); + + ZipArchiveEntry audioEntry = + archive.GetEntry("audio") + ?? ( + !string.IsNullOrEmpty(dto.AudioFileName) + ? archive.GetEntry(dto.AudioFileName) + : null + ) + ?? throw new InvalidRhmFormatException( + "The RHM archive is missing its required audio entry." + ); + + if (string.IsNullOrEmpty(dto.ImagePath)) + { + throw new InvalidRhmFormatException( + "The RHM map does not specify its required cover entry." + ); + } + + ZipArchiveEntry coverEntry = + archive.GetEntry(dto.ImagePath) + ?? throw new InvalidRhmFormatException( + $"The RHM archive is missing its required cover entry '{dto.ImagePath}'." + ); + + byte[] audio = ReadEntry(audioEntry, options.MaximumAudioSize, "audio"); + byte[] cover = ReadEntry(coverEntry, options.MaximumCoverSize, "cover"); + + RhythiaMap map = RhmMapConverter.ToModel(dto); + map.Audio = audio; + map.Cover = cover; + + string extension = Path.GetExtension(audioEntry.FullName); + map.AudioExtension = string.IsNullOrEmpty(extension) ? null : extension; + return map; + } + catch (InvalidRhmFormatException) + { + throw; + } + catch (InvalidDataException exception) + { + throw new InvalidRhmFormatException( + "The input is not a valid RHM ZIP archive.", + exception + ); + } + } + + public static void Write(Stream stream, RhythiaMap map) + { + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(map); + + if (!stream.CanWrite) + throw new ArgumentException("The stream must be writable.", nameof(stream)); + + RhmValidation.ValidateMapForWriting(map); + + string audioEntryName = GetAudioEntryName(map.AudioExtension); + const string coverEntryName = DefaultCoverEntryName; + RhmMapDto dto = RhmMapConverter.ToDto(map, audioEntryName, coverEntryName); + + using var archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true); + + ZipArchiveEntry mapEntry = archive.CreateEntry(MapEntryName, CompressionLevel.Optimal); + using (Stream mapStream = mapEntry.Open()) + RhmMapCodec.Write(mapStream, dto); + + WriteEntry(archive, audioEntryName, map.Audio!); + WriteEntry(archive, coverEntryName, map.Cover!); + } + + private static byte[] ReadEntry(ZipArchiveEntry entry, long maximumSize, string kind) + { + RhmValidation.ValidateEntrySize(entry, maximumSize, kind); + + using Stream input = entry.Open(); + using var output = new MemoryStream((int)entry.Length); + input.CopyTo(output); + return output.ToArray(); + } + + private static void WriteEntry(ZipArchive archive, string name, byte[] data) + { + ZipArchiveEntry entry = archive.CreateEntry(name, CompressionLevel.Optimal); + using Stream output = entry.Open(); + output.Write(data); + } + + private static string GetAudioEntryName(string? extension) + { + if (string.IsNullOrWhiteSpace(extension)) + return "audio"; + + string trimmed = extension.Trim(); + if (trimmed.IndexOfAny(['/', '\\']) >= 0) + { + throw new ArgumentException( + "The audio extension cannot contain path separators.", + nameof(extension) + ); + } + + if (trimmed == ".") + return "audio"; + + return trimmed[0] == '.' ? $"audio{trimmed}" : $"audio.{trimmed}"; + } + } +} diff --git a/RhythiaLib/Rhm/Internal/RhmMapCodec.cs b/RhythiaLib/Rhm/Internal/RhmMapCodec.cs new file mode 100644 index 0000000..10717c5 --- /dev/null +++ b/RhythiaLib/Rhm/Internal/RhmMapCodec.cs @@ -0,0 +1,41 @@ +using System.Text.Json; + +namespace RhythiaLib.Rhm.Internal +{ + internal static class RhmMapCodec + { + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNameCaseInsensitive = false, + WriteIndented = false, + }; + + public static RhmMapDto Read(Stream stream) + { + ArgumentNullException.ThrowIfNull(stream); + + try + { + RhmMapDto? map = JsonSerializer.Deserialize(stream, JsonOptions); + return map + ?? throw new InvalidRhmFormatException( + "The RHM map JSON has a null root object." + ); + } + catch (JsonException exception) + { + throw new InvalidRhmFormatException( + "The RHM map entry contains malformed JSON.", + exception + ); + } + } + + public static void Write(Stream stream, RhmMapDto map) + { + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(map); + JsonSerializer.Serialize(stream, map, JsonOptions); + } + } +} diff --git a/RhythiaLib/Rhm/Internal/RhmMapConverter.cs b/RhythiaLib/Rhm/Internal/RhmMapConverter.cs new file mode 100644 index 0000000..823e9de --- /dev/null +++ b/RhythiaLib/Rhm/Internal/RhmMapConverter.cs @@ -0,0 +1,91 @@ +using RhythiaLib.Maps; + +namespace RhythiaLib.Rhm.Internal +{ + internal static class RhmMapConverter + { + public static RhythiaMap ToModel(RhmMapDto dto) + { + ArgumentNullException.ThrowIfNull(dto); + + string displayTitle = dto.Title ?? string.Empty; + string[] titleParts = displayTitle.Split(" - ", 2, StringSplitOptions.None); + + var notes = new List(dto.Notes.Count); + foreach (RhmNoteDto note in dto.Notes) + { + notes.Add( + new RhythiaNote + { + Index = notes.Count, + TimeMilliseconds = note.Time, + X = note.X - 1f, + Y = 1f - note.Y, + } + ); + } + + notes.Sort( + static (left, right) => + { + int timeComparison = left.TimeMilliseconds.CompareTo(right.TimeMilliseconds); + return timeComparison != 0 ? timeComparison : left.Index.CompareTo(right.Index); + } + ); + for (int index = 0; index < notes.Count; index++) + notes[index].Index = index; + + return new RhythiaMap + { + Id = !string.IsNullOrEmpty(dto.LegacyId) + ? dto.LegacyId + : dto.OnlineId ?? string.Empty, + Artist = titleParts.Length == 2 ? titleParts[0] : string.Empty, + Title = titleParts.Length == 2 ? titleParts[1] : displayTitle, + Rating = (float)dto.StarRating, + Mappers = [.. dto.Mappers], + Difficulty = dto.Difficulty, + DifficultyName = dto.CustomDifficultyName ?? string.Empty, + LengthMilliseconds = dto.Duration, + Notes = notes, + }; + } + + public static RhmMapDto ToDto(RhythiaMap map, string audioEntryName, string coverEntryName) + { + ArgumentNullException.ThrowIfNull(map); + + string displayTitle = string.IsNullOrWhiteSpace(map.Artist) + ? map.Title + : $"{map.Artist} - {map.Title}"; + + var notes = new List(map.Notes.Count); + foreach (RhythiaNote note in map.Notes) + { + notes.Add( + new RhmNoteDto + { + Time = note.TimeMilliseconds, + X = note.X + 1f, + Y = 1f - note.Y, + } + ); + } + + return new RhmMapDto + { + LegacyId = map.Id, + SongName = displayTitle, + Mappers = [.. map.Mappers], + Title = displayTitle, + Duration = map.LengthMilliseconds, + Difficulty = map.Difficulty, + CustomDifficultyName = map.DifficultyName, + StarRating = map.Rating, + Notes = notes, + AudioFileName = audioEntryName, + ImagePath = coverEntryName, + }; + } + } +} diff --git a/RhythiaLib/Rhm/Internal/RhmMapDto.cs b/RhythiaLib/Rhm/Internal/RhmMapDto.cs new file mode 100644 index 0000000..d02692e --- /dev/null +++ b/RhythiaLib/Rhm/Internal/RhmMapDto.cs @@ -0,0 +1,19 @@ +namespace RhythiaLib.Rhm.Internal +{ + internal sealed class RhmMapDto + { + public string? OnlineId { get; set; } + public object? OnlineStatus { get; set; } + public string? LegacyId { get; set; } + public string SongName { get; set; } = string.Empty; + public List Mappers { get; set; } = []; + public string Title { get; set; } = string.Empty; // no clue what the difference between this and SongName is + public int Duration { get; set; } + public int Difficulty { get; set; } + public string CustomDifficultyName { get; set; } = string.Empty; + public double StarRating { get; set; } + public List Notes { get; set; } = []; + public string ImagePath { get; set; } = string.Empty; + public string AudioFileName { get; set; } = string.Empty; + } +} diff --git a/RhythiaLib/Rhm/Internal/RhmNoteDto.cs b/RhythiaLib/Rhm/Internal/RhmNoteDto.cs new file mode 100644 index 0000000..782d8c0 --- /dev/null +++ b/RhythiaLib/Rhm/Internal/RhmNoteDto.cs @@ -0,0 +1,9 @@ +namespace RhythiaLib.Rhm.Internal +{ + internal sealed class RhmNoteDto + { + public int Time { get; set; } + public float X { get; set; } + public float Y { get; set; } + } +} diff --git a/RhythiaLib/Rhm/Internal/RhmValidation.cs b/RhythiaLib/Rhm/Internal/RhmValidation.cs new file mode 100644 index 0000000..e616532 --- /dev/null +++ b/RhythiaLib/Rhm/Internal/RhmValidation.cs @@ -0,0 +1,167 @@ +using System.IO.Compression; +using RhythiaLib.Maps; + +namespace RhythiaLib.Rhm.Internal +{ + internal static class RhmValidation + { + public static void ValidateReadOptions(RhmReadOptions options) + { + ArgumentNullException.ThrowIfNull(options); + + if (options.MaximumMapSize < 0) + throw new ArgumentOutOfRangeException( + nameof(options), + "Maximum map size must be nonnegative." + ); + if (options.MaximumAudioSize < 0) + throw new ArgumentOutOfRangeException( + nameof(options), + "Maximum audio size must be nonnegative." + ); + if (options.MaximumCoverSize < 0) + throw new ArgumentOutOfRangeException( + nameof(options), + "Maximum cover size must be nonnegative." + ); + if (options.MaximumNoteCount < 0) + throw new ArgumentOutOfRangeException( + nameof(options), + "Maximum note count must be nonnegative." + ); + } + + public static void ValidateEntrySize(ZipArchiveEntry entry, long maximumSize, string kind) + { + ArgumentNullException.ThrowIfNull(entry); + + if (entry.Length > maximumSize) + { + throw new InvalidRhmFormatException( + $"The RHM {kind} entry size of {entry.Length} bytes exceeds " + + $"the configured maximum of {maximumSize} bytes." + ); + } + + if (entry.Length > int.MaxValue) + { + throw new InvalidRhmFormatException( + $"The RHM {kind} entry is too large to load into memory." + ); + } + } + + public static void ValidateDto(RhmMapDto map, RhmReadOptions options) + { + if (map.Difficulty is < 1 or > 5) + throw new InvalidRhmFormatException( + $"RHM difficulty {map.Difficulty} is outside the supported range 1 through 5." + ); + + if (map.Duration < 0) + throw new InvalidRhmFormatException("The RHM map duration is negative."); + + if (map.Mappers is null) + throw new InvalidRhmFormatException("The RHM mappers collection is null."); + + if (map.Notes is null) + throw new InvalidRhmFormatException("The RHM notes collection is null."); + + if (map.Notes.Count > options.MaximumNoteCount) + { + throw new InvalidRhmFormatException( + $"The RHM note count of {map.Notes.Count} exceeds " + + $"the configured maximum of {options.MaximumNoteCount}." + ); + } + + if (!double.IsFinite(map.StarRating)) + throw new InvalidRhmFormatException("The RHM star rating is not finite."); + + for (int index = 0; index < map.Notes.Count; index++) + { + RhmNoteDto note = + map.Notes[index] + ?? throw new InvalidRhmFormatException($"RHM note {index} is null."); + + if (note.Time < 0) + throw new InvalidRhmFormatException($"RHM note {index} has a negative time."); + + if (!float.IsFinite(note.X) || !float.IsFinite(note.Y)) + { + throw new InvalidRhmFormatException( + $"RHM note {index} contains a non-finite coordinate." + ); + } + } + } + + public static void ValidateMapForWriting(RhythiaMap map) + { + ArgumentNullException.ThrowIfNull(map); + + if (map.Audio is null) + throw new ArgumentException("RHM maps require audio data.", nameof(map)); + + if (map.Cover is null) + throw new ArgumentException("RHM maps require cover-image data.", nameof(map)); + + if (map.Difficulty is < 1 or > 5) + { + throw new ArgumentOutOfRangeException( + nameof(map), + map.Difficulty, + "RHM difficulty must be between 1 and 5." + ); + } + + if (map.Title is null) + throw new ArgumentException("The map title cannot be null.", nameof(map)); + + if (map.Mappers is null) + throw new ArgumentException( + "The map mappers collection cannot be null.", + nameof(map) + ); + + if (map.Notes is null) + throw new ArgumentException( + "The map notes collection cannot be null.", + nameof(map) + ); + + if (!float.IsFinite(map.Rating)) + throw new ArgumentException("The map rating must be finite.", nameof(map)); + + if (map.LengthMilliseconds < 0) + throw new ArgumentOutOfRangeException( + nameof(map), + map.LengthMilliseconds, + "The map length cannot be negative." + ); + + for (int index = 0; index < map.Notes.Count; index++) + { + RhythiaNote note = + map.Notes[index] + ?? throw new ArgumentException($"Map note {index} is null.", nameof(map)); + + if (note.TimeMilliseconds < 0) + { + throw new ArgumentException( + $"Map note {index} has a negative time.", + nameof(map) + ); + } + + if (!float.IsFinite(note.X) || !float.IsFinite(note.Y)) + { + throw new ArgumentException( + $"Map note {index} contains a non-finite coordinate.", + nameof(map) + ); + } + } + } + } +} diff --git a/RhythiaLib/Rhm/InvalidRhmFormatException.cs b/RhythiaLib/Rhm/InvalidRhmFormatException.cs new file mode 100644 index 0000000..eb47a8d --- /dev/null +++ b/RhythiaLib/Rhm/InvalidRhmFormatException.cs @@ -0,0 +1,11 @@ +namespace RhythiaLib.Rhm +{ + public sealed class InvalidRhmFormatException : Exception + { + public InvalidRhmFormatException(string message) + : base(message) { } + + public InvalidRhmFormatException(string message, Exception exception) + : base(message, exception) { } + } +} diff --git a/RhythiaLib/Rhm/RhmFile.cs b/RhythiaLib/Rhm/RhmFile.cs new file mode 100644 index 0000000..9189d37 --- /dev/null +++ b/RhythiaLib/Rhm/RhmFile.cs @@ -0,0 +1,48 @@ +using RhythiaLib.Maps; +using RhythiaLib.Rhm.Internal; + +namespace RhythiaLib.Rhm +{ + public static class RhmFile + { + public static RhythiaMap Read(string path, RhmReadOptions? options = null) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(path); + + using FileStream stream = File.OpenRead(path); + return Read(stream, options); + } + + public static RhythiaMap Read(Stream stream, RhmReadOptions? options = null) + { + return RhmArchiveCodec.Read(stream, options ?? new RhmReadOptions()); + } + + public static void Write(string path, RhythiaMap map) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(path); + using FileStream stream = File.OpenWrite(path); + Write(stream, map); + } + + public static void Write(Stream stream, RhythiaMap map) + { + RhmArchiveCodec.Write(stream, map); + } + + public static byte[] Encode(RhythiaMap map) + { + using var stream = new MemoryStream(); + Write(stream, map); + return stream.ToArray(); + } + + public static RhythiaMap Decode(ReadOnlySpan data, RhmReadOptions? options = null) + { + byte[] buffer = data.ToArray(); + using var stream = new MemoryStream(buffer, writable: false); + + return Read(stream, options); + } + } +} diff --git a/RhythiaLib/Rhm/RhmReadOptions.cs b/RhythiaLib/Rhm/RhmReadOptions.cs new file mode 100644 index 0000000..720180b --- /dev/null +++ b/RhythiaLib/Rhm/RhmReadOptions.cs @@ -0,0 +1,10 @@ +namespace RhythiaLib.Rhm +{ + public sealed class RhmReadOptions + { + public long MaximumMapSize { get; init; } = 16 * 1024 * 1024; // 16 MB + public long MaximumAudioSize { get; init; } = 128 * 1024 * 1024; // 128 MB + public long MaximumCoverSize { get; init; } = 32 * 1024 * 1024; // 32 MB + public int MaximumNoteCount { get; init; } = 5_000_000; + } +} diff --git a/RhythiaLib/Rhm/USAGE.md b/RhythiaLib/Rhm/USAGE.md new file mode 100644 index 0000000..f57e7e4 --- /dev/null +++ b/RhythiaLib/Rhm/USAGE.md @@ -0,0 +1,59 @@ +## Basic usage + +### Read an RHM file + +```csharp +using RhythiaLib.Maps; +using RhythiaLib.Rhm; + +RhythiaMap map = RhmFile.Read("map.rhm"); + +Console.WriteLine($"Artist: {map.Artist}"); +Console.WriteLine($"Title: {map.Title}"); +Console.WriteLine($"Difficulty: {map.Difficulty}"); +Console.WriteLine($"Rating: {map.Rating}"); +Console.WriteLine($"Length: {map.LengthMilliseconds}ms"); +Console.WriteLine($"Notes: {map.Notes.Count}"); +``` + +### Read from a stream + +```csharp +using RhythiaLib.Maps; +using RhythiaLib.Rhm; + +using var stream = File.OpenRead("map.rhm"); +RhythiaMap map = RhmFile.Read(stream); +``` + +### Decode from bytes + +```csharp +using RhythiaLib.Maps; +using RhythiaLib.Rhm; + +byte[] data = File.ReadAllBytes("map.rhm"); +RhythiaMap map = RhmFile.Decode(data); +``` + +### Write an RHM file + +```csharp +using RhythiaLib.Maps; +using RhythiaLib.Rhm; + +RhythiaMap map = RhmFile.Read("map.rhm"); +map.Title = "New Title"; +RhmFile.Write("new-map.rhm", map); +``` + +### Encode to bytes + +```csharp +using RhythiaLib.Maps; +using RhythiaLib.Rhm; + +RhythiaMap map = RhmFile.Read("map.rhm"); +byte[] data = RhmFile.Encode(map); +File.WriteAllBytes("new-map.rhm", data); +```