Browse Source

script to translate MIDI messages

Johan Le Baut 2 tuần trước cách đây
mục cha
commit
51cb365070

+ 23 - 0
README.md

@@ -30,11 +30,13 @@ This records the preparation already performed on `rigforge` and is a starting p
 ## Repository layout
 
 - `config/desired-state.yaml`: versioned desired audio topology and provisional target mapping.
+- `config/midi-bindings.yaml`: MIDI event-to-action mapping for the general MIDI bridge; SooperLooper bindings remain in their native `.slb` file.
 - `config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf`: tested filter-chain node configuration for the four-input mono direct mixer.
 - `config/sooperlooper/fcb1010.slb`: supplied FCB1010 binding file, pending on-target verification.
 - `build/arm64/`: shared ARM64 build image and task scripts for SooperLooper and mod-host.
 - `scripts/validate_desired_state.py`: validates topology and routing invariants without changing the target.
 - `scripts/observe_pipewire.py`: read-only comparison by default, with explicit one-shot repair for declared missing links.
+- `scripts/midi_action_bridge.py`: translates declared ALSA MIDI note events into mod-host NAM model actions.
 - `scripts/deploy.sh` and `scripts/deploy.py`: scoped user-level installation, removal, and reload of declared PipeWire and LV2 plugin bundles.
 - `tests/`: unit tests for desired-state validation, PipeWire observation/reconciliation, and deployment operations.
 - `artifacts/sooperlooper/arm64/` and `artifacts/mod-host/arm64/`: generated binaries, runtime dependency reports, and build provenance; commit after reviewing licensing and repository size.
@@ -130,6 +132,27 @@ Before starting mod-host, `scripts/wait_mod_host_ports.py` waits up to 45 second
 
 `reload mod-host` restarts the service and rebuilds the plugin graph, briefly interrupting the processed guitar path. `PartOf=` couples mod-host restarts to PipeWire, WirePlumber, and `filter-chain.service` restarts; its startup configurator then rebuilds the NAM/IR chain. The mod-host control socket uses TCP port 5555 and this build listens on `0.0.0.0` without authentication. This is retained for the current test by owner request and must be restricted before treating the setup as hardened.
 
+### FCB NAM model selection
+
+`config/midi-bindings.yaml` maps MIDI Note On events on channel 1 (channel index 0) to actions, rather than storing plugin paths or commands in the controller configuration. Notes 6–9 select the declared guitar NAM models: Crystal Clean TB, Edge of Breakup TB, Crunch TB, and Overdriven TB. Note Off and Note On with velocity zero are ignored. Each selection declares Crystal Clean TB as its missing-file fallback. If both the requested model and fallback are unavailable, the bridge reports the error and leaves the currently loaded model unchanged.
+
+The NAM model catalog and MIDI input/socket settings are declared in `config/desired-state.yaml`. Actions identify their target by chain and processor IDs, so the bridge itself does not hard-code the guitar instance; adding a bass chain will also require extending and validating the desired audio topology. SooperLooper’s `config/sooperlooper/fcb1010.slb` remains independent and unchanged.
+
+The bridge requires Debian’s `python3-rtmidi` package on the target; this dependency has not been installed or tested there. Install it manually when ready with `sudo apt install python3-rtmidi`. Check the configuration and inspect MIDI input names with:
+
+```sh
+python3 scripts/midi_action_bridge.py --check
+python3 scripts/midi_action_bridge.py --list-ports
+```
+
+Set `controls.midi_bridge.input_port_name_contains` to a unique substring of the actual UMC MIDI input name if `UMC404HD` does not match it. Then run the bridge in the foreground during a safe test:
+
+```sh
+python3 scripts/midi_action_bridge.py
+```
+
+The bridge connects to mod-host over loopback and issues only `patch_set` for the configured NAM processor. It does not alter PipeWire links or start automatically; a dedicated user service and target verification are future work. The current mod-host startup model remains the declared `Crunch_TB`; Crystal Clean is the runtime fallback for a selected model whose file is absent.
+
 ### Rigforge graph reconciliation
 
 `install reconcile` separately installs and enables a `systemd --user` oneshot service and 15-second timer for **all** links in `routing.managed_links`, regardless of whether they belong to mod-host, SooperLooper, or another declared component. It is explicit and not part of `install all`; `install mod-host` does not install it. On each run it repairs declared links and removes only links explicitly listed in `routing.managed_unlinks`, deferring removals until all desired managed links are present. It never prunes other unexpected links. `reload reconcile` runs one reconciliation immediately; `uninstall reconcile` stops and removes the timer/service while restoring any prior unit files. The timer retries after graph changes such as a USB interface reconnect, but verifies topology only, not audio signal quality.

