230 lines
8.1 KiB
C#
230 lines
8.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
|
|
namespace Code.Game.Minigames.MusicGame
|
|
{
|
|
public static class BitwigMidiUtility
|
|
{
|
|
private struct RawNote
|
|
{
|
|
public long tick;
|
|
public int noteNumber;
|
|
}
|
|
|
|
private struct TempoChange
|
|
{
|
|
public long tick;
|
|
public int microsecondsPerQuarterNote;
|
|
}
|
|
|
|
public static BeatNode[] ParseMidi(
|
|
byte[] midiBytes,
|
|
int sampleRate,
|
|
double fallbackBpm = 120.0,
|
|
int attackBaseNote = 60,
|
|
int defenseBaseNote = 72,
|
|
int maxLanes = 12)
|
|
{
|
|
if (midiBytes == null || midiBytes.Length < 14)
|
|
return Array.Empty<BeatNode>();
|
|
|
|
int offset = 0;
|
|
|
|
// Проверка заголовка "MThd" (0x4D546864)
|
|
if (ReadInt32BigEndian(midiBytes, ref offset) != 0x4D546864)
|
|
throw new ArgumentException("Некорректный заголовок MIDI-файла (ожидался MThd).");
|
|
|
|
int headerLength = ReadInt32BigEndian(midiBytes, ref offset);
|
|
int headerEnd = offset + headerLength;
|
|
|
|
ReadUInt16BigEndian(midiBytes, ref offset); // Формат MIDI (0 или 1)
|
|
int tracksCount = ReadUInt16BigEndian(midiBytes, ref offset);
|
|
int division = ReadUInt16BigEndian(midiBytes, ref offset);
|
|
|
|
if ((division & 0x8000) != 0)
|
|
throw new NotSupportedException(
|
|
"SMPTE таймкод не поддерживается, используйте стандартный PPQ в Bitwig.");
|
|
|
|
int ticksPerQuarterNote = division;
|
|
offset = headerEnd;
|
|
|
|
List<RawNote> rawNotes = new List<RawNote>(256);
|
|
List<TempoChange> tempoMap = new List<TempoChange>(8);
|
|
|
|
for (int t = 0; t < tracksCount && offset + 8 <= midiBytes.Length; t++)
|
|
{
|
|
int chunkId = ReadInt32BigEndian(midiBytes, ref offset);
|
|
int chunkLength = ReadInt32BigEndian(midiBytes, ref offset);
|
|
int trackEnd = offset + chunkLength;
|
|
|
|
// Пропускаем нестандартные чанки, если это не "MTrk" (0x4D54726B)
|
|
if (chunkId != 0x4D54726B)
|
|
{
|
|
offset = trackEnd;
|
|
continue;
|
|
}
|
|
|
|
long currentTick = 0;
|
|
byte runningStatus = 0;
|
|
|
|
while (offset < trackEnd)
|
|
{
|
|
currentTick += ReadVarLen(midiBytes, ref offset);
|
|
byte status = midiBytes[offset];
|
|
|
|
if (status < 0x80)
|
|
{
|
|
status = runningStatus;
|
|
}
|
|
else
|
|
{
|
|
offset++;
|
|
if (status < 0xF0)
|
|
runningStatus = status;
|
|
}
|
|
|
|
int messageType = status & 0xF0;
|
|
|
|
if (messageType == 0x90) // Note On
|
|
{
|
|
byte note = midiBytes[offset++];
|
|
byte velocity = midiBytes[offset++];
|
|
|
|
if (velocity > 0)
|
|
{
|
|
rawNotes.Add(new RawNote { tick = currentTick, noteNumber = note });
|
|
}
|
|
}
|
|
else if (messageType == 0x80 || messageType == 0xA0 || messageType == 0xB0 || messageType == 0xE0)
|
|
{
|
|
offset += 2;
|
|
}
|
|
else if (messageType == 0xC0 || messageType == 0xD0)
|
|
{
|
|
offset += 1;
|
|
}
|
|
else if (status == 0xFF) // Meta Event
|
|
{
|
|
byte metaType = midiBytes[offset++];
|
|
int metaLength = (int)ReadVarLen(midiBytes, ref offset);
|
|
|
|
// 0x51 = Set Tempo (3 байта: микросекунды на четвертную ноту)
|
|
if (metaType == 0x51 && metaLength == 3)
|
|
{
|
|
int mpqn = (midiBytes[offset] << 16) | (midiBytes[offset + 1] << 8) | midiBytes[offset + 2];
|
|
tempoMap.Add(new TempoChange { tick = currentTick, microsecondsPerQuarterNote = mpqn });
|
|
}
|
|
|
|
offset += metaLength;
|
|
}
|
|
else if (status == 0xF0 || status == 0xF7) // SysEx
|
|
{
|
|
int sysexLength = (int)ReadVarLen(midiBytes, ref offset);
|
|
offset += sysexLength;
|
|
}
|
|
}
|
|
|
|
offset = trackEnd;
|
|
}
|
|
|
|
tempoMap.Sort((a, b) => a.tick.CompareTo(b.tick));
|
|
int defaultMpqn = (int)Math.Round(60_000_000.0 / fallbackBpm);
|
|
|
|
List<BeatNode> beatNodes = new List<BeatNode>(rawNotes.Count);
|
|
|
|
for (int i = 0; i < rawNotes.Count; i++)
|
|
{
|
|
RawNote raw = rawNotes[i];
|
|
BeatType type;
|
|
int lane;
|
|
|
|
if (raw.noteNumber >= attackBaseNote && raw.noteNumber < attackBaseNote + maxLanes)
|
|
{
|
|
type = BeatType.Attack;
|
|
lane = raw.noteNumber - attackBaseNote;
|
|
}
|
|
else if (raw.noteNumber >= defenseBaseNote && raw.noteNumber < defenseBaseNote + maxLanes)
|
|
{
|
|
type = BeatType.Defense;
|
|
lane = raw.noteNumber - defenseBaseNote;
|
|
}
|
|
else
|
|
{
|
|
continue;
|
|
}
|
|
|
|
double timeSeconds = TicksToSeconds(raw.tick, ticksPerQuarterNote, tempoMap, defaultMpqn);
|
|
int sampleIndex = (int)Math.Round(timeSeconds * sampleRate);
|
|
|
|
beatNodes.Add(new BeatNode
|
|
{
|
|
sampleIndex = sampleIndex,
|
|
type = type,
|
|
laneIndex = lane
|
|
});
|
|
}
|
|
|
|
beatNodes.Sort((a, b) => a.sampleIndex.CompareTo(b.sampleIndex));
|
|
return beatNodes.ToArray();
|
|
}
|
|
|
|
private static double TicksToSeconds(long targetTick, int ticksPerQuarterNote, List<TempoChange> tempoMap,
|
|
int defaultMpqn)
|
|
{
|
|
double totalSeconds = 0.0;
|
|
long lastTick = 0;
|
|
int currentMpqn = defaultMpqn;
|
|
|
|
for (int i = 0; i < tempoMap.Count; i++)
|
|
{
|
|
TempoChange change = tempoMap[i];
|
|
if (change.tick >= targetTick)
|
|
break;
|
|
|
|
long deltaTicks = change.tick - lastTick;
|
|
if (deltaTicks > 0)
|
|
{
|
|
totalSeconds += (deltaTicks / (double)ticksPerQuarterNote) * (currentMpqn / 1_000_000.0);
|
|
lastTick = change.tick;
|
|
}
|
|
|
|
currentMpqn = change.microsecondsPerQuarterNote;
|
|
}
|
|
|
|
long remainingTicks = targetTick - lastTick;
|
|
if (remainingTicks > 0)
|
|
{
|
|
totalSeconds += (remainingTicks / (double)ticksPerQuarterNote) * (currentMpqn / 1_000_000.0);
|
|
}
|
|
|
|
return totalSeconds;
|
|
}
|
|
|
|
private static int ReadInt32BigEndian(byte[] data, ref int offset)
|
|
{
|
|
int value = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3];
|
|
offset += 4;
|
|
return value;
|
|
}
|
|
|
|
private static int ReadUInt16BigEndian(byte[] data, ref int offset)
|
|
{
|
|
int value = (data[offset] << 8) | data[offset + 1];
|
|
offset += 2;
|
|
return value;
|
|
}
|
|
|
|
private static long ReadVarLen(byte[] data, ref int offset)
|
|
{
|
|
long value = 0;
|
|
byte b;
|
|
do
|
|
{
|
|
b = data[offset++];
|
|
value = (value << 7) | (uint)(b & 0x7F);
|
|
} while ((b & 0x80) != 0);
|
|
|
|
return value;
|
|
}
|
|
}
|
|
} |