diff --git a/scripts/pad_colours.py b/scripts/pad_colours.py new file mode 100644 index 0000000..ede62d0 --- /dev/null +++ b/scripts/pad_colours.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +"""Store scene colours in an SMC-PAD preset bank. + +Pad bank 1 is notes 36–51 and pad bank 2 is notes 52–67, bottom-left +first. Note messages do not change these lamps. The colour is three +bytes in the preset, written over the Private USB port. + + .venv/bin/python scripts/pad_colours.py --xchc --bank 2 + .venv/bin/python scripts/pad_colours.py --dry-run + .venv/bin/python scripts/pad_colours.py --clear + +The write is checked by reading it back. It is sent to the running copy +and to the stored preset, and it leaves notes, channels, and knobs as +they are. An empty write at the start of the preset then commits it, +which is what MidiSuite's Save button sends. +""" + +from __future__ import annotations + +import argparse +import glob +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) + +from patch_smc_pad import PAD_COLORS # noqa: E402 + +# Preset image, memory type 5. Each of these offsets is a note-36 pad, +# and the next 15 records are notes 37–51. The running copy is at RAM. +RECORD = 26 +RGB_AT = 4 +BANKS = (1044, 8122, 11661, 15200, 18739, 22278, 25817) +RAM = 0x80000000 +FULL = 0xF0 + + +def encode(source: bytes) -> bytes: + """Pack a protocol message into the 7-bit SysEx body.""" + bit_num = 0 + accum = 0 + out = bytearray() + for byte in source: + accum = ((byte << (bit_num & 0x1F)) | accum) & 0xFFFFFFFF + bit_num += 1 + while True: + out.append(accum & 0x7F) + accum = (accum >> 7) & 0xFFFFFFFF + if bit_num < 7: + break + bit_num -= 7 + out.append(accum & 0x7F) + return bytes(out) + + +def decode(source: bytes) -> bytes: + bit_num = 0 + last_val = 0 + out = bytearray() + for byte in source: + accum = byte & (0xFFFFFFFF >> (32 - bit_num) if bit_num else 0) + if bit_num > 0: + out.append((last_val & 0x7F) | ((accum << (8 - bit_num)) & 0xFF)) + last_val = byte >> bit_num + bit_num = (bit_num + 1) % 8 + if last_val > 0: + out.append(last_val) + return bytes(out) + + +def checksum(payload: bytes) -> int: + total = 0 + for byte in payload: + total = (total + byte) & 0xFF + return (~total) & 0xFF + + +def frame(command: int, payload: bytes) -> list[int]: + data = bytearray((0x00, 0x59, command)) + data += len(payload).to_bytes(3, "little") + data += payload + data.append(checksum(payload)) + return [0xF0, *encode(bytes(data)), 0xF7] + + +def read_request(address: int, size: int) -> list[int]: + payload = bytes([5]) + address.to_bytes(4, "little") + size.to_bytes(3, "little") + return frame(0x23, payload) + + +def write_request(address: int, data: bytes) -> list[int]: + payload = bytes([5]) + address.to_bytes(4, "little") + len(data).to_bytes(3, "little") + data + return frame(0x22, payload) + + +def save_request() -> list[int]: + """Commit the running preset. MidiSuite's Save is this empty write.""" + return write_request(0, b"") + + +def scale(value: int) -> int: + """Map 0–255 onto the pad's 0–240 colour range.""" + return (value * FULL + 127) // 255 + + +def led_rgb(r: int, g: int, b: int, w: int) -> tuple[int, int, int]: + return (min(255, r + w), min(255, g + w), min(255, b + w)) + + +# shows/xchc.qxw functions 0–8, in that order. The pad lamps are RGB, so +# the white scene is stored as white rather than the can's white channel. +XCHC_COLOURS = ( + ("Red", 255, 0, 0), + ("Orange", 255, 127, 0), + ("Yellow", 255, 255, 0), + ("Green", 0, 255, 0), + ("Cyan", 0, 255, 255), + ("Blue", 0, 0, 255), + ("Violet", 127, 0, 255), + ("Magenta", 255, 0, 255), + ("White", 255, 255, 255), +) + + +def scene_colours(clear: bool = False) -> list[tuple[str, bytes]]: + colours = [] + for name, r, g, b, w in PAD_COLORS: + if clear: + colours.append((name, b"\x00\x00\x00")) + continue + red, green, blue = led_rgb(r, g, b, w) + colours.append((name, bytes((scale(red), scale(green), scale(blue))))) + return colours + + +def xchc_colours(clear: bool = False) -> list[tuple[str, bytes]]: + """The nine xchc colour scenes, then the rest of the 16-pad bank off.""" + colours = [] + for name, red, green, blue in XCHC_COLOURS: + rgb = b"\x00\x00\x00" if clear else bytes((scale(red), scale(green), scale(blue))) + colours.append((name, rgb)) + colours.extend(("", b"\x00\x00\x00") for _ in range(16 - len(colours))) + return colours + + +def bank_bases(bank: int) -> tuple[int, ...]: + """Preset addresses where this pad bank's note records start.""" + if bank < 1: + raise ValueError(f"pad bank {bank} is not on this controller") + skip = (bank - 1) * 16 * RECORD + return tuple(base + skip for base in BANKS) + + +def colour_writes( + clear: bool = False, + bank: int = 1, + colours: list[tuple[str, bytes]] | None = None, +) -> list[tuple[str, int, bytes]]: + """(name, address, rgb) for one pad bank in every preset.""" + palette = scene_colours(clear) if colours is None else list(colours) + if clear and colours is not None: + palette = [(name, b"\x00\x00\x00") for name, _rgb in palette] + placed = [] + for base in bank_bases(bank): + for index, (name, rgb) in enumerate(palette): + placed.append((name, base + index * RECORD + RGB_AT, rgb)) + return placed + + +def payload_data(decoded: bytes) -> bytes: + """Bytes after the type, address, and length in a read reply.""" + if decoded[:3] != b"\x00\x59\x23": + raise ValueError(f"unexpected reply {decoded[:8].hex()}") + payload = decoded[6:-1] + return payload[8:] + + +def private_port(names: list[str]) -> str: + for name in names: + if "Private" in name: + return name + raise SystemExit( + "SMC-PAD Private port not found. Ports:\n " + "\n ".join(names or ["(none)"]) + ) + + +def _transact(midiout, midiin, message: list[int], timeout: float = 0.8) -> bytes: + while True: + item = midiin.get_message() + if not item or not item[0]: + break + midiout.send_message(message) + deadline = time.time() + timeout + while time.time() < deadline: + item = midiin.get_message() + if not item or not item[0]: + time.sleep(0.004) + continue + raw = bytes(item[0]) + if raw[:1] == b"\xf0" and raw[-1:] == b"\xf7": + return decode(raw[1:-1]) + raise TimeoutError("the pad did not answer") + + +def apply(clear: bool, bank: int = 1, colours: list[tuple[str, bytes]] | None = None) -> None: + for path in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")): + if path not in sys.path: + sys.path.insert(0, path) + import rtmidi + + midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA) + midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA) + port = private_port(midiout.get_ports()) + index = midiout.get_ports().index(port) + midiin.open_port(index) + midiin.ignore_types(sysex=False, timing=True, active_sense=True) + midiout.open_port(index) + print(f"Port: {port}", flush=True) + try: + note = 36 + (bank - 1) * 16 + for base in bank_bases(bank): + reply = _transact(midiout, midiin, read_request(base, 2)) + mark = payload_data(reply) + if mark[:2] != bytes((0x09, note)): + raise SystemExit( + f"preset at {base} is {mark.hex()}, not the note-{note} pads; nothing was written" + ) + bases = (RAM, 0) + shown = set() + for name, address, rgb in colour_writes(clear, bank, colours): + for base in bases: + _transact(midiout, midiin, write_request(base + address, rgb)) + if name in shown: + continue + check = payload_data(_transact(midiout, midiin, read_request(address, 3))) + if check != rgb: + raise SystemExit(f"{name or 'pad'} read back {check.hex()}, expected {rgb.hex()}") + shown.add(name) + if name: + print(f" {name:<8} {address:#06x} {rgb.hex()}", flush=True) + reply = _transact(midiout, midiin, save_request()) + if reply[:3] != b"\x00\x59\x00" or reply[6:7] != b"\x00": + raise SystemExit(f"the pad did not accept the save ({reply.hex()})") + print("Saved on the pad.", flush=True) + finally: + midiout.close_port() + midiin.close_port() + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--bank", type=int, default=1, help="pad bank to write (2 is notes 52–67)") + parser.add_argument("--xchc", action="store_true", help="use the solid colour scenes from shows/xchc.qxw") + parser.add_argument("--clear", action="store_true", help="store black on every scene pad") + parser.add_argument("--dry-run", action="store_true", help="print the colours and do not open a port") + args = parser.parse_args(argv) + palette = xchc_colours(args.clear) if args.xchc else None + if args.dry_run: + seen = set() + for name, address, rgb in colour_writes(args.clear, args.bank, palette): + if not name or name in seen: + continue + seen.add(name) + print(f"{name:<8} {address:#06x} {rgb.hex()}") + return 0 + apply(args.clear, args.bank, palette) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_pad_colours.py b/tests/test_pad_colours.py new file mode 100644 index 0000000..27d7a75 --- /dev/null +++ b/tests/test_pad_colours.py @@ -0,0 +1,101 @@ +"""Scene colours become preset RGB writes, and the codec matches a known message.""" + +from __future__ import annotations + +import importlib.util +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("pad_colours", ROOT / "scripts" / "pad_colours.py") +colours = importlib.util.module_from_spec(spec) +assert spec.loader is not None +sys.modules["pad_colours"] = colours +spec.loader.exec_module(colours) + + +def test_codec_matches_the_published_write(): + inner = bytes.fromhex("00592209000005000000800100000178") + wire = bytes([0xF0, *colours.encode(inner), 0xF7]) + assert wire == bytes.fromhex("f000320949000040020000000018000000017001f7") + assert colours.decode(wire[1:-1]) == inner + + +def test_scene_colours_are_stored_on_the_note_36_pads(): + writes = colours.colour_writes() + first = writes[:16] + assert [name for name, _addr, _rgb in first] == [ + "Red", + "Green", + "Blue", + "White", + "Yellow", + "Cyan", + "Magenta", + "Orange", + "Warm", + "Cool", + "Pink", + "Lime", + "Full", + "Half", + "Dim50", + "Black", + ] + assert first[0][1:] == (1048, bytes.fromhex("f00000")) + assert first[1][1:] == (1074, bytes.fromhex("00f000")) + assert first[2][1:] == (1100, bytes.fromhex("0000f0")) + assert first[3][1:] == (1126, bytes.fromhex("f0f0f0")) + assert first[15][1:] == (1048 + 15 * 26, b"\x00\x00\x00") + assert len(writes) == 16 * len(colours.BANKS) + assert {address for _name, address, _rgb in writes if _name == "Red"} == { + bank + 4 for bank in colours.BANKS + } + + +def test_xchc_colours_are_stored_on_pad_bank_2(): + writes = colours.colour_writes(bank=2, colours=colours.xchc_colours()) + first = [item for item in writes if item[1] < colours.BANKS[1]] + assert [name for name, _addr, _rgb in first] == [ + "Red", + "Orange", + "Yellow", + "Green", + "Cyan", + "Blue", + "Violet", + "Magenta", + "White", + "", + "", + "", + "", + "", + "", + "", + ] + assert first[0][1:] == (1464, bytes.fromhex("f00000")) + assert first[1][1:] == (1490, bytes.fromhex("f07800")) + assert first[6][1:] == (1464 + 6 * 26, bytes.fromhex("7800f0")) + assert first[8][1:] == (1464 + 8 * 26, bytes.fromhex("f0f0f0")) + assert first[9][1:] == (1464 + 9 * 26, b"\x00\x00\x00") + assert {address for name, address, _rgb in writes if name == "Red"} == { + base + 16 * 26 + 4 for base in colours.BANKS + } + + +def test_save_is_the_empty_write_midi_suite_sends(): + inner = colours.decode(bytes(colours.save_request()[1:-1])) + assert inner[:3] == b"\x00\x59\x22" + length = int.from_bytes(inner[3:6], "little") + assert inner[6:6 + length] == bytes([5, 0, 0, 0, 0, 0, 0, 0]) + assert len(colours.save_request()) == 20 + + +def test_private_port_is_not_the_master_or_qlc(): + names = [ + "SINCO:SINCO SMC-PAD-Master 20:1", + "SINCO:SINCO SMC-PAD-Private 20:0", + "qlcplus:__QLC__ 128:0", + ] + assert colours.private_port(names) == "SINCO:SINCO SMC-PAD-Private 20:0"