Commit ·
554be89
1
Parent(s): 379cce1
PLUS: живая громкость из аудио вместо константы velocity=100
Browse files- plus/velocity.py +228 -0
plus/velocity.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Живая громкость вместо константы 100.
|
| 2 |
+
|
| 3 |
+
MuScriptor предсказывает только «нота началась», а velocity в MIDI пишет
|
| 4 |
+
одну и ту же — 100. Здесь громкость берётся из самой записи: для каждой ноты
|
| 5 |
+
меряется RMS и пик в окне 250 мс от атаки, раскладывается по перцентилям
|
| 6 |
+
и превращается в velocity 1..124.
|
| 7 |
+
|
| 8 |
+
Ключевое: файл не пересочиняется. Меняются ТОЛЬКО байты velocity у note_on,
|
| 9 |
+
поэтому каналы, программа, темп, метки и всё прочее остаётся как было.
|
| 10 |
+
|
| 11 |
+
Проверка: python plus/velocity.py audio.wav in.mid out.mid
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import math
|
| 15 |
+
import struct
|
| 16 |
+
import sys
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# ---------- разбор и правка SMF ----------
|
| 20 |
+
|
| 21 |
+
def _vlq(data, index):
|
| 22 |
+
value, shift = 0, 0
|
| 23 |
+
while True:
|
| 24 |
+
byte = data[index]
|
| 25 |
+
index += 1
|
| 26 |
+
value = (value << 7) | (byte & 0x7F)
|
| 27 |
+
if not byte & 0x80:
|
| 28 |
+
return value, index
|
| 29 |
+
shift += 7
|
| 30 |
+
if shift > 28:
|
| 31 |
+
raise ValueError("битый delta")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def scan_midi(data):
|
| 35 |
+
"""Вернуть ноты и места, где лежит их velocity."""
|
| 36 |
+
if data[:4] != b"MThd":
|
| 37 |
+
raise ValueError("это не MIDI")
|
| 38 |
+
header_len = struct.unpack(">I", data[4:8])[0]
|
| 39 |
+
division = struct.unpack(">H", data[8 + header_len - 2:8 + header_len])[0]
|
| 40 |
+
ticks_per_beat = division if division & 0x8000 == 0 else 480
|
| 41 |
+
|
| 42 |
+
notes = []
|
| 43 |
+
tempos = [(0, 500000)]
|
| 44 |
+
index = 8 + header_len
|
| 45 |
+
while index + 8 <= len(data):
|
| 46 |
+
chunk = data[index:index + 4]
|
| 47 |
+
length = struct.unpack(">I", data[index + 4:index + 8])[0]
|
| 48 |
+
body_start, body_end = index + 8, index + 8 + length
|
| 49 |
+
if chunk != b"MTrk":
|
| 50 |
+
index = body_end
|
| 51 |
+
continue
|
| 52 |
+
i, tick, running = body_start, 0, None
|
| 53 |
+
open_notes = {}
|
| 54 |
+
while i < body_end:
|
| 55 |
+
delta, i = _vlq(data, i)
|
| 56 |
+
tick += delta
|
| 57 |
+
status = data[i]
|
| 58 |
+
if status < 0x80:
|
| 59 |
+
if running is None:
|
| 60 |
+
raise ValueError("running status без статуса")
|
| 61 |
+
status = running
|
| 62 |
+
else:
|
| 63 |
+
i += 1
|
| 64 |
+
if status < 0xF0:
|
| 65 |
+
running = status
|
| 66 |
+
kind = status & 0xF0
|
| 67 |
+
if status == 0xFF:
|
| 68 |
+
meta_type = data[i]
|
| 69 |
+
meta_len, i = _vlq(data, i + 1)
|
| 70 |
+
if meta_type == 0x51 and meta_len >= 3:
|
| 71 |
+
tempos.append((tick, int.from_bytes(data[i:i + 3], "big")))
|
| 72 |
+
i += meta_len
|
| 73 |
+
elif status in (0xF0, 0xF7):
|
| 74 |
+
meta_len, i = _vlq(data, i)
|
| 75 |
+
i += meta_len
|
| 76 |
+
elif kind in (0x80, 0x90):
|
| 77 |
+
pitch, velocity = data[i], data[i + 1]
|
| 78 |
+
key = (status & 0x0F, pitch)
|
| 79 |
+
if kind == 0x90 and velocity > 0:
|
| 80 |
+
open_notes[key] = len(notes)
|
| 81 |
+
notes.append({"tick": tick, "pitch": pitch, "channel": status & 0x0F,
|
| 82 |
+
"velocity_at": i + 1, "velocity": velocity,
|
| 83 |
+
"track": body_start})
|
| 84 |
+
elif key in open_notes:
|
| 85 |
+
notes[open_notes.pop(key)]["end_tick"] = tick
|
| 86 |
+
i += 2
|
| 87 |
+
elif kind in (0xA0, 0xB0, 0xE0):
|
| 88 |
+
i += 2
|
| 89 |
+
elif kind in (0xC0, 0xD0):
|
| 90 |
+
i += 1
|
| 91 |
+
else:
|
| 92 |
+
raise ValueError("неизвестный статус 0x%02X" % status)
|
| 93 |
+
index = body_end
|
| 94 |
+
|
| 95 |
+
for note in notes:
|
| 96 |
+
note.setdefault("end_tick", note["tick"] + ticks_per_beat // 4)
|
| 97 |
+
|
| 98 |
+
tempos.sort()
|
| 99 |
+
notes.sort(key=lambda n: n["tick"])
|
| 100 |
+
for note in notes:
|
| 101 |
+
note["start"] = ticks_to_seconds(note["tick"], tempos, ticks_per_beat)
|
| 102 |
+
note["end"] = ticks_to_seconds(note["end_tick"], tempos, ticks_per_beat)
|
| 103 |
+
return notes
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def ticks_to_seconds(tick, tempos, ticks_per_beat):
|
| 107 |
+
seconds, previous_tick, micros = 0.0, 0, 500000
|
| 108 |
+
for tempo_tick, tempo_micros in tempos:
|
| 109 |
+
if tick <= tempo_tick:
|
| 110 |
+
break
|
| 111 |
+
seconds += (tempo_tick - previous_tick) / ticks_per_beat * micros / 1_000_000.0
|
| 112 |
+
previous_tick, micros = tempo_tick, tempo_micros
|
| 113 |
+
seconds += (tick - previous_tick) / ticks_per_beat * micros / 1_000_000.0
|
| 114 |
+
return seconds
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# ---------- громкость из записи ----------
|
| 118 |
+
|
| 119 |
+
def decode_audio(path):
|
| 120 |
+
import numpy
|
| 121 |
+
try:
|
| 122 |
+
import soundfile
|
| 123 |
+
samples, rate = soundfile.read(path, dtype="float32", always_2d=True)
|
| 124 |
+
return samples.mean(axis=1), rate
|
| 125 |
+
except Exception:
|
| 126 |
+
pass
|
| 127 |
+
try:
|
| 128 |
+
import librosa
|
| 129 |
+
samples, rate = librosa.load(path, sr=None, mono=True)
|
| 130 |
+
return numpy.asarray(samples, dtype="float32"), rate
|
| 131 |
+
except Exception as problem:
|
| 132 |
+
raise RuntimeError("не читается аудио: %s" % problem)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def measure(notes, samples, rate, window=0.25):
|
| 136 |
+
import numpy
|
| 137 |
+
window_n = max(16, int(window * rate))
|
| 138 |
+
levels, attacks = [], []
|
| 139 |
+
for note in notes:
|
| 140 |
+
start = int(note["start"] * rate)
|
| 141 |
+
if start >= len(samples):
|
| 142 |
+
continue
|
| 143 |
+
chunk = samples[start:start + window_n]
|
| 144 |
+
if len(chunk) < 16:
|
| 145 |
+
continue
|
| 146 |
+
rms = float(numpy.sqrt(numpy.mean(chunk.astype("float64") ** 2)))
|
| 147 |
+
peak = float(numpy.max(numpy.abs(chunk)))
|
| 148 |
+
if rms <= 1e-7:
|
| 149 |
+
continue
|
| 150 |
+
levels.append(20.0 * math.log10(rms))
|
| 151 |
+
attacks.append(max(1e-6, peak / rms))
|
| 152 |
+
note["_level"] = levels[-1]
|
| 153 |
+
note["_attack"] = attacks[-1]
|
| 154 |
+
return levels, attacks
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def to_velocity(notes):
|
| 158 |
+
import numpy
|
| 159 |
+
levels = numpy.array([n["_level"] for n in notes])
|
| 160 |
+
attacks = numpy.array([n["_attack"] for n in notes])
|
| 161 |
+
quiet = numpy.percentile(levels, 4)
|
| 162 |
+
loud = numpy.percentile(levels, 99.7)
|
| 163 |
+
span = max(0.5, loud - quiet)
|
| 164 |
+
low_attack = numpy.percentile(attacks, 10)
|
| 165 |
+
high_attack = numpy.percentile(attacks, 90)
|
| 166 |
+
attack_span = max(0.05, high_attack - low_attack)
|
| 167 |
+
for note in notes:
|
| 168 |
+
share = min(1.0, max(0.0, (note["_level"] - quiet) / span))
|
| 169 |
+
accent = min(1.0, max(0.0, (note["_attack"] - low_attack) / attack_span))
|
| 170 |
+
shaped = (share ** 0.65) * (1.0 + 0.18 * accent)
|
| 171 |
+
note["_new"] = int(round(1 + min(1.0, shaped) * 123))
|
| 172 |
+
return [n["_new"] for n in notes]
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# ---------- главное ----------
|
| 176 |
+
|
| 177 |
+
def apply(audio_path, midi_bytes):
|
| 178 |
+
"""Вернуть MIDI с измеренной громкостью и краткую статистику."""
|
| 179 |
+
notes = scan_midi(midi_bytes)
|
| 180 |
+
if not notes:
|
| 181 |
+
return midi_bytes, {"notes": 0}
|
| 182 |
+
samples, rate = decode_audio(audio_path)
|
| 183 |
+
measured = [n for n in notes if n.get("_level") is not None] or notes
|
| 184 |
+
measure(notes, samples, rate)
|
| 185 |
+
measured = [n for n in notes if n.get("_level") is not None]
|
| 186 |
+
if not measured:
|
| 187 |
+
return midi_bytes, {"notes": len(notes), "measured": 0}
|
| 188 |
+
velocities = to_velocity(measured)
|
| 189 |
+
|
| 190 |
+
fallback = int(round(sum(velocities) / len(velocities)))
|
| 191 |
+
patched = bytearray(midi_bytes)
|
| 192 |
+
silent = 0
|
| 193 |
+
for note in notes:
|
| 194 |
+
if note.get("_new") is None:
|
| 195 |
+
note["_new"] = fallback # окно попало в тишину
|
| 196 |
+
silent += 1
|
| 197 |
+
patched[note["velocity_at"]] = note["_new"]
|
| 198 |
+
stats = {
|
| 199 |
+
"notes": len(notes),
|
| 200 |
+
"measured": len(measured),
|
| 201 |
+
"velocity_min": min(velocities),
|
| 202 |
+
"velocity_max": max(velocities),
|
| 203 |
+
"velocity_mean": round(sum(velocities) / len(velocities), 1),
|
| 204 |
+
"distinct": len({n["_new"] for n in notes}),
|
| 205 |
+
"silent": silent,
|
| 206 |
+
"duration_s": round(notes[-1]["end"], 2),
|
| 207 |
+
}
|
| 208 |
+
return bytes(patched), stats
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def main(argv=None):
|
| 212 |
+
argv = argv or sys.argv[1:]
|
| 213 |
+
if len(argv) < 3:
|
| 214 |
+
print(__doc__)
|
| 215 |
+
return 2
|
| 216 |
+
audio_path, midi_path, out_path = argv[:3]
|
| 217 |
+
with open(midi_path, "rb") as handle:
|
| 218 |
+
original = handle.read()
|
| 219 |
+
patched, stats = apply(audio_path, original)
|
| 220 |
+
with open(out_path, "wb") as handle:
|
| 221 |
+
handle.write(patched)
|
| 222 |
+
print("нот: %(notes)d, измерено: %(measured)d | velocity %(velocity_min)d..%(velocity_max)d"
|
| 223 |
+
" (среднее %(velocity_mean).1f, разных значений %(distinct)d)" % stats)
|
| 224 |
+
return 0
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if __name__ == "__main__":
|
| 228 |
+
sys.exit(main())
|