-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsequencer.py
More file actions
2628 lines (2311 loc) · 95.4 KB
/
Copy pathsequencer.py
File metadata and controls
2628 lines (2311 loc) · 95.4 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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
MIDI Chat Sequencer — drive Reason (or any DAW) via a conversational CLI.
Dependencies:
pip install mido python-rtmidi
Setup:
- macOS/Linux: virtual MIDI port is created automatically
- Windows: install loopMIDI first, create a port named "Chat Sequencer"
"""
import json
import logging
import re
import sys
import threading
import time
from collections import defaultdict
from dataclasses import dataclass, field
from pathlib import Path
import mido
logger = logging.getLogger(__name__)
def configure_logging(level: str = "INFO"):
"""Configure root logger. Call from entry points only (server, CLI, desktop)."""
logging.basicConfig(
level=getattr(logging, level.upper(), logging.INFO),
format="%(asctime)s %(name)s %(levelname)s %(message)s",
datefmt="%H:%M:%S",
)
# ─── Constants ────────────────────────────────────────────────────────────────
NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
DRUM_MAP = {
"kick": 36,
"snare": 38,
"clap": 39,
"hihat": 42,
"ohh": 46,
"tom1": 48,
"tom2": 45,
"tom3": 43,
"crash": 49,
"ride": 51,
"cowbell": 56,
"rimshot": 37,
}
_GM_DRUM_DEFAULTS = dict(DRUM_MAP) # immutable copy for drummap replacements
def remap_drum_notes(patterns: dict) -> None:
"""Remap notes in ch9 patterns where GM defaults differ from current DRUM_MAP."""
for pat in patterns.values():
if pat.channel != 9:
continue
for name, new_note in DRUM_MAP.items():
gm_note = _GM_DRUM_DEFAULTS.get(name)
if gm_note is not None and gm_note != new_note:
for step in list(pat.data.keys()):
pat.data[step] = [
(new_note, v, g) if n == gm_note else (n, v, g)
for n, v, g in pat.data[step]
]
OCTAVE_PRESETS = {
"element": 0, # MIDI 60 = C5 (Element, current default)
"yamaha": -1, # MIDI 60 = C4 (Yamaha, Roland, Logic)
"ableton": -2, # MIDI 60 = C3 (Ableton, Battery, FL Studio)
}
SCALE_INTERVALS = {
"major": [0, 2, 4, 5, 7, 9, 11],
"minor": [0, 2, 3, 5, 7, 8, 10],
"dorian": [0, 2, 3, 5, 7, 9, 10],
"mixolydian": [0, 2, 4, 5, 7, 9, 10],
"pentatonic": [0, 2, 4, 7, 9],
"blues": [0, 3, 5, 6, 7, 10],
"chromatic": list(range(12)),
}
CATEGORY_ORDER = [
"transport",
"patterns",
"editing",
"generators",
"cc automation",
"midi",
"other",
]
# ─── Helpers ──────────────────────────────────────────────────────────────────
_FLAT_TO_SHARP = {"Cb": "B", "Db": "C#", "Eb": "D#", "Fb": "E", "Gb": "F#", "Ab": "G#", "Bb": "A#"}
def note_name_to_midi(name: str, octave_offset: int = 0) -> int:
"""Convert e.g. 'C4', 'F#3', 'Bb5' to MIDI note number."""
name = name.strip()
# Normalize flats to sharps (Bb5 -> A#5, Eb3 -> D#3)
for flat, sharp in _FLAT_TO_SHARP.items():
if name.upper().startswith(flat.upper()):
name = sharp + name[2:]
break
match = re.match(r"^([A-G]#?)(-?\d+)$", name, re.IGNORECASE)
if not match:
raise ValueError(f"Invalid note name: {name}")
pitch, octave = match.group(1).upper(), int(match.group(2))
return NOTE_NAMES.index(pitch) + (octave - octave_offset) * 12
def midi_to_note_name(midi_num: int, octave_offset: int = 0) -> str:
octave = midi_num // 12 + octave_offset
return f"{NOTE_NAMES[midi_num % 12]}{octave}"
def parse_note_list(text: str, octave_offset: int = 0) -> list[int]:
"""Parse a space/comma separated list of note names or MIDI numbers."""
tokens = re.split(r"[\s,]+", text.strip())
notes = []
for t in tokens:
if not t:
continue
if t.isdigit():
notes.append(int(t))
elif t.lower() in DRUM_MAP:
notes.append(DRUM_MAP[t.lower()])
else:
notes.append(note_name_to_midi(t, octave_offset))
return notes
# ─── Pattern ──────────────────────────────────────────────────────────────────
class Pattern:
"""A pattern is a fixed-length step sequence on a single MIDI channel."""
def __init__(self, name: str, steps: int = 16, channel: int = 0):
self.name = name
self.steps = steps
self.channel = channel
# Each step: list of (note, velocity, gate_steps)
self.data: dict[int, list[tuple[int, int, int]]] = defaultdict(list)
self.muted = False
self.muted_notes: set[int] = set()
self.swing = 0 # 0-100, applies to whole pattern
self.swing_notes: dict[int, int] = {} # note -> swing%, overrides pattern swing
self.cc_auto: dict[int, dict[int, int]] = {} # {cc_number: {step: value}}
self.cc_interp: dict[int, str] = {} # {cc_number: "linear"|"step"|"exp"}
def set_step(self, step: int, note: int, velocity: int = 100, gate: int = 1):
step = step % self.steps
self.data[step].append((note, velocity, gate))
def clear_step(self, step: int):
step = step % self.steps
self.data[step] = []
def clear(self):
self.data.clear()
def to_dict(self) -> dict:
return {
"name": self.name,
"steps": self.steps,
"channel": self.channel,
"muted": self.muted,
"muted_notes": list(self.muted_notes),
"swing": self.swing,
"swing_notes": {str(k): v for k, v in self.swing_notes.items()},
"cc_auto": {
str(k): {str(s): v for s, v in kf.items()} for k, kf in self.cc_auto.items()
},
"cc_interp": {str(k): v for k, v in self.cc_interp.items()},
"data": {str(k): v for k, v in self.data.items()},
}
@classmethod
def from_dict(cls, d: dict) -> "Pattern":
pat = cls(d["name"], d["steps"], d["channel"])
pat.muted = d.get("muted", False)
pat.muted_notes = set(d.get("muted_notes", []))
pat.swing = d.get("swing", 0)
pat.swing_notes = {int(k): v for k, v in d.get("swing_notes", {}).items()}
pat.cc_auto = {
int(k): {int(s): v for s, v in kf.items()} for k, kf in d.get("cc_auto", {}).items()
}
pat.cc_interp = {int(k): v for k, v in d.get("cc_interp", {}).items()}
for step_str, notes in d["data"].items():
pat.data[int(step_str)] = [tuple(n) for n in notes]
return pat
def __repr__(self):
active = sorted(self.data.keys())
return f"Pattern('{self.name}', ch={self.channel}, steps={self.steps}, active={active})"
# ─── Sequencer Engine ─────────────────────────────────────────────────────────
class Sequencer:
def __init__(self, port_name: str = "Chat Sequencer"):
self.bpm = 120
self.steps_per_beat = 4 # 16th notes
self.playing = False
self.current_step = 0
self.patterns: dict[str, Pattern] = {}
settings = _load_settings()
self.octave_offset: int = settings.get("octave_offset", 0)
self.active_notes: list[tuple[int, int, float]] = [] # (note, channel, off_time)
# Open virtual MIDI port
try:
self.port = mido.open_output(port_name, virtual=True)
logger.info("Opened virtual MIDI port: %s", port_name)
print(f"✓ Virtual MIDI port '{port_name}' created.")
print(f" → In your Synth software : set MIDI input to '{port_name}'")
except Exception:
# Fallback: try to find an existing port (Windows with loopMIDI)
available = mido.get_output_names()
match = [p for p in available if port_name.lower() in p.lower()]
if match:
self.port = mido.open_output(match[0])
logger.info("Connected to existing MIDI port: %s", match[0])
print(f"✓ Connected to existing port '{match[0]}'")
else:
logger.error("Could not create virtual MIDI port. Available: %s", available)
print("✗ Could not create virtual port. Available ports:")
for p in available:
print(f" {p}")
print(" On Windows, install loopMIDI and create a port named 'Chat Sequencer'.")
sys.exit(1)
self._listeners: list = []
self._thread = None
self._stop_event = threading.Event()
def add_listener(self, callback):
self._listeners.append(callback)
def remove_listener(self, callback):
self._listeners.remove(callback)
def _notify(self, event: dict):
for cb in self._listeners:
cb(event)
@property
def step_duration(self) -> float:
return 60.0 / (self.bpm * self.steps_per_beat)
def _send(self, msg):
self.port.send(msg)
def _fire_notes(self, pat, step_notes, now, *, step=None, swing=0):
"""Send note_on for a pattern's step notes, skipping muted notes."""
fired = []
for note, vel, gate in step_notes:
if note in pat.muted_notes:
continue
msg = mido.Message("note_on", note=note, channel=pat.channel, velocity=vel)
self._send(msg)
off_time = now + self.step_duration * gate * 0.9
self.active_notes.append((note, pat.channel, off_time))
note_name = midi_to_note_name(note, self.octave_offset)
fired.append(
{
"note": note,
"name": note_name,
"vel": vel,
"gate": gate,
"ch": pat.channel,
"swing": swing,
}
)
if fired:
self._notify(
{
"type": "midi_out",
"pattern": pat.name,
"step": step if step is not None else -1,
"notes": fired,
}
)
def _interpolate_cc(
self, keyframes: dict[int, int], step: int, total_steps: int, mode: str
) -> int:
"""Interpolate CC value at a given step from keyframes with wrap-around."""
if not keyframes:
return 0
sorted_steps = sorted(keyframes.keys())
if len(sorted_steps) == 1:
return keyframes[sorted_steps[0]]
step = step % total_steps
# Exact keyframe hit
if step in keyframes:
return keyframes[step]
# Find surrounding keyframes (with wrap-around)
prev_s = next_s = None
for s in sorted_steps:
if s < step:
prev_s = s
elif s > step and next_s is None:
next_s = s
if prev_s is None:
prev_s = sorted_steps[-1] # wrap from end
if next_s is None:
next_s = sorted_steps[0] # wrap to start
prev_v = keyframes[prev_s]
next_v = keyframes[next_s]
# Calculate fractional position between keyframes
if prev_s < next_s:
span = next_s - prev_s
pos = step - prev_s
else:
# Wrapped around
span = (total_steps - prev_s) + next_s
pos = (step - prev_s) % total_steps
t = pos / span if span > 0 else 0.0
if mode == "step":
return prev_v
elif mode == "exp":
t = t * t # quadratic ease-in
# linear (or exp after t transformation)
return max(0, min(127, round(prev_v + (next_v - prev_v) * t)))
def _all_notes_off(self):
# Send note_off for every active note individually
for note, ch, _off_time in self.active_notes:
self._send(mido.Message("note_off", note=note, channel=ch, velocity=0))
# Then CC123 (all notes off) on all channels as a safety net
for ch in range(16):
self._send(mido.Message("control_change", channel=ch, control=123, value=0))
def _kill_thread(self):
"""Ensure the playback thread is fully stopped."""
self._stop_event.set()
if self._thread and self._thread.is_alive():
self._thread.join(timeout=2)
self._thread = None
def _run(self):
_debug = logger.isEnabledFor(logging.DEBUG)
while not self._stop_event.is_set():
try:
step_time = time.perf_counter()
now = step_time
if _debug:
logger.debug("step %d", self.current_step)
# Turn off expired notes
still_active = []
for note, ch, off_time in self.active_notes:
if now >= off_time:
self._send(mido.Message("note_off", note=note, channel=ch, velocity=0))
else:
still_active.append((note, ch, off_time))
self.active_notes = still_active
# Check again after note-off processing
if self._stop_event.is_set():
break
# Fire current step across all patterns
is_odd_step = self.current_step % 2 == 1
for pat in self.patterns.values():
if pat.muted:
continue
cur = self.current_step % pat.steps
# Send CC automation before notes
if pat.cc_auto:
cc_sent = []
for cc_num, keyframes in pat.cc_auto.items():
mode = pat.cc_interp.get(cc_num, "linear")
val = self._interpolate_cc(keyframes, cur, pat.steps, mode)
self._send(
mido.Message(
"control_change",
channel=pat.channel,
control=cc_num,
value=val,
)
)
cc_sent.append({"cc": cc_num, "value": val})
if cc_sent:
self._notify(
{
"type": "midi_out",
"pattern": pat.name,
"step": cur,
"notes": [],
"cc": cc_sent,
}
)
step_notes = pat.data.get(cur, [])
if not step_notes:
continue
if not is_odd_step:
self._fire_notes(pat, step_notes, now, step=cur)
else:
# Group notes by their swing amount
straight = []
by_swing: dict[int, list] = {}
for entry in step_notes:
note = entry[0]
sw = pat.swing_notes.get(note, pat.swing)
if sw == 0:
straight.append(entry)
else:
by_swing.setdefault(sw, []).append(entry)
if straight:
self._fire_notes(pat, straight, now, step=cur)
for sw_val, notes in by_swing.items():
delay = self.step_duration * (sw_val / 100) * 0.5
threading.Timer(
delay,
self._fire_notes,
args=(pat, notes, now + delay),
kwargs={"step": cur, "swing": sw_val},
).start()
self.current_step += 1
self._notify({"type": "playhead", "step": self.current_step - 1})
# Sleep until next step
elapsed = time.perf_counter() - step_time
sleep_time = self.step_duration - elapsed
if sleep_time > 0:
self._stop_event.wait(sleep_time)
except Exception:
logger.error("Exception in playback thread", exc_info=True)
break
def play(self) -> str | None:
if self.playing:
return None
logger.info("Starting playback at %s BPM", self.bpm)
self._kill_thread()
self.playing = True
self.current_step = 0
self._stop_event.clear()
self._thread = threading.Thread(target=self._run, daemon=True, name="sequencer-playback")
self._thread.start()
self._notify({"type": "transport", "playing": True, "bpm": self.bpm})
return f"▶ Playing at {self.bpm} BPM"
def stop(self) -> str | None:
if not self.playing:
return None
logger.info("Stopping playback")
self.playing = False
self._kill_thread()
self._all_notes_off()
self.active_notes.clear()
self._notify({"type": "transport", "playing": False, "bpm": self.bpm})
return "⏹ Stopped"
def close(self):
self.stop()
self.port.close()
logger.info("MIDI port closed")
def get_state(self) -> dict:
state = {
"type": "state",
"bpm": self.bpm,
"playing": self.playing,
"octave_offset": self.octave_offset,
"patterns": {name: pat.to_dict() for name, pat in self.patterns.items()},
"drum_map": {v: k for k, v in DRUM_MAP.items()},
}
return state
def describe(self) -> str:
"""Return a compact human-readable description of the full song state."""
lines = []
status = "playing" if self.playing else "stopped"
preset = next((k for k, v in OCTAVE_PRESETS.items() if v == self.octave_offset), "custom")
lines.append(f"BPM: {self.bpm} Status: {status} Octave: {preset}")
lines.append(f"Patterns: {len(self.patterns)}")
lines.append("")
if not self.patterns:
lines.append("(no patterns)")
return "\n".join(lines)
# Build reverse drum map for channel 9 labels
reverse_drums = {v: k for k, v in DRUM_MAP.items()}
for pat in self.patterns.values():
muted = " [MUTED]" if pat.muted else ""
swing_info = f" swing={pat.swing}%" if pat.swing else ""
lines.append(
f'Pattern "{pat.name}" (ch={pat.channel}, {pat.steps} steps{muted}{swing_info}):'
)
# Collect all notes used
all_notes: set[int] = set()
for step_notes in pat.data.values():
for n, _v, _g in step_notes:
all_notes.add(n)
if not all_notes:
lines.append(" (empty)")
else:
for note in sorted(all_notes):
# Label: drum name for ch9, note name otherwise
if pat.channel == 9 and note in reverse_drums:
label = f"{reverse_drums[note]}({note})"
else:
label = f"{midi_to_note_name(note, self.octave_offset)}({note})"
# Collect steps, velocities, gates for this note
hits = []
for step in sorted(pat.data.keys()):
for n, v, g in pat.data[step]:
if n == note:
hits.append((step, v, g))
steps = [h[0] for h in hits]
vels = {h[1] for h in hits}
gates = {h[2] for h in hits}
# Compact: show vel/gate only if non-default or mixed
suffix = ""
if len(vels) == 1:
v = next(iter(vels))
if v != 100:
suffix += f" v{v}"
else:
suffix += f" v[{','.join(str(v) for v in sorted(vels))}]"
if len(gates) == 1:
g = next(iter(gates))
if g != 1:
suffix += f" g{g}"
else:
suffix += f" g[{','.join(str(g) for g in sorted(gates))}]"
# Per-note swing
if note in pat.swing_notes:
suffix += f" sw{pat.swing_notes[note]}%"
# Muted note
if note in pat.muted_notes:
suffix += " [muted]"
lines.append(f" {label:>14s}: [{','.join(str(s) for s in steps)}]{suffix}")
# CC automation summary
if pat.cc_auto:
for cc_num in sorted(pat.cc_auto):
mode = pat.cc_interp.get(cc_num, "linear")
kf = pat.cc_auto[cc_num]
kf_str = " ".join(f"{s}:{v}" for s, v in sorted(kf.items()))
lines.append(f" CC{cc_num} ({mode}): {kf_str}")
lines.append("")
return "\n".join(lines)
def save(self, filepath: str):
data = {
"bpm": self.bpm,
"steps_per_beat": self.steps_per_beat,
"octave_offset": self.octave_offset,
"patterns": {name: pat.to_dict() for name, pat in self.patterns.items()},
"drum_map": dict(DRUM_MAP),
}
path = Path(filepath)
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w") as f:
json.dump(data, f, indent=2)
logger.info("Saved %d patterns to %s", len(self.patterns), path)
return str(path)
def load(self, filepath: str):
with open(filepath) as f:
data = json.load(f)
self.bpm = data["bpm"]
self.steps_per_beat = data.get("steps_per_beat", 4)
self.octave_offset = data.get("octave_offset", 0)
self.patterns.clear()
for name, pat_dict in data["patterns"].items():
self.patterns[name] = Pattern.from_dict(pat_dict)
DRUM_MAP.clear()
DRUM_MAP.update(data.get("drum_map", _GM_DRUM_DEFAULTS))
remap_drum_notes(self.patterns)
logger.info("Loaded %d patterns from %s", len(self.patterns), filepath)
return str(filepath)
# ─── Command Registry ────────────────────────────────────────────────────────
@dataclass
class Macro:
name: str
commands: list[str]
params: list[str]
description: str = ""
scope: str = "project"
def to_dict(self) -> dict:
return {
"name": self.name,
"commands": self.commands,
"params": self.params,
"description": self.description,
"scope": self.scope,
}
@classmethod
def from_dict(cls, d: dict) -> "Macro":
return cls(
name=d["name"],
commands=d["commands"],
params=d.get("params", []),
description=d.get("description", ""),
scope=d.get("scope", "project"),
)
MACROS_DIR = Path(__file__).parent / "macros"
SETTINGS_FILE = Path(__file__).parent / "settings.json"
def _load_settings() -> dict:
if SETTINGS_FILE.exists():
try:
return json.loads(SETTINGS_FILE.read_text())
except (json.JSONDecodeError, OSError):
logger.error("Failed to load settings from %s", SETTINGS_FILE, exc_info=True)
return {}
def _save_settings(settings: dict):
SETTINGS_FILE.write_text(json.dumps(settings, indent=2))
@dataclass
class CommandDef:
name: str
handler: str
category: str
description: str
usage: str = ""
aliases: list[str] = field(default_factory=list)
hint_args: list[str] = field(default_factory=list)
hidden: bool = False
_command_registry: list[CommandDef] = []
_COMMAND_DETAILS: dict[str, str] = {
"put": """\
Set notes at specific steps in a pattern.
Usage: put <pattern> <steps> <notes> [velocity] [gate]
Steps: 0,4,8 individual steps
0-15 range (inclusive)
0-15:2 range with stride (every 2nd step)
Notes: C3 note name + octave
kick drum name (ch 9 only)
60 raw MIDI number
C3,E3,G3 multiple notes (chord)
Velocity: 1-127 (default 100)
Gate: duration in steps (default 1)
Examples:
put drums 0,4,8,12 kick four-on-floor kick
put drums 2,6,10,14 snare 80 snare at velocity 80
put bass 0 C3 100 2 C3, vel 100, gate 2 steps
put keys 0-7 C3,E3,G3 chord across 8 steps
put drums 0-15:2 hihat 60 hihat on even steps""",
"euclid": """\
Generate a Euclidean rhythm — evenly distributing hits across the pattern.
Usage: euclid <pattern> <hits> [notes] [velocity]
The Bjorklund algorithm spaces N hits as evenly as possible across
the pattern's total steps. Clears the pattern first.
Common rhythms:
euclid drums 4 → 4 hits in 16 steps = kick on 0,4,8,12
euclid drums 3 → 3 hits in 16 steps = tresillo
euclid drums 5 → 5 in 8 = classic clave feel (if 8-step pattern)
euclid drums 7 → 7 in 16 = West African bell pattern
Examples:
euclid drums 4 kick four-on-floor kick
euclid hihat 7 hihat 80 hihat Euclidean at vel 80
euclid perc 3 C3,E3 chord hits, tresillo spacing""",
"arp": """\
Fill a pattern with an arpeggiated note sequence. Clears the pattern first.
Usage: arp <pattern> <notes> <style>
Styles:
up — ascending through notes, repeating
down — descending through notes, repeating
updown — ascending then descending (ping-pong)
random — randomized order
Notes are comma-separated: C3,E3,G3,C4
Examples:
arp keys C3,E3,G3 up ascending triad
arp bass C2,G2,C3,G3 updown bass arpeggio ping-pong
arp lead D3,F#3,A3,D4 random random arp""",
"clear": """\
Clear all notes from a pattern, specific steps, or a single note from steps.
Usage: clear <pattern> [steps] [note]
Without steps: clears the entire pattern (all notes, all steps).
With steps: clears only the specified steps.
With note: removes only that note from the specified steps.
Step syntax: same as put (0,4,8 / 0-15 / 0-15:2)
Examples:
clear drums wipe entire drum pattern
clear bass 0-3 clear first 4 steps of bass
clear keys 0,4,8 clear specific steps
clear drums 0-15 kick remove kick from all steps
clear keys 0,4 E3 remove E3 from steps 0 and 4""",
"new": """\
Create a new pattern.
Usage: new <name> [steps] [channel]
name — unique pattern name (no spaces)
steps — number of steps (default 16)
channel — MIDI channel 0-15 (default 0, use 9 for drums)
Channel 9 is the GM drum channel. When channel is 9, drum names
(kick, snare, hihat, etc.) can be used in put/euclid commands.
Examples:
new drums 16 9 16-step drum pattern on ch 9
new bass 16-step pattern on ch 0
new lead 32 1 32-step pattern on ch 1
new hihat 8 9 8-step drum pattern""",
"volume": """\
Adjust velocity of all hits in a pattern.
Usage: volume <pattern> <+/-N or +/-N%>
Absolute offset: +10, -20 — adds/subtracts from each velocity.
Percentage: +50%, -25% — scales each velocity by that amount.
Velocities are clamped to 1-127.
Examples:
volume drums +10 boost all drum hits by 10
volume bass -20 reduce bass velocity by 20
volume keys +50% scale keys up by 50% (100 → 150 → clamped to 127)
volume drums -25% reduce drums by 25% (100 → 75)
Alias: vol""",
"swing": """\
Add swing (timing offset) to a pattern or specific note.
Usage: swing <pattern> <0-100> [note]
Swing delays even-numbered steps. 0 = no swing (straight),
50 = moderate shuffle, 100 = maximum swing (triplet feel).
Without note: applies to entire pattern.
With note: per-note swing (e.g., different swing for hihat vs kick).
Examples:
swing drums 50 moderate shuffle on all drums
swing drums 60 hihat extra swing on hihat only
swing drums 0 hihat remove per-note swing from hihat""",
"vel": """\
Change the velocity of existing hits at specific steps.
Usage: vel <pattern> <steps> <note> <velocity>
Only modifies hits that already exist — does not create new ones.
Examples:
vel drums 0,8 kick 127 accent kick on beats 1 and 3
vel drums 4,12 snare 60 ghost snare on beats 2 and 4
vel bass 0-15 C3 80 set all C3 hits to vel 80""",
"remove": """\
Remove a specific note from steps in a pattern.
Usage: remove <pattern> <steps> <note>
Unlike clear (which removes all notes from a step), remove targets
a specific note and leaves other notes on those steps intact.
Examples:
remove drums 0,4 kick remove kick from steps 0 and 4
remove keys 0-7 E3 remove E3 from first 8 steps
remove drums 0-15 hihat remove all hihat hits""",
"replace": """\
Swap one note for another across an entire pattern.
Usage: replace <pattern> <old_note> <new_note>
Preserves velocity and gate of each hit. Useful for changing
drum sounds or transposing a single note.
Examples:
replace drums kick tom1 swap kick for tom1
replace bass C3 D3 transpose C3 to D3
replace drums hihat ohh open hihat instead of closed""",
"transpose": """\
Shift notes up or down by semitones.
Usage: transpose <pattern> <+/-N> shift all notes
transpose <pattern> <note> <+/-N> shift only that note
Values are clamped to the MIDI range 0-127.
Examples:
transpose bass +7 all notes up a fifth
transpose keys -12 all notes down an octave
transpose bass C3 +2 only C3 notes become D3""",
"auto": """\
Set CC automation keyframes on a pattern.
Usage:
auto <pattern> cc<N> <step:val ...> set keyframes
auto <pattern> cc<N> interp <mode> set interpolation
auto <pattern> cc<N> clear remove automation
auto <pattern> list show all CC lanes
Keyframes are step:value pairs (value 0-127).
Interpolation modes: linear (smooth), step (jump), exp (exponential).
Examples:
auto bass cc74 0:0 8:127 15:0 filter sweep
auto bass cc74 interp exp exponential curve
auto pad cc1 0:0 4:64 8:127 mod wheel ramp
auto drums list show drum CC lanes""",
"mute": """\
Toggle mute on a pattern or a specific note within a pattern.
Usage: mute <pattern> [note]
Without note: mutes/unmutes the entire pattern.
With note: mutes/unmutes just that note (other notes still play).
Examples:
mute drums toggle mute on entire drum pattern
mute drums hihat mute just the hihat
mute drums hihat (again) unmute the hihat""",
"solo": """\
Solo a pattern or specific note — mute everything else.
Usage: solo <pattern> [note]
Without note: mutes all other patterns, unmutes this one.
Running solo again on the same pattern un-solos.
With note: mutes all other notes in the pattern.
Examples:
solo bass hear only the bass
solo bass (again) un-solo, unmute all
solo drums kick hear only the kick in drums""",
"macro": """\
Define and manage reusable command sequences.
Subcommands:
macro def <name> [desc] ; <cmd1> ; <cmd2> ... define a macro
macro list list all macros
macro show <name> show macro commands
macro delete <name> delete a macro
macro edit <name> <cmd_index> <new_cmd> edit a command
macro global <name> promote to global
macro local <name> demote to project
macro import <file> import from file
Parameters: use $1, $2, ... in commands. Pass values when running.
Examples:
macro def 4floor ; new drums 16 9 ; put drums 0,4,8,12 kick
4floor run the macro
macro def beat $bpm ; bpm $bpm ; new drums 16 9
beat 120 run with bpm=120""",
"save": """\
Save the current session to a JSON file.
Usage: save [filename]
Without filename: saves to the last used file, or prompts.
With filename: saves to that file (adds .json if missing).
Saves: all patterns (notes, velocities, gates, CC automation,
swing, mute state), BPM, and drum map customizations.
Examples:
save mysong save to mysong.json
save re-save to last used file""",
"load": """\
Load a session from a JSON file.
Usage: load <filename>
Replaces all current patterns and settings with the saved state.
Loads: patterns, BPM, and drum map customizations.
Examples:
load mysong load from mysong.json
load mysong.json same thing""",
"history": """\
View and manipulate command history.
Subcommands:
history view [id|range] show history (all or filtered)
history delete <id|range> remove entries
history copy <id|range> copy commands to clipboard
history paste <after_id> replay clipboard commands
Range syntax: single ID (5) or range (3-7).
Examples:
history view show all history
history view 1-5 show entries 1 through 5
history copy 3-7 copy commands 3-7
history paste 0 replay copied commands""",
"tap": """\
Play a single note immediately (preview a sound).
Usage: tap <note> [velocity] [channel]
Sends note_on, then note_off after 300ms. Does not affect patterns.
Examples:
tap C3 play C3 at vel 100 on ch 0
tap kick play kick drum (ch 0, vel 100)
tap D#4 80 1 play D#4 at vel 80 on ch 1""",
"octave": """\
Set the note naming convention (affects display only, not MIDI).
Usage: octave <preset>
Presets:
element — MIDI 60 = C3 (Element, Reason)
yamaha — MIDI 60 = C3 (Yamaha convention)
ableton — MIDI 60 = C3 (Ableton default)
Without args: shows current setting and available presets.
This setting persists across sessions.
Examples:
octave show current octave convention
octave element use Element/Reason naming""",
"drummap": """\
Customize drum name → MIDI note mappings.
Usage:
drummap <name> <note> set or add a mapping
drummap <name> show current mapping for a name
drummap reset reset to GM defaults
When you change a mapping, existing hits on ch 9 patterns are
automatically updated to the new note number.
Examples:
drummap kick 36 set kick to note 36 (GM default)
drummap kick C2 set kick using note name
drummap snare 40 move snare from 38 to 40
drummap reset restore all GM defaults""",
}
def command(
name: str,
category: str,
description: str,
usage: str = "",
aliases: list[str] | None = None,
hint_args: list[str] | None = None,
hidden: bool = False,
):
def decorator(fn):
_command_registry.append(
CommandDef(
name=name,
handler=fn.__name__,