+ 13 - 0
config/desired-state.yaml

@@ -92,6 +92,14 @@ modes:
     enabled: false
     transport: ethernet
 
+controls:
+  midi_bridge:
+    bindings_file: config/midi-bindings.yaml
+    input_port_name_contains: UMC404HD
+    mod_host:
+      host: 127.0.0.1
+      port: 5555
+
 sources:
   - id: guitar
     physical_input: 1
@@ -175,6 +183,11 @@ routing:
           bundle_path: .lv2/neural_amp_modeler.lv2
           file_property: http://github.com/mikeoliphant/neural-amp-modeler-lv2#model
           asset_path: amp_emul/amphead/VOX_AC15/Vox_AC15CH_Crunch_TB.nam
+          available_models:
+            crystal_clean_tb: amp_emul/amphead/VOX_AC15/Vox_AC15CH_Crystal_Clean_TB.nam
+            edge_of_breakup_tb: amp_emul/amphead/VOX_AC15/Vox_AC15CH_Edge_of_Breakup_TB.nam
+            crunch_tb: amp_emul/amphead/VOX_AC15/Vox_AC15CH_Crunch_TB.nam
+            overdriven_tb: amp_emul/amphead/VOX_AC15/Vox_AC15CH_Overdriven_TB.nam
           input_port: effect_0:input
           output_port: effect_0:output
           parameters:

+ 55 - 0
config/midi-bindings.yaml

@@ -0,0 +1,55 @@
+---
+schema_version: 1
+
+bindings:
+  - id: guitar-crystal-clean
+    event:
+      type: note_on
+      channel: 0
+      note: 6
+    action:
+      type: select_nam_model
+      target:
+        chain: guitar
+        processor: amp-head
+      model: crystal_clean_tb
+      fallback_model: crystal_clean_tb
+
+  - id: guitar-edge-of-breakup
+    event:
+      type: note_on
+      channel: 0
+      note: 7
+    action:
+      type: select_nam_model
+      target:
+        chain: guitar
+        processor: amp-head
+      model: edge_of_breakup_tb
+      fallback_model: crystal_clean_tb
+
+  - id: guitar-crunch
+    event:
+      type: note_on
+      channel: 0
+      note: 8
+    action:
+      type: select_nam_model
+      target:
+        chain: guitar
+        processor: amp-head
+      model: crunch_tb
+      fallback_model: crystal_clean_tb
+
+  - id: guitar-overdriven
+    event:
+      type: note_on
+      channel: 0
+      note: 9
+    action:
+      type: select_nam_model
+      target:
+        chain: guitar
+        processor: amp-head
+      model: overdriven_tb
+      fallback_model: crystal_clean_tb

+ 357 - 0
scripts/midi_action_bridge.py

@@ -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())

+ 52 - 0
scripts/validate_desired_state.py

@@ -73,6 +73,20 @@ def validate_mod_host_chain(routing, source_by_id):
         for key in ("bundle_path", "asset_path"):
             if not safe_relative_path(processor.get(key)):
                 errors.append(f"{location}.{key} must be a safe relative path")
+        if index == 0:
+            expected_models = {
+                "crystal_clean_tb": "amp_emul/amphead/VOX_AC15/Vox_AC15CH_Crystal_Clean_TB.nam",
+                "edge_of_breakup_tb": "amp_emul/amphead/VOX_AC15/Vox_AC15CH_Edge_of_Breakup_TB.nam",
+                "crunch_tb": "amp_emul/amphead/VOX_AC15/Vox_AC15CH_Crunch_TB.nam",
+                "overdriven_tb": "amp_emul/amphead/VOX_AC15/Vox_AC15CH_Overdriven_TB.nam",
+            }
+            models = processor.get("available_models")
+            if not isinstance(models, dict) or models != expected_models:
+                errors.append(f"{location}.available_models must declare the four approved Vox TB models")
+            elif any(not safe_relative_path(path) for path in models.values()):
+                errors.append(f"{location}.available_models paths must be safe relative paths")
+            elif processor.get("asset_path") not in models.values():
+                errors.append(f"{location}.asset_path must be one of the declared available_models")
     if isinstance(processors[0], dict):
         parameters = processors[0].get("parameters")
         if not isinstance(parameters, dict):
