-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmidi_utils.py
More file actions
804 lines (639 loc) · 28 KB
/
midi_utils.py
File metadata and controls
804 lines (639 loc) · 28 KB
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple
# ---- MIDI Meta types (official common set) ----
META_SEQUENCE_NUMBER = 0x00
META_TEXT = 0x01
META_COPYRIGHT = 0x02
META_TRACK_NAME = 0x03
META_INSTRUMENT_NAME = 0x04
META_LYRICS = 0x05
META_MARKER = 0x06
META_CUE_POINT = 0x07
META_CHANNEL_PREFIX = 0x20
META_END_OF_TRACK = 0x2F
META_SET_TEMPO = 0x51
META_SMPTE_OFFSET = 0x54
META_TIME_SIGNATURE = 0x58
META_KEY_SIGNATURE = 0x59
META_SEQUENCER_SPECIFIC= 0x7F
from midi_types import (
DkMidiEvent,
GuiNoteSegmentSeconds,
MidiEvent,
MidiFile,
MidiTrack,
NoteSegment,
NoteSegmentSeconds,
XpMidiEvent
)
# tempo_map entry: (tick, sec_at_tick, us_per_quarter)
TempoEntry = Tuple[int, float, int]
def build_tempo_map(midi: MidiFile) -> List[TempoEntry]:
"""
Build a tempo map from track 0.
Assumes event_type 'set_tempo' with data['microseconds_per_quarter_note'].
"""
division = midi.division
tempo_events: List[Tuple[int, int]] = [] # (tick, us_per_quarter)
for ev in midi.tracks[0].events:
if ev.event_type == "set_tempo":
usq = ev.data.get("microseconds_per_quarter_note", 500_000)
tempo_events.append((ev.absolute_time, usq))
if not tempo_events:
tempo_events = [(0, 500_000)] # default 120 bpm
# Build cumulative map: (tick, sec_from_start, us_per_quarter)
tempo_events.sort(key=lambda x: x[0])
tempo_map: List[TempoEntry] = []
last_tick = tempo_events[0][0]
last_sec = 0.0
last_usq = tempo_events[0][1]
tempo_map.append((last_tick, last_sec, last_usq))
for tick, usq in tempo_events[1:]:
dticks = tick - last_tick
sec_per_tick = (last_usq / 1_000_000.0) / division
last_sec += dticks * sec_per_tick
last_tick = tick
last_usq = usq
tempo_map.append((last_tick, last_sec, last_usq))
return tempo_map
def ticks_to_seconds(tick: int, tempo_map: List[TempoEntry], division: int) -> float:
# Find last tempo segment with tick_i <= tick
entry = tempo_map[0]
for e in tempo_map:
if e[0] <= tick:
entry = e
else:
break
tick_i, sec_i, us_q = entry
sec_per_tick = (us_q / 1_000_000.0) / division
return sec_i + (tick - tick_i) * sec_per_tick
def seconds_to_ticks(sec: float, tempo_map: List[TempoEntry], division: int) -> int:
# Find segment where sec falls
# First compute approximate sec ranges between tempo entries
for i in range(len(tempo_map) - 1):
tick_i, sec_i, us_q = tempo_map[i]
tick_j, sec_j, _ = tempo_map[i + 1]
if sec_i <= sec < sec_j:
sec_per_tick = (us_q / 1_000_000.0) / division
return int(round(tick_i + (sec - sec_i) / sec_per_tick))
# After last tempo entry
tick_last, sec_last, us_q_last = tempo_map[-1]
sec_per_tick = (us_q_last / 1_000_000.0) / division
return int(round(tick_last + (sec - sec_last) / sec_per_tick))
# better version for loading midifile into PianoRollGUI
def build_note_segments_from_midifile(midi: MidiFile) -> List[NoteSegmentSeconds]:
tempo_map = build_tempo_map(midi)
division = midi.division
segments: List[NoteSegmentSeconds] = []
for ti, track in enumerate(midi.tracks):
# active notes: (channel, pitch) -> start_tick
active: Dict[Tuple[int, int], int] = {}
for ev in track.events:
if ev.event_type not in ("note_on", "note_off"):
continue
ch = ev.channel if ev.channel is not None else 0
pitch = ev.data.get("key", 0)
vel = ev.data.get("velocity", 0)
key = (ch, pitch)
if ev.event_type == "note_on" and vel > 0:
# start note
active[key] = ev.absolute_time
else:
# note_off, or note_on with vel=0
start_tick = active.pop(key, None)
if start_tick is None:
continue
end_tick = ev.absolute_time
start_sec = ticks_to_seconds(start_tick, tempo_map, division)
end_sec = ticks_to_seconds(end_tick, tempo_map, division)
dur_sec = max(0.001, end_sec - start_sec)
segments.append(
NoteSegmentSeconds(
start_sec=start_sec,
duration_sec=dur_sec,
pitch=pitch,
channel=ch
)
)
segments.sort(key=lambda s: s.start_sec)
return segments
def _first_primary_midi_event(dkl: "DkMidiEvent") -> Optional["MidiEvent"]:
if not dkl.events:
return None
if not dkl.events[0].events:
return None
return dkl.events[0].events[0]
def extract_note_on_off_from_dkl(dkl: "DkMidiEvent") -> Tuple[Optional["MidiEvent"], Optional["MidiEvent"]]:
note_on = None
note_off = None
for xp in dkl.events:
if not xp.events:
continue
ev = xp.events[0] # primary
if ev.event_type == "note_on" and note_on is None:
note_on = ev
elif ev.event_type == "note_off" and note_off is None:
note_off = ev
return note_on, note_off
def build_note_segments_from_dkl_events(
dkl_events: List["DkMidiEvent"],
tempo_map,
division: int
) -> List["GuiNoteSegmentSeconds"]:
out: List[GuiNoteSegmentSeconds] = []
for dkl in dkl_events:
note_on, note_off = extract_note_on_off_from_dkl(dkl)
if note_on is None or note_off is None:
# policy: skip incomplete blocks in the piano roll
continue
key = int(note_on.data["key"])
ch = note_on.channel if note_on.channel is not None else 0
start_sec = ticks_to_seconds(note_on.absolute_time, tempo_map, division)
end_sec = ticks_to_seconds(note_off.absolute_time, tempo_map, division)
if end_sec <= start_sec:
continue
seg = GuiNoteSegmentSeconds(
start_sec=start_sec,
duration_sec=(end_sec - start_sec),
pitch=key,
channel=ch,
dkl_event=dkl
)
out.append(seg)
# sort like your previous notes list
out.sort(key=lambda s: (s.start_sec, s.pitch))
return out
from copy import deepcopy
def crop_track_events(
events: List[MidiEvent],
sel_start_tick: int,
sel_end_tick: int
) -> List[MidiEvent]:
"""Return new events cropped to [sel_start_tick, sel_end_tick).
Channel events are kept only if they fall inside the window.
Meta/sysex are kept regardless of window, but their time is re-based so that:
- events before the crop start are clamped to tick 0 (avoid negative ticks)
- events at/after crop start are shifted by -sel_start_tick
This guarantees non-negative, non-decreasing absolute_time and delta_time in
the exported/cropped MIDI, so re-loading starts at tick 0.
"""
kept: List[MidiEvent] = []
for ev in events:
is_meta_sysex = ev.event_type in ("meta", "sysex")
in_window = sel_start_tick <= ev.absolute_time < sel_end_tick
if not in_window and not is_meta_sysex:
continue
new_ev = deepcopy(ev)
if is_meta_sysex and ev.absolute_time < sel_start_tick:
# Keep pre-roll meta/sysex (tempo, track name, etc.) at time 0
new_ev.absolute_time = 0
elif is_meta_sysex and ev.absolute_time > sel_end_tick: # typically the end of track meta event
new_ev.absolute_time = sel_end_tick + 1
else:
new_ev.absolute_time = ev.absolute_time - sel_start_tick
kept.append(new_ev)
kept.sort(key=lambda e: e.absolute_time)
last_abs = 0
for ev in kept:
# Clamp to ensure we never emit negative delta times
ev.delta_time = max(0, ev.absolute_time - last_abs)
last_abs = ev.absolute_time
return kept
def crop_midifile(midi: MidiFile, sel_start_tick: int, sel_end_tick: int) -> MidiFile:
new_tracks: List[MidiTrack] = []
for track in midi.tracks:
new_events = crop_track_events(track.events, sel_start_tick, sel_end_tick)
xp_events = build_xp_events(new_events, strict=False)
dk_events = build_dkl_events(xp_events, strict=False)
dk_events = prune_dkl_malformed_note_events(dk_events)
new_tracks.append(MidiTrack(events=new_events, xp_events=xp_events, dk_events=dk_events))
return MidiFile(
format_type=midi.format_type,
num_tracks=len(new_tracks),
division=midi.division,
tracks=new_tracks,
)
def extract_track_name(midi: MidiFile, track_index: int = 0) -> str | None:
if track_index < 0 or track_index >= len(midi.tracks):
raise ValueError(f"Invalid track index {track_index}")
track = midi.tracks[track_index]
for ev in track.events:
if ev.event_type == "meta" and ev.data.get("meta_type") == META_TRACK_NAME:
raw = ev.data.get("raw_data", b"")
if isinstance(raw, (bytes, bytearray)):
return raw.decode("latin-1", errors="replace")
return str(raw)
return None
def set_track_name(midi: MidiFile, new_name: str, track_index: int = 0) -> None:
"""
Update Track 0 track name meta event in-place.
If no TRACKNAME meta exists, insert one near the start (after time 0 metas).
"""
if track_index < 0 or track_index >= len(midi.tracks):
raise ValueError(f"Invalid track index {track_index}")
new_bytes = new_name.encode("latin-1", errors="replace")
track = midi.tracks[track_index]
# 1) If exists, update it
for ev in track.events:
if ev.event_type == "meta" and ev.data.get("meta_type") == META_TRACK_NAME:
ev.data["raw_data"] = new_bytes
return
# 2) Else create it. Insert at absolute_time 0 after other abs=0 meta events.
insert_at = 0
while insert_at < len(track.events) and track.events[insert_at].absolute_time == 0:
# keep existing time-zero metas first (tempo, timesig, etc.)
insert_at += 1
trackname_ev = MidiEvent(
delta_time=0,
absolute_time=0,
event_type="meta",
channel=None,
status_byte=None,
data={
"meta_type": META_TRACK_NAME,
"raw_data": new_bytes,
# If your writer needs length/type fields, add them here accordingly.
},
)
track.events.insert(insert_at, trackname_ev)
# Recompute delta times for this track (since we inserted)
track.events.sort(key=lambda e: e.absolute_time)
last = 0
for ev in track.events:
ev.delta_time = ev.absolute_time - last
last = ev.absolute_time
def build_xp_events(midi_events: List["MidiEvent"], strict: bool = False) -> List["XpMidiEvent"]:
"""
Build XpMidiEvent list from flat MidiEvent list.
Correctly handles MANY events sharing the same (absolute_time, channel) by:
- grouping consecutive events with same tick+channel into a block
- parsing that block left-to-right, consuming CC81/CC16 suffixes
Patterns (within same tick+channel, suffixes must appear AFTER the primary event):
- note_on/note_off + CC16
- poly_aftertouch + CC81 + CC16
- CC64/66/67 + CC16
strict=False: if suffix missing/malformed, emit single XpMidiEvent([primary]) and continue
strict=True: raise ValueError on malformed XP sequences when it looks like a suffix is present but wrong
"""
out: List[XpMidiEvent] = []
i = 0
n = len(midi_events)
def ch(ev: "MidiEvent") -> int:
return ev.channel if ev.channel is not None else 0
def same_tick_chan(a: "MidiEvent", b: "MidiEvent") -> bool:
return a.absolute_time == b.absolute_time and ch(a) == ch(b)
def is_cc(ev: "MidiEvent", controller: Optional[int] = None) -> bool:
if ev.event_type != "control_change":
return False
if controller is None:
return True
return ev.data.get("controller") == controller
def is_pedal_primary(ev: "MidiEvent") -> bool:
return ev.event_type == "control_change" and ev.data.get("controller") in (64, 66, 67)
def fail(msg: str):
if strict:
raise ValueError(msg)
def parse_block(block: List["MidiEvent"], base_index: int):
"""
Parse a list of events that all share same (tick, channel), sequentially.
Emits XpMidiEvent(s) into out.
base_index is only for error messages.
"""
j = 0
m = len(block)
while j < m:
ev0 = block[j]
# ---- poly_aftertouch + CC81 + CC16 ----
if ev0.event_type == "poly_aftertouch":
if j + 2 < m:
ev1 = block[j + 1]
ev2 = block[j + 2]
if is_cc(ev1, 81) and is_cc(ev2, 16):
out.append(XpMidiEvent(events=[ev0, ev1, ev2]))
j += 3
continue
# If we see CCs right after but not matching pattern, that's suspicious
if is_cc(ev1) or is_cc(ev2):
fail(f"Malformed XP poly_aftertouch group at global index ~{base_index + j}")
out.append(XpMidiEvent(events=[ev0]))
j += 1
continue
# ---- note_on/note_off + CC16 ----
if ev0.event_type in ("note_on", "note_off"):
if j + 1 < m:
ev1 = block[j + 1]
if is_cc(ev1, 16):
out.append(XpMidiEvent(events=[ev0, ev1]))
j += 2
continue
if is_cc(ev1): # looks like a suffix but wrong controller
fail(f"Expected CC16 after {ev0.event_type} at global index ~{base_index + j}")
out.append(XpMidiEvent(events=[ev0]))
j += 1
continue
# ---- pedal CC64/66/67 + CC16 ----
if is_pedal_primary(ev0):
if j + 1 < m:
ev1 = block[j + 1]
if is_cc(ev1, 16):
out.append(XpMidiEvent(events=[ev0, ev1]))
j += 2
continue
if is_cc(ev1):
fail(f"Expected CC16 after pedal CC{ev0.data.get('controller')} at global index ~{base_index + j}")
out.append(XpMidiEvent(events=[ev0]))
j += 1
continue
# ---- default: single event ----
out.append(XpMidiEvent(events=[ev0]))
j += 1
while i < n:
ev0 = midi_events[i]
# Gather consecutive events with same tick+channel
block = [ev0]
j = i + 1
while j < n and same_tick_chan(ev0, midi_events[j]):
block.append(midi_events[j])
j += 1
# Parse that block safely (consuming suffixes)
parse_block(block, base_index=i)
# Advance to next block
i = j
return out
def build_dkl_events(xp_events: List["XpMidiEvent"], strict: bool = False) -> List[DkMidiEvent]:
"""
Group XpMidiEvent into DisklavierXpMidiNoteEvent blocks with the rule:
For each (channel,key), a block is:
poly_aftertouch + (optional) note_on + (optional) note_off
Additional logic:
- ALWAYS start a NEW block when encountering poly_aftertouch for (channel,key).
If there is an existing open block for that (channel,key), finalize it immediately.
- note_on / note_off attach only to the currently-open block for that (channel,key).
- meta/sysex/pedal(CC64/66/67) => standalone block (single XpMidiEvent)
- non-keyed non-barrier events => standalone block
strict=False:
- note_on/off with no open block => standalone
strict=True:
- note_on/off with no open block => ValueError
"""
def primary(xp: "XpMidiEvent") -> Optional["MidiEvent"]:
return xp.events[0] if xp.events else None
def ch(ev: "MidiEvent") -> int:
return ev.channel if ev.channel is not None else 0
def key_of(ev: "MidiEvent") -> Optional[int]:
if ev.event_type in ("note_on", "note_off", "poly_aftertouch"):
return ev.data.get("key")
return None
def is_pedal(ev: "MidiEvent") -> bool:
return ev.event_type == "control_change" and ev.data.get("controller") in (64, 66, 67)
def is_barrier(ev: "MidiEvent") -> bool:
return ev.event_type in ("meta", "sysex") or is_pedal(ev)
def fail(msg: str):
if strict:
raise ValueError(msg)
@dataclass
class _Session:
events: List["XpMidiEvent"] = field(default_factory=list)
seen_note_on: bool = False
seen_note_off: bool = False
# At most ONE open session per (channel,key)
open_session: Dict[Tuple[int, int], _Session] = {}
out: List[DkMidiEvent] = []
def finalize_session(ck: Tuple[int, int]):
s = open_session.pop(ck, None)
if s is not None and s.events:
out.append(DkMidiEvent(events=s.events))
for xp in xp_events:
ev0 = primary(xp)
if ev0 is None:
continue
# Barriers => standalone
if is_barrier(ev0):
out.append(DkMidiEvent(events=[xp]))
continue
k = key_of(ev0)
if k is None:
# Non-keyed events => standalone (safe default)
out.append(DkMidiEvent(events=[xp]))
continue
ck = (ch(ev0), int(k))
if ev0.event_type == "poly_aftertouch":
# NEW RULE: always start a new sequence on poly_aftertouch
# finalize any existing open one first
finalize_session(ck)
s = _Session()
s.events.append(xp)
open_session[ck] = s
continue
# note_on/off: attach to current open session, if any
s = open_session.get(ck)
if ev0.event_type == "note_on":
if s is None:
fail(f"note_on with no open poly_aftertouch session for ch={ck[0]} key={ck[1]} tick={ev0.absolute_time}")
finalize_session(ck)
s = _Session()
s.events.append(xp)
open_session[ck] = s
continue
s.events.append(xp)
s.seen_note_on = True
continue
if ev0.event_type == "note_off":
if s is None:
fail(f"note_off with no open poly_aftertouch session for ch={ck[0]} key={ck[1]} tick={ev0.absolute_time}")
out.append(DkMidiEvent(events=[xp]))
continue
s.events.append(xp)
s.seen_note_off = True
# We do NOT necessarily finalize here, because your rule says note_off is optional.
# But typically a note sequence should end when note_off happens:
finalize_session(ck)
continue
# fallback (shouldn't happen)
out.append(DkMidiEvent(events=[xp]))
# flush any remaining open sessions at end
for ck in list(open_session.keys()):
finalize_session(ck)
return sorted(out)
def prune_dkl_malformed_note_events(dk_events: List["DkMidiEvent"]) -> List[DkMidiEvent]:
def dk_event_valid(ev: DkMidiEvent):
has_note_on = False
has_note_off = False
for e in ev.events:
if e.events[0].event_type == 'note_on':
has_note_on = True
if e.events[0].event_type == 'note_off':
has_note_off = True
return ((has_note_on and has_note_off) or ((not has_note_on) and (not has_note_off)))
return [ e for e in dk_events if dk_event_valid(e )]
def get_midi_events_for_dkevent(dk_ev: DkMidiEvent) -> List[MidiEvent]:
evs = []
for xp_ev in dk_ev.events:
evs = evs + xp_ev.events
return evs
def delete_dkl_event_from_track(midi: MidiFile, dkl: "DkMidiEvent", track_index: int = 0) -> None:
track = midi.tracks[track_index]
# collect MidiEvent objects to remove (identity-based)
to_remove_ids = set()
for xp in dkl.events:
for ev in xp.events:
to_remove_ids.add(id(ev))
# filter track.events in place (preserve order)
track.events = [ev for ev in track.events if id(ev) not in to_remove_ids]
# we count on rebuild_scene in PianoRollGUI to recreate the XP and DK events lists
def midi_key_to_note_name(key: int, prefer_flats: bool = False) -> str:
if not (0 <= key <= 127):
raise ValueError(f"MIDI key out of range: {key}")
sharp = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
flat = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"]
names = flat if prefer_flats else sharp
name = names[key % 12]
octave = (key // 12) - 1
return f"{name}{octave}"
def dk_note_description(dk: DkMidiEvent, tempo_map: List[TempoEntry], division: int) -> str:
if not dk.events:
return ""
# Expecting a Note DK event type
poly_ev = None
note_on = None
note_off = None
for xp in dk.events:
poly_ev = xp if xp.events[0].event_type == 'poly_aftertouch' else poly_ev
note_on = xp if xp.events[0].event_type == 'note_on' else note_on
note_off = xp if xp.events[0].event_type == 'note_off' else note_off
if poly_ev is not None and note_on is not None and note_off is not None:
channel = note_on.events[0].channel
piano_key = note_on.events[0].data['key']
piano_note = midi_key_to_note_name(piano_key, prefer_flats=False)
tick_note_on = note_on.events[0].absolute_time
tick_note_off = note_off.events[0].absolute_time
tick_poly = poly_ev.events[0].absolute_time
note_on_velocity = ((note_on.events[0].data['velocity'] & 0x7F) << 3) + ((note_on.events[1].data['value'] & 0x70) >> 4)
note_off_velocity = ((note_off.events[0].data['velocity'] & 0x7F) << 3) + ((note_off.events[1].data['value'] & 0x70) >> 4)
key_sensor_velocity = (((poly_ev.events[1].data['value'] & 0x7F) << 3) + ((poly_ev.events[2].data['value'] & 0x70) >> 4)) if len(poly_ev.events)==3 else -1
key_sensor_time = ticks_to_seconds(tick_poly, tempo_map, division)
start_time = ticks_to_seconds(tick_note_on, tempo_map, division)
end_time = ticks_to_seconds(tick_note_off, tempo_map, division)
duration = end_time - start_time
key_sensor_delta_ms = (key_sensor_time - start_time)*1000 # expected (almost) always negative : poly_aftertouch event comes before note_on
return f"Tick = {tick_note_on} | Channel = {channel} | Note = {piano_note} ({piano_key}) | StartTime(s) = {start_time:.3f} | Duration(s) = {duration:.3f} | Key-Sensor Delta(ms) = {key_sensor_delta_ms:.3f} | Key-Sensor = {key_sensor_velocity:4} | Note On Velocity = {note_on_velocity} | Note Off Velocity = {note_off_velocity}"
return ""
def raw_bytes(ev) -> bytes:
"""
Meta/Sysex payload bytes stored in ev.data['raw_data'].
Supports bytes/bytearray or list[int].
"""
b = ev.data.get("raw_data", b"")
if isinstance(b, (bytes, bytearray)):
return bytes(b)
if isinstance(b, list):
return bytes(int(x) & 0xFF for x in b)
return b"" # fallback
def hex_bytes(b: bytes, group: int = 1) -> str:
if not b:
return ""
if group <= 1:
return " ".join(f"{x:02X}" for x in b)
# group into chunks: e.g. group=4 -> "00 11 22 33 | 44 55 66 77"
parts = []
for i in range(0, len(b), group):
parts.append(" ".join(f"{x:02X}" for x in b[i:i+group]))
return " | ".join(parts)
def _decode_text(b: bytes) -> str:
if not b:
return ""
# Many MIDI text meta events are Latin-1 / ASCII-ish in practice
try:
return b.decode("utf-8")
except Exception:
return b.decode("latin-1", errors="replace")
def format_meta_event(ev) -> tuple[str, str]:
"""
Returns (meta_type_str, pretty_value_str) for a meta event.
Expects ev.data['meta_type'] and raw bytes in ev.data['raw_data'] (common in your code).
"""
meta_type = ev.data.get("meta_type", None)
b = raw_bytes(ev)
if meta_type is None:
return ("", f"raw={hex_bytes(b)}")
# Helpful label
meta_labels = {
META_SEQUENCE_NUMBER: "Sequence Number",
META_TEXT: "Text",
META_COPYRIGHT: "Copyright",
META_TRACK_NAME: "Track Name",
META_INSTRUMENT_NAME: "Instrument Name",
META_LYRICS: "Lyrics",
META_MARKER: "Marker",
META_CUE_POINT: "Cue Point",
META_CHANNEL_PREFIX: "Channel Prefix",
META_END_OF_TRACK: "End Of Track",
META_SET_TEMPO: "Set Tempo",
META_SMPTE_OFFSET: "SMPTE Offset",
META_TIME_SIGNATURE: "Time Signature",
META_KEY_SIGNATURE: "Key Signature",
META_SEQUENCER_SPECIFIC: "Sequencer Specific",
}
label = meta_labels.get(meta_type, f"Meta 0x{meta_type:02X}")
# Decode by type
if meta_type in (META_TEXT, META_COPYRIGHT, META_TRACK_NAME, META_INSTRUMENT_NAME,
META_LYRICS, META_MARKER, META_CUE_POINT):
txt = _decode_text(b)
return (f"0x{meta_type:02X} ({label})", txt)
if meta_type == META_SEQUENCE_NUMBER:
# 2 bytes big-endian
if len(b) >= 2:
num = (b[0] << 8) | b[1]
return (f"0x{meta_type:02X} ({label})", str(num))
return (f"0x{meta_type:02X} ({label})", f"raw={hex_bytes(b)}")
if meta_type == META_CHANNEL_PREFIX:
if len(b) >= 1:
return (f"0x{meta_type:02X} ({label})", f"channel={b[0]}")
return (f"0x{meta_type:02X} ({label})", f"raw={hex_bytes(b)}")
if meta_type == META_END_OF_TRACK:
return (f"0x{meta_type:02X} ({label})", "(end)")
if meta_type == META_SET_TEMPO:
# 3 bytes: microseconds per quarter note
if len(b) == 3:
us_per_qn = (b[0] << 16) | (b[1] << 8) | b[2]
bpm = 60_000_000 / us_per_qn if us_per_qn else 0.0
return (f"0x{meta_type:02X} ({label})", f"{bpm:.3f} BPM (us/qn={us_per_qn})")
return (f"0x{meta_type:02X} ({label})", f"raw={hex_bytes(b)}")
if meta_type == META_TIME_SIGNATURE:
# 4 bytes: nn dd cc bb
# denom = 2**dd
if len(b) >= 4:
nn = b[0]
dd = b[1]
denom = 2 ** dd
cc = b[2] # MIDI clocks per metronome click
bb = b[3] # 32nd notes per quarter note (usually 8)
return (f"0x{meta_type:02X} ({label})", f"{nn}/{denom} (clocks/click={cc}, 32nds/qn={bb})")
return (f"0x{meta_type:02X} ({label})", f"raw={hex_bytes(b)}")
if meta_type == META_KEY_SIGNATURE:
# 2 bytes: sf (signed), mi (0=major 1=minor)
if len(b) >= 2:
sf = int.from_bytes(bytes([b[0]]), byteorder="big", signed=True)
mi = b[1]
mode = "minor" if mi == 1 else "major"
return (f"0x{meta_type:02X} ({label})", f"sf={sf} ({mode})")
return (f"0x{meta_type:02X} ({label})", f"raw={hex_bytes(b)}")
if meta_type == META_SMPTE_OFFSET:
if len(b) >= 5:
hh, mm, ss, fr, ff = b[:5]
return (f"0x{meta_type:02X} ({label})", f"{hh:02}:{mm:02}:{ss:02} frame={fr} subframe={ff}")
return (f"0x{meta_type:02X} ({label})", f"raw={hex_bytes(b)}")
if meta_type == META_SEQUENCER_SPECIFIC:
# show hex
return (f"0x{meta_type:02X} ({label})", f"hex={hex_bytes(b)}")
# Unknown meta: show hex
return (f"0x{meta_type:02X} ({label})", f"hex={hex_bytes(b)}")
def format_sysex_event(ev) -> tuple[str, str]:
"""
Returns (string_repr, hex_repr) for a sysex event.
"""
b = raw_bytes(ev)
# string repr: try show printable chars but keep safe
s = _decode_text(b)
# usually sysex is binary; so also show length
return (f"len={len(b)} {s}", hex_bytes(b, group=4))