diff --git a/Pipfile b/Pipfile index 3c6bb31..4ba33c1 100644 --- a/Pipfile +++ b/Pipfile @@ -16,3 +16,4 @@ python_version = "3.12" positions = "python scripts/position_movers.py" pattern = "python -m pattern_pad" midi = "python scripts/midi.py" +padeditor = "python -m padeditor" diff --git a/padeditor/__init__.py b/padeditor/__init__.py new file mode 100644 index 0000000..6f4e9ac --- /dev/null +++ b/padeditor/__init__.py @@ -0,0 +1 @@ +"""SMC-PAD preset editor.""" diff --git a/padeditor/__main__.py b/padeditor/__main__.py new file mode 100644 index 0000000..cb6f625 --- /dev/null +++ b/padeditor/__main__.py @@ -0,0 +1,33 @@ +"""python3 -m padeditor [--port 8770]""" + +from __future__ import annotations + +import argparse +import threading +import webbrowser + +from padeditor.server import make_server + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="padeditor", description="SMC-PAD preset editor") + parser.add_argument("--host", default="127.0.0.1") + parser.add_argument("--port", type=int, default=8770) + parser.add_argument("--no-browser", action="store_true") + args = parser.parse_args(argv) + server = make_server(args.host, args.port) + url = f"http://{args.host}:{args.port}/" + print(f"SMC-PAD editor → {url} Ctrl+C to quit") + if not args.no_browser: + threading.Timer(0.4, webbrowser.open, args=(url,)).start() + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.server_close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/padeditor/device.py b/padeditor/device.py new file mode 100644 index 0000000..b9ae7be --- /dev/null +++ b/padeditor/device.py @@ -0,0 +1,313 @@ +"""Read and save the SMC-PAD preset over the Private USB port. + +Writes go to the preset address, as MidiSuite sends them; the lamps follow +straight away. Save writes the bytes that differ, checks each read-back, +then sends the empty write MidiSuite's Save button sends, which keeps the +preset after a power cycle. It never sends erase. +""" + +from __future__ import annotations + +import glob +import sys +import time +from pathlib import Path + +from padeditor.preset import GLOBAL_LEN, IMAGE_LEN, changed_ranges +from padeditor.sysex import ( + CMD_READ, + MEM_GLOBAL, + MEM_PRESET, + RAM, + payload_data, + read_request, + save_request, + write_request, +) + +ROOT = Path(__file__).resolve().parents[1] +READ_CHUNK = 512 +WRITE_CHUNK = 64 + + +class PadError(RuntimeError): + pass + + +def load_rtmidi(): + 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 + + return rtmidi + + +def private_port(names: list[str]) -> str: + for name in names: + if "Private" in name: + return name + raise PadError( + "SMC-PAD Private port not found. Ports:\n " + "\n ".join(names or ["(none)"]) + ) + + +def master_port(names: list[str]) -> str: + for name in names: + if "Master" in name: + return name + raise PadError( + "SMC-PAD Master port not found. Ports:\n " + "\n ".join(names or ["(none)"]) + ) + + +def transact(midiout, midiin, message: list[int], timeout: float = 0.8, expect: int | None = None) -> 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" or raw[-1:] != b"\xf7": + continue + decoded = decode_body(raw) + if expect is not None and (len(decoded) < 3 or decoded[2] != expect): + continue + return decoded + raise PadError("the pad did not answer") + + +def decode_body(raw: bytes) -> bytes: + from padeditor.sysex import decode + + return decode(raw[1:-1]) + + +class Link: + """One open Private port, input and output.""" + + def __init__(self): + rtmidi = load_rtmidi() + self.midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA) + self.midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA) + self.name = private_port(self.midiout.get_ports()) + index = self.midiout.get_ports().index(self.name) + self.midiin.open_port(index) + self.midiin.ignore_types(sysex=False, timing=True, active_sense=True) + self.midiout.open_port(index) + + def close(self) -> None: + self.midiout.close_port() + self.midiin.close_port() + + def read(self, address: int, size: int, memory: int = MEM_PRESET) -> bytes: + reply = transact(self.midiout, self.midiin, read_request(address, size, memory), expect=CMD_READ) + data = payload_data(reply) + return data[:size] + + def write(self, address: int, data: bytes, memory: int = MEM_PRESET) -> None: + transact(self.midiout, self.midiin, write_request(address, data, memory)) + + def __enter__(self) -> "Link": + return self + + def __exit__(self, *exc) -> None: + self.close() + + +def read_image(link: Link | None = None) -> bytes: + own = link is None + if link is None: + link = Link() + try: + got = bytearray() + while len(got) < IMAGE_LEN: + ask = min(READ_CHUNK, IMAGE_LEN - len(got)) + part = link.read(len(got), ask) + if not part: + raise PadError(f"empty read at {len(got)}") + got += part[:ask] + return bytes(got[:IMAGE_LEN]) + finally: + if own: + link.close() + + +def _port_names(kind: str) -> list[str]: + rtmidi = load_rtmidi() + probe = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA) if kind == "out" else rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA) + try: + return list(probe.get_ports()) + finally: + del probe + + +def read_port_names() -> list[str]: + return _port_names("out") + + +def input_names() -> list[str]: + return _port_names("in") + + +def connected() -> str | None: + try: + return private_port(read_port_names()) + except PadError: + return None + + +def read_global(link: Link | None = None) -> bytes: + """The 12-byte settings block MidiSuite polls: tempo, swing, curve, transpose.""" + own = link is None + if link is None: + link = Link() + try: + data = link.read(0, GLOBAL_LEN, MEM_GLOBAL) + if len(data) < GLOBAL_LEN: + raise PadError(f"global block read {len(data)} bytes, expected {GLOBAL_LEN}") + return data[:GLOBAL_LEN] + finally: + if own: + link.close() + + +def save_image(desired: bytes, link: Link | None = None, settings: bytes | None = None) -> int: + """Write differing bytes to the preset and commit them. + + Returns how many bytes were written. An unchanged image still gets + MidiSuite's empty save, so Save always commits. The settings block, + when given and changed, is written whole, as MidiSuite does. + """ + if len(desired) != IMAGE_LEN: + raise PadError(f"preset image is {len(desired)} bytes, expected {IMAGE_LEN}") + if settings is not None and len(settings) != GLOBAL_LEN: + raise PadError(f"global block is {len(settings)} bytes, expected {GLOBAL_LEN}") + own = link is None + if link is None: + link = Link() + try: + current = read_image(link) + ranges = changed_ranges(current, desired, WRITE_CHUNK) + for address, data in ranges: + _write_checked(link, address, data) + written = sum(len(data) for _address, data in ranges) + if settings is not None and read_global(link) != settings: + link.write(0, settings, MEM_GLOBAL) + if read_global(link) != settings: + raise PadError("the pad did not keep the global settings") + written += len(settings) + _commit(link) + return written + finally: + if own: + link.close() + + +def write_colour(preset: int, index: int, rgb: tuple[int, int, int] | list[int]) -> int: + """Light one pad. The same three-byte write MidiSuite sends while its + colour picker moves. It does not commit; Save does that.""" + from padeditor.preset import colour_offset + + if len(rgb) != 3: + raise PadError("a pad colour needs red, green, and blue") + payload = bytes(int(channel) & 0xFF for channel in rgb) + offset = colour_offset(preset, index) + with Link() as link: + _write_checked(link, offset, payload) + return offset + + +def _write_checked(link: Link, address: int, data: bytes) -> None: + """Write the preset address, as MidiSuite does, then read it back.""" + link.write(address, data) + reply = transact(link.midiout, link.midiin, read_request(address, len(data))) + got = payload_data(reply) + if got[:len(data)] != data: + raise PadError( + f"read-back at {address:#x} was {got[:len(data)].hex()}, expected {data.hex()}" + ) + + +def _commit(link: Link) -> None: + reply = transact(link.midiout, link.midiin, save_request()) + if reply[:3] != b"\x00\x59\x00" or reply[6:7] != b"\x00": + raise PadError(f"the pad did not accept the save ({reply.hex()})") + + +def probe_relative(listen: float = 2.5) -> str: + """Try knob type 0x03 in RAM only, on every preset's last knob. + + Restores the original six bytes. Does not save. Returns ``relative`` + when a turn of that knob sends a step, ``absolute`` when it sends a + running value, or ``silent`` when nothing arrives. + """ + from padeditor.preset import KNOB_AT, KNOB_COUNT, KNOB_LEN, PRESET_COUNT, PRESET_LEN, RELATIVE_TYPE + + knob = KNOB_COUNT - 1 + offsets = [index * PRESET_LEN + KNOB_AT + knob * KNOB_LEN for index in range(PRESET_COUNT)] + rtmidi = load_rtmidi() + master_name = master_port(input_names()) + heard: list[tuple[int, int, int]] = [] + watched: set[tuple[int, int]] = set() + with Link() as link: + original = [link.read(offset, KNOB_LEN) for offset in offsets] + watched = {(rec[2], rec[3]) for rec in original} + try: + for offset, rec in zip(offsets, original): + link.write(RAM + offset, bytes((RELATIVE_TYPE,)) + rec[1:]) + heard = _listen_cc(rtmidi, master_name, listen) + finally: + for offset, rec in zip(offsets, original): + link.write(RAM + offset, rec) + matched = [item for item in heard if (item[0], item[1]) in watched] + return _classify(matched) + + +def _listen_cc(rtmidi, port_name: str, listen: float) -> list[tuple[int, int, int]]: + midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA) + names = midiin.get_ports() + midiin.open_port(names.index(port_name)) + midiin.ignore_types(sysex=True, timing=True, active_sense=True) + found: list[tuple[int, int, int]] = [] + try: + deadline = time.time() + listen + while time.time() < deadline: + item = midiin.get_message() + if not item or not item[0]: + time.sleep(0.004) + continue + data = bytes(item[0]) + if len(data) >= 3 and (data[0] & 0xF0) == 0xB0: + found.append((data[0] & 0x0F, data[1], data[2])) + finally: + midiin.close_port() + return found + + +def _classify(messages: list[tuple[int, int, int]]) -> str: + if not messages: + return "silent" + values = [value for _channel, _cc, value in messages] + unique = set(values) + if unique <= {0, 1, 127} or unique <= {63, 64, 65} or _steps(values): + return "relative" + if len(unique) >= 4: + return "absolute" + return "silent" + + +def _steps(values: list[int]) -> bool: + """1..63 clockwise and 65..127 counter-clockwise, with no running ramp.""" + for value in values: + if value == 0 or value == 64 or value > 127: + return False + if value >= 16 and value <= 111: + return False + return True diff --git a/padeditor/preset.py b/padeditor/preset.py new file mode 100644 index 0000000..0be3f0f --- /dev/null +++ b/padeditor/preset.py @@ -0,0 +1,311 @@ +"""SMC-PAD preset image: 8 × 3539 bytes, the map MidiSuite edits.""" + +from __future__ import annotations + +IMAGE_LEN = 28312 +PRESET_LEN = 3539 +PRESET_COUNT = 8 + +BUTTON_COUNT = 5 +BUTTON_LEN = 23 +BUTTON_NAMES = ("Left", "Right", "Play", "Stop", "Record") + +KNOB_AT = 115 +KNOB_COUNT = 16 +KNOB_LEN = 6 +KNOB_BANK = 8 + +GAP_AT = 211 + +PAD_AT = 212 +PAD_LEN = 26 +PAD_COUNT = 128 +PAGE_LEN = 16 +PAGE_COUNT = 8 +RGB_AT = 4 + +# Global settings, memory type 4. Offsets are the fields MidiSuite's Glob +# panel showed against the factory block 78 00 32 04 00 00 02 00 01 01 00 00. +GLOBAL_LEN = 12 +GLOBAL_TEMPO = 0 # two bytes, little-endian +GLOBAL_SWING = 2 +GLOBAL_CURVE = 6 +GLOBAL_TRANSPOSE = 7 # signed + +# File bytes. Names are only values MidiSuite has shown for this pad's +# factory image, or a RAM probe on this pad has heard. +KNOB_TYPES = {0x00: "CC"} +BUTTON_TYPES = {0x02: "CC Push"} + +# Set after a RAM-only probe hears a relative step from type 0x03. +RELATIVE_TYPE = 0x03 +RELATIVE_CONFIRMED = False + +FULL = 0xF0 +SYSEX_ROOM = 16 # button bytes 6..21; byte 22 is the flag + + +def scale(value: int) -> int: + """Map 0–255 onto the pad's 0–240 colour range.""" + return (value * FULL + 127) // 255 + + +def knob_type_names() -> dict[int, str]: + names = dict(KNOB_TYPES) + if RELATIVE_CONFIRMED: + names[RELATIVE_TYPE] = "Relative" + return names + + +def type_catalog() -> dict[str, list[dict[str, int | str]]]: + def rows(names: dict[int, str]) -> list[dict[str, int | str]]: + return [{"value": value, "name": name} for value, name in sorted(names.items())] + + return { + "knob": rows(knob_type_names()), + "button": rows(BUTTON_TYPES), + } + + +class PresetError(ValueError): + pass + + +def _byte(value: object, label: str) -> int: + if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 255: + raise PresetError(f"{label} must be a byte") + return value + + +def _channel(value: object, label: str) -> int: + """MIDI channel 1–16 as stored, which is 0–15.""" + if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= 16: + raise PresetError(f"{label} must be MIDI channel 1–16") + return value - 1 + + +def _hex(value: object, label: str) -> bytes: + if not isinstance(value, str) or len(value) % 2: + raise PresetError(f"{label} must be even-length hex") + try: + return bytes.fromhex(value) + except ValueError as exc: + raise PresetError(f"{label} is not hex") from exc + + +def unpack(image: bytes) -> dict: + if len(image) != IMAGE_LEN: + raise PresetError(f"preset image is {len(image)} bytes, expected {IMAGE_LEN}") + presets = [] + for index in range(PRESET_COUNT): + block = image[index * PRESET_LEN:(index + 1) * PRESET_LEN] + presets.append(_unpack_preset(block)) + return {"presets": presets, "types": type_catalog(), "relative": RELATIVE_CONFIRMED} + + +def pack(document: dict) -> bytes: + presets = document.get("presets") + if not isinstance(presets, list) or len(presets) != PRESET_COUNT: + raise PresetError(f"expected {PRESET_COUNT} presets") + out = bytearray() + for index, preset in enumerate(presets): + out += _pack_preset(preset, index) + if len(out) != IMAGE_LEN: + raise PresetError(f"packed {len(out)} bytes, expected {IMAGE_LEN}") + return bytes(out) + + +def colour_offset(preset: int, index: int) -> int: + """Where one pad's colour sits. MidiSuite writes only this address.""" + if not 0 <= preset < PRESET_COUNT: + raise PresetError(f"preset {preset + 1} is not on this controller") + if not 0 <= index < PAD_COUNT: + raise PresetError(f"pad {index + 1} is not on this controller") + return preset * PRESET_LEN + PAD_AT + index * PAD_LEN + RGB_AT + + +def unpack_global(raw: bytes) -> dict: + if len(raw) != GLOBAL_LEN: + raise PresetError(f"global block is {len(raw)} bytes, expected {GLOBAL_LEN}") + return { + "tempo": int.from_bytes(raw[GLOBAL_TEMPO:GLOBAL_TEMPO + 2], "little"), + "swing": raw[GLOBAL_SWING], + "curve": raw[GLOBAL_CURVE], + "transpose": int.from_bytes(raw[GLOBAL_TRANSPOSE:GLOBAL_TRANSPOSE + 1], "little", signed=True), + "raw": raw.hex(), + } + + +def pack_global(block: dict) -> bytes: + """The named fields over the bytes that were read, so unknown ones stay put.""" + out = bytearray(_hex(block.get("raw", ""), "global block")) + if len(out) != GLOBAL_LEN: + raise PresetError(f"global block is {len(out)} bytes, expected {GLOBAL_LEN}") + tempo = block.get("tempo") + if isinstance(tempo, bool) or not isinstance(tempo, int) or not 1 <= tempo <= 0xFFFF: + raise PresetError("tempo must be a whole number of BPM") + out[GLOBAL_TEMPO:GLOBAL_TEMPO + 2] = tempo.to_bytes(2, "little") + out[GLOBAL_SWING] = _byte(block.get("swing"), "swing") + out[GLOBAL_CURVE] = _byte(block.get("curve"), "pad curve") + transpose = block.get("transpose") + if isinstance(transpose, bool) or not isinstance(transpose, int) or not -128 <= transpose <= 127: + raise PresetError("transpose must be -128 to 127") + out[GLOBAL_TRANSPOSE] = transpose & 0xFF + return bytes(out) + + +def changed_ranges(before: bytes, after: bytes, limit: int = 64) -> list[tuple[int, bytes]]: + """Coalesce differing bytes, then split each run into write-sized pieces.""" + if len(before) != len(after): + raise PresetError(f"cannot compare {len(before)} bytes with {len(after)}") + runs: list[tuple[int, int]] = [] + start = None + for index, (old, new) in enumerate(zip(before, after)): + if old != new: + if start is None: + start = index + elif start is not None: + runs.append((start, index)) + start = None + if start is not None: + runs.append((start, len(after))) + pieces: list[tuple[int, bytes]] = [] + for run_at, run_end in runs: + at = run_at + while at < run_end: + stop = min(run_end, at + limit) + pieces.append((at, after[at:stop])) + at = stop + return pieces + + +def _unpack_preset(block: bytes) -> dict: + buttons = [] + for index in range(BUTTON_COUNT): + rec = block[index * BUTTON_LEN:(index + 1) * BUTTON_LEN] + length = rec[5] + if length > SYSEX_ROOM: + sysex, padding = rec[6:22], b"" + else: + sysex, padding = rec[6:6 + length], rec[6 + length:22] + buttons.append({ + "name": BUTTON_NAMES[index], + "type": rec[0], + "channel": rec[1] + 1, + "number": rec[2], + "min": rec[3], + "max": rec[4], + "sysex": sysex.hex(), + "padding": padding.hex(), + "led": rec[22], + }) + knobs = [] + for index in range(KNOB_COUNT): + at = KNOB_AT + index * KNOB_LEN + rec = block[at:at + KNOB_LEN] + knobs.append({ + "type": rec[0], + "speed": rec[1], + "channel": rec[2] + 1, + "number": rec[3], + "left": rec[4], + "right": rec[5], + }) + pads = [] + for index in range(PAD_COUNT): + at = PAD_AT + index * PAD_LEN + rec = block[at:at + PAD_LEN] + pads.append({ + "channel": rec[0] + 1, + "note": rec[1], + "min": rec[2], + "max": rec[3], + "rgb": [rec[4], rec[5], rec[6]], + "led": rec[7], + "tail": rec[8:].hex(), + }) + return {"gap": block[GAP_AT], "buttons": buttons, "knobs": knobs, "pads": pads} + + +def _pack_preset(preset: dict, index: int) -> bytes: + out = bytearray(PRESET_LEN) + buttons = preset.get("buttons") + knobs = preset.get("knobs") + pads = preset.get("pads") + if not isinstance(buttons, list) or len(buttons) != BUTTON_COUNT: + raise PresetError(f"preset {index + 1} needs {BUTTON_COUNT} buttons") + if not isinstance(knobs, list) or len(knobs) != KNOB_COUNT: + raise PresetError(f"preset {index + 1} needs {KNOB_COUNT} knobs") + if not isinstance(pads, list) or len(pads) != PAD_COUNT: + raise PresetError(f"preset {index + 1} needs {PAD_COUNT} pads") + for number, button in enumerate(buttons): + out[number * BUTTON_LEN:(number + 1) * BUTTON_LEN] = _pack_button(button, index, number) + for number, knob in enumerate(knobs): + at = KNOB_AT + number * KNOB_LEN + out[at:at + KNOB_LEN] = _pack_knob(knob, index, number) + out[GAP_AT] = _byte(preset.get("gap", 0), f"preset {index + 1} gap") + for number, pad in enumerate(pads): + at = PAD_AT + number * PAD_LEN + rec = _pack_pad(pad, index, number) + room = PRESET_LEN - at + if len(rec) > room: + raise PresetError(f"preset {index + 1} pad {number + 1} does not fit") + out[at:at + len(rec)] = rec + return bytes(out) + + +def _pack_button(button: dict, preset: int, index: int) -> bytes: + label = f"preset {preset + 1} {BUTTON_NAMES[index]}" + sysex = _hex(button.get("sysex", ""), f"{label} sysex") + if len(sysex) > SYSEX_ROOM: + raise PresetError(f"{label} sysex is longer than {SYSEX_ROOM} bytes") + padding = _hex(button.get("padding", ""), f"{label} padding") + room = SYSEX_ROOM - len(sysex) + padding = padding[:room] + rec = bytearray(BUTTON_LEN) + rec[0] = _byte(button.get("type"), f"{label} type") + rec[1] = _channel(button.get("channel"), f"{label} channel") + rec[2] = _byte(button.get("number"), f"{label} number") + rec[3] = _byte(button.get("min"), f"{label} min") + rec[4] = _byte(button.get("max"), f"{label} max") + rec[5] = len(sysex) + rec[6:6 + len(sysex)] = sysex + rec[6 + len(sysex):22] = padding + bytes(room - len(padding)) + rec[22] = _byte(button.get("led"), f"{label} led") + return bytes(rec) + + +def _pack_knob(knob: dict, preset: int, index: int) -> bytes: + label = f"preset {preset + 1} knob {index + 1}" + # Any stored type byte round-trips. The editor only offers names it has seen. + return bytes(( + _byte(knob.get("type"), f"{label} type"), + _byte(knob.get("speed"), f"{label} speed"), + _channel(knob.get("channel"), f"{label} channel"), + _byte(knob.get("number"), f"{label} number"), + _byte(knob.get("left"), f"{label} left"), + _byte(knob.get("right"), f"{label} right"), + )) + + +def _pack_pad(pad: dict, preset: int, index: int) -> bytes: + label = f"preset {preset + 1} pad {index + 1}" + rgb = pad.get("rgb") + if not isinstance(rgb, list) or len(rgb) != 3: + raise PresetError(f"{label} colour needs three bytes") + tail = _hex(pad.get("tail", ""), f"{label} tail") + stored = PAD_LEN if index < PAD_COUNT - 1 else PRESET_LEN - (PAD_AT + (PAD_COUNT - 1) * PAD_LEN) + tail_room = stored - 8 + if len(tail) > tail_room: + raise PresetError(f"{label} tail is longer than {tail_room} bytes") + rec = bytearray(stored) + rec[0] = _channel(pad.get("channel"), f"{label} channel") + rec[1] = _byte(pad.get("note"), f"{label} note") + rec[2] = _byte(pad.get("min"), f"{label} min velocity") + rec[3] = _byte(pad.get("max"), f"{label} max velocity") + rec[4] = _byte(rgb[0], f"{label} red") + rec[5] = _byte(rgb[1], f"{label} green") + rec[6] = _byte(rgb[2], f"{label} blue") + rec[7] = _byte(pad.get("led"), f"{label} led") + rec[8:8 + len(tail)] = tail + return bytes(rec) diff --git a/padeditor/server.py b/padeditor/server.py new file mode 100644 index 0000000..7bed31d --- /dev/null +++ b/padeditor/server.py @@ -0,0 +1,195 @@ +"""Local editor: load the SMC-PAD preset, edit it, save it back.""" + +from __future__ import annotations + +import json +import mimetypes +import threading +import traceback +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import urlparse + +from padeditor.device import Link, PadError, connected, read_global, read_image, save_image, write_colour +from padeditor.preset import IMAGE_LEN, PresetError, pack, pack_global, unpack, unpack_global + +STATIC_DIR = Path(__file__).parent / "static" + + +class ApiError(Exception): + def __init__(self, message: str, status: int = 400): + super().__init__(message) + self.status = status + + +class Editor: + def __init__(self): + self.lock = threading.Lock() + + def status(self) -> dict: + port = connected() + return {"connected": port is not None, "port": port} + + def load(self) -> dict: + with self.lock: + try: + with Link() as link: + document = unpack(read_image(link)) + document["global"] = unpack_global(read_global(link)) + return document + except PadError as exc: + raise ApiError(str(exc), 503) from exc + + def save(self, document: dict) -> dict: + try: + desired = pack(document) + block = document.get("global") + settings = pack_global(block) if isinstance(block, dict) else None + except PresetError as exc: + raise ApiError(str(exc)) from exc + with self.lock: + try: + written = save_image(desired, settings=settings) + except PadError as exc: + raise ApiError(str(exc), 503) from exc + if written: + message = f"Saved on the pad. {written} bytes written." + else: + message = "Saved on the pad." + return {"ok": True, "message": message, "bytes": written} + + def colour(self, body: dict) -> dict: + try: + preset = int(body["preset"]) + index = int(body["index"]) + rgb = body["rgb"] + if not isinstance(rgb, list) or len(rgb) != 3: + raise PresetError("a pad colour needs red, green, and blue") + except (KeyError, TypeError, ValueError) as exc: + raise ApiError("colour needs a preset, a pad, and an rgb colour") from exc + with self.lock: + try: + offset = write_colour(preset, index, rgb) + except PresetError as exc: + raise ApiError(str(exc)) from exc + except PadError as exc: + raise ApiError(str(exc), 503) from exc + return {"ok": True, "offset": offset} + + def imported(self, raw: bytes) -> dict: + try: + return unpack(raw) + except PresetError as exc: + raise ApiError(str(exc)) from exc + + def exported(self, document: dict) -> bytes: + try: + return pack(document) + except PresetError as exc: + raise ApiError(str(exc)) from exc + + +def make_server(host: str = "127.0.0.1", port: int = 8770) -> ThreadingHTTPServer: + editor = Editor() + handler = type("BoundHandler", (Handler,), {"editor": editor}) + server = ThreadingHTTPServer((host, port), handler) + server.editor = editor # type: ignore[attr-defined] + return server + + +class Handler(BaseHTTPRequestHandler): + editor: Editor + + def log_message(self, fmt: str, *args) -> None: + return + + def _json(self, status: int, body: dict) -> None: + raw = json.dumps(body).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(raw))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(raw) + + def _bytes(self, raw: bytes, content_type: str, filename: str | None = None) -> None: + self.send_response(200) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(raw))) + self.send_header("Cache-Control", "no-store") + if filename: + self.send_header("Content-Disposition", f'attachment; filename="{filename}"') + self.end_headers() + self.wfile.write(raw) + + def _read(self) -> bytes: + n = int(self.headers.get("Content-Length") or 0) + return self.rfile.read(n) if n > 0 else b"" + + def _json_body(self) -> dict: + raw = self._read() + if not raw: + return {} + try: + body = json.loads(raw.decode("utf-8")) + except json.JSONDecodeError as exc: + raise ApiError(f"invalid JSON: {exc}") from exc + if not isinstance(body, dict): + raise ApiError("expected a JSON object") + return body + + def _static(self, rel: str) -> None: + rel = rel.lstrip("/") or "index.html" + path = (STATIC_DIR / rel).resolve() + if STATIC_DIR.resolve() not in path.parents or not path.is_file(): + self.send_error(404) + return + ctype = mimetypes.guess_type(path.name)[0] or "application/octet-stream" + if ctype.startswith("text/") or ctype.endswith(("javascript", "json")): + ctype = f"{ctype}; charset=utf-8" + self._bytes(path.read_bytes(), ctype) + + def _dispatch(self, method: str) -> None: + url = urlparse(self.path) + editor = self.editor + try: + if not url.path.startswith("/api/"): + if method != "GET": + self.send_error(405) + return + if url.path == "/favicon.ico": + self.send_response(204) + self.send_header("Content-Length", "0") + self.end_headers() + return + self._static(url.path) + return + route = (method, url.path) + if route == ("GET", "/api/status"): + self._json(200, editor.status()) + elif route == ("POST", "/api/load"): + self._json(200, editor.load()) + elif route == ("POST", "/api/save"): + self._json(200, editor.save(self._json_body())) + elif route == ("POST", "/api/colour"): + self._json(200, editor.colour(self._json_body())) + elif route == ("POST", "/api/import"): + raw = self._read() + if len(raw) != IMAGE_LEN: + raise ApiError(f"preset file is {len(raw)} bytes, expected {IMAGE_LEN}") + self._json(200, editor.imported(raw)) + elif route == ("POST", "/api/export"): + self._bytes(editor.exported(self._json_body()), "application/octet-stream", "smc-pad-preset.bin") + else: + self._json(404, {"error": f"no route {method} {url.path}"}) + except ApiError as exc: + self._json(exc.status, {"error": str(exc)}) + except Exception as exc: # noqa: BLE001 — surface anything else to the UI + traceback.print_exc() + self._json(500, {"error": f"{type(exc).__name__}: {exc}"}) + + def do_GET(self) -> None: # noqa: N802 + self._dispatch("GET") + + def do_POST(self) -> None: # noqa: N802 + self._dispatch("POST") diff --git a/padeditor/static/app.js b/padeditor/static/app.js new file mode 100644 index 0000000..a09a44e --- /dev/null +++ b/padeditor/static/app.js @@ -0,0 +1,441 @@ +const PAGE = 16; +const state = { + doc: null, + saved: null, + preset: 0, + page: 2, + bank: 0, + kind: null, + index: 0, +}; + +const $ = (id) => document.getElementById(id); + +// Colours are stored as the picker gives them, 0–255, as MidiSuite writes them. +function cssColour(rgb) { + return `rgb(${rgb.join(",")})`; +} + +function ink(rgb) { + const [r, g, b] = rgb; + return (r * 0.3 + g * 0.59 + b * 0.11) > 150 ? "#111" : "#f4f6fb"; +} + +function hexColour(rgb) { + return `#${rgb.map((part) => part.toString(16).padStart(2, "0")).join("")}`; +} + +function setStatus(text, kind) { + const node = $("status"); + node.textContent = text; + node.className = kind || ""; +} + +function dirty() { + return state.doc !== null && JSON.stringify(state.doc) !== state.saved; +} + +function preset() { + return state.doc.presets[state.preset]; +} + +function selected() { + if (!state.doc || !state.kind) return null; + const block = preset(); + if (state.kind === "pad") return block.pads[state.page * PAGE + state.index]; + if (state.kind === "knob") return block.knobs[state.bank * 8 + state.index]; + return block.buttons[state.index]; +} + +function typeChoices(kind, current) { + const known = (state.doc.types && state.doc.types[kind]) || []; + const options = known.map((item) => ({ value: item.value, name: item.name })); + if (!options.some((item) => item.value === current)) { + const hex = current.toString(16).padStart(2, "0"); + options.push({ value: current, name: `0x${hex}` }); + } + return options; +} + +async function request(url, options) { + const response = await fetch(url, options); + const type = response.headers.get("Content-Type") || ""; + if (type.includes("application/json")) { + const body = await response.json(); + if (!response.ok) throw new Error(body.error || response.statusText); + return body; + } + if (!response.ok) throw new Error(response.statusText); + return response.blob(); +} + +function mark() { + const unsaved = dirty(); + $("save").disabled = !state.doc; + $("export").disabled = !state.doc; + $("save").classList.toggle("dirty", unsaved); + return unsaved; +} + +function touch() { + if (mark()) setStatus("Not saved on the pad.", "dirty"); + else setStatus("No unsaved edits.", "ok"); +} + +function showEmpty(text, kind) { + const node = $("empty"); + node.hidden = false; + node.textContent = text; + node.className = kind || ""; + $("board").classList.remove("ready"); +} + +async function load(manual) { + if (manual && dirty() && !window.confirm("Load from the pad and drop these edits?")) return; + setStatus("Loading the pad…"); + showEmpty("Loading the pad…"); + try { + state.doc = await request("/api/load", { method: "POST" }); + state.saved = JSON.stringify(state.doc); + render(); + setStatus("Loaded from the pad.", "ok"); + } catch (error) { + setStatus(error.message, "err"); + showEmpty(error.message, "err"); + } +} + +async function save() { + if (!state.doc) return; + setStatus("Saving…"); + $("save").disabled = true; + try { + const body = await request("/api/save", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(state.doc), + }); + state.saved = JSON.stringify(state.doc); + setStatus(body.message, "ok"); + } catch (error) { + setStatus(error.message, "err"); + } + mark(); +} + +async function exportFile() { + if (!state.doc) return; + try { + const blob = await request("/api/export", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(state.doc), + }); + const url = URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + link.download = "smc-pad-preset.bin"; + link.click(); + URL.revokeObjectURL(url); + } catch (error) { + setStatus(error.message, "err"); + } +} + +async function importFile(file) { + setStatus("Reading file…"); + try { + const raw = new Uint8Array(await file.arrayBuffer()); + state.doc = await request("/api/import", { + method: "POST", + headers: { "Content-Type": "application/octet-stream" }, + body: raw, + }); + render(); + setStatus("Imported. Save to pad to store it.", "dirty"); + } catch (error) { + setStatus(error.message, "err"); + } +} + +function render() { + if (!state.doc) return; + $("board").classList.add("ready"); + renderGlobal(); + renderPresets(); + renderPages(); + renderPads(); + renderKnobs(); + renderButtons(); + renderInspector(); + mark(); +} + +function renderGlobal() { + const row = $("global"); + row.replaceChildren(); + const block = state.doc.global; + if (!block) return; + const fields = [ + ["Tempo", "tempo", 1, 999], + ["Swing", "swing", 0, 255], + ["Pad curve", "curve", 0, 255], + ["Transpose", "transpose", -128, 127], + ]; + for (const [label, key, min, max] of fields) { + row.append(field(label, numberInput(block, key, min, max))); + } +} + +function renderPresets() { + const row = $("presets"); + row.replaceChildren(); + state.doc.presets.forEach((_preset, index) => { + const button = document.createElement("button"); + button.type = "button"; + button.textContent = String(index + 1); + button.classList.toggle("selected", index === state.preset); + button.addEventListener("click", () => { + state.preset = index; + render(); + }); + row.append(button); + }); +} + +function renderPages() { + const select = $("page"); + const current = select.value; + select.replaceChildren(); + const order = [2, 3, 0, 1, 4, 5, 6, 7]; + const names = { 2: "Bank 1", 3: "Bank 2" }; + for (const page of order) { + const pads = preset().pads.slice(page * PAGE, page * PAGE + PAGE); + const option = document.createElement("option"); + option.value = String(page); + const name = names[page] || `Page ${page + 1}`; + option.textContent = `${name} · notes ${pads[0].note}–${pads[PAGE - 1].note}`; + select.append(option); + } + select.value = current || String(state.page); + state.page = Number(select.value); + const pads = preset().pads.slice(state.page * PAGE, state.page * PAGE + PAGE); + $("page-notes").textContent = `notes ${pads[0].note}–${pads[PAGE - 1].note}`; +} + +function paint(node, rgb) { + node.style.background = cssColour(rgb); + node.style.color = ink(rgb); +} + +function renderPads() { + const grid = $("pads"); + grid.replaceChildren(); + const pads = preset().pads; + for (let row = 3; row >= 0; row -= 1) { + for (let col = 0; col < 4; col += 1) { + const index = row * 4 + col; + const pad = pads[state.page * PAGE + index]; + const button = document.createElement("button"); + button.type = "button"; + button.className = "pad"; + button.textContent = String(index + 1); + paint(button, pad.rgb); + button.style.opacity = pad.led ? "" : "0.35"; + button.classList.toggle("selected", state.kind === "pad" && state.index === index); + button.addEventListener("click", () => select("pad", index)); + grid.append(button); + } + } +} + +function renderKnobs() { + const row = $("knobs"); + row.replaceChildren(); + for (let index = 0; index < 8; index += 1) { + const knob = preset().knobs[state.bank * 8 + index]; + const button = document.createElement("button"); + button.type = "button"; + button.className = "knob"; + button.textContent = String(state.bank * 8 + index + 1); + button.title = `CC ${knob.number}`; + button.classList.toggle("selected", state.kind === "knob" && state.index === index); + button.addEventListener("click", () => select("knob", index)); + row.append(button); + } +} + +function renderButtons() { + const row = $("buttons"); + row.replaceChildren(); + preset().buttons.forEach((button, index) => { + const node = document.createElement("button"); + node.type = "button"; + node.className = "btn"; + node.textContent = button.name; + node.classList.toggle("selected", state.kind === "button" && state.index === index); + node.addEventListener("click", () => select("button", index)); + row.append(node); + }); +} + +let colourTimer = 0; + +function paintColour(index, rgb) { + const edited = state.preset; + preset().pads[index].rgb = rgb.slice(); + renderPads(); + window.clearTimeout(colourTimer); + colourTimer = window.setTimeout(() => sendColour(edited, index, rgb), 180); +} + +async function sendColour(preset, index, rgb) { + try { + await request("/api/colour", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ preset, index, rgb }), + }); + } catch (error) { + setStatus(error.message, "err"); + } +} + +function select(kind, index) { + state.kind = kind; + state.index = index; + render(); +} + +function field(label, node) { + const wrap = document.createElement("label"); + wrap.className = "field"; + wrap.append(label, node); + return wrap; +} + +function numberInput(item, key, min, max) { + const input = document.createElement("input"); + input.type = "number"; + input.min = String(min); + input.max = String(max); + input.value = String(item[key]); + input.addEventListener("input", () => { + const value = Number(input.value); + if (!Number.isInteger(value) || value < min || value > max) return; + item[key] = value; + if (key === "led") renderPads(); + if (key === "note") { + const pads = preset().pads.slice(state.page * PAGE, state.page * PAGE + PAGE); + $("page-notes").textContent = `notes ${pads[0].note}–${pads[PAGE - 1].note}`; + } + touch(); + }); + return input; +} + +function renderInspector() { + const aside = $("inspector"); + const item = selected(); + aside.replaceChildren(); + const title = document.createElement("h2"); + if (!item) { + title.textContent = "Control"; + const note = document.createElement("p"); + note.className = "muted"; + note.textContent = "Pick a pad, knob, or button."; + aside.append(title, note); + return; + } + if (state.kind === "pad") title.textContent = `Pad ${state.index + 1}`; + else if (state.kind === "knob") title.textContent = `Knob ${state.bank * 8 + state.index + 1}`; + else title.textContent = item.name; + aside.append(title); + + if (state.kind !== "pad") { + const type = document.createElement("select"); + typeChoices(state.kind, item.type).forEach((option) => { + const node = document.createElement("option"); + node.value = String(option.value); + node.textContent = option.name; + node.selected = option.value === item.type; + type.append(node); + }); + type.addEventListener("change", () => { + item.type = Number(type.value); + touch(); + }); + aside.append(field(state.kind === "button" ? "Mode" : "Type", type)); + } + aside.append(field("Channel", numberInput(item, "channel", 1, 16))); + + if (state.kind === "pad") { + aside.append(field("Note", numberInput(item, "note", 0, 127))); + aside.append(field("Min velocity", numberInput(item, "min", 0, 127))); + aside.append(field("Max velocity", numberInput(item, "max", 0, 127))); + const colour = document.createElement("input"); + colour.type = "color"; + colour.value = hexColour(item.rgb); + colour.addEventListener("input", () => { + const hex = colour.value; + const rgb = [1, 3, 5].map((at) => parseInt(hex.slice(at, at + 2), 16)); + paintColour(state.page * PAGE + state.index, rgb); + touch(); + }); + aside.append(field("Colour", colour)); + aside.append(field("Led", numberInput(item, "led", 0, 255))); + } else if (state.kind === "knob") { + aside.append(field("CC", numberInput(item, "number", 0, 127))); + aside.append(field("Speed", numberInput(item, "speed", 0, 127))); + aside.append(field("Min", numberInput(item, "left", 0, 127))); + aside.append(field("Max", numberInput(item, "right", 0, 127))); + if (state.doc.relative) { + const hint = document.createElement("p"); + hint.className = "hint"; + hint.textContent = "Relative sends the left value one way and the right value the other."; + aside.append(hint); + } + } else { + aside.append(field("CC", numberInput(item, "number", 0, 127))); + aside.append(field("Value 1", numberInput(item, "min", 0, 127))); + aside.append(field("Value 2", numberInput(item, "max", 0, 127))); + aside.append(field("Led", numberInput(item, "led", 0, 255))); + const sysex = document.createElement("input"); + sysex.type = "text"; + sysex.value = item.sysex; + sysex.spellcheck = false; + sysex.addEventListener("input", () => { + const hex = sysex.value.replace(/\s+/g, "").toLowerCase(); + if (hex.length % 2 || /[^0-9a-f]/.test(hex) || hex.length > 32) return; + item.sysex = hex; + touch(); + }); + aside.append(field("SysEx", sysex)); + } + + const hint = document.createElement("p"); + hint.className = "hint"; + hint.textContent = "A pad colour lights the lamp as you pick it. Save keeps every edit after a power cycle."; + aside.append(hint); +} + +$("load").addEventListener("click", () => load(true)); +$("save").addEventListener("click", save); +$("export").addEventListener("click", exportFile); +$("import").addEventListener("change", () => { + const file = $("import").files[0]; + $("import").value = ""; + if (file) importFile(file); +}); +$("page").addEventListener("change", () => { + state.page = Number($("page").value); + state.kind = state.kind === "pad" ? null : state.kind; + render(); +}); +$("bank").addEventListener("change", () => { + state.bank = Number($("bank").value); + state.kind = state.kind === "knob" ? null : state.kind; + render(); +}); + +load(false); diff --git a/padeditor/static/index.html b/padeditor/static/index.html new file mode 100644 index 0000000..8000bcb --- /dev/null +++ b/padeditor/static/index.html @@ -0,0 +1,45 @@ + + + + + +SMC-PAD editor + + + +
+

SMC-PAD

+ + + + + + Load the preset from the pad. +
+
+
+

Loading the pad…

+
+
+
+ + + +
+
+
+
+
+ +
+ + + diff --git a/padeditor/static/style.css b/padeditor/static/style.css new file mode 100644 index 0000000..de8e7dc --- /dev/null +++ b/padeditor/static/style.css @@ -0,0 +1,102 @@ +:root { + --bg: #15171c; + --panel: #1e2129; + --panel-2: #262a34; + --line: #343946; + --text: #e6e8ee; + --muted: #8d94a6; + --accent: #5aa9ff; + --danger: #ff6b6b; + --ok: #52d273; +} + +* { box-sizing: border-box; } +html, body { height: 100%; margin: 0; } +body { + background: var(--bg); + color: var(--text); + font: 13px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + display: flex; + flex-direction: column; +} + +header { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 14px; + background: var(--panel); + border-bottom: 1px solid var(--line); +} +header h1 { font-size: 15px; margin: 0 8px 0 0; } +.spacer { flex: 1; } +#status { color: var(--muted); max-width: 46ch; } +#status.err { color: var(--danger); } +#status.ok { color: var(--ok); } +#status.dirty { color: var(--accent); } + +button, select, input[type="number"], input[type="text"] { + background: var(--panel-2); + color: var(--text); + border: 1px solid var(--line); + border-radius: 6px; + padding: 6px 10px; + font: inherit; +} +button { cursor: pointer; } +button:disabled { opacity: 0.45; cursor: default; } +button.primary { background: #245a9e; border-color: #3d7dcc; } +button.primary.dirty { background: #1e6b38; border-color: var(--ok); } +button.selected, .pad.selected, .knob.selected, .btn.selected { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +label.file { color: var(--muted); } +label.file input { display: none; } +label.file { cursor: pointer; border: 1px solid var(--line); border-radius: 6px; padding: 6px 10px; background: var(--panel-2); color: var(--text); } + +main { display: flex; min-height: 0; flex: 1; } +#empty { color: var(--muted); margin: 48px 0; } +#empty.err { color: var(--danger); } +#board.ready #empty { display: none; } +#board, #inspector { padding: 16px; } +#board { flex: 1; } +#inspector { + width: 320px; + background: var(--panel); + border-left: 1px solid var(--line); + overflow: auto; +} +#inspector h2 { margin: 0 0 12px; font-size: 15px; } +.muted { color: var(--muted); } +.row { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; flex-wrap: wrap; } +.row label { display: flex; align-items: center; gap: 6px; color: var(--muted); } + +#presets { gap: 6px; } +#pads { + display: grid; + grid-template-columns: repeat(4, 76px); + gap: 8px; + margin: 8px 0 18px; +} +.pad, .knob, .btn { + border: 1px solid #0008; + color: #111; + font-weight: 650; + text-align: center; +} +.pad { height: 64px; border-radius: 8px; } +.knob { + width: 64px; + height: 64px; + border-radius: 50%; + background: #d7dbe6; +} +#knobs, #buttons { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 14px; } +.btn { min-width: 72px; height: 36px; border-radius: 6px; background: #c9ceda; } +.field { display: flex; flex-direction: column; gap: 4px; margin-bottom: 10px; color: var(--muted); } +.field input, .field select { width: 100%; } +.hint { color: var(--muted); margin-top: 8px; } +#global .field { margin-bottom: 0; } +#global input { width: 90px; } diff --git a/padeditor/sysex.py b/padeditor/sysex.py new file mode 100644 index 0000000..d24da7c --- /dev/null +++ b/padeditor/sysex.py @@ -0,0 +1,81 @@ +"""SINCO / M-VAVE SysEx codec used by MidiSuite and the SMC-PAD.""" + +from __future__ import annotations + +MEM_GLOBAL = 4 +MEM_PRESET = 5 +CMD_ACK = 0x00 +CMD_WRITE = 0x22 +CMD_READ = 0x23 +RAM = 0x80000000 + + +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, memory: int = MEM_PRESET) -> list[int]: + payload = bytes([memory]) + address.to_bytes(4, "little") + size.to_bytes(3, "little") + return frame(CMD_READ, payload) + + +def write_request(address: int, data: bytes, memory: int = MEM_PRESET) -> list[int]: + payload = bytes([memory]) + address.to_bytes(4, "little") + len(data).to_bytes(3, "little") + data + return frame(CMD_WRITE, payload) + + +def save_request() -> list[int]: + """Commit the running preset. MidiSuite's Save is this empty write.""" + return write_request(0, b"") + + +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:] diff --git a/scripts/decode_usbmon.py b/scripts/decode_usbmon.py new file mode 100644 index 0000000..00f60de --- /dev/null +++ b/scripts/decode_usbmon.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Print the SMC-PAD SysEx in a usbmon capture. + + sudo tcpdump -i usbmon1 -s 0 -U -w - > pad.pcap + python3 scripts/decode_usbmon.py pad.pcap --device 21 + +Each USB-MIDI packet is reassembled into messages per cable, then SINCO +SysEx is decoded to its command, memory, address, and data. +""" + +from __future__ import annotations + +import argparse +import struct +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from padeditor.sysex import decode # noqa: E402 + +LINKTYPE_USB_LINUX_MMAPPED = 220 +HEADER = struct.Struct("> 4 + if head == 0: + continue + body = data[at + 1:at + 1 + CIN_SIZE.get(cin, 0)] + key = (direction, cable) + if cin in (0x4, 0x5, 0x6, 0x7) or (pending.get(key) and cin == 0xF): + buf = pending.setdefault(key, bytearray()) + buf += body + if cin != 0x4 and buf.endswith(b"\xf7"): + yield stamp, direction, cable, bytes(buf) + del pending[key] + else: + yield stamp, direction, cable, bytes(body) + + +def describe(message: bytes) -> str: + if message[:1] != b"\xf0" or message[-1:] != b"\xf7": + return message.hex(" ") + inner = decode(message[1:-1]) + if inner[:2] != b"\x00\x59" or len(inner) < 7: + return f"sysex {inner.hex(' ')}" + command = COMMANDS.get(inner[2], f"cmd {inner[2]:#04x}") + length = int.from_bytes(inner[3:6], "little") + payload = inner[6:6 + length] + if inner[2] in (0x22, 0x23) and len(payload) >= 8: + memory = payload[0] + address = int.from_bytes(payload[1:5], "little") + size = int.from_bytes(payload[5:8], "little") + data = payload[8:] + text = f"{command} mem {memory} addr {address:#010x} len {size}" + return f"{text} data {data.hex()}" if data else text + return f"{command} {payload.hex(' ')}" + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("capture", type=Path) + parser.add_argument("--device", type=int, help="USB device number from lsusb") + args = parser.parse_args(argv) + start = None + for stamp, direction, cable, message in messages(args.capture, args.device): + start = stamp if start is None else start + print(f"{stamp - start:8.3f} {direction} cable {cable} {describe(message)}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/data/smc_pad_factory.bin b/tests/data/smc_pad_factory.bin new file mode 100644 index 0000000..cb743c8 Binary files /dev/null and b/tests/data/smc_pad_factory.bin differ diff --git a/tests/test_padeditor.py b/tests/test_padeditor.py new file mode 100644 index 0000000..5c75372 --- /dev/null +++ b/tests/test_padeditor.py @@ -0,0 +1,171 @@ +"""Preset image round-trip: factory knob and note-36 pad stay put.""" + +from __future__ import annotations + +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from padeditor.preset import ( # noqa: E402 + GAP_AT, + IMAGE_LEN, + KNOB_AT, + PAD_AT, + PAD_LEN, + PRESET_LEN, + changed_ranges, + pack, + scale, + unpack, +) +from padeditor.sysex import decode, encode # noqa: E402 + +FACTORY_KNOB = bytes.fromhex("0002001e007f") + + +def _image() -> bytearray: + raw = bytearray(IMAGE_LEN) + raw[KNOB_AT:KNOB_AT + len(FACTORY_KNOB)] = FACTORY_KNOB + raw[GAP_AT] = 0x5A + # Note 36 is pad record 32: channel 10, note, min and max velocity, + # RGB, then Led, as MidiSuite shows PAD1. + pad = PAD_AT + 32 * PAD_LEN + assert pad == 1044 + raw[pad:pad + 8] = bytes((0x09, 36, 0, 0x7F, 0xF0, 0x00, 0x00, 0xFF)) + raw[pad + 8] = 0xAB + # Last pad of preset 0 is one byte short of a full record. + last = PAD_AT + 127 * PAD_LEN + raw[last] = 0x09 + raw[last + 1] = 67 + raw[PRESET_LEN - 1] = 0x11 + # A button with a sysex payload and a flag, matching the factory shape. + raw[0:23] = bytes.fromhex("020019007f06f07f7f0601f700000000000000000000ff") + return raw + + +def test_codec_vector_lives_with_the_editor(): + inner = bytes.fromhex("00592209000005000000800100000178") + wire = bytes([0xF0, *encode(inner), 0xF7]) + assert wire == bytes.fromhex("f000320949000040020000000018000000017001f7") + assert decode(wire[1:-1]) == inner + + +def test_factory_knob_and_note_36_pad(): + raw = bytes(_image()) + assert raw[KNOB_AT:KNOB_AT + 6] == FACTORY_KNOB + assert raw[1044:1046] == bytes((0x09, 36)) + assert raw[1048:1051] == bytes.fromhex("f00000") + + doc = unpack(raw) + knob = doc["presets"][0]["knobs"][0] + assert knob == {"type": 0, "speed": 2, "channel": 1, "number": 30, "left": 0, "right": 127} + pad = doc["presets"][0]["pads"][32] + assert pad["note"] == 36 + assert pad["channel"] == 10 + assert (pad["min"], pad["max"]) == (0, 127) + assert pad["rgb"] == [0xF0, 0x00, 0x00] + assert pad["led"] == 0xFF + assert doc["presets"][0]["gap"] == 0x5A + assert doc["presets"][0]["buttons"][0]["name"] == "Left" + assert doc["presets"][0]["buttons"][0]["sysex"] == "f07f7f0601f7" + assert pack(doc) == raw + + +def test_an_edit_dirties_only_that_byte(): + raw = bytes(_image()) + doc = unpack(raw) + doc["presets"][0]["knobs"][0]["number"] = 31 + edited = pack(doc) + assert changed_ranges(raw, edited) == [(KNOB_AT + 3, b"\x1f")] + assert edited[GAP_AT] == 0x5A + assert edited[1048:1051] == raw[1048:1051] + at = KNOB_AT + 3 + assert edited[:at] + edited[at + 1:] == raw[:at] + raw[at + 1:] + + +def test_a_colour_is_one_write_like_midisuite(monkeypatch): + from padeditor import device + from padeditor.preset import colour_offset + + # MidiSuite set preset 5 record 21 green with one write to 0x3a46. + assert colour_offset(4, 21) == 0x3A46 + writes = [] + + class FakeLink: + def __enter__(self): + return self + + def __exit__(self, *exc): + pass + + monkeypatch.setattr(device, "Link", FakeLink) + monkeypatch.setattr(device, "_write_checked", lambda link, address, data: writes.append((address, data))) + device.write_colour(4, 21, [0, 0xFF, 0]) + assert writes == [(0x3A46, b"\x00\xff\x00")] + + +def test_global_block_matches_midisuite(): + from padeditor.preset import pack_global, unpack_global + + factory = bytes.fromhex("780032040000020001010000") + block = unpack_global(factory) + assert (block["tempo"], block["swing"], block["curve"], block["transpose"]) == (120, 50, 2, 0) + assert pack_global(block) == factory + assert unpack_global(bytes.fromhex("77003204000001f601010400"))["transpose"] == -10 + block["transpose"] = -10 + block["tempo"] = 119 + assert pack_global(block) == bytes.fromhex("770032040000 02f6 01010000".replace(" ", "")) + + +def test_colour_scale_matches_the_pad_lamps(): + assert scale(0) == 0 + assert scale(255) == 0xF0 + assert scale(127) == 0x78 + + +def test_a_step_is_relative_and_a_ramp_is_absolute(): + from padeditor.device import _classify + + assert _classify([]) == "silent" + assert _classify([(0, 45, 1), (0, 45, 127)]) == "relative" + assert _classify([(0, 45, value) for value in range(10, 20)]) == "absolute" + + +def test_export_packs_the_image_without_opening_midi(): + from padeditor.server import ApiError, Editor + + raw = bytes(_image()) + assert Editor().exported(unpack(raw)) == raw + try: + Editor().save({"presets": []}) + except ApiError as exc: + assert "8" in str(exc) + else: + raise AssertionError("a short preset list should be refused before any MIDI") + + +def test_last_pad_keeps_its_short_tail(): + raw = bytes(_image()) + doc = unpack(raw) + tail = doc["presets"][0]["pads"][127]["tail"] + assert len(bytes.fromhex(tail)) == 17 + assert pack(doc)[PRESET_LEN - 1] == 0x11 + + +def test_factory_image_reads_as_midisuite_shows_it(): + # Captured from MidiSuite's Reset with scripts/decode_usbmon.py. + raw = (ROOT / "tests" / "data" / "smc_pad_factory.bin").read_bytes() + doc = unpack(raw) + assert pack(doc) == raw + first = doc["presets"][0] + # PAD4, bottom right of the PAD1–PAD16 grid: Note 39, Channel 10, 0–127, Led 255. + pad4 = first["pads"][2 * 16 + 3] + assert (pad4["note"], pad4["channel"], pad4["min"], pad4["max"], pad4["led"]) == (39, 10, 0, 127, 255) + # The [<] button: CC Push, Channel 1, CC 25, 0–127, Led 255. + left = first["buttons"][0] + assert (left["type"], left["channel"], left["number"], left["min"], left["max"], left["led"]) == (2, 1, 25, 0, 127, 255) + # Knob 6: CC, Channel 1, CC 35, 0–127. + knob6 = first["knobs"][5] + assert (knob6["type"], knob6["channel"], knob6["number"], knob6["left"], knob6["right"]) == (0, 1, 35, 0, 127)