-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmidi2nbs.py
277 lines (254 loc) · 12.2 KB
/
midi2nbs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# This file is a part of:
# ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
# ███▄▄▄▄ ▀█████████▄ ▄████████ ███ ▄██████▄ ▄██████▄ ▄█
# ███▀▀▀██▄ ███ ███ ███ ███ ▀█████████▄ ███ ███ ███ ███ ███
# ███ ███ ███ ███ ███ █▀ ▀███▀▀██ ███ ███ ███ ███ ███
# ███ ███ ▄███▄▄▄██▀ ███ ███ ▀ ███ ███ ███ ███ ███
# ███ ███ ▀▀███▀▀▀██▄ ▀███████████ ███ ███ ███ ███ ███ ███
# ███ ███ ███ ██▄ ███ ███ ███ ███ ███ ███ ███
# ███ ███ ███ ███ ▄█ ███ ███ ███ ███ ███ ███ ███▌ ▄
# ▀█ █▀ ▄█████████▀ ▄████████▀ ▄████▀ ▀██████▀ ▀██████▀ █████▄▄██
# __________________________________________________________________________________
# NBSTool is a tool to work with .nbs (Note Block Studio) files.
# Author: IoeCmcomc (https://github.com/IoeCmcomc)
# Programming language: Python
# License: MIT license
# Source codes are hosted on: GitHub (https://github.com/IoeCmcomc/NBSTool)
# ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
from asyncio import sleep
from collections import namedtuple
from dataclasses import dataclass
from math import gcd
from os.path import basename
from traceback import print_exc
from typing import Optional, Tuple
from mido import MidiFile, merge_tracks, tempo2bpm
from numpy import interp
from common import (MIDI_DRUMS, MIDI_INSTRUMENTS, NBS_PITCH_IN_MIDI_PITCHBEND,
MidiInstrument)
from nbsio import PERC_INSTS, Layer, NbsSong, Note
MIDI_DRUMS_BY_MIDI_PITCH = {obj.pitch: obj for obj in MIDI_DRUMS}
NOTE_POS_MULTIPLIER = 18
"""The value must be divisible by 2, 3 to handle triplets.
It also limits the maximum expand multiplier."""
MidiNoteMsgKey = namedtuple("MidiNoteMsgKey", ("note", "channel"))
@dataclass
class MidiNoteMsgValue:
note: Note
duration: int = 1
def extractKeyAndInst(
msg, trackInst: int, keyShift: int
) -> Optional[Tuple[int, int]]:
if msg.channel == 9:
midiDrum = MIDI_DRUMS_BY_MIDI_PITCH.get(
msg.note, MIDI_DRUMS_BY_MIDI_PITCH[27])
if midiDrum.nbs_instrument == -1:
return None
key = midiDrum.nbs_pitch + 36
inst = midiDrum.nbs_instrument
else:
key = max(0, (msg.note - 21) + keyShift)
inst = trackInst
return key, inst
async def midi2nbs(
filepath: str,
expandMultiplier=1,
importDurations=False,
durationSpacing=1,
importVelocities=True,
importPanning=True,
importPitches=True,
dialog=None,
) -> NbsSong:
autoExpand = expandMultiplier == 0
if autoExpand:
expandMultiplier = 1
mid = MidiFile(filepath)
tpb = mid.ticks_per_beat
# The time signature upper number in ONBS
# doesn't affect the overall tempo at all.
timeSign = 4
tempo = -1
nbs: NbsSong = NbsSong()
headers, notes, layers = nbs.header, nbs.notes, nbs.layers
headers.import_name = basename(filepath)
if dialog:
dialog.currentProgress.set(10)
await sleep(0.001)
absTime: int = 0
notePosGcd: int = -1
for msg in merge_tracks(mid.tracks):
absTime += msg.time
if msg.is_meta:
if msg.type == "time_signature":
headers.time_sign = msg.numerator
elif (msg.type == "set_tempo") and (tempo == -1):
tempo = tempo2bpm(msg.tempo)
headers.tempo = tempo * timeSign / 60
elif autoExpand:
# Perform automatic space expanding (if specified)
if msg.type == "note_on":
if msg.velocity > 0:
notePos = round(absTime * timeSign *
NOTE_POS_MULTIPLIER / tpb)
if notePos % 2 == 1:
notePos += 1 # Make all notePos even
# to reduce the expand multiplier
if notePosGcd != -1:
notePosGcd = gcd(notePosGcd, notePos)
else:
notePosGcd = notePos
if autoExpand:
expandMultiplier = NOTE_POS_MULTIPLIER / notePosGcd
headers.tempo *= expandMultiplier
headers.time_sign = int(headers.time_sign * expandMultiplier)
emptyTracks = [] # Tracks which don't have any 'note_on' message
percTracks = [] # Tracks containing only percussion messages
for i, track in enumerate(mid.tracks):
isEmpty = True
isPerc = True
for msg in track:
if msg.type == "note_on":
isEmpty = False
if msg.channel != 9:
isPerc = False
break
if isEmpty:
emptyTracks.append(i)
if isPerc:
percTracks.append(i)
if dialog:
dialog.currentProgress.set(40)
await sleep(0.001)
baseLayer = -1
totalTracks = len(mid.tracks)
ceilingLayer = baseLayer
for i, track in enumerate(mid.tracks):
if i in emptyTracks:
continue
absTime: int = 0
trackInst: int = 0
keyShift: int = 0
trackVel = 100
isPerc = i in percTracks
trackName = "Percussion" if isPerc else ""
if isPerc:
layers.append(Layer(trackName, False, trackVel))
pan = 0
pitch = 0
baseLayer = ceilingLayer + 1
layer = baseLayer
lastTick = -1
isNoteEnd = False
playingNotes: dict[MidiNoteMsgKey, MidiNoteMsgValue] = {} # Messages of playing notes
currentNotes: list[Note] = [] # Notes in the current tick
innerBaseLayer = baseLayer
for msg in track:
absTime += msg.time
if msg.is_meta:
if (msg.type == "track_name") and not trackName:
trackName = msg.name
layers.append(Layer(trackName, False, trackVel))
else:
tick = round(absTime * timeSign / tpb * expandMultiplier)
if msg.type == "note_on":
extracted = extractKeyAndInst(msg, trackInst, keyShift)
if not extracted:
continue
key, inst = extracted
velocity = (
int(msg.velocity * 100 / 127) if importVelocities else 100
)
if msg.velocity > 0 and velocity > 0:
if importDurations and (inst not in PERC_INSTS):
enoughSpace = not playingNotes
else:
enoughSpace = tick != lastTick
if not enoughSpace:
layer += 1
if layer >= len(layers):
layers.append(
Layer(
f"{trackName} ({layer-innerBaseLayer+1})",
False, trackVel,
)
)
else:
layer = innerBaseLayer
note = Note(tick, layer, inst, key,
velocity, pan, pitch)
notes.append(note)
currentNotes.append(note)
if importDurations:
playingNotes[MidiNoteMsgKey(msg.note, msg.channel)] = MidiNoteMsgValue(note)
ceilingLayer = max(ceilingLayer, layer)
lastTick = tick
elif importDurations and msg.velocity == 0:
try:
playingNote = playingNotes[MidiNoteMsgKey(
msg.note, msg.channel)]
playingNote.duration = tick - playingNote.note.tick
isNoteEnd = True
except KeyError:
pass
elif importDurations and (msg.type == "note_off"):
try:
playingNote = playingNotes[MidiNoteMsgKey(
msg.note, msg.channel)]
playingNote.duration = tick - playingNote.note.tick
isNoteEnd = True
except KeyError:
print_exc()
print(playingNotes)
elif (msg.type == "program_change") and not isPerc:
midiInst: MidiInstrument = MIDI_INSTRUMENTS[msg.program] # type: ignore
trackInst = midiInst.nbs_instrument
if trackInst == -1:
trackInst = 0
keyShift = midiInst.octave_shift * 12
if not trackName:
trackName = (
midiInst.short_name
if midiInst.short_name
else midiInst.name
)
layers.append(Layer(trackName, False, trackVel))
elif msg.type == "control_change":
if importPanning and (msg.control == 10): # Pan
pan = int(interp(msg.value, (0, 127), (-100, 100)))
elif importVelocities and (msg.control == 7): # Volume
trackVel = int(msg.value * 100 / 127)
elif importPitches and (msg.type == "pitchwheel"):
pitch = int(msg.pitch / NBS_PITCH_IN_MIDI_PITCHBEND)
if isNoteEnd and currentNotes:
midiMsgKey = MidiNoteMsgKey(msg.note, msg.channel)
if midiMsgKey in playingNotes:
playingNote = playingNotes[midiMsgKey]
extracted = extractKeyAndInst(msg, trackInst, keyShift)
duration = playingNote.duration
if extracted and duration > 1:
note = playingNote.note
key, inst = extracted
if not note.isPerc:
for durationIndex, newTick in enumerate(
range(tick - duration, tick)
):
if durationIndex == 0:
continue
vel = int(
note.vel * (duration - durationIndex) / duration)
if (vel > 1) and (durationIndex % durationSpacing == 0):
newNote = Note(newTick, note.layer,
note.inst, note.key, vel,
pan, pitch,
)
notes.append(newNote)
currentNotes.remove(note)
del playingNotes[midiMsgKey]
layer -= 1
isNoteEnd = False
if dialog:
dialog.currentProgress.set(40 + i * 40 / totalTracks)
await sleep(0.001)
nbs.correctData()
return nbs