@@ -251,6 +265,44 @@ def validate_state(state):
 
     errors.extend(validate_mod_host_chain(routing, source_by_id))
 
+    controls = state.get("controls")
+    if not isinstance(controls, dict):
+        errors.append("controls must be a mapping")
+    else:
+        midi_bridge = controls.get("midi_bridge")
+        if not isinstance(midi_bridge, dict):
+            errors.append("controls.midi_bridge must be a mapping")
+        else:
+            if midi_bridge.get("bindings_file") != "config/midi-bindings.yaml":
+                errors.append("controls.midi_bridge.bindings_file must be config/midi-bindings.yaml")
+            if (
+                not isinstance(midi_bridge.get("input_port_name_contains"), str)
+                or not midi_bridge["input_port_name_contains"].strip()
+            ):
+                errors.append("controls.midi_bridge.input_port_name_contains must be non-empty")
+            mod_host = midi_bridge.get("mod_host")
+            if not isinstance(mod_host, dict):
+                errors.append("controls.midi_bridge.mod_host must be a mapping")
+            else:
+                if mod_host.get("host") != "127.0.0.1":
+                    errors.append("controls.midi_bridge.mod_host.host must be 127.0.0.1")
+                port = mod_host.get("port")
+                if (
+                    not isinstance(port, int)
+                    or isinstance(port, bool)
+                    or not 1 <= port <= 65535
+                ):
+                    errors.append("controls.midi_bridge.mod_host.port must be a valid TCP port")
+                elif isinstance(deployment := state.get("deployment"), dict):
+                    host_deployment = deployment.get("mod_host")
+                    if (
+                        isinstance(host_deployment, dict)
+                        and host_deployment.get("socket_port") != port
+                    ):
+                        errors.append(
+                            "controls.midi_bridge.mod_host.port must match deployment.mod_host.socket_port"
+                        )
+
     connections = state.get("connections", [])
     if not isinstance(connections, list):
         errors.append("connections must be a list")

+ 25 - 0
tests/test_desired_state.py

@@ -102,6 +102,31 @@ class DesiredStateValidationTests(unittest.TestCase):
         state["routing"]["mod_host_chains"]["guitar"]["processors"][0]["parameters"]["output_level"] = 30
         self.assertIn("NAM output_level must be between -20 and 20 dB", validate_state(state))
 
+    def test_declares_safe_midi_bridge_and_nam_models(self):
+        processor = self.state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
+        self.assertEqual(set(processor["available_models"]), {
+            "crystal_clean_tb", "edge_of_breakup_tb", "crunch_tb", "overdriven_tb"
+        })
+
+        state = copy.deepcopy(self.state)
+        state["routing"]["mod_host_chains"]["guitar"]["processors"][0]["available_models"][
+            "crystal_clean_tb"
+        ] = "../../outside.nam"
+        self.assertTrue(any("available_models" in error for error in validate_state(state)))
+
+        state = copy.deepcopy(self.state)
+        state["controls"]["midi_bridge"]["mod_host"]["host"] = "0.0.0.0"
+        self.assertIn(
+            "controls.midi_bridge.mod_host.host must be 127.0.0.1",
+            validate_state(state),
+        )
+
+        state = copy.deepcopy(self.state)
+        state["controls"]["midi_bridge"]["mod_host"]["port"] = 5556
+        self.assertTrue(
+            any("must match deployment.mod_host.socket_port" in error for error in validate_state(state))
+        )
+
     def test_deployment_targets_are_declared_and_valid(self):
         self.assertEqual(validate_state(self.state), [])
 

+ 149 - 0
tests/test_midi_action_bridge.py

@@ -0,0 +1,149 @@
+import copy
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+import yaml
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+
+from midi_action_bridge import (
+    binding_index,
+    handle_midi_message,
+    load_configuration,
+    select_nam_model,
+    validate_bindings,
+)
+
+
+class MidiActionBridgeTests(unittest.TestCase):
+    @classmethod
+    def setUpClass(cls):
+        cls.state, cls.bindings, cls.repo_root = load_configuration(
+            ROOT / "config" / "desired-state.yaml",
+            repo_root=ROOT,
+        )
+
+    def test_current_bindings_map_notes_six_through_nine_to_guitar_tb_models(self):
+        self.assertEqual(validate_bindings(self.bindings, self.state), [])
+        events = {
+            entry["event"]["note"]: entry["action"]["model"]
+            for entry in self.bindings["bindings"]
+        }
+        self.assertEqual(
+            events,
+            {
+                6: "crystal_clean_tb",
+                7: "edge_of_breakup_tb",
+                8: "crunch_tb",
+                9: "overdriven_tb",
+            },
+        )
+        self.assertTrue(
+            all(
+                entry["action"]["fallback_model"] == "crystal_clean_tb"
+                for entry in self.bindings["bindings"]
+            )
+        )
+
+    def test_note_on_sends_patch_set_for_declared_nam_instance(self):
+        commands = []
+
+        def command(host, port, text):
+            commands.append((host, port, text))
+            return "resp 0"
+
+        actions = binding_index(self.bindings)
+        result = handle_midi_message(
+            [0x90, 7, 127], actions, self.state, ROOT, command=command
+        )
+
+        model = ROOT / self.state["routing"]["mod_host_chains"]["guitar"]["processors"][0][
+            "available_models"
+        ]["edge_of_breakup_tb"]
+        self.assertEqual(result["model"], "edge_of_breakup_tb")
+        self.assertEqual(result["note"], 7)
+        self.assertEqual(
+            commands,
+            [(
+                "127.0.0.1",
+                5555,
+                "patch_set 0 http://github.com/mikeoliphant/neural-amp-modeler-lv2#model "
+                + str(model),
+            )],
+        )
+
+    def test_note_off_zero_velocity_and_unbound_channel_do_nothing(self):
+        commands = []
+        command = lambda *_args: commands.append(_args) or "resp 0"
+        actions = binding_index(self.bindings)
+
+        self.assertIsNone(handle_midi_message([0x80, 7, 0], actions, self.state, ROOT, command))
+        self.assertIsNone(handle_midi_message([0x90, 7, 0], actions, self.state, ROOT, command))
+        self.assertIsNone(handle_midi_message([0x91, 7, 127], actions, self.state, ROOT, command))
+        self.assertEqual(commands, [])
+
+    def test_missing_requested_model_uses_declared_clean_fallback(self):
+        state = copy.deepcopy(self.state)
+        models = state["routing"]["mod_host_chains"]["guitar"]["processors"][0][
+            "available_models"
+        ]
+        models["edge_of_breakup_tb"] = "models/missing.nam"
+        models["crystal_clean_tb"] = "models/clean.nam"
+        action = copy.deepcopy(self.bindings["bindings"][1]["action"])
+
+        with tempfile.TemporaryDirectory() as directory:
+            root = Path(directory)
+            clean_model = root / "models" / "clean.nam"
+            clean_model.parent.mkdir()
+            clean_model.write_text("test fixture", encoding="utf-8")
+            commands = []
+
+            def command(host, port, text):
+                commands.append((host, port, text))
+                return "resp 0"
+
+            selected_id, selected_path = select_nam_model(
+                action, state, root, command=command
+            )
+
+        self.assertEqual(selected_id, "crystal_clean_tb")
+        self.assertEqual(selected_path, clean_model)
+        self.assertIn("models/clean.nam", commands[0][2])
+
+    def test_missing_requested_and_fallback_model_does_not_call_mod_host(self):
+        state = copy.deepcopy(self.state)
+        models = state["routing"]["mod_host_chains"]["guitar"]["processors"][0][
+            "available_models"
+        ]
+        models["edge_of_breakup_tb"] = "models/missing-edge.nam"
+        models["crystal_clean_tb"] = "models/missing-clean.nam"
+        commands = []
+        action = copy.deepcopy(self.bindings["bindings"][1]["action"])
+
+        with tempfile.TemporaryDirectory() as directory:
+            with self.assertRaises(FileNotFoundError):
+                select_nam_model(
+                    action,
+                    state,
+                    Path(directory),
+                    command=lambda *args: commands.append(args) or "resp 0",
+                )
+        self.assertEqual(commands, [])
+
+    def test_invalid_or_duplicate_binding_is_rejected(self):
+        bindings = copy.deepcopy(self.bindings)
+        bindings["bindings"][1]["event"]["note"] = 6
+        errors = validate_bindings(bindings, self.state)
+        self.assertTrue(any("duplicate MIDI note binding" in error for error in errors))
+
+        bindings = copy.deepcopy(self.bindings)
+        bindings["bindings"][0]["action"]["target"]["processor"] = "not-a-processor"
+        errors = validate_bindings(bindings, self.state)
+        self.assertTrue(any("must identify exactly one processor" in error for error in errors))
+
+
+if __name__ == "__main__":
+    unittest.main()