#!/usr/bin/env python3 """Apply the small Rigforge integration patch to the pinned mod-ui source tree.""" import sys from pathlib import Path def replace_once(path, original, replacement): text = path.read_text(encoding="utf-8") if replacement in text: return if text.count(original) != 1: raise RuntimeError(f"expected one upstream match in {path}") path.write_text(text.replace(original, replacement), encoding="utf-8") def replace_if_present(path, original, replacement): text = path.read_text(encoding="utf-8") if (replacement and replacement in text) or original not in text: return if text.count(original) != 1: raise RuntimeError(f"expected at most one upstream match in {path}") path.write_text(text.replace(original, replacement), encoding="utf-8") def replace_host_method(path, method_name, replacement): """Replace a complete Host method, independent of its upstream body variant.""" text = path.read_text(encoding="utf-8") marker = f" def {method_name}(" start = text.find(marker) if start < 0: raise RuntimeError(f"could not find Host.{method_name} in {path}") next_method = text.find("\n def ", start + len(marker)) end = len(text) if next_method < 0 else next_method + 1 replacement = replacement.rstrip() + "\n\n" updated = text[:start] + replacement + text[end:] if updated != text: path.write_text(updated, encoding="utf-8") def patch_host_connection_methods(host): """Normalize manual connection handling across old Rigforge patch variants.""" replace_host_method( host, "connect", ''' def connect(self, port_from, port_to, callback): if (port_from, port_to) in self.connections: logging.info("[host] NOTE: Requested connection already exists") callback(True) return resolved = pedalboard_connection( port_from, port_to, self.rigforge_capture_ports, self.rigforge_playback_ports, self._fix_host_connection_port ) if resolved is not None and resolved[0] == "pipewire": pipewire_link = resolved[1] ok = connect_link(*pipewire_link) callback(ok) if ok: self.connections.append((port_from, port_to)) self.pedalboard_modified = True self.msg_callback("connect %s %s" % (port_from, port_to)) else: logging.error( "[host] PipeWire backend failed to connect ports: '%s' => '%s'", pipewire_link[0], pipewire_link[1] ) return def host_callback(ok): callback(ok) if ok: self.connections.append((port_from, port_to)) self.msg_callback("connect %s %s" % (port_from, port_to)) else: logging.error("[host] backend failed to connect ports: '%s' => '%s'", port_from, port_to) if resolved is not None: port_from_2, port_to_2 = resolved[1] else: port_from_2 = self._fix_host_connection_port(port_from) port_to_2 = self._fix_host_connection_port(port_to) self.send_modified( "connect %s %s" % (port_from_2, port_to_2), host_callback, datatype='boolean' )''', ) text = host.read_text(encoding="utf-8") if " def _rigforge_pipewire_boundary(" in text: replace_host_method( host, "_rigforge_pipewire_boundary", ''' def _rigforge_pipewire_boundary(self, port_from, port_to): resolved = pedalboard_connection( port_from, port_to, self.rigforge_capture_ports, self.rigforge_playback_ports, self._fix_host_connection_port ) if resolved is not None and resolved[0] == "pipewire": return resolved[1] return None''', ) replace_host_method( host, "disconnect", ''' def disconnect(self, port_from, port_to, callback): resolved = pedalboard_connection( port_from, port_to, self.rigforge_capture_ports, self.rigforge_playback_ports, self._fix_host_connection_port ) if resolved is not None and resolved[0] == "pipewire": pipewire_link = resolved[1] ok = disconnect_link(*pipewire_link) callback(ok) if ok: self.msg_callback("disconnect %s %s" % (port_from, port_to)) self.pedalboard_modified = True try: self.connections.remove((port_from, port_to)) except ValueError: logging.info( "[host] Requested '%s' => '%s' connection was not in the UI state", port_from, port_to ) else: logging.error( "[host] PipeWire backend failed to disconnect ports: '%s' => '%s'", pipewire_link[0], pipewire_link[1] ) return def host_callback(ok): # Upstream disconnect failures are not fatal to the UI state. callback(True) self.msg_callback("disconnect %s %s" % (port_from, port_to)) if not ok: logging.error("[host] disconnect '%s' => '%s' failed", port_from, port_to) self.pedalboard_modified = True try: self.connections.remove((port_from, port_to)) except ValueError: logging.info( "[host] NOTE: Requested '%s' => '%s' connection doesn't exist", port_from, port_to ) if resolved is not None: port_from_2, port_to_2 = resolved[1] else: try: port_from_2 = self._fix_host_connection_port(port_from) except Exception: logging.info("[host] NOTE: Requested '%s' source port doesn't exist, assume disconnected", port_from) return host_callback(True) try: port_to_2 = self._fix_host_connection_port(port_to) except Exception: logging.info("[host] NOTE: Requested '%s' target port doesn't exist, assume disconnected", port_to) return host_callback(True) if len(self.connections) == 0: return host_callback(False) self.send_modified( "disconnect %s %s" % (port_from_2, port_to_2), host_callback, datatype='boolean' )''', ) def patch_load_connections(host): """Make pedalboard restore use the same resolution as manual UI actions.""" text = host.read_text(encoding="utf-8") original_text = text resolver_marker = " def _fix_host_connection_port(self, port):" resolver_start = text.find(resolver_marker) if resolver_start < 0: raise RuntimeError(f"could not locate Host._fix_host_connection_port in {host}") resolver_end = text.find( "\n def ", resolver_start + len(resolver_marker) ) if resolver_end < 0: raise RuntimeError(f"could not locate end of Host._fix_host_connection_port in {host}") resolver_method = text[resolver_start:resolver_end] if ( "# Rigforge bare boundary port alias; web_connect removes /graph/." not in resolver_method ): marker = ' data = port.split("/")\n' if resolver_method.count(marker) != 1: raise RuntimeError(f"could not identify port resolver body in {host}") updated_resolver = resolver_method.replace( marker, ''' # Rigforge bare boundary port alias; web_connect removes /graph/. if port in self.rigforge_capture_ports: return self.rigforge_capture_ports[port] if port in self.rigforge_playback_ports: return self.rigforge_playback_ports[port] data = port.split("/") if len(data) == 2 and data[0] == "" and ( data[1] in self.rigforge_capture_ports or data[1] in self.rigforge_playback_ports ): symbol = data[1] return self.rigforge_capture_ports.get( symbol, self.rigforge_playback_ports.get(symbol) ) ''', 1, ) if updated_resolver == resolver_method: raise RuntimeError(f"could not add Rigforge alias to {host}") text = text[:resolver_start] + updated_resolver + text[resolver_end:] method_marker = " def load_pb_connections(" method_start = text.find(method_marker) if method_start < 0: raise RuntimeError(f"could not find Host.load_pb_connections in {host}") block_start = text.find(" if doConnectionNow:", method_start) block_end = text.find( "\n elif aliasname1 is not None or aliasname2 is not None:", block_start, ) if block_start < 0 or block_end < 0: raise RuntimeError( f"could not identify mod-ui pedalboard connection restoration block in {host}" ) replacement = ''' if doConnectionNow: resolved = pedalboard_connection( port_from, port_to, self.rigforge_capture_ports, self.rigforge_playback_ports, self._fix_host_connection_port ) if resolved is not None and resolved[0] == "pipewire": self._rigforge_restore_pipewire_boundary( resolved[1], port_from, port_to, attempts_left=60 ) continue try: if resolved is not None: port_from_2, port_to_2 = resolved[1] else: port_from_2 = self._fix_host_connection_port(port_from) port_to_2 = self._fix_host_connection_port(port_to) except Exception: continue self.send_notmodified("connect %s %s" % (port_from_2, port_to_2)) self.connections.append((port_from, port_to)) self.msg_callback("connect %s %s" % (port_from, port_to))''' updated = text[:block_start] + replacement + text[block_end:] restore_method = ''' def _rigforge_restore_pipewire_boundary( self, pipewire_link, port_from, port_to, attempts_left ): if not hasattr(self, "_rigforge_restore_attempts"): self._rigforge_restore_attempts = {} edge = (port_from, port_to) attempts_left = min( attempts_left, self._rigforge_restore_attempts.get(edge, 60) ) if not ( self.rigforge_capture_ports and self.rigforge_playback_ports and all( "capture_%d" % index in self.audioportsIn for index in range(1, len(self.rigforge_capture_ports) + 1) ) and all( "playback_%d" % index in self.audioportsOut for index in range(1, len(self.rigforge_playback_ports) + 1) ) ): ready = False else: result = subprocess.run( ["pw-link", "-o"], check=False, capture_output=True, text=True, ) ready = result.returncode == 0 and all( port in result.stdout.splitlines() for port in ( *self.rigforge_capture_ports.values(), *self.rigforge_playback_ports.values(), ) ) connections_now = self.connections if edge in connections_now: self._rigforge_restore_attempts.pop(edge, None) return if not ready and attempts_left == 60: logging.error( "[host] PipeWire boundary readiness failed: inputs=%r outputs=%r " "configured_capture=%r configured_playback=%r", self.audioportsIn, self.audioportsOut, sorted(self.rigforge_capture_ports), sorted(self.rigforge_playback_ports), ) if ready and connect_link(*pipewire_link): self._rigforge_restore_attempts.pop(edge, None) if edge not in self.connections: self.connections.append(edge) self.msg_callback("connect %s %s" % (port_from, port_to)) return if not ready and edge not in self._rigforge_restore_attempts: logging.error( "[host] PipeWire boundary ports are not ready for restore: '%s' => '%s' " "(capture ports: %s; playback ports: %s)", pipewire_link[0], pipewire_link[1], sorted(self.rigforge_capture_ports.values()), sorted(self.rigforge_playback_ports.values()), ) if attempts_left <= 1: logging.error( "[host] PipeWire backend failed to restore ports: '%s' => '%s'", pipewire_link[0], pipewire_link[1] ) return self._rigforge_restore_attempts[edge] = attempts_left - 1 IOLoop.instance().call_later( 0.5, self._rigforge_restore_pipewire_boundary, pipewire_link, port_from, port_to, connections_now, attempts_left - 1 ) ''' restore_marker = " def _rigforge_restore_pipewire_boundary(" restore_start = updated.find(restore_marker) if restore_start >= 0: restore_end = updated.find("\n def ", restore_start + len(restore_marker)) if restore_end < 0: raise RuntimeError(f"could not locate end of restore method in {host}") updated = updated[:restore_start] + restore_method.rstrip() + "\n\n" + updated[restore_end + 1:] else: marker = " def load_pb_connections(" position = updated.find(marker) if position < 0: raise RuntimeError(f"could not insert PipeWire restore method in {host}") updated = updated[:position] + restore_method + updated[position:] if updated != original_text: host.write_text(updated, encoding="utf-8") def apply(source_root): app = Path(source_root) helper = Path(__file__).with_name("mod_ui_pipewire.py") (app / "mod" / "rigforge_pipewire.py").write_bytes(helper.read_bytes()) replace_if_present( app / "mod" / "host.py", "from mod import (\n", "from mod.rigforge_pipewire import boundary_connection, connect_link, disconnect_link, pedalboard_connection\n" "from mod import (\n", ) replace_if_present( app / "mod" / "host.py", "import os, json, socket, time, logging, sys\n", "import os, json, socket, time, logging, sys, subprocess\n", ) replace_if_present( app / "mod" / "host.py", ''' self.jack_hw_capture_prefix = "mod-host:out" if self.descriptor.get('has_noisegate', False) else "system:capture_" ''', ''' self.jack_hw_capture_prefix = "mod-host:out" if self.descriptor.get('has_noisegate', False) else "system:capture_" self.rigforge_capture_ports = { "capture_%d" % (index + 1): port for index, port in enumerate( os.environ.get("MOD_RIGFORGE_CAPTURE_PORTS", "").split(",") ) if port } self.rigforge_playback_ports = { "playback_%d" % (index + 1): port for index, port in enumerate( os.environ.get("MOD_RIGFORGE_PLAYBACK_PORTS", "").split(",") ) if port } ''', ) replace_if_present( app / "mod" / "host.py", ''' self.rigforge_capture_port = os.environ.get("MOD_RIGFORGE_CAPTURE_PORT") self.rigforge_playback_port = os.environ.get("MOD_RIGFORGE_PLAYBACK_PORT") ''', "", ) replace_if_present( app / "mod" / "host.py", ''' if self.rigforge_capture_port and self.rigforge_playback_port: # These graph symbols map to Rigforge's stable virtual PipeWire boundary ports. self.audioportsIn = ["capture_1"] self.audioportsOut = ["playback_1"] ''', ''' if self.rigforge_capture_ports and self.rigforge_playback_ports: # These graph symbols map to Rigforge's stable virtual PipeWire boundary ports. self.audioportsIn = [ "capture_%d" % index for index in range(1, len(self.rigforge_capture_ports) + 1) ] self.audioportsOut = [ "playback_%d" % index for index in range(1, len(self.rigforge_playback_ports) + 1) ] ''', ) replace_once( app / "mod" / "host.py", ''' for port in get_jack_hardware_ports(True, False): client_name, port_name = port.split(":",1) if client_name == "mod-spi2jack": cv_port_name = CV_PREFIX + port_name self.cvportsIn.append(cv_port_name) self.addressings.add_hw_cv_port('/cv/graph/' + cv_port_name) else: self.audioportsIn.append(port_name) for port in get_jack_hardware_ports(True, True): client_name, port_name = port.split(":",1) if client_name == "mod-jack2spi": self.cvportsOut.append(CV_PREFIX + port_name) else: self.audioportsOut.append(port_name) ''', ''' if self.rigforge_capture_ports and self.rigforge_playback_ports: # These graph symbols map to Rigforge's stable virtual PipeWire boundary ports. self.audioportsIn = [ "capture_%d" % index for index in range(1, len(self.rigforge_capture_ports) + 1) ] self.audioportsOut = [ "playback_%d" % index for index in range(1, len(self.rigforge_playback_ports) + 1) ] else: for port in get_jack_hardware_ports(True, False): client_name, port_name = port.split(":",1) if client_name == "mod-spi2jack": cv_port_name = CV_PREFIX + port_name self.cvportsIn.append(cv_port_name) self.addressings.add_hw_cv_port('/cv/graph/' + cv_port_name) else: self.audioportsIn.append(port_name) for port in get_jack_hardware_ports(True, True): client_name, port_name = port.split(":",1) if client_name == "mod-jack2spi": self.cvportsOut.append(CV_PREFIX + port_name) else: self.audioportsOut.append(port_name) ''', ) replace_if_present( app / "mod" / "host.py", ''' if data[2] == "capture_1" and self.rigforge_capture_port: return self.rigforge_capture_port if data[2] == "playback_1" and self.rigforge_playback_port: return self.rigforge_playback_port ''', ''' if data[2] in self.rigforge_capture_ports: return self.rigforge_capture_ports[data[2]] if data[2] in self.rigforge_playback_ports: return self.rigforge_playback_ports[data[2]] ''', ) replace_if_present( app / "mod" / "host.py", "import os, json, socket, time, logging, sys\n", "import os, json, socket, time, logging, sys, subprocess\n", ) host_file = app / "mod" / "host.py" patch_load_connections(host_file) patch_host_connection_methods(host_file) replace_once( host_file, ''' if bundlepath and (bundlepath.startswith(LV2_PEDALBOARDS_DIR) or bundlepath.startswith(LV2_FACTORY_PEDALBOARDS_DIR)): save_last_bank_and_pedalboard(self.bank_id, bundlepath) else: save_last_bank_and_pedalboard(0, "") ''', ''' if bundlepath and ( bundlepath.startswith(LV2_PEDALBOARDS_DIR) or bundlepath.startswith(LV2_FACTORY_PEDALBOARDS_DIR) or bundlepath.startswith(os.path.join(DATA_DIR, "references")) ): save_last_bank_and_pedalboard(self.bank_id, bundlepath) else: save_last_bank_and_pedalboard(0, "") ''', ) replace_if_present( app / "mod" / "session.py", ''' # Set a plugin block position within the canvas ''', ''' def ws_rigforge_patch_set(self, request_id, instance, uri, valuetype, valuedata, ws): if valuetype != "p": ws.write_message("rigforge_patch_set_ack %s 0" % request_id) return def completed(ok): status = 1 if ok else 0 if ok: self.msg_callback_broadcast( "patch_set %s 1 %s %c %s" % (instance, uri, valuetype, valuedata), ws, ) ws.write_message("rigforge_patch_set_ack %s %d" % (request_id, status)) self.host.patch_set(instance, uri, valuedata, completed) # Set a plugin block position within the canvas ''', ) replace_if_present( app / "mod" / "webserver.py", ''' elif cmd == "plugin_pos": ''', ''' elif cmd == "rigforge_patch_set": data = data[1].split(" ", 4) if len(data) != 5: self.write_message("rigforge_patch_set_ack invalid 0") return request_id, inst, uri, vtype, value = data if not request_id.isalnum(): self.write_message("rigforge_patch_set_ack invalid 0") return SESSION.ws_rigforge_patch_set( request_id, inst, uri, vtype, value, self ) elif cmd == "plugin_pos": ''', ) replace_if_present( app / "server.py", "os.environ['MOD_DEVICE_WEBSERVER_PORT'] = '8888'", "os.environ.setdefault('MOD_DEVICE_WEBSERVER_PORT', '8888')", ) replace_if_present( app / "server.py", "os.environ['MOD_DEFAULT_PEDALBOARD'] = os.path.join(ROOT, 'default.pedalboard')", "os.environ.setdefault('MOD_DEFAULT_PEDALBOARD', os.path.join(ROOT, 'default.pedalboard'))", ) replace_if_present( app / "html" / "js" / "pedalboard.js", ''' var captureTitles = { 1: 'Guitar - Mod-UI Input', 2: 'Bass - Mod-UI Input', 3: 'Micro - Mod-UI Input', 4: 'Synth - Mod-UI Input' } var captureTitle = captureTitles[i] || ('Hardware Capture ' + i) var hw = $('
') ''', ''' var captureTitles = { 1: 'Guitare - Entrée mod-ui', 2: 'Basse - Entrée mod-ui', 3: 'Micro - Entrée mod-ui', 4: 'Synthé - Entrée mod-ui' } var captureTitle = captureTitles[i] || ('Hardware Capture ' + i) var hw = $('
') ''', ) replace_if_present( app / "html" / "js" / "pedalboard.js", ''' var playbackTitles = { 1: 'Guitar - Mod-UI Output', 2: 'Bass - Mod-UI Output', 3: 'Micro - Mod-UI Output', 4: 'Synth - Mod-UI Output' } var playbackTitle = playbackTitles[i] || ('Hardware Playback ' + i) var hw = $('
') ''', ''' var playbackTitles = { 1: 'Guitare - Sortie mod-ui', 2: 'Basse - Sortie mod-ui', 3: 'Micro - Sortie mod-ui', 4: 'Synthé - Sortie mod-ui' } var playbackTitle = playbackTitles[i] || ('Hardware Playback ' + i) var hw = $('
') ''', ) replace_if_present( app / "html" / "js" / "pedalboard.js", ''' var captureTitle = (i === 1) ? 'Rigforge Mod-Host Input' : ('Hardware Capture ' + i) var hw = $('
') ''', ''' var captureTitles = { 1: 'Guitare - Entrée mod-ui', 2: 'Basse - Entrée mod-ui', 3: 'Micro - Entrée mod-ui', 4: 'Synthé - Entrée mod-ui' } var captureTitle = captureTitles[i] || ('Hardware Capture ' + i) var hw = $('
') ''', ) replace_if_present( app / "html" / "js" / "pedalboard.js", ''' var playbackTitle = (i === 1) ? 'Rigforge Mod-Host Output' : ('Hardware Playback ' + i) var hw = $('
') ''', ''' var playbackTitles = { 1: 'Guitare - Sortie mod-ui', 2: 'Basse - Sortie mod-ui', 3: 'Micro - Sortie mod-ui', 4: 'Synthé - Sortie mod-ui' } var playbackTitle = playbackTitles[i] || ('Hardware Playback ' + i) var hw = $('
') ''', ) replace_once( app / "html" / "js" / "pedalboard.js", ''' var hw = $('
') ''', ''' var captureTitles = { 1: 'Guitare - Entrée mod-ui', 2: 'Basse - Entrée mod-ui', 3: 'Micro - Entrée mod-ui', 4: 'Synthé - Entrée mod-ui' } var captureTitle = captureTitles[i] || ('Hardware Capture ' + i) var hw = $('
') ''', ) replace_once( app / "html" / "js" / "pedalboard.js", ''' var hw = $('
') ''', ''' var playbackTitles = { 1: 'Guitare - Sortie mod-ui', 2: 'Basse - Sortie mod-ui', 3: 'Micro - Sortie mod-ui', 4: 'Synthé - Sortie mod-ui' } var playbackTitle = playbackTitles[i] || ('Hardware Playback ' + i) var hw = $('
') ''', ) js_file = app / "html" / "js" / "pedalboard.js" if not js_file.read_bytes().endswith(b"\n"): js_file.write_bytes(js_file.read_bytes() + b"\n") if __name__ == "__main__": if len(sys.argv) != 2: raise SystemExit("Usage: patch_mod_ui_rigforge.py path/to/mod-ui/app") apply(Path(sys.argv[1]))