Jelajahi Sumber

add pipewire observer

Johan Le Baut 55 menit lalu
induk
melakukan
743bfdda76
4 mengubah file dengan 230 tambahan dan 2 penghapusan
  1. 11 2
      README.md
  2. 2 0
      config/desired-state.yaml
  3. 139 0
      scripts/observe_pipewire.py
  4. 78 0
      tests/test_pipewire_observer.py

+ 11 - 2
README.md

@@ -21,7 +21,7 @@ sudo apt update
 sudo apt upgrade
 sudo apt install --no-install-recommends \\
   rtkit pipewire pipewire-jack wireplumber \\
-  libspa-0.2-modules liblo-tools
+  libspa-0.2-modules liblo-tools git
 ```
 
 This records the preparation already performed on `rigforge` and is a starting point for documenting a second Pi. It is not yet a verified, version-pinned rebuild procedure: package versions, additional runtime dependencies, audio configuration, and service setup still need to be confirmed before reusing it as a complete deployment recipe.
@@ -32,7 +32,8 @@ This records the preparation already performed on `rigforge` and is a starting p
 - `config/sooperlooper/fcb1010.slb`: supplied FCB1010 binding file, pending on-target verification.
 - `build/sooperlooper/`: reserved for the later ARM64 Docker build definition.
 - `scripts/validate_desired_state.py`: validates topology and routing invariants without changing the target.
-- `tests/test_desired_state.py`: unit tests for desired-state validation.
+- `scripts/observe_pipewire.py`: read-only comparison for explicitly declared UMC AUX ports and links.
+- `tests/`: unit tests for desired-state validation and the PipeWire observer.
 - `artifacts/sooperlooper/arm64/`: reserved for an artifact and its provenance, subject to repository hosting limits and redistribution terms.
 
 The YAML describes desired state; a control surface is not a second source of truth. The initial audio profile declares 48 kHz and a quantum of 128 frames, which was reported to sound good during a temporary target test. At 48 kHz, 128 frames is about 2.7 ms per period, not the end-to-end latency. This runtime value has not yet been made persistent or measured under sustained load; apply it temporarily on the target with `pw-metadata -n settings 0 clock.force-quantum 128` and return to automatic selection with `pw-metadata -n settings 0 clock.force-quantum 0`. Concrete PipeWire ports, buffer settings, package names, services, and artifact installation path will only be recorded as verified after target tests.
@@ -46,6 +47,14 @@ python3 -m unittest discover -s tests -v
 
 The validator checks that there are four distinct physical inputs, one four-channel looper with each source assigned once, a declared mix output, and no active or planned route from looper returns back to looper inputs. It is read-only and does not connect audio ports or modify the target.
 
+For an initial read-only graph observation on a system with `pw-link`, run:
+
+```sh
+python3 scripts/observe_pipewire.py
+```
+
+The observer reads `pw-link -l` and compares only connections whose endpoints are explicitly listed under `routing.managed_ports`; expected edges go in `routing.managed_links`. Both lists are empty at this stage, so it intentionally reports no project mismatches. The existing WirePlumber links between UMC AUX ports and their split monitor ports are not classified as project-managed. Only concrete UMC ALSA AUX port names are accepted; logical nodes such as `direct_mix` are rejected until an actual PipeWire node/port exists. The observer only prints missing or unexpected link proposals; it never creates or deletes links. No polling or automatic repair is enabled in this increment.
+
 ## Development PC
 
 The development host is Ubuntu AMD64 with Docker. The SooperLooper source under evaluation is <https://github.com/abarker/sooperlooper-mods>. The Docker build procedure is intentionally not yet provided: first select a tag and inspect that tag's build instructions and licensing. The eventual build command must take an explicit tag, resolve and record its exact commit, build for ARM64, and record artifact architecture, runtime dependencies, provenance, and checksum. The container is for building only; SooperLooper will run natively on the Raspberry Pi.

+ 2 - 0
config/desired-state.yaml

@@ -105,6 +105,8 @@ routing:
   looper_returns:
     destination: direct_mix
     feed_looper_inputs: false
+  managed_ports: []
+  managed_links: []
   monitoring:
     hardware_monitoring: verify-on-target
     software_monitoring: verify-on-target

+ 139 - 0
scripts/observe_pipewire.py

@@ -0,0 +1,139 @@
+import argparse
+import json
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+import yaml
+
+from validate_desired_state import validate_state as validate_desired_state
+
+
+MANAGED_ENDPOINT_PATTERN = re.compile(
+    r"^alsa_(?:input|output)\.hw_U192k_0:(?:capture|playback)_AUX[0-3]$"
+)
+
+
+def load_state(path):
+    with path.open(encoding="utf-8") as state_stream:
+        state = yaml.safe_load(state_stream)
+    errors = validate_desired_state(state)
+    errors.extend(validate_managed_links(state))
+    if errors:
+        raise ValueError("invalid desired state: " + "; ".join(errors))
+    return state
+
+
+def validate_managed_links(state):
+    errors = []
+    if not isinstance(state, dict):
+        return ["document root must be a mapping"]
+    routing = state.get("routing")
+    if not isinstance(routing, dict):
+        return ["routing must be a mapping"]
+    managed_ports = routing.get("managed_ports")
+    if not isinstance(managed_ports, list):
+        errors.append("routing.managed_ports must be a list")
+        managed_ports = []
+    for index, port in enumerate(managed_ports):
+        if not isinstance(port, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(port):
+            errors.append(f"routing.managed_ports[{index}] must be a concrete UMC AUX port")
+    if len(managed_ports) != len(set(port for port in managed_ports if isinstance(port, str))):
+        errors.append("routing.managed_ports must not contain duplicate ports")
+
+    managed_links = routing.get("managed_links")
+    if not isinstance(managed_links, list):
+        errors.append("routing.managed_links must be a list")
+        managed_links = []
+    for index, link in enumerate(managed_links):
+        if not isinstance(link, dict):
+            errors.append(f"routing.managed_links[{index}] must be a mapping")
+            continue
+        source = link.get("from")
+        destination = link.get("to")
+        if not isinstance(source, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(source):
+            errors.append(f"routing.managed_links[{index}].from must be a concrete UMC AUX port")
+        if not isinstance(destination, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(destination):
+            errors.append(f"routing.managed_links[{index}].to must be a concrete UMC AUX port")
+        if (
+            isinstance(source, str)
+            and isinstance(destination, str)
+            and (source not in managed_ports or destination not in managed_ports)
+        ):
+            errors.append(f"routing.managed_links[{index}] endpoints must be listed in routing.managed_ports")
+        if source == destination:
+            errors.append(f"routing.managed_links[{index}] cannot link a port to itself")
+        if link.get("status") not in {"planned", "observed"}:
+            errors.append(f"routing.managed_links[{index}].status must be planned or observed")
+    return errors
+
+
+def parse_pw_link_output(text):
+    links = set()
+    current_source = None
+    for line in text.splitlines():
+        if not line.strip():
+            continue
+        if line.startswith("  |-> "):
+            if current_source is None:
+                raise ValueError("pw-link output has a destination without a source")
+            destination = line.removeprefix("  |-> ")
+            links.add((current_source, destination))
+            continue
+        if line.startswith("  |<- "):
+            destination = line.removeprefix("  |<- ")
+            links.add((destination, current_source))
+            continue
+        current_source = line.strip()
+    return links
+
+
+def observe(state, links):
+    managed_ports = set(state["routing"]["managed_ports"])
+    managed = {
+        (link["from"], link["to"])
+        for link in state["routing"]["managed_links"]
+        if link["status"] in {"planned", "observed"}
+    }
+    observed_managed = {
+        link
+        for link in links
+        if link[0] in managed_ports and link[1] in managed_ports
+    }
+    reports = []
+    for source, destination in sorted(managed - observed_managed):
+        reports.append({"kind": "missing", "from": source, "to": destination, "action": "would-link"})
+    for source, destination in sorted(observed_managed - managed):
+        reports.append({"kind": "unexpected", "from": source, "to": destination, "action": "would-review"})
+    return reports
+
+
+def main(argv=None):
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "--state",
+        type=Path,
+        default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
+    )
+    args = parser.parse_args(argv)
+    try:
+        state = load_state(args.state)
+        result = subprocess.run(
+            ["pw-link", "-l"],
+            check=True,
+            capture_output=True,
+            text=True,
+        )
+        links = parse_pw_link_output(result.stdout)
+    except (OSError, subprocess.CalledProcessError, ValueError, yaml.YAMLError) as error:
+        print(f"ERROR: {error}", file=sys.stderr)
+        return 2
+
+    reports = observe(state, links)
+    print(json.dumps({"mode": "observe-only", "managed_links": len(state["routing"]["managed_links"]), "differences": reports}, indent=2))
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 78 - 0
tests/test_pipewire_observer.py

@@ -0,0 +1,78 @@
+import copy
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+
+from observe_pipewire import load_state, observe, parse_pw_link_output, validate_managed_links
+
+CAPTURE_0 = "alsa_input.hw_U192k_0:capture_AUX0"
+CAPTURE_2 = "alsa_input.hw_U192k_0:capture_AUX2"
+CAPTURE_3 = "alsa_input.hw_U192k_0:capture_AUX3"
+PLAYBACK_0 = "alsa_output.hw_U192k_0:playback_AUX0"
+
+
+class PipeWireObserverTests(unittest.TestCase):
+    @classmethod
+    def setUpClass(cls):
+        cls.state = load_state(ROOT / "config" / "desired-state.yaml")
+
+    def test_empty_managed_set_ignores_wireplumber_hardware_links(self):
+        observed = parse_pw_link_output(
+            "alsa_output.usb-umc:Line1.split:output_AUX0\n"
+            f"  |-> {PLAYBACK_0}\n"
+            f"{CAPTURE_0}\n"
+            "  |-> alsa_input.usb-umc:Mic1.split:input_AUX0\n"
+        )
+        self.assertEqual(observe(self.state, observed), [])
+
+    def test_reports_missing_and_unexpected_managed_links_without_mutating(self):
+        state = copy.deepcopy(self.state)
+        state["routing"]["managed_ports"] = [CAPTURE_0, CAPTURE_2, CAPTURE_3, PLAYBACK_0]
+        state["routing"]["managed_links"] = [
+            {"from": CAPTURE_0, "to": PLAYBACK_0, "status": "planned"},
+            {"from": CAPTURE_2, "to": PLAYBACK_0, "status": "observed"},
+        ]
+        observed = {
+            (CAPTURE_2, PLAYBACK_0),
+            (CAPTURE_3, PLAYBACK_0),
+        }
+        reports = observe(state, observed)
+        self.assertEqual(
+            reports,
+            [
+                {"kind": "missing", "from": CAPTURE_0, "to": PLAYBACK_0, "action": "would-link"},
+                {"kind": "unexpected", "from": CAPTURE_3, "to": PLAYBACK_0, "action": "would-review"},
+            ],
+        )
+        self.assertEqual(state["routing"]["managed_links"][0]["status"], "planned")
+
+    def test_parser_handles_incoming_and_outgoing_link_views(self):
+        links = parse_pw_link_output(
+            f"{CAPTURE_0}\n"
+            f"  |-> {PLAYBACK_0}\n"
+            f"{PLAYBACK_0}\n"
+            f"  |<- {CAPTURE_0}\n"
+        )
+        self.assertEqual(links, {(CAPTURE_0, PLAYBACK_0)})
+
+    def test_rejects_logical_mix_endpoint(self):
+        state = copy.deepcopy(self.state)
+        state["routing"]["managed_ports"] = [PLAYBACK_0]
+        state["routing"]["managed_links"] = [
+            {"from": "direct_mix", "to": PLAYBACK_0, "status": "planned"}
+        ]
+        self.assertTrue(any("concrete UMC AUX port" in error for error in validate_managed_links(state)))
+
+    def test_managed_links_must_use_declared_ports(self):
+        state = copy.deepcopy(self.state)
+        state["routing"]["managed_links"] = [
+            {"from": CAPTURE_0, "to": PLAYBACK_0, "status": "planned"}
+        ]
+        self.assertTrue(any("endpoints must be listed" in error for error in validate_managed_links(state)))
+
+
+if __name__ == "__main__":
+    unittest.main()