patch_mod_ui_rigforge.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. #!/usr/bin/env python3
  2. """Apply the small Rigforge integration patch to the pinned mod-ui source tree."""
  3. import sys
  4. from pathlib import Path
  5. def replace_once(path, original, replacement):
  6. text = path.read_text(encoding="utf-8")
  7. if replacement in text:
  8. return
  9. if text.count(original) != 1:
  10. raise RuntimeError(f"expected one upstream match in {path}")
  11. path.write_text(text.replace(original, replacement), encoding="utf-8")
  12. def replace_if_present(path, original, replacement):
  13. text = path.read_text(encoding="utf-8")
  14. if (replacement and replacement in text) or original not in text:
  15. return
  16. if text.count(original) != 1:
  17. raise RuntimeError(f"expected at most one upstream match in {path}")
  18. path.write_text(text.replace(original, replacement), encoding="utf-8")
  19. def replace_host_method(path, method_name, replacement):
  20. """Replace a complete Host method, independent of its upstream body variant."""
  21. text = path.read_text(encoding="utf-8")
  22. marker = f" def {method_name}("
  23. start = text.find(marker)
  24. if start < 0:
  25. raise RuntimeError(f"could not find Host.{method_name} in {path}")
  26. next_method = text.find("\n def ", start + len(marker))
  27. end = len(text) if next_method < 0 else next_method + 1
  28. replacement = replacement.rstrip() + "\n\n"
  29. updated = text[:start] + replacement + text[end:]
  30. if updated != text:
  31. path.write_text(updated, encoding="utf-8")
  32. def patch_host_connection_methods(host):
  33. """Normalize manual connection handling across old Rigforge patch variants."""
  34. replace_host_method(
  35. host,
  36. "connect",
  37. ''' def connect(self, port_from, port_to, callback):
  38. if (port_from, port_to) in self.connections:
  39. logging.info("[host] NOTE: Requested connection already exists")
  40. callback(True)
  41. return
  42. resolved = pedalboard_connection(
  43. port_from, port_to, self.rigforge_capture_ports,
  44. self.rigforge_playback_ports, self._fix_host_connection_port
  45. )
  46. if resolved is not None and resolved[0] == "pipewire":
  47. pipewire_link = resolved[1]
  48. ok = connect_link(*pipewire_link)
  49. callback(ok)
  50. if ok:
  51. self.connections.append((port_from, port_to))
  52. self.pedalboard_modified = True
  53. self.msg_callback("connect %s %s" % (port_from, port_to))
  54. else:
  55. logging.error(
  56. "[host] PipeWire backend failed to connect ports: '%s' => '%s'",
  57. pipewire_link[0], pipewire_link[1]
  58. )
  59. return
  60. def host_callback(ok):
  61. callback(ok)
  62. if ok:
  63. self.connections.append((port_from, port_to))
  64. self.msg_callback("connect %s %s" % (port_from, port_to))
  65. else:
  66. logging.error("[host] backend failed to connect ports: '%s' => '%s'", port_from, port_to)
  67. if resolved is not None:
  68. port_from_2, port_to_2 = resolved[1]
  69. else:
  70. port_from_2 = self._fix_host_connection_port(port_from)
  71. port_to_2 = self._fix_host_connection_port(port_to)
  72. self.send_modified(
  73. "connect %s %s" % (port_from_2, port_to_2),
  74. host_callback,
  75. datatype='boolean'
  76. )''',
  77. )
  78. text = host.read_text(encoding="utf-8")
  79. if " def _rigforge_pipewire_boundary(" in text:
  80. replace_host_method(
  81. host,
  82. "_rigforge_pipewire_boundary",
  83. ''' def _rigforge_pipewire_boundary(self, port_from, port_to):
  84. resolved = pedalboard_connection(
  85. port_from, port_to, self.rigforge_capture_ports,
  86. self.rigforge_playback_ports, self._fix_host_connection_port
  87. )
  88. if resolved is not None and resolved[0] == "pipewire":
  89. return resolved[1]
  90. return None''',
  91. )
  92. replace_host_method(
  93. host,
  94. "disconnect",
  95. ''' def disconnect(self, port_from, port_to, callback):
  96. resolved = pedalboard_connection(
  97. port_from, port_to, self.rigforge_capture_ports,
  98. self.rigforge_playback_ports, self._fix_host_connection_port
  99. )
  100. if resolved is not None and resolved[0] == "pipewire":
  101. pipewire_link = resolved[1]
  102. ok = disconnect_link(*pipewire_link)
  103. callback(ok)
  104. if ok:
  105. self.msg_callback("disconnect %s %s" % (port_from, port_to))
  106. self.pedalboard_modified = True
  107. try:
  108. self.connections.remove((port_from, port_to))
  109. except ValueError:
  110. logging.info(
  111. "[host] Requested '%s' => '%s' connection was not in the UI state",
  112. port_from, port_to
  113. )
  114. else:
  115. logging.error(
  116. "[host] PipeWire backend failed to disconnect ports: '%s' => '%s'",
  117. pipewire_link[0], pipewire_link[1]
  118. )
  119. return
  120. def host_callback(ok):
  121. # Upstream disconnect failures are not fatal to the UI state.
  122. callback(True)
  123. self.msg_callback("disconnect %s %s" % (port_from, port_to))
  124. if not ok:
  125. logging.error("[host] disconnect '%s' => '%s' failed", port_from, port_to)
  126. self.pedalboard_modified = True
  127. try:
  128. self.connections.remove((port_from, port_to))
  129. except ValueError:
  130. logging.info(
  131. "[host] NOTE: Requested '%s' => '%s' connection doesn't exist",
  132. port_from, port_to
  133. )
  134. if resolved is not None:
  135. port_from_2, port_to_2 = resolved[1]
  136. else:
  137. try:
  138. port_from_2 = self._fix_host_connection_port(port_from)
  139. except Exception:
  140. logging.info("[host] NOTE: Requested '%s' source port doesn't exist, assume disconnected", port_from)
  141. return host_callback(True)
  142. try:
  143. port_to_2 = self._fix_host_connection_port(port_to)
  144. except Exception:
  145. logging.info("[host] NOTE: Requested '%s' target port doesn't exist, assume disconnected", port_to)
  146. return host_callback(True)
  147. if len(self.connections) == 0:
  148. return host_callback(False)
  149. self.send_modified(
  150. "disconnect %s %s" % (port_from_2, port_to_2),
  151. host_callback,
  152. datatype='boolean'
  153. )''',
  154. )
  155. def patch_pipewire_helper(helper):
  156. """Keep bare Rigforge boundary-to-boundary cables on concrete PipeWire ports."""
  157. text = helper.read_text(encoding="utf-8")
  158. marker = ''' if "/" in destination_path and not destination_is_playback:
  159. playbacks = {}
  160. '''
  161. replacement = marker + ''' # mod-ui's effect/connect route may pass bare boundary symbols and its
  162. # generic host-port resolver can turn playback_4 into system:playback_4.
  163. # Resolve an explicit Rigforge boundary pair before trying JACK aliases.
  164. if source_path in captures and destination_path in playbacks:
  165. return "pipewire", (captures[source_path], playbacks[destination_path])
  166. '''
  167. if replacement in text:
  168. updated = text
  169. else:
  170. if text.count(marker) != 1:
  171. raise RuntimeError(f"could not identify boundary resolution block in {helper}")
  172. updated = text.replace(marker, replacement, 1)
  173. reverb_marker = ''' "output_r": "lv2_audio_out_2",
  174. },
  175. '''
  176. reverb_replacement = ''' "output_r": "lv2_audio_out_2",
  177. "lv2_audio_in_1": "lv2_audio_in_1",
  178. "lv2_audio_out_1": "lv2_audio_out_1",
  179. "lv2_audio_in_2": "lv2_audio_in_2",
  180. "lv2_audio_out_2": "lv2_audio_out_2",
  181. },
  182. '''
  183. if reverb_replacement not in updated:
  184. if updated.count(reverb_marker) != 1:
  185. raise RuntimeError(f"could not identify reverb port map in {helper}")
  186. updated = updated.replace(reverb_marker, reverb_replacement, 1)
  187. source_marker = ''' pipewire_link = (
  188. captures[source_path],
  189. resolve_pedalboard_port(port_to, resolve_host_port),
  190. )
  191. '''
  192. source_replacement = ''' resolved_destination = resolve_pedalboard_port(port_to, resolve_host_port)
  193. if resolved_destination is not None:
  194. pipewire_link = (captures[source_path], resolved_destination)
  195. '''
  196. if source_replacement not in updated:
  197. if updated.count(source_marker) != 1:
  198. raise RuntimeError(f"could not identify boundary source resolution in {helper}")
  199. updated = updated.replace(source_marker, source_replacement, 1)
  200. destination_marker = ''' pipewire_link = (
  201. resolve_pedalboard_port(port_from, resolve_host_port),
  202. playbacks[destination_path],
  203. )
  204. '''
  205. destination_replacement = ''' resolved_source = resolve_pedalboard_port(port_from, resolve_host_port)
  206. if resolved_source is not None:
  207. pipewire_link = (resolved_source, playbacks[destination_path])
  208. '''
  209. if destination_replacement not in updated:
  210. if updated.count(destination_marker) != 1:
  211. raise RuntimeError(f"could not identify boundary destination resolution in {helper}")
  212. updated = updated.replace(destination_marker, destination_replacement, 1)
  213. if updated != text:
  214. helper.write_text(updated, encoding="utf-8")
  215. def patch_hardware_count_reporting(app):
  216. """Report Rigforge's four mapped boundaries, not only hardware RDF ports."""
  217. javascript = app / "html" / "js" / "pedalboard.js"
  218. source_text = javascript.read_text(encoding="utf-8")
  219. if "window.rigforgeBoundaryChannels = 4;" not in source_text:
  220. source_text = "window.rigforgeBoundaryChannels = 4;\n" + source_text
  221. javascript.write_text(source_text, encoding="utf-8")
  222. replace_if_present(
  223. javascript,
  224. """ for (var i=1, count=data.hardware.audio_ins; i<=count; i++) {""",
  225. """ for (var i=1, count=(window.rigforgeBoundaryChannels || data.hardware.audio_ins); i<=count; i++) {""",
  226. )
  227. replace_if_present(
  228. javascript,
  229. """ for (var i=1, count=data.hardware.audio_outs; i<=count; i++) {""",
  230. """ for (var i=1, count=(window.rigforgeBoundaryChannels || data.hardware.audio_outs); i<=count; i++) {""",
  231. )
  232. text = javascript.read_text(encoding="utf-8")
  233. text = text.replace(
  234. "if (data.hardware) {",
  235. "if (data.hardware || data.plugins) {",
  236. 1,
  237. )
  238. if text != javascript.read_text(encoding="utf-8"):
  239. if not text.endswith("\n"):
  240. text += "\n"
  241. javascript.write_text(text, encoding="utf-8")
  242. def patch_load_connections(host):
  243. """Make pedalboard restore use the same resolution as manual UI actions."""
  244. text = host.read_text(encoding="utf-8")
  245. original_text = text
  246. resolver_marker = " def _fix_host_connection_port(self, port):"
  247. resolver_start = text.find(resolver_marker)
  248. if resolver_start < 0:
  249. raise RuntimeError(f"could not locate Host._fix_host_connection_port in {host}")
  250. resolver_end = text.find(
  251. "\n def ", resolver_start + len(resolver_marker)
  252. )
  253. if resolver_end < 0:
  254. raise RuntimeError(f"could not locate end of Host._fix_host_connection_port in {host}")
  255. resolver_method = text[resolver_start:resolver_end]
  256. if (
  257. "# Rigforge bare boundary port alias; web_connect removes /graph/."
  258. not in resolver_method
  259. ):
  260. marker = ' data = port.split("/")\n'
  261. if resolver_method.count(marker) != 1:
  262. raise RuntimeError(f"could not identify port resolver body in {host}")
  263. updated_resolver = resolver_method.replace(
  264. marker,
  265. ''' # Rigforge bare boundary port alias; web_connect removes /graph/.
  266. if port in self.rigforge_capture_ports:
  267. return self.rigforge_capture_ports[port]
  268. if port in self.rigforge_playback_ports:
  269. return self.rigforge_playback_ports[port]
  270. data = port.split("/")
  271. if len(data) == 2 and data[0] == "" and (
  272. data[1] in self.rigforge_capture_ports
  273. or data[1] in self.rigforge_playback_ports
  274. ):
  275. symbol = data[1]
  276. return self.rigforge_capture_ports.get(
  277. symbol, self.rigforge_playback_ports.get(symbol)
  278. )
  279. ''',
  280. 1,
  281. )
  282. if updated_resolver == resolver_method:
  283. raise RuntimeError(f"could not add Rigforge alias to {host}")
  284. text = text[:resolver_start] + updated_resolver + text[resolver_end:]
  285. method_marker = " def load_pb_connections("
  286. method_start = text.find(method_marker)
  287. if method_start < 0:
  288. raise RuntimeError(f"could not find Host.load_pb_connections in {host}")
  289. block_start = text.find(" if doConnectionNow:", method_start)
  290. block_end = text.find(
  291. "\n elif aliasname1 is not None or aliasname2 is not None:",
  292. block_start,
  293. )
  294. if block_start < 0 or block_end < 0:
  295. raise RuntimeError(
  296. f"could not identify mod-ui pedalboard connection restoration block in {host}"
  297. )
  298. replacement = ''' if doConnectionNow:
  299. resolved = pedalboard_connection(
  300. port_from, port_to, self.rigforge_capture_ports,
  301. self.rigforge_playback_ports, self._fix_host_connection_port
  302. )
  303. if (
  304. port_from.removeprefix("/graph/") == "capture_4"
  305. and port_to.removeprefix("/graph/") == "playback_4"
  306. and self.rigforge_capture_ports
  307. and self.rigforge_playback_ports
  308. ):
  309. resolved = (
  310. "pipewire",
  311. (
  312. self.rigforge_capture_ports["capture_4"],
  313. self.rigforge_playback_ports["playback_4"],
  314. ),
  315. )
  316. if resolved is not None and resolved[0] == "pipewire":
  317. self._rigforge_restore_pipewire_boundary(
  318. resolved[1],
  319. port_from,
  320. port_to,
  321. attempts_left=60
  322. )
  323. continue
  324. try:
  325. if resolved is not None:
  326. port_from_2, port_to_2 = resolved[1]
  327. else:
  328. port_from_2 = self._fix_host_connection_port(port_from)
  329. port_to_2 = self._fix_host_connection_port(port_to)
  330. except Exception:
  331. continue
  332. self.send_notmodified("connect %s %s" % (port_from_2, port_to_2))
  333. self.connections.append((port_from, port_to))
  334. self.msg_callback("connect %s %s" % (port_from, port_to))'''
  335. updated = text[:block_start] + replacement + text[block_end:]
  336. restore_method = ''' def _rigforge_restore_pipewire_boundary(
  337. self, pipewire_link, port_from, port_to, attempts_left
  338. ):
  339. if not hasattr(self, "_rigforge_restore_attempts"):
  340. self._rigforge_restore_attempts = {}
  341. edge = (port_from, port_to)
  342. attempts_left = min(
  343. attempts_left, self._rigforge_restore_attempts.get(edge, 60)
  344. )
  345. if not (
  346. self.rigforge_capture_ports
  347. and self.rigforge_playback_ports
  348. and all(
  349. "capture_%d" % index in self.audioportsIn
  350. for index in range(1, len(self.rigforge_capture_ports) + 1)
  351. )
  352. and all(
  353. "playback_%d" % index in self.audioportsOut
  354. for index in range(1, len(self.rigforge_playback_ports) + 1)
  355. )
  356. ):
  357. ready = False
  358. else:
  359. result = subprocess.run(
  360. ["pw-link", "-o"],
  361. check=False,
  362. capture_output=True,
  363. text=True,
  364. )
  365. ready = result.returncode == 0 and all(
  366. port in result.stdout.splitlines()
  367. for port in (
  368. *self.rigforge_capture_ports.values(),
  369. *self.rigforge_playback_ports.values(),
  370. )
  371. )
  372. if edge in self.connections:
  373. self._rigforge_restore_attempts.pop(edge, None)
  374. return
  375. if not ready and attempts_left == 60:
  376. logging.error(
  377. "[host] PipeWire boundary readiness failed: inputs=%r outputs=%r "
  378. "configured_capture=%r configured_playback=%r",
  379. self.audioportsIn,
  380. self.audioportsOut,
  381. sorted(self.rigforge_capture_ports),
  382. sorted(self.rigforge_playback_ports),
  383. )
  384. if ready and connect_link(*pipewire_link):
  385. self._rigforge_restore_attempts.pop(edge, None)
  386. if edge not in self.connections:
  387. self.connections.append(edge)
  388. self.msg_callback("connect %s %s" % (port_from, port_to))
  389. return
  390. if not ready and edge not in self._rigforge_restore_attempts:
  391. logging.error(
  392. "[host] PipeWire boundary ports are not ready for restore: '%s' => '%s' "
  393. "(capture ports: %s; playback ports: %s)",
  394. pipewire_link[0],
  395. pipewire_link[1],
  396. sorted(self.rigforge_capture_ports.values()),
  397. sorted(self.rigforge_playback_ports.values()),
  398. )
  399. if attempts_left <= 1:
  400. logging.error(
  401. "[host] PipeWire backend failed to restore ports: '%s' => '%s'",
  402. pipewire_link[0], pipewire_link[1]
  403. )
  404. return
  405. self._rigforge_restore_attempts[edge] = attempts_left - 1
  406. IOLoop.instance().call_later(
  407. 0.5,
  408. self._rigforge_restore_pipewire_boundary,
  409. pipewire_link,
  410. port_from,
  411. port_to,
  412. attempts_left - 1
  413. )
  414. '''
  415. restore_marker = " def _rigforge_restore_pipewire_boundary("
  416. restore_start = updated.find(restore_marker)
  417. if restore_start >= 0:
  418. restore_end = updated.find("\n def ", restore_start + len(restore_marker))
  419. if restore_end < 0:
  420. raise RuntimeError(f"could not locate end of restore method in {host}")
  421. updated = updated[:restore_start] + restore_method.rstrip() + "\n\n" + updated[restore_end + 1:]
  422. else:
  423. marker = " def load_pb_connections("
  424. position = updated.find(marker)
  425. if position < 0:
  426. raise RuntimeError(f"could not insert PipeWire restore method in {host}")
  427. updated = updated[:position] + restore_method + updated[position:]
  428. if updated != original_text:
  429. host.write_text(updated, encoding="utf-8")
  430. def apply(source_root):
  431. app = Path(source_root)
  432. patch_hardware_count_reporting(app)
  433. helper = Path(__file__).with_name("mod_ui_pipewire.py")
  434. patch_pipewire_helper(helper)
  435. (app / "mod" / "rigforge_pipewire.py").write_bytes(helper.read_bytes())
  436. replace_if_present(
  437. app / "mod" / "host.py",
  438. "from mod import (\n",
  439. "from mod.rigforge_pipewire import boundary_connection, connect_link, disconnect_link, pedalboard_connection\n"
  440. "from mod import (\n",
  441. )
  442. replace_if_present(
  443. app / "mod" / "host.py",
  444. "import os, json, socket, time, logging, sys\n",
  445. "import os, json, socket, time, logging, sys, subprocess\n",
  446. )
  447. replace_if_present(
  448. app / "mod" / "host.py",
  449. ''' self.jack_hw_capture_prefix = "mod-host:out" if self.descriptor.get('has_noisegate', False) else "system:capture_"
  450. ''',
  451. ''' self.jack_hw_capture_prefix = "mod-host:out" if self.descriptor.get('has_noisegate', False) else "system:capture_"
  452. self.rigforge_capture_ports = {
  453. "capture_%d" % (index + 1): port
  454. for index, port in enumerate(
  455. os.environ.get("MOD_RIGFORGE_CAPTURE_PORTS", "").split(",")
  456. )
  457. if port
  458. }
  459. self.rigforge_playback_ports = {
  460. "playback_%d" % (index + 1): port
  461. for index, port in enumerate(
  462. os.environ.get("MOD_RIGFORGE_PLAYBACK_PORTS", "").split(",")
  463. )
  464. if port
  465. }
  466. ''',
  467. )
  468. replace_if_present(
  469. app / "mod" / "host.py",
  470. ''' self.rigforge_capture_port = os.environ.get("MOD_RIGFORGE_CAPTURE_PORT")
  471. self.rigforge_playback_port = os.environ.get("MOD_RIGFORGE_PLAYBACK_PORT")
  472. ''',
  473. "",
  474. )
  475. replace_if_present(
  476. app / "mod" / "host.py",
  477. ''' if self.rigforge_capture_port and self.rigforge_playback_port:
  478. # These graph symbols map to Rigforge's stable virtual PipeWire boundary ports.
  479. self.audioportsIn = ["capture_1"]
  480. self.audioportsOut = ["playback_1"]
  481. ''',
  482. ''' if self.rigforge_capture_ports and self.rigforge_playback_ports:
  483. # These graph symbols map to Rigforge's stable virtual PipeWire boundary ports.
  484. self.audioportsIn = [
  485. "capture_%d" % index
  486. for index in range(1, len(self.rigforge_capture_ports) + 1)
  487. ]
  488. self.audioportsOut = [
  489. "playback_%d" % index
  490. for index in range(1, len(self.rigforge_playback_ports) + 1)
  491. ]
  492. ''',
  493. )
  494. replace_once(
  495. app / "mod" / "host.py",
  496. ''' for port in get_jack_hardware_ports(True, False):
  497. client_name, port_name = port.split(":",1)
  498. if client_name == "mod-spi2jack":
  499. cv_port_name = CV_PREFIX + port_name
  500. self.cvportsIn.append(cv_port_name)
  501. self.addressings.add_hw_cv_port('/cv/graph/' + cv_port_name)
  502. else:
  503. self.audioportsIn.append(port_name)
  504. for port in get_jack_hardware_ports(True, True):
  505. client_name, port_name = port.split(":",1)
  506. if client_name == "mod-jack2spi":
  507. self.cvportsOut.append(CV_PREFIX + port_name)
  508. else:
  509. self.audioportsOut.append(port_name)
  510. ''',
  511. ''' if self.rigforge_capture_ports and self.rigforge_playback_ports:
  512. # These graph symbols map to Rigforge's stable virtual PipeWire boundary ports.
  513. self.audioportsIn = [
  514. "capture_%d" % index
  515. for index in range(1, len(self.rigforge_capture_ports) + 1)
  516. ]
  517. self.audioportsOut = [
  518. "playback_%d" % index
  519. for index in range(1, len(self.rigforge_playback_ports) + 1)
  520. ]
  521. else:
  522. for port in get_jack_hardware_ports(True, False):
  523. client_name, port_name = port.split(":",1)
  524. if client_name == "mod-spi2jack":
  525. cv_port_name = CV_PREFIX + port_name
  526. self.cvportsIn.append(cv_port_name)
  527. self.addressings.add_hw_cv_port('/cv/graph/' + cv_port_name)
  528. else:
  529. self.audioportsIn.append(port_name)
  530. for port in get_jack_hardware_ports(True, True):
  531. client_name, port_name = port.split(":",1)
  532. if client_name == "mod-jack2spi":
  533. self.cvportsOut.append(CV_PREFIX + port_name)
  534. else:
  535. self.audioportsOut.append(port_name)
  536. ''',
  537. )
  538. replace_if_present(
  539. app / "mod" / "host.py",
  540. ''' if data[2] == "capture_1" and self.rigforge_capture_port:
  541. return self.rigforge_capture_port
  542. if data[2] == "playback_1" and self.rigforge_playback_port:
  543. return self.rigforge_playback_port
  544. ''',
  545. ''' if data[2] in self.rigforge_capture_ports:
  546. return self.rigforge_capture_ports[data[2]]
  547. if data[2] in self.rigforge_playback_ports:
  548. return self.rigforge_playback_ports[data[2]]
  549. ''',
  550. )
  551. replace_if_present(
  552. app / "mod" / "host.py",
  553. "import os, json, socket, time, logging, sys\n",
  554. "import os, json, socket, time, logging, sys, subprocess\n",
  555. )
  556. host_file = app / "mod" / "host.py"
  557. patch_load_connections(host_file)
  558. patch_host_connection_methods(host_file)
  559. replace_once(
  560. host_file,
  561. ''' if bundlepath and (bundlepath.startswith(LV2_PEDALBOARDS_DIR) or
  562. bundlepath.startswith(LV2_FACTORY_PEDALBOARDS_DIR)):
  563. save_last_bank_and_pedalboard(self.bank_id, bundlepath)
  564. else:
  565. save_last_bank_and_pedalboard(0, "")
  566. ''',
  567. ''' if bundlepath and (
  568. bundlepath.startswith(LV2_PEDALBOARDS_DIR)
  569. or bundlepath.startswith(LV2_FACTORY_PEDALBOARDS_DIR)
  570. or bundlepath.startswith(os.path.join(DATA_DIR, "references"))
  571. ):
  572. save_last_bank_and_pedalboard(self.bank_id, bundlepath)
  573. else:
  574. save_last_bank_and_pedalboard(0, "")
  575. ''',
  576. )
  577. replace_if_present(
  578. app / "mod" / "session.py",
  579. ''' # Set a plugin block position within the canvas
  580. ''',
  581. ''' def ws_rigforge_patch_set(self, request_id, instance, uri, valuetype, valuedata, ws):
  582. if valuetype != "p":
  583. ws.write_message("rigforge_patch_set_ack %s 0" % request_id)
  584. return
  585. def completed(ok):
  586. status = 1 if ok else 0
  587. if ok:
  588. self.msg_callback_broadcast(
  589. "patch_set %s 1 %s %c %s" % (instance, uri, valuetype, valuedata),
  590. ws,
  591. )
  592. ws.write_message("rigforge_patch_set_ack %s %d" % (request_id, status))
  593. self.host.patch_set(instance, uri, valuedata, completed)
  594. # Set a plugin block position within the canvas
  595. ''',
  596. )
  597. replace_if_present(
  598. app / "mod" / "webserver.py",
  599. ''' elif cmd == "plugin_pos":
  600. ''',
  601. ''' elif cmd == "rigforge_patch_set":
  602. data = data[1].split(" ", 4)
  603. if len(data) != 5:
  604. self.write_message("rigforge_patch_set_ack invalid 0")
  605. return
  606. request_id, inst, uri, vtype, value = data
  607. if not request_id.isalnum():
  608. self.write_message("rigforge_patch_set_ack invalid 0")
  609. return
  610. SESSION.ws_rigforge_patch_set(
  611. request_id, inst, uri, vtype, value, self
  612. )
  613. elif cmd == "plugin_pos":
  614. ''',
  615. )
  616. replace_if_present(
  617. app / "server.py",
  618. "os.environ['MOD_DEVICE_WEBSERVER_PORT'] = '8888'",
  619. "os.environ.setdefault('MOD_DEVICE_WEBSERVER_PORT', '8888')",
  620. )
  621. replace_if_present(
  622. app / "server.py",
  623. "os.environ['MOD_DEFAULT_PEDALBOARD'] = os.path.join(ROOT, 'default.pedalboard')",
  624. "os.environ.setdefault('MOD_DEFAULT_PEDALBOARD', os.path.join(ROOT, 'default.pedalboard'))",
  625. )
  626. replace_if_present(
  627. app / "html" / "js" / "pedalboard.js",
  628. ''' var captureTitles = {
  629. 1: 'Guitar - Mod-UI Input',
  630. 2: 'Bass - Mod-UI Input',
  631. 3: 'Micro - Mod-UI Input',
  632. 4: 'Synth - Mod-UI Input'
  633. }
  634. var captureTitle = captureTitles[i] || ('Hardware Capture ' + i)
  635. var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="' + i + '" title="' + captureTitle + '">')
  636. ''',
  637. ''' var captureTitles = {
  638. 1: 'Guitare - Entrée mod-ui',
  639. 2: 'Basse - Entrée mod-ui',
  640. 3: 'Micro - Entrée mod-ui',
  641. 4: 'Synthé - Entrée mod-ui'
  642. }
  643. var captureTitle = captureTitles[i] || ('Hardware Capture ' + i)
  644. var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="' + i + '" title="' + captureTitle + '">')
  645. ''',
  646. )
  647. replace_if_present(
  648. app / "html" / "js" / "pedalboard.js",
  649. ''' var playbackTitles = {
  650. 1: 'Guitar - Mod-UI Output',
  651. 2: 'Bass - Mod-UI Output',
  652. 3: 'Micro - Mod-UI Output',
  653. 4: 'Synth - Mod-UI Output'
  654. }
  655. var playbackTitle = playbackTitles[i] || ('Hardware Playback ' + i)
  656. var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="' + i + '" title="' + playbackTitle + '">')
  657. ''',
  658. ''' var playbackTitles = {
  659. 1: 'Guitare - Sortie mod-ui',
  660. 2: 'Basse - Sortie mod-ui',
  661. 3: 'Micro - Sortie mod-ui',
  662. 4: 'Synthé - Sortie mod-ui'
  663. }
  664. var playbackTitle = playbackTitles[i] || ('Hardware Playback ' + i)
  665. var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="' + i + '" title="' + playbackTitle + '">')
  666. ''',
  667. )
  668. replace_if_present(
  669. app / "html" / "js" / "pedalboard.js",
  670. ''' var captureTitle = (i === 1) ? 'Rigforge Mod-Host Input' : ('Hardware Capture ' + i)
  671. var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="' + i + '" title="' + captureTitle + '">')
  672. ''',
  673. ''' var captureTitles = {
  674. 1: 'Guitare - Entrée mod-ui',
  675. 2: 'Basse - Entrée mod-ui',
  676. 3: 'Micro - Entrée mod-ui',
  677. 4: 'Synthé - Entrée mod-ui'
  678. }
  679. var captureTitle = captureTitles[i] || ('Hardware Capture ' + i)
  680. var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="' + i + '" title="' + captureTitle + '">')
  681. ''',
  682. )
  683. replace_if_present(
  684. app / "html" / "js" / "pedalboard.js",
  685. ''' var playbackTitle = (i === 1) ? 'Rigforge Mod-Host Output' : ('Hardware Playback ' + i)
  686. var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="' + i + '" title="' + playbackTitle + '">')
  687. ''',
  688. ''' var playbackTitles = {
  689. 1: 'Guitare - Sortie mod-ui',
  690. 2: 'Basse - Sortie mod-ui',
  691. 3: 'Micro - Sortie mod-ui',
  692. 4: 'Synthé - Sortie mod-ui'
  693. }
  694. var playbackTitle = playbackTitles[i] || ('Hardware Playback ' + i)
  695. var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="' + i + '" title="' + playbackTitle + '">')
  696. ''',
  697. )
  698. replace_if_present(
  699. app / "html" / "js" / "pedalboard.js",
  700. ''' var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="' + i + '" title="Hardware Capture ' + i + '">')
  701. ''',
  702. ''' var captureTitles = {
  703. 1: 'Guitare - Entrée mod-ui',
  704. 2: 'Basse - Entrée mod-ui',
  705. 3: 'Micro - Entrée mod-ui',
  706. 4: 'Synthé - Entrée mod-ui'
  707. }
  708. var captureTitle = captureTitles[i] || ('Hardware Capture ' + i)
  709. var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="' + i + '" title="' + captureTitle + '">')
  710. ''',
  711. )
  712. replace_if_present(
  713. app / "html" / "js" / "pedalboard.js",
  714. ''' var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="' + i + '" title="Hardware Playback ' + i + '">')
  715. ''',
  716. ''' var playbackTitles = {
  717. 1: 'Guitare - Sortie mod-ui',
  718. 2: 'Basse - Sortie mod-ui',
  719. 3: 'Micro - Sortie mod-ui',
  720. 4: 'Synthé - Sortie mod-ui'
  721. }
  722. var playbackTitle = playbackTitles[i] || ('Hardware Playback ' + i)
  723. var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="' + i + '" title="' + playbackTitle + '">')
  724. ''',
  725. )
  726. replace_if_present(
  727. app / "html" / "js" / "pedalboard.js",
  728. "symbol = (i < 3) ? ('/graph/capture_' + i) : ('/graph/audio_from_slave_' + (i-2))",
  729. "symbol = '/graph/capture_' + i",
  730. )
  731. replace_if_present(
  732. app / "html" / "js" / "pedalboard.js",
  733. "symbol = (i < 3) ? ('/graph/playback_' + i) : ('/graph/audio_to_slave_' + (i-2))",
  734. "symbol = '/graph/playback_' + i",
  735. )
  736. js_file = app / "html" / "js" / "pedalboard.js"
  737. if not js_file.read_bytes().endswith(b"\n"):
  738. js_file.write_bytes(js_file.read_bytes() + b"\n")
  739. if __name__ == "__main__":
  740. if len(sys.argv) != 2:
  741. raise SystemExit("Usage: patch_mod_ui_rigforge.py path/to/mod-ui/app")
  742. apply(Path(sys.argv[1]))