Skip to content

Commit bb8ac3a

Browse files
committed
Make MIDI event serialization safer with int bound checks
1 parent adbb299 commit bb8ac3a

1 file changed

Lines changed: 15 additions & 9 deletions

File tree

mingus/midi/midi_track.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,9 @@ def play_Note(self, note):
7575
if self.change_instrument:
7676
self.set_instrument(channel, self.instrument)
7777
self.change_instrument = False
78+
79+
assert 0 <= velocity <= 0x7f
80+
7881
self.track_data += self.note_on(channel, int(note) + 12, velocity)
7982

8083
def play_NoteContainer(self, notecontainer):
@@ -175,15 +178,18 @@ def get_midi_data(self):
175178
return self.header() + self.track_data + self.end_of_track()
176179

177180
def midi_event(self, event_type, channel, param1, param2=None):
178-
"""Convert and return the paraters as a MIDI event in bytes."""
179-
assert event_type < 0x80 and event_type >= 0
180-
assert channel < 16 and channel >= 0
181-
tc = a2b_hex("%x%x" % (event_type, channel))
182-
if param2 is None:
183-
params = a2b_hex("%02x" % param1)
184-
else:
185-
params = a2b_hex("%02x%02x" % (param1, param2))
186-
return self.delta_time + tc + params
181+
"""Convert and return the parameters as a MIDI event in bytes."""
182+
assert 0 <= event_type < 16
183+
assert 0 <= channel < 16
184+
assert 0 <= param1 <= 0x7f
185+
assert param2 is None or 0 <= param2 <= 0x7f
186+
187+
status_byte = channel | (event_type << 4)
188+
params = [param1]
189+
if param2 is not None:
190+
params.append(param2)
191+
192+
return self.delta_time + bytes([status_byte] + params)
187193

188194
def note_off(self, channel, note, velocity):
189195
"""Return bytes for a 'note off' event."""

0 commit comments

Comments
 (0)