feat: rhm

This commit is contained in:
2026-07-23 22:19:33 -04:00
parent 569cdbd14a
commit c92b395a3e
21 changed files with 1090 additions and 7 deletions
+21
View File
@@ -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<string> Mappers { get; set; } = [];
public int Difficulty { get; set; }
public string DifficultyName { get; set; } = string.Empty;
public int LengthMilliseconds { get; set; }
public List<RhythiaNote> Notes { get; set; } = [];
public byte[]? Audio { get; set; }
public string? AudioExtension { get; set; }
public byte[]? Cover { get; set; }
public byte[]? Video { get; set; }
}
}
+10
View File
@@ -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; }
}
}
+147
View File
@@ -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}";
}
}
}
+41
View File
@@ -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<RhmMapDto>(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);
}
}
}
@@ -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<RhythiaNote>(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<RhmNoteDto>(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,
};
}
}
}
+19
View File
@@ -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<string> 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<RhmNoteDto> Notes { get; set; } = [];
public string ImagePath { get; set; } = string.Empty;
public string AudioFileName { get; set; } = string.Empty;
}
}
+9
View File
@@ -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; }
}
}
+167
View File
@@ -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)
);
}
}
}
}
}
@@ -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) { }
}
}
+48
View File
@@ -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<byte> data, RhmReadOptions? options = null)
{
byte[] buffer = data.ToArray();
using var stream = new MemoryStream(buffer, writable: false);
return Read(stream, options);
}
}
}
+10
View File
@@ -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;
}
}
+59
View File
@@ -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);
```