|
|
@@ -0,0 +1,357 @@
|
|
|
+#!/usr/bin/env python3
|
|
|
+"""Translate configured MIDI events into safe mod-host actions."""
|
|
|
+
|
|
|
+import argparse
|
|
|
+import socket
|
|
|
+import sys
|
|
|
+import time
|
|
|
+from pathlib import Path, PurePosixPath
|
|
|
+
|
|
|
+import yaml
|
|
|
+
|
|
|
+from validate_desired_state import safe_relative_path, validate_state
|
|
|
+
|
|
|
+
|
|
|
+def load_yaml(path):
|
|
|
+ with path.open(encoding="utf-8") as stream:
|
|
|
+ return yaml.safe_load(stream)
|
|
|
+
|
|
|
+
|
|
|
+def bridge_config(state):
|
|
|
+ return state["controls"]["midi_bridge"]
|
|
|
+
|
|
|
+
|
|
|
+def resolve_processor(state, target):
|
|
|
+ chain_id = target["chain"]
|
|
|
+ processor_id = target["processor"]
|
|
|
+ chain = state["routing"]["mod_host_chains"].get(chain_id)
|
|
|
+ if not isinstance(chain, dict):
|
|
|
+ raise ValueError(f"unknown mod-host chain in MIDI action: {chain_id}")
|
|
|
+ processors = chain.get("processors")
|
|
|
+ if not isinstance(processors, list):
|
|
|
+ raise ValueError(f"mod-host chain has no processor list: {chain_id}")
|
|
|
+ matches = [
|
|
|
+ processor for processor in processors
|
|
|
+ if isinstance(processor, dict) and processor.get("id") == processor_id
|
|
|
+ ]
|
|
|
+ if len(matches) != 1:
|
|
|
+ raise ValueError(
|
|
|
+ f"MIDI action target must identify exactly one processor: "
|
|
|
+ f"{chain_id}.{processor_id}"
|
|
|
+ )
|
|
|
+ return matches[0]
|
|
|
+
|
|
|
+
|
|
|
+def validate_bindings(bindings, state):
|
|
|
+ errors = []
|
|
|
+ if not isinstance(bindings, dict):
|
|
|
+ return ["MIDI bindings document root must be a mapping"]
|
|
|
+ if bindings.get("schema_version") != 1:
|
|
|
+ errors.append("MIDI bindings schema_version must be 1")
|
|
|
+ entries = bindings.get("bindings")
|
|
|
+ if not isinstance(entries, list):
|
|
|
+ return errors + ["MIDI bindings must contain a bindings list"]
|
|
|
+
|
|
|
+ binding_ids = set()
|
|
|
+ events = set()
|
|
|
+ for index, binding in enumerate(entries):
|
|
|
+ location = f"bindings[{index}]"
|
|
|
+ if not isinstance(binding, dict):
|
|
|
+ errors.append(f"{location} must be a mapping")
|
|
|
+ continue
|
|
|
+
|
|
|
+ binding_id = binding.get("id")
|
|
|
+ if not isinstance(binding_id, str) or not binding_id:
|
|
|
+ errors.append(f"{location}.id must be a non-empty string")
|
|
|
+ elif binding_id in binding_ids:
|
|
|
+ errors.append(f"duplicate MIDI binding id: {binding_id}")
|
|
|
+ else:
|
|
|
+ binding_ids.add(binding_id)
|
|
|
+
|
|
|
+ event = binding.get("event")
|
|
|
+ if not isinstance(event, dict):
|
|
|
+ errors.append(f"{location}.event must be a mapping")
|
|
|
+ continue
|
|
|
+ if event.get("type") != "note_on":
|
|
|
+ errors.append(f"{location}.event.type must be note_on")
|
|
|
+ continue
|
|
|
+ channel = event.get("channel")
|
|
|
+ note = event.get("note")
|
|
|
+ if not isinstance(channel, int) or isinstance(channel, bool) or channel not in range(16):
|
|
|
+ errors.append(f"{location}.event.channel must be an integer from 0 through 15")
|
|
|
+ if not isinstance(note, int) or isinstance(note, bool) or note not in range(128):
|
|
|
+ errors.append(f"{location}.event.note must be an integer from 0 through 127")
|
|
|
+ if (
|
|
|
+ isinstance(channel, int)
|
|
|
+ and not isinstance(channel, bool)
|
|
|
+ and channel in range(16)
|
|
|
+ and isinstance(note, int)
|
|
|
+ and not isinstance(note, bool)
|
|
|
+ and note in range(128)
|
|
|
+ ):
|
|
|
+ event_key = (channel, note)
|
|
|
+ if event_key in events:
|
|
|
+ errors.append(f"duplicate MIDI note binding on channel {channel}, note {note}")
|
|
|
+ events.add(event_key)
|
|
|
+
|
|
|
+ action = binding.get("action")
|
|
|
+ if not isinstance(action, dict):
|
|
|
+ errors.append(f"{location}.action must be a mapping")
|
|
|
+ continue
|
|
|
+ if action.get("type") != "select_nam_model":
|
|
|
+ errors.append(f"{location}.action.type must be select_nam_model")
|
|
|
+ continue
|
|
|
+ target = action.get("target")
|
|
|
+ if not isinstance(target, dict) or set(target) != {"chain", "processor"}:
|
|
|
+ errors.append(f"{location}.action.target must declare chain and processor")
|
|
|
+ continue
|
|
|
+ try:
|
|
|
+ processor = resolve_processor(state, target)
|
|
|
+ except (KeyError, TypeError, ValueError) as error:
|
|
|
+ errors.append(f"{location}.action.target: {error}")
|
|
|
+ continue
|
|
|
+ if processor.get("plugin_uri") != "http://github.com/mikeoliphant/neural-amp-modeler-lv2":
|
|
|
+ errors.append(f"{location}.action target is not a NAM processor")
|
|
|
+ continue
|
|
|
+ models = processor.get("available_models")
|
|
|
+ if not isinstance(models, dict) or not models:
|
|
|
+ errors.append(f"{location}.action target has no available_models")
|
|
|
+ continue
|
|
|
+ for model_field in ("model", "fallback_model"):
|
|
|
+ model_id = action.get(model_field)
|
|
|
+ if not isinstance(model_id, str) or model_id not in models:
|
|
|
+ errors.append(
|
|
|
+ f"{location}.action.{model_field} must name a model declared on its target"
|
|
|
+ )
|
|
|
+
|
|
|
+ return errors
|
|
|
+
|
|
|
+
|
|
|
+def load_configuration(state_path, bindings_path=None, repo_root=None):
|
|
|
+ state = load_yaml(Path(state_path))
|
|
|
+ state_errors = validate_state(state)
|
|
|
+ if state_errors:
|
|
|
+ raise ValueError("invalid desired state: " + "; ".join(state_errors))
|
|
|
+
|
|
|
+ root = Path(repo_root).resolve() if repo_root is not None else Path(__file__).resolve().parents[1]
|
|
|
+ config = bridge_config(state)
|
|
|
+ declared_bindings = config["bindings_file"]
|
|
|
+ if not safe_relative_path(declared_bindings):
|
|
|
+ raise ValueError("controls.midi_bridge.bindings_file must be a safe relative path")
|
|
|
+ path = Path(bindings_path) if bindings_path is not None else root / declared_bindings
|
|
|
+ bindings = load_yaml(path)
|
|
|
+ binding_errors = validate_bindings(bindings, state)
|
|
|
+ if binding_errors:
|
|
|
+ raise ValueError("invalid MIDI bindings: " + "; ".join(binding_errors))
|
|
|
+ return state, bindings, root
|
|
|
+
|
|
|
+
|
|
|
+def resolve_asset(repo_root, relative_path):
|
|
|
+ if not safe_relative_path(relative_path):
|
|
|
+ raise ValueError(f"unsafe NAM model asset path: {relative_path!r}")
|
|
|
+ relative = PurePosixPath(relative_path)
|
|
|
+ resolved = (repo_root / Path(*relative.parts)).resolve()
|
|
|
+ if not resolved.is_relative_to(repo_root.resolve()):
|
|
|
+ raise ValueError(f"NAM model asset escapes the repository: {resolved}")
|
|
|
+ return resolved
|
|
|
+
|
|
|
+
|
|
|
+def mod_host_command(host, port, command, timeout=5):
|
|
|
+ payload = command.encode("utf-8") + b"\0"
|
|
|
+ with socket.create_connection((host, port), timeout=timeout) as connection:
|
|
|
+ connection.settimeout(timeout)
|
|
|
+ connection.sendall(payload)
|
|
|
+ response = bytearray()
|
|
|
+ while b"\0" not in response:
|
|
|
+ chunk = connection.recv(4096)
|
|
|
+ if not chunk:
|
|
|
+ raise RuntimeError(f"mod-host closed the socket before replying to {command!r}")
|
|
|
+ response.extend(chunk)
|
|
|
+ return bytes(response).split(b"\0", 1)[0].decode("utf-8", errors="replace")
|
|
|
+
|
|
|
+
|
|
|
+def check_mod_host_response(response, command):
|
|
|
+ fields = response.split()
|
|
|
+ if len(fields) < 2 or fields[0] != "resp":
|
|
|
+ raise RuntimeError(f"unexpected mod-host response to {command!r}: {response!r}")
|
|
|
+ try:
|
|
|
+ status = int(fields[1])
|
|
|
+ except ValueError as error:
|
|
|
+ raise RuntimeError(f"invalid mod-host response to {command!r}: {response!r}") from error
|
|
|
+ if status < 0:
|
|
|
+ raise RuntimeError(f"mod-host rejected {command!r}: {response}")
|
|
|
+ return status
|
|
|
+
|
|
|
+
|
|
|
+def select_nam_model(action, state, repo_root, command=mod_host_command):
|
|
|
+ processor = resolve_processor(state, action["target"])
|
|
|
+ models = processor["available_models"]
|
|
|
+ requested_id = action["model"]
|
|
|
+ fallback_id = action["fallback_model"]
|
|
|
+
|
|
|
+ requested_path = resolve_asset(repo_root, models[requested_id])
|
|
|
+ selected_id = requested_id
|
|
|
+ selected_path = requested_path
|
|
|
+ if not requested_path.is_file():
|
|
|
+ selected_id = fallback_id
|
|
|
+ selected_path = resolve_asset(repo_root, models[fallback_id])
|
|
|
+ if not selected_path.is_file():
|
|
|
+ raise FileNotFoundError(
|
|
|
+ f"requested NAM model and fallback are both missing: "
|
|
|
+ f"{requested_path}, {selected_path}"
|
|
|
+ )
|
|
|
+ print(
|
|
|
+ f"WARNING: NAM model {requested_id!r} is missing; "
|
|
|
+ f"using fallback {fallback_id!r} ({selected_path})",
|
|
|
+ file=sys.stderr,
|
|
|
+ )
|
|
|
+
|
|
|
+ host_config = bridge_config(state)["mod_host"]
|
|
|
+ instance = processor["instance"]
|
|
|
+ property_uri = processor["file_property"]
|
|
|
+ command_text = f"patch_set {instance} {property_uri} {selected_path}"
|
|
|
+ response = command(host_config["host"], host_config["port"], command_text)
|
|
|
+ check_mod_host_response(response, command_text)
|
|
|
+ return selected_id, selected_path
|
|
|
+
|
|
|
+
|
|
|
+def binding_index(bindings):
|
|
|
+ return {
|
|
|
+ (entry["event"]["channel"], entry["event"]["note"]): entry
|
|
|
+ for entry in bindings["bindings"]
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+def handle_midi_message(message, bindings, state, repo_root, command=mod_host_command):
|
|
|
+ if not message or len(message) < 3:
|
|
|
+ return None
|
|
|
+ status, note, velocity = message[:3]
|
|
|
+ if (status & 0xF0) != 0x90 or velocity == 0:
|
|
|
+ return None
|
|
|
+
|
|
|
+ channel = status & 0x0F
|
|
|
+ binding = bindings.get((channel, note))
|
|
|
+ if binding is None:
|
|
|
+ return None
|
|
|
+ model_id, model_path = select_nam_model(
|
|
|
+ binding["action"], state, repo_root, command=command
|
|
|
+ )
|
|
|
+ return {
|
|
|
+ "binding": binding["id"],
|
|
|
+ "channel": channel,
|
|
|
+ "note": note,
|
|
|
+ "model": model_id,
|
|
|
+ "path": model_path,
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+def list_midi_ports():
|
|
|
+ try:
|
|
|
+ import rtmidi
|
|
|
+ except ImportError as error:
|
|
|
+ raise RuntimeError(
|
|
|
+ "python-rtmidi is required; install the python3-rtmidi package"
|
|
|
+ ) from error
|
|
|
+ midi_in = rtmidi.MidiIn()
|
|
|
+ ports = midi_in.get_ports()
|
|
|
+ if not ports:
|
|
|
+ print("No ALSA MIDI input ports found.")
|
|
|
+ for index, name in enumerate(ports):
|
|
|
+ print(f"{index}: {name}")
|
|
|
+
|
|
|
+
|
|
|
+def open_midi_input(rtmidi, name_contains):
|
|
|
+ midi_in = rtmidi.MidiIn()
|
|
|
+ ports = midi_in.get_ports()
|
|
|
+ matches = [
|
|
|
+ (index, name) for index, name in enumerate(ports)
|
|
|
+ if name_contains.casefold() in name.casefold()
|
|
|
+ ]
|
|
|
+ if len(matches) != 1:
|
|
|
+ available = ", ".join(ports) if ports else "(none)"
|
|
|
+ raise RuntimeError(
|
|
|
+ f"expected exactly one MIDI input containing {name_contains!r}; "
|
|
|
+ f"found {len(matches)}. Available inputs: {available}"
|
|
|
+ )
|
|
|
+ index, name = matches[0]
|
|
|
+ midi_in.open_port(index, "Rigforge MIDI action bridge")
|
|
|
+ return midi_in, name
|
|
|
+
|
|
|
+
|
|
|
+def run_bridge(state, bindings, repo_root, rtmidi_module=None, sleeper=time.sleep):
|
|
|
+ if rtmidi_module is None:
|
|
|
+ try:
|
|
|
+ import rtmidi as rtmidi_module
|
|
|
+ except ImportError as error:
|
|
|
+ raise RuntimeError(
|
|
|
+ "python-rtmidi is required; install the python3-rtmidi package"
|
|
|
+ ) from error
|
|
|
+
|
|
|
+ config = bridge_config(state)
|
|
|
+ name_contains = config["input_port_name_contains"]
|
|
|
+ actions = binding_index(bindings)
|
|
|
+ print(f"Looking for ALSA MIDI input containing {name_contains!r}…")
|
|
|
+ while True:
|
|
|
+ midi_in = None
|
|
|
+ try:
|
|
|
+ midi_in, port_name = open_midi_input(rtmidi_module, name_contains)
|
|
|
+ print(f"Listening on {port_name}")
|
|
|
+ while True:
|
|
|
+ received = midi_in.get_message()
|
|
|
+ if received:
|
|
|
+ try:
|
|
|
+ result = handle_midi_message(
|
|
|
+ received[0], actions, state, repo_root
|
|
|
+ )
|
|
|
+ if result:
|
|
|
+ print(
|
|
|
+ f"{result['binding']}: MIDI ch {result['channel'] + 1} "
|
|
|
+ f"note {result['note']} -> {result['model']}"
|
|
|
+ )
|
|
|
+ except (OSError, RuntimeError, ValueError, KeyError) as error:
|
|
|
+ print(f"MIDI action failed: {error}", file=sys.stderr)
|
|
|
+ sleeper(0.005)
|
|
|
+ except KeyboardInterrupt:
|
|
|
+ return
|
|
|
+ except (OSError, RuntimeError) as error:
|
|
|
+ print(f"MIDI bridge: {error}; retrying in 2 seconds", file=sys.stderr)
|
|
|
+ sleeper(2)
|
|
|
+ finally:
|
|
|
+ if midi_in is not None:
|
|
|
+ midi_in.close_port()
|
|
|
+
|
|
|
+
|
|
|
+def main(argv=None):
|
|
|
+ root = Path(__file__).resolve().parents[1]
|
|
|
+ parser = argparse.ArgumentParser(description=__doc__)
|
|
|
+ parser.add_argument("--state", type=Path, default=root / "config" / "desired-state.yaml")
|
|
|
+ parser.add_argument("--bindings", type=Path)
|
|
|
+ parser.add_argument("--repo-root", type=Path, default=root)
|
|
|
+ parser.add_argument("--check", action="store_true", help="validate state and bindings, then exit")
|
|
|
+ parser.add_argument("--list-ports", action="store_true", help="list available ALSA MIDI inputs")
|
|
|
+ args = parser.parse_args(argv)
|
|
|
+
|
|
|
+ if args.list_ports:
|
|
|
+ try:
|
|
|
+ list_midi_ports()
|
|
|
+ except RuntimeError as error:
|
|
|
+ print(f"ERROR: {error}", file=sys.stderr)
|
|
|
+ return 1
|
|
|
+ return 0
|
|
|
+
|
|
|
+ try:
|
|
|
+ state, bindings, repo_root = load_configuration(
|
|
|
+ args.state, args.bindings, args.repo_root
|
|
|
+ )
|
|
|
+ if args.check:
|
|
|
+ print(f"Valid MIDI bindings: {len(bindings['bindings'])}")
|
|
|
+ return 0
|
|
|
+ run_bridge(state, bindings, repo_root)
|
|
|
+ except (OSError, RuntimeError, ValueError, KeyError, TypeError, yaml.YAMLError) as error:
|
|
|
+ print(f"ERROR: {error}", file=sys.stderr)
|
|
|
+ return 1
|
|
|
+ return 0
|
|
|
+
|
|
|
+
|
|
|
+if __name__ == "__main__":
|
|
|
+ raise SystemExit(main())
|