314 lines
10 KiB
Python
314 lines
10 KiB
Python
"""最小化的 MIDI 读写(不依赖 mido / pretty_midi)。
|
|
|
|
只实现本项目需要的部分:标准 MIDI 文件的头块、轨道块、变速(running status)、
|
|
note-on / note-off、以及 tempo / 轨道名元事件。够用来导入旋律 MIDI,
|
|
也能把内置曲库导出成 MIDI 便于外部核对。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import struct
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
|
|
from .melody import Melody
|
|
|
|
__all__ = ["MidiNote", "MidiTrack", "MidiFile", "read_midi", "write_midi", "melody_from_midi"]
|
|
|
|
_DEFAULT_TEMPO_US = 500_000 # 120 BPM
|
|
|
|
|
|
@dataclass
|
|
class MidiNote:
|
|
pitch: int
|
|
start: float # 秒
|
|
dur: float # 秒
|
|
velocity: int = 80
|
|
|
|
@property
|
|
def end(self) -> float:
|
|
return self.start + self.dur
|
|
|
|
|
|
@dataclass
|
|
class MidiTrack:
|
|
name: str = ""
|
|
program: int = 0
|
|
channel: int = 0
|
|
notes: list[MidiNote] = field(default_factory=list)
|
|
|
|
@property
|
|
def median_pitch(self) -> float:
|
|
return float(np.median([n.pitch for n in self.notes])) if self.notes else 0.0
|
|
|
|
@property
|
|
def polyphony(self) -> float:
|
|
"""同时发声音符的平均数量,1.0 表示严格单音。"""
|
|
if not self.notes:
|
|
return 0.0
|
|
events: list[tuple[float, int]] = []
|
|
for n in self.notes:
|
|
events.append((n.start, 1))
|
|
events.append((n.end, -1))
|
|
events.sort(key=lambda e: (e[0], e[1]))
|
|
active = 0
|
|
peak = 0
|
|
for _, delta in events:
|
|
active += delta
|
|
peak = max(peak, active)
|
|
return float(peak)
|
|
|
|
|
|
@dataclass
|
|
class MidiFile:
|
|
ppq: int
|
|
tracks: list[MidiTrack]
|
|
tempo_us: int = _DEFAULT_TEMPO_US
|
|
|
|
@property
|
|
def bpm(self) -> float:
|
|
return 60_000_000.0 / self.tempo_us
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# 解析
|
|
# --------------------------------------------------------------------------- #
|
|
def _read_varlen(data: bytes, pos: int) -> tuple[int, int]:
|
|
value = 0
|
|
while True:
|
|
if pos >= len(data):
|
|
raise ValueError("MIDI 数据在变长整数处意外结束")
|
|
byte = data[pos]
|
|
pos += 1
|
|
value = (value << 7) | (byte & 0x7F)
|
|
if not byte & 0x80:
|
|
return value, pos
|
|
|
|
|
|
def _parse_track(data: bytes, tempo_us: int, ppq: int) -> tuple[MidiTrack, int]:
|
|
"""解析一条轨道,同时返回该轨道中最后一次生效的 tempo。"""
|
|
track = MidiTrack()
|
|
pos = 0
|
|
tick = 0
|
|
status = 0
|
|
active: dict[tuple[int, int], MidiNote] = {}
|
|
sec_per_tick = tempo_us / 1_000_000.0 / ppq
|
|
|
|
while pos < len(data):
|
|
delta, pos = _read_varlen(data, pos)
|
|
tick += delta
|
|
if pos >= len(data):
|
|
break
|
|
byte = data[pos]
|
|
|
|
if byte & 0x80:
|
|
status = byte
|
|
pos += 1
|
|
# else: running status,沿用上一个 status
|
|
|
|
if status == 0xFF: # meta
|
|
if pos >= len(data):
|
|
break
|
|
meta_type = data[pos]
|
|
pos += 1
|
|
length, pos = _read_varlen(data, pos)
|
|
payload = data[pos : pos + length]
|
|
pos += length
|
|
if meta_type == 0x51 and length == 3:
|
|
tempo_us = int.from_bytes(payload, "big")
|
|
sec_per_tick = tempo_us / 1_000_000.0 / ppq
|
|
elif meta_type == 0x03:
|
|
track.name = payload.decode("utf-8", errors="replace").strip()
|
|
elif status in (0xF0, 0xF7): # sysex
|
|
length, pos = _read_varlen(data, pos)
|
|
pos += length
|
|
else:
|
|
kind = status & 0xF0
|
|
if kind in (0x80, 0x90, 0xA0, 0xB0, 0xE0):
|
|
if pos + 1 >= len(data):
|
|
break
|
|
d1, d2 = data[pos], data[pos + 1]
|
|
pos += 2
|
|
if kind == 0xC0:
|
|
pass
|
|
if kind == 0x90 and d2 > 0:
|
|
track.channel = status & 0x0F
|
|
active[(track.channel, d1)] = MidiNote(
|
|
pitch=d1, start=tick * sec_per_tick, dur=0.0, velocity=d2
|
|
)
|
|
elif kind == 0x80 or (kind == 0x90 and d2 == 0):
|
|
key = (status & 0x0F, d1)
|
|
note = active.pop(key, None)
|
|
if note is not None:
|
|
note.dur = max(tick * sec_per_tick - note.start, 1e-3)
|
|
track.notes.append(note)
|
|
elif kind in (0xC0, 0xD0):
|
|
if pos < len(data):
|
|
if kind == 0xC0:
|
|
track.program = data[pos]
|
|
pos += 1
|
|
|
|
# 未闭合的 note-on:以最后一拍收尾
|
|
for note in active.values():
|
|
note.dur = max(tick * sec_per_tick - note.start, 1e-3)
|
|
track.notes.append(note)
|
|
|
|
track.notes.sort(key=lambda n: (n.start, n.pitch))
|
|
return track, tempo_us
|
|
|
|
|
|
def read_midi(path: str | Path | bytes) -> MidiFile:
|
|
"""读取标准 MIDI 文件。"""
|
|
data = path if isinstance(path, bytes) else Path(path).read_bytes()
|
|
if data[:4] != b"MThd":
|
|
raise ValueError("不是合法的 MIDI 文件(缺少 MThd 头)")
|
|
header_len = struct.unpack(">I", data[4:8])[0]
|
|
fmt, n_tracks, division = struct.unpack(">HHH", data[8 : 8 + 6])
|
|
pos = 8 + header_len
|
|
|
|
if division & 0x8000:
|
|
raise ValueError("不支持 SMPTE 时间格式的 MIDI")
|
|
ppq = division
|
|
|
|
tracks: list[MidiTrack] = []
|
|
tempo_us = _DEFAULT_TEMPO_US
|
|
for _ in range(n_tracks):
|
|
if data[pos : pos + 4] != b"MTrk":
|
|
break
|
|
length = struct.unpack(">I", data[pos + 4 : pos + 8])[0]
|
|
chunk = data[pos + 8 : pos + 8 + length]
|
|
pos += 8 + length
|
|
track, tempo_us = _parse_track(chunk, tempo_us, ppq)
|
|
if track.notes:
|
|
tracks.append(track)
|
|
if not tracks:
|
|
raise ValueError("MIDI 文件中没有音符")
|
|
return MidiFile(ppq=ppq, tracks=tracks, tempo_us=tempo_us)
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# 旋律抽取
|
|
# --------------------------------------------------------------------------- #
|
|
def _monophonize(notes: list[MidiNote]) -> list[MidiNote]:
|
|
"""把可能复调的音符压成单音:重叠时保留较高音,并截断被覆盖的音。"""
|
|
ordered = sorted(notes, key=lambda n: (n.start, -n.pitch))
|
|
out: list[MidiNote] = []
|
|
for note in ordered:
|
|
if out and note.start < out[-1].end - 1e-6:
|
|
if note.pitch > out[-1].pitch:
|
|
out[-1].dur = max(1e-3, note.start - out[-1].start)
|
|
out.append(MidiNote(note.pitch, note.start, note.dur, note.velocity))
|
|
# 低音被覆盖则丢弃
|
|
else:
|
|
out.append(MidiNote(note.pitch, note.start, note.dur, note.velocity))
|
|
return [n for n in out if n.dur >= 0.03]
|
|
|
|
|
|
def pick_melody_track(midi: MidiFile) -> MidiTrack:
|
|
"""在复音/多轨 MIDI 中挑出最像主旋律的轨道。
|
|
|
|
评分偏好:单音(polyphony 低)、音符数适中、音高偏高的轨道。
|
|
"""
|
|
if len(midi.tracks) == 1:
|
|
return midi.tracks[0]
|
|
|
|
best, best_score = midi.tracks[0], float("-inf")
|
|
for track in midi.tracks:
|
|
n = len(track.notes)
|
|
if n < 4:
|
|
continue
|
|
poly = track.polyphony
|
|
score = (
|
|
np.log1p(n)
|
|
+ 0.02 * track.median_pitch
|
|
- 1.5 * max(0.0, poly - 1.0)
|
|
)
|
|
if score > best_score:
|
|
best, best_score = track, score
|
|
return best
|
|
|
|
|
|
def melody_from_midi(
|
|
midi: MidiFile, song_id: str = "", title: str = ""
|
|
) -> Melody:
|
|
"""从 MIDI 中抽取单声部旋律。"""
|
|
track = pick_melody_track(midi)
|
|
notes = _monophonize(track.notes)
|
|
if not notes:
|
|
return Melody.empty(song_id, title)
|
|
notes.sort(key=lambda n: n.start)
|
|
base = notes[0].start
|
|
mel = Melody(
|
|
np.array([n.pitch for n in notes], dtype=np.float64),
|
|
np.array([n.start - base for n in notes], dtype=np.float64),
|
|
np.array([n.dur for n in notes], dtype=np.float64),
|
|
song_id,
|
|
title,
|
|
{"midi_track": track.name, "bpm": round(midi.bpm, 2), "program": track.program},
|
|
)
|
|
return mel
|
|
|
|
|
|
def read_midi_melody(path: str | Path, song_id: str = "", title: str = "") -> Melody:
|
|
"""一步读取 MIDI 文件并抽取旋律。"""
|
|
return melody_from_midi(read_midi(path), song_id or Path(path).stem, title)
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# 写出
|
|
# --------------------------------------------------------------------------- #
|
|
def _write_varlen(value: int) -> bytes:
|
|
if value < 0:
|
|
raise ValueError("变长整数不能为负")
|
|
out = bytearray([value & 0x7F])
|
|
value >>= 7
|
|
while value:
|
|
out.append((value & 0x7F) | 0x80)
|
|
value >>= 7
|
|
out.reverse()
|
|
return bytes(out)
|
|
|
|
|
|
def write_midi(
|
|
path: str | Path,
|
|
mel: Melody,
|
|
*,
|
|
ppq: int = 480,
|
|
bpm: float = 100.0,
|
|
program: int = 0,
|
|
) -> None:
|
|
"""把旋律写成单轨 MIDI(用于外部核对/导出)。"""
|
|
tempo_us = int(round(60_000_000.0 / max(bpm, 1e-6)))
|
|
sec_per_tick = tempo_us / 1_000_000.0 / ppq
|
|
|
|
events: list[tuple[int, bytes]] = []
|
|
events.append((0, b"\xff\x51\x03" + tempo_us.to_bytes(3, "big")))
|
|
events.append((0, bytes([0xC0 | 0x0F, program & 0x7F])))
|
|
|
|
for pitch, onset, dur in zip(mel.midis, mel.starts, mel.durs):
|
|
start_tick = int(round(onset / sec_per_tick))
|
|
end_tick = max(start_tick + 1, int(round((onset + dur) / sec_per_tick)))
|
|
value = int(round(pitch))
|
|
value = max(0, min(127, value))
|
|
events.append((start_tick, bytes([0x90, value, 80])))
|
|
events.append((end_tick, bytes([0x80, value, 0])))
|
|
|
|
events.sort(key=lambda e: e[0])
|
|
|
|
body = bytearray()
|
|
last_tick = 0
|
|
for tick, payload in events:
|
|
body += _write_varlen(tick - last_tick)
|
|
body += payload
|
|
last_tick = tick
|
|
body += _write_varlen(0) + b"\xff\x2f\x00"
|
|
|
|
chunk = b"MTrk" + struct.pack(">I", len(body)) + bytes(body)
|
|
header = b"MThd" + struct.pack(">IHHH", 6, 0, 1, ppq)
|
|
|
|
path = Path(path)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_bytes(header + chunk)
|