#!/usr/bin/env python3 """Translate configured MIDI events into guitar model and level changes via mod-ui.""" import argparse import hashlib import sys import time from pathlib import Path, PurePosixPath import yaml from mod_ui_websocket import ModUiWebSocketClient from validate_desired_state import safe_relative_path, validate_state IR_OUTPUT_GAIN_PARAMETER = "g_out" DEFAULT_IR_OUTPUT_GAIN = 1.0 IR_OUTPUT_GAIN_BY_MODEL = { "edge_of_breakup_tb": 1.5, } 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 resolve_mod_ui_model(state, repo_root, source_path, user_files_root=None): """Resolve a repository NAM model to the matching mod-ui user-files copy.""" source_path = Path(source_path).resolve() deployment = state.get("deployment", {}).get("mod_ui", {}) user_files_directory = deployment.get("user_files_directory") if not safe_relative_path(user_files_directory): raise ValueError("deployment.mod_ui.user_files_directory must be a safe relative path") if user_files_root is None: user_files_root = Path.home() / Path(*PurePosixPath(user_files_directory).parts) user_files_root = Path(user_files_root).resolve() ui_model = (user_files_root / "NAM Models" / "Rigforge" / source_path.name).resolve() if not ui_model.is_relative_to(user_files_root): raise ValueError(f"mod-ui NAM model escapes its user-files directory: {ui_model}") if not ui_model.is_file(): raise FileNotFoundError( f"mod-ui NAM model copy is missing: {ui_model}; reinstall mod-ui to stage it" ) source_digest = hashlib.sha256(source_path.read_bytes()).digest() ui_digest = hashlib.sha256(ui_model.read_bytes()).digest() if source_digest != ui_digest: raise RuntimeError(f"mod-ui NAM model copy differs from its repository source: {ui_model}") return ui_model def mod_ui_command(config, instance, property_uri, value): with ModUiWebSocketClient( config["host"], config["port"], config["websocket_path"], ) as client: return client.set_patch(instance, property_uri, value) def mod_ui_parameter_command(client, instance, symbol, value): """Set a regular LV2 control port through mod-ui's WebSocket protocol.""" client.connect() client.send_text( f"param_set {instance}/{symbol} {float(value):.6f}" ) return True def select_nam_model(action, state, repo_root, command=None, user_files_root=None): processor = resolve_processor(state, action["target"]) models = processor["available_models"] requested_id = action["model"] fallback_id = action["fallback_model"] requested_source = resolve_asset(repo_root, models[requested_id]) selected_id = requested_id selected_source = requested_source if not requested_source.is_file(): selected_id = fallback_id selected_source = resolve_asset(repo_root, models[fallback_id]) if not selected_source.is_file(): raise FileNotFoundError( f"requested NAM model and fallback are both missing: " f"{requested_source}, {selected_source}" ) print( f"WARNING: NAM model {requested_id!r} is missing; " f"using fallback {fallback_id!r} ({selected_source})", file=sys.stderr, ) selected_path = resolve_mod_ui_model( state, repo_root, selected_source, user_files_root=user_files_root ) ui_config = bridge_config(state)["mod_ui"] instance = processor["mod_ui_instance"] property_uri = processor["file_property"] if command is None: command = lambda instance, property_uri, value: mod_ui_command( ui_config, instance, property_uri, value ) if not command(instance, property_uri, str(selected_path)): raise RuntimeError(f"mod-ui did not apply NAM model {selected_id!r}") 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=None, user_files_root=None, parameter_command=None, ): 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, user_files_root=user_files_root, ) result = { "binding": binding["id"], "channel": channel, "note": note, "model": model_id, "path": model_path, } target = binding["action"]["target"] if target.get("chain") == "guitar" and target.get("processor") == "amp-head": ir_processor = resolve_processor( state, {"chain": "guitar", "processor": "cabinet-ir"} ) ir_output_gain = IR_OUTPUT_GAIN_BY_MODEL.get( model_id, DEFAULT_IR_OUTPUT_GAIN ) if parameter_command is not None and not parameter_command( ir_processor["mod_ui_instance"], IR_OUTPUT_GAIN_PARAMETER, ir_output_gain, ): raise RuntimeError("mod-ui did not apply the cabinet IR output gain") result["ir_output_gain"] = ir_output_gain return result 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) ui_config = config["mod_ui"] mod_ui_client = ModUiWebSocketClient( ui_config["host"], ui_config["port"], ui_config["websocket_path"], ) def set_nam_model(instance, property_uri, value): return mod_ui_client.set_patch(instance, property_uri, value) def set_plugin_parameter(instance, symbol, value): return mod_ui_parameter_command( mod_ui_client, instance, symbol, value ) 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: if mod_ui_client.connection is not None: try: mod_ui_client.serve_once(timeout=0.001) except (OSError, RuntimeError) as error: print(f"mod-ui WebSocket closed: {error}; reconnecting on next action", file=sys.stderr) mod_ui_client.close() received = midi_in.get_message() if received: try: result = handle_midi_message( received[0], actions, state, repo_root, command=set_nam_model, parameter_command=set_plugin_parameter, ) if result: gain_message = ( f", IR gain {result['ir_output_gain']:.2f}" if "ir_output_gain" in result else "" ) print( f"{result['binding']}: MIDI ch {result['channel'] + 1} " f"note {result['note']} -> {result['model']}" f"{gain_message}" ) except (OSError, RuntimeError, ValueError, KeyError) as error: print(f"MIDI action failed: {error}", file=sys.stderr) mod_ui_client.close() 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() mod_ui_client.close() 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())