This commit is contained in:
2026-07-23 08:59:10 -04:00
commit fc970fa3d8
30 changed files with 1376 additions and 0 deletions
+79
View File
@@ -0,0 +1,79 @@
namespace RhythiaLib.Rhr.Internal
{
internal static class RhrFrameCodec
{
public const int WireSize = 17; // total size of frame in bytes
public static RhrReplayFrame Read(BinaryReader reader, int version)
{
ArgumentNullException.ThrowIfNull(reader);
bool usesInt32Time = version >= RhrVersions.Int32Time;
float? legacyWireTime = usesInt32Time ? null : reader.ReadSingle();
int time = usesInt32Time
? reader.ReadInt32()
: ConvertLegacyTime(legacyWireTime!.Value);
float positionX = reader.ReadSingle();
float positionY = reader.ReadSingle();
float health = reader.ReadSingle();
byte isImportantFrame = reader.ReadByte();
if (version < RhrVersions.NegateY)
positionY = -positionY;
return new RhrReplayFrame
{
Time = time,
PositionX = positionX,
PositionY = positionY,
Health = health,
IsImportantFrame = isImportantFrame,
LegacyWireTime = legacyWireTime,
DecodedLegacyTime = legacyWireTime.HasValue ? time : null,
};
}
public static void Write(BinaryWriter writer, RhrReplayFrame frame, int version)
{
ArgumentNullException.ThrowIfNull(writer);
ArgumentNullException.ThrowIfNull(frame);
bool usesInt32Time = version >= RhrVersions.Int32Time;
bool negateY = version < RhrVersions.NegateY;
if (usesInt32Time)
writer.Write(frame.Time);
else
writer.Write(
frame.LegacyWireTime.HasValue && frame.DecodedLegacyTime == frame.Time
? frame.LegacyWireTime.Value
: (float)frame.Time
);
writer.Write(frame.PositionX);
writer.Write(negateY ? -frame.PositionY : frame.PositionY);
writer.Write(frame.Health);
writer.Write(frame.IsImportantFrame);
}
private static int ConvertLegacyTime(float value)
{
if (!float.IsFinite(value))
{
throw new InvalidRhrFormatException(
"A legacy replay frame contains a non finite time."
);
}
if (value > int.MaxValue || value < int.MinValue)
{
throw new InvalidRhrFormatException(
$"Legacy frame time {value} is outside the Int32 range."
);
}
return (int)value;
}
}
}
+54
View File
@@ -0,0 +1,54 @@
using System.Text;
namespace RhythiaLib.Rhr.Internal
{
internal static class RhrReader
{
public static RhrReplay Read(Stream stream, RhrReadOptions options)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentNullException.ThrowIfNull(options);
if (!stream.CanRead)
throw new ArgumentException("The stream must be readable.", nameof(stream));
using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true);
try
{
int version = reader.ReadInt32();
RhrScoreData scoreData = RhrScoreDataCodec.Read(reader, version);
int frameCount = reader.ReadInt32();
RhrValidation.ValidateFrameCount(stream, frameCount, options);
var frames = new List<RhrReplayFrame>(frameCount);
for (int index = 0; index < frameCount; index++)
{
RhrReplayFrame frame = RhrFrameCodec.Read(reader, version);
frames.Add(frame);
}
RhrValidation.ValidateEndOfStream(stream);
return new RhrReplay
{
Version = version,
ScoreData = scoreData,
Frames = frames,
};
}
catch (EndOfStreamException exception)
{
throw new InvalidRhrFormatException("The replay is truncated.", exception);
}
catch (IOException exception)
{
throw new InvalidRhrFormatException("The replay could not be read.", exception);
}
}
}
}
@@ -0,0 +1,95 @@
namespace RhythiaLib.Rhr.Internal
{
internal static class RhrScoreDataCodec
{
public static RhrScoreData Read(BinaryReader reader, int version)
{
ArgumentNullException.ThrowIfNull(reader);
var scoreData = new RhrScoreData
{
TimestampTicks = reader.ReadInt64(),
PlayerName = reader.ReadString(),
LegacyMapId = reader.ReadString(),
MapId = reader.ReadInt32(),
StartFrom = reader.ReadInt32(),
Mode = reader.ReadString(),
};
if (version >= RhrVersions.ExtendedFields)
{
scoreData.Passed = reader.ReadBoolean();
scoreData.ModsJson = reader.ReadString();
scoreData.Spin = reader.ReadBoolean();
scoreData.Speed = reader.ReadSingle();
scoreData.TotalScore = reader.ReadInt64();
}
else
{
scoreData.Passed = true;
scoreData.ModsJson = "[]";
scoreData.Spin = false;
scoreData.Speed = 0f;
scoreData.TotalScore = 0;
}
scoreData.Accuracy = reader.ReadSingle();
scoreData.Hits = reader.ReadInt32();
scoreData.Misses = reader.ReadInt32();
scoreData.Points = reader.ReadSingle();
if (version >= RhrVersions.FailTime)
{
scoreData.FailTime = reader.ReadInt32();
scoreData.Failed = scoreData.FailTime >= 0;
}
else
{
scoreData.FailTime = -1;
scoreData.Failed = false;
}
scoreData.BeatmapHash =
version >= RhrVersions.BeatmapHash ? reader.ReadString() : string.Empty;
return scoreData;
}
public static void Write(BinaryWriter writer, RhrScoreData scoreData, int version)
{
ArgumentNullException.ThrowIfNull(writer);
ArgumentNullException.ThrowIfNull(scoreData);
writer.Write(scoreData.TimestampTicks);
writer.Write(scoreData.PlayerName);
writer.Write(scoreData.LegacyMapId);
writer.Write(scoreData.MapId);
writer.Write(scoreData.StartFrom);
writer.Write(scoreData.Mode);
if (version >= RhrVersions.ExtendedFields)
{
writer.Write(scoreData.Passed);
writer.Write(scoreData.ModsJson);
writer.Write(scoreData.Spin);
writer.Write(scoreData.Speed);
writer.Write(scoreData.TotalScore);
}
writer.Write(scoreData.Accuracy);
writer.Write(scoreData.Hits);
writer.Write(scoreData.Misses);
writer.Write(scoreData.Points);
if (version >= RhrVersions.FailTime)
{
writer.Write(scoreData.Failed ? scoreData.FailTime : -1);
}
if (version >= RhrVersions.BeatmapHash)
{
writer.Write(scoreData.BeatmapHash);
}
}
}
}
+104
View File
@@ -0,0 +1,104 @@
namespace RhythiaLib.Rhr.Internal
{
internal static class RhrValidation
{
public static void ValidateFrameCount(
Stream streamm,
int frameCount,
RhrReadOptions options
)
{
ArgumentNullException.ThrowIfNull(streamm);
ArgumentNullException.ThrowIfNull(options);
if (frameCount < 0)
throw new InvalidRhrFormatException($"Negative frame count: {frameCount}.");
if (frameCount > options.MaximumFrameCount)
throw new InvalidRhrFormatException(
$"Frame count {frameCount} exceeded the configured maximum of {options.MaximumFrameCount}"
);
if (!streamm.CanSeek)
return;
long requiredBytes = checked((long)frameCount * RhrFrameCodec.WireSize);
long remainingBytes = streamm.Length - streamm.Position;
if (remainingBytes < requiredBytes)
{
throw new InvalidRhrFormatException(
$"The replay declares {frameCount} frames, "
+ $"requiring {requiredBytes} bytes, "
+ $"but only {remainingBytes} bytes remain"
);
}
}
public static void ValidateEndOfStream(Stream stream)
{
if (!stream.CanSeek)
return;
if (stream.Position != stream.Length)
{
long trailingByteCount = stream.Length - stream.Position;
throw new InvalidRhrFormatException(
$"The replay contains {trailingByteCount} unexpected trailing bytes."
);
}
}
public static void ValidateReplay(RhrReplay replay)
{
ArgumentNullException.ThrowIfNull(replay);
ArgumentNullException.ThrowIfNull(replay.ScoreData);
ArgumentNullException.ThrowIfNull(replay.Frames);
ValidateScoreData(replay.ScoreData);
for (int index = 0; index < replay.Frames.Count; index++)
{
RhrReplayFrame frame =
replay.Frames[index]
?? throw new ArgumentException($"Frame {index} is null", nameof(replay));
ValidateFrame(frame, index);
}
}
private static void ValidateScoreData(RhrScoreData scoreData)
{
ArgumentNullException.ThrowIfNull(scoreData.PlayerName);
ArgumentNullException.ThrowIfNull(scoreData.LegacyMapId);
ArgumentNullException.ThrowIfNull(scoreData.Mode);
ArgumentNullException.ThrowIfNull(scoreData.ModsJson);
ArgumentNullException.ThrowIfNull(scoreData.BeatmapHash);
if (!float.IsFinite(scoreData.Speed))
throw new ArgumentException("Replay speed must be finite.");
if (!float.IsFinite(scoreData.Accuracy))
throw new ArgumentException("Replay accuracy must be finite.");
if (!float.IsFinite(scoreData.Points))
throw new ArgumentException("Replay points must be finite.");
if (scoreData.Failed && scoreData.FailTime < 0)
throw new ArgumentException("A failed replay must have a non-negative fail time.");
}
private static void ValidateFrame(RhrReplayFrame frame, int index)
{
if (
!float.IsFinite(frame.PositionX)
|| !float.IsFinite(frame.PositionY)
|| !float.IsFinite(frame.Health)
)
{
throw new ArgumentException($"Frame {index} contains a non-finite value.");
}
}
}
}
+31
View File
@@ -0,0 +1,31 @@
using System.Text;
namespace RhythiaLib.Rhr.Internal
{
internal static class RhrWriter
{
public static void Write(Stream stream, RhrReplay replay)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentNullException.ThrowIfNull(replay);
if (!stream.CanWrite)
throw new ArgumentException("The stream must be writable.", nameof(stream));
RhrValidation.ValidateReplay(replay);
using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true);
writer.Write(replay.Version);
RhrScoreDataCodec.Write(writer, replay.ScoreData, replay.Version);
writer.Write(replay.Frames.Count);
foreach (RhrReplayFrame frame in replay.Frames)
{
RhrFrameCodec.Write(writer, frame, replay.Version);
}
}
}
}
@@ -0,0 +1,11 @@
namespace RhythiaLib.Rhr
{
public sealed class InvalidRhrFormatException : Exception
{
public InvalidRhrFormatException(string message)
: base(message) { }
public InvalidRhrFormatException(string message, Exception exception)
: base(message, exception) { }
}
}
+47
View File
@@ -0,0 +1,47 @@
using RhythiaLib.Rhr.Internal;
namespace RhythiaLib.Rhr
{
public static class RhrFile
{
public static RhrReplay Read(string path, RhrReadOptions? options = null)
{
ArgumentNullException.ThrowIfNullOrWhiteSpace(path);
using FileStream stream = File.OpenRead(path);
return Read(stream, options);
}
public static RhrReplay Read(Stream stream, RhrReadOptions? options = null)
{
return RhrReader.Read(stream, options ?? new RhrReadOptions());
}
public static void Write(string path, RhrReplay replay)
{
ArgumentNullException.ThrowIfNullOrWhiteSpace(path);
using FileStream stream = File.OpenWrite(path);
Write(stream, replay);
}
public static void Write(Stream stream, RhrReplay replay)
{
RhrWriter.Write(stream, replay);
}
public static byte[] Encode(RhrReplay replay)
{
using var stream = new MemoryStream();
Write(stream, replay);
return stream.ToArray();
}
public static RhrReplay Decode(ReadOnlySpan<byte> data, RhrReadOptions? options = null)
{
byte[] buffer = data.ToArray();
using var stream = new MemoryStream(buffer, writable: false);
return Read(stream, options);
}
}
}
+7
View File
@@ -0,0 +1,7 @@
namespace RhythiaLib.Rhr
{
public sealed class RhrReadOptions
{
public int MaximumFrameCount { get; init; } = 10_000_000;
}
}
+9
View File
@@ -0,0 +1,9 @@
namespace RhythiaLib.Rhr
{
public sealed class RhrReplay
{
public int Version { get; set; }
public RhrScoreData ScoreData { get; set; } = new();
public List<RhrReplayFrame> Frames { get; set; } = [];
}
}
+14
View File
@@ -0,0 +1,14 @@
namespace RhythiaLib.Rhr
{
public sealed class RhrReplayFrame
{
public int Time { get; set; }
public float PositionX { get; set; }
public float PositionY { get; set; }
public float Health { get; set; }
public byte IsImportantFrame { get; set; } // im ngl, i have NO clue what this is/does
internal float? LegacyWireTime { get; set; }
internal int? DecodedLegacyTime { get; set; }
}
}
+42
View File
@@ -0,0 +1,42 @@
namespace RhythiaLib.Rhr
{
public sealed class RhrScoreData
{
public long TimestampTicks { get; set; }
public string PlayerName { get; set; } = string.Empty;
public string LegacyMapId { get; set; } = string.Empty;
public int MapId { get; set; }
public int StartFrom { get; set; }
public string Mode { get; set; } = string.Empty;
public bool Passed { get; set; } = true;
public string ModsJson { get; set; } = "[]";
public bool Spin { get; set; }
public float Speed { get; set; }
public long TotalScore { get; set; }
public float Accuracy { get; set; }
public int Hits { get; set; }
public int Misses { get; set; }
public float Points { get; set; }
public bool Failed { get; set; }
public int FailTime { get; set; } = -1;
public string BeatmapHash { get; set; } = string.Empty;
public DateTime DatePlayed
{
get
{
try
{
return new DateTime(TimestampTicks, DateTimeKind.Unspecified);
}
catch (ArgumentOutOfRangeException exception)
{
throw new InvalidRhrFormatException(
$"Invalid timestamp value: {TimestampTicks}.",
exception
);
}
}
}
}
}
+14
View File
@@ -0,0 +1,14 @@
// version dates & info from:
// https://github.com/yo-ru/rhrParse/blob/69642c3347724c73fc95df18474fe0cf1c1ddb76/include/rhrParse/rhrParse.h#L79-L100
namespace RhythiaLib.Rhr
{
public static class RhrVersions
{
public const int NegateY = 2026_01_18;
public const int ExtendedFields = 2026_01_25;
public const int FailTime = 2026_02_22;
public const int Int32Time = 2026_05_10;
public const int BeatmapHash = 2026_05_17;
}
}
+55
View File
@@ -0,0 +1,55 @@
## Basic usage
### Read an RHR file
```csharp
using RhythiaLib.Rhr;
RhrReplay replay = RhrFile.Read("replay.rhr");
Console.WriteLine($"Version: {replay.Version}");
Console.WriteLine($"Player: {replay.ScoreData.PlayerName}");
Console.WriteLine($"Map: {replay.ScoreData.LegacyMapId}");
Console.WriteLine($"Accuracy: {replay.ScoreData.Accuracy}%");
Console.WriteLine($"Score: {replay.ScoreData.TotalScore}");
Console.WriteLine($"Frames: {replay.Frames.Count}");
```
### Read from a stream
```csharp
using RhythiaLib.Rhr;
using var stream = File.OpenRead("replay.rhr");
RhrReplay replay = RhrFile.Read(stream);
```
### Decode from bytes
```csharp
using RhythiaLib.Rhr;
byte[] data = File.ReadAllBytes("score-replay.rhr");
RhrReplay replay = RhrFile.Decode(data);
```
### Write an RHR file
```csharp
using RhythiaLib.Rhr;
RhrReplay replay = RhrFile.Read("replay.rhr");
replay.ScoreData.PlayerName = "NewPlayerName";
RhrFile.Write("new-replay.rhr", replay);
```
### Encode to bytes
```csharp
using RhythiaLib.Rhr;
RhrReplay replay = RhrFile.Read("replay.rhr");
byte[] data = RhrFile.Encode(replay);
File.WriteAllBytes("new-replay.rhr", data);
```
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>RhythiaLib</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Authors>$(AssemblyName)</Authors>
</PropertyGroup>
</Project>