generate_mod_ui_pedalboard.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. #!/usr/bin/env python3
  2. """Generate Rigforge's four-source reference pedalboard bundle for mod-ui."""
  3. import argparse
  4. import hashlib
  5. import json
  6. import os
  7. import shutil
  8. import sys
  9. import tempfile
  10. from pathlib import Path, PurePosixPath
  11. import yaml
  12. from validate_desired_state import safe_relative_path, validate_state
  13. ROOT = Path(__file__).resolve().parents[1]
  14. def turtle_string(value):
  15. return json.dumps(str(value), ensure_ascii=False)
  16. def plugin_state_files(processor, plugin_path):
  17. instance = processor["instance"]
  18. plugin_uri = processor["plugin_uri"]
  19. file_property = processor["file_property"]
  20. state_dir = f"effect-{instance}"
  21. effect_ttl = (
  22. "@prefix atom: <http://lv2plug.in/ns/ext/atom#> .\n"
  23. "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
  24. "@prefix pset: <http://lv2plug.in/ns/ext/presets#> .\n"
  25. "@prefix state: <http://lv2plug.in/ns/ext/state#> .\n\n"
  26. "<>\n"
  27. " a pset:Preset ;\n"
  28. f" lv2:appliesTo <{plugin_uri}> ;\n"
  29. " state:state [\n"
  30. f" <{file_property}> {turtle_string(plugin_path)}^^atom:Path\n"
  31. " ] .\n"
  32. )
  33. manifest_ttl = (
  34. "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
  35. "@prefix pset: <http://lv2plug.in/ns/ext/presets#> .\n"
  36. "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\n"
  37. "<effect.ttl>\n"
  38. f" lv2:appliesTo <{plugin_uri}> ;\n"
  39. " a pset:Preset ;\n"
  40. " rdfs:seeAlso <effect.ttl> .\n"
  41. )
  42. return {
  43. f"{state_dir}/effect.ttl": effect_ttl.encode("utf-8"),
  44. f"{state_dir}/manifest.ttl": manifest_ttl.encode("utf-8"),
  45. }
  46. def resolved_asset(repo_root, relative):
  47. if not safe_relative_path(relative):
  48. raise ValueError(f"unsafe pedalboard asset path: {relative!r}")
  49. path = (repo_root / Path(*PurePosixPath(relative).parts)).resolve()
  50. if not path.is_relative_to(repo_root.resolve()) or not path.is_file():
  51. raise FileNotFoundError(f"pedalboard asset is missing or outside repository: {path}")
  52. return path
  53. def generate_bundle_files(state, repo_root=ROOT, asset_root=None, nam_model_path=None):
  54. errors = validate_state(state)
  55. if errors:
  56. raise ValueError("invalid desired state: " + "; ".join(errors))
  57. repo_root = Path(repo_root).resolve()
  58. asset_root = Path(asset_root or repo_root / "artifacts" / "mod-ui" / "arm64" / "current" / "app" / "default.pedalboard")
  59. routing = state["routing"]["mod_host_chains"]["guitar"]
  60. nam, ir = routing["processors"]
  61. nam_source_path = resolved_asset(repo_root, nam["asset_path"])
  62. nam_path = Path(nam_model_path).resolve() if nam_model_path else nam_source_path
  63. if not nam_path.is_file():
  64. raise FileNotFoundError(f"NAM model file is missing: {nam_path}")
  65. ir_path = resolved_asset(repo_root, ir["asset_path"])
  66. output_level = nam["parameters"]["output_level"]
  67. nam_instance = nam["mod_ui_instance"].removeprefix("/graph/")
  68. ir_instance = ir["mod_ui_instance"].removeprefix("/graph/")
  69. nam_model_uri = nam["file_property"]
  70. ir_file_uri = ir["file_property"]
  71. source_labels = {
  72. "guitar": "Guitare",
  73. "bass": "Basse",
  74. "voice": "Micro",
  75. "synth": "Synthé",
  76. }
  77. source_ids = {source["id"] for source in state["sources"]}
  78. passthrough_channels = [
  79. (index, source_labels[source_id])
  80. for index, source_id in enumerate(("guitar", "bass", "voice", "synth"), start=1)
  81. if source_id != "guitar" and source_id in source_ids
  82. ]
  83. additional_ports_ttl = "\n\n".join(
  84. f'''<capture_{index}>
  85. lv2:index {9 + (index - 2) * 2} ;
  86. lv2:name "{label} - Entrée mod-ui" ;
  87. lv2:portProperty lv2:connectionOptional ;
  88. lv2:symbol "capture_{index}" ;
  89. a lv2:AudioPort, lv2:InputPort .
  90. <playback_{index}>
  91. lv2:index {10 + (index - 2) * 2} ;
  92. lv2:name "{label} - Sortie mod-ui" ;
  93. lv2:portProperty lv2:connectionOptional ;
  94. lv2:symbol "playback_{index}" ;
  95. a lv2:AudioPort, lv2:OutputPort .'''
  96. for index, label in passthrough_channels
  97. )
  98. additional_ports_list = ",\n ".join(
  99. f"<{symbol}_{index}>"
  100. for index, _label in passthrough_channels
  101. for symbol in ("capture", "playback")
  102. )
  103. additional_arcs_list = ", ".join(
  104. f"_:b{index + 2}" for index, _label in passthrough_channels
  105. )
  106. additional_arcs_ttl = "\n\n".join(
  107. f"_:b{index + 2} ingen:tail <capture_{index}> ;\n"
  108. f" ingen:head <playback_{index}> ."
  109. for index, _label in passthrough_channels
  110. )
  111. ttl = f"""\
  112. @prefix atom: <http://lv2plug.in/ns/ext/atom#> .
  113. @prefix doap: <http://usefulinc.com/ns/doap#> .
  114. @prefix ingen: <http://drobilla.net/ns/ingen#> .
  115. @prefix lv2: <http://lv2plug.in/ns/lv2core#> .
  116. @prefix midi: <http://lv2plug.in/ns/ext/midi#> .
  117. @prefix mod: <http://moddevices.com/ns/mod#> .
  118. @prefix patch: <http://lv2plug.in/ns/ext/patch#> .
  119. @prefix pedal: <http://moddevices.com/ns/modpedal#> .
  120. @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
  121. @prefix state: <http://lv2plug.in/ns/ext/state#> .
  122. @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
  123. <capture_1>
  124. lv2:index 5 ;
  125. lv2:name "Guitare - Entrée mod-ui" ;
  126. lv2:portProperty lv2:connectionOptional ;
  127. lv2:symbol "capture_1" ;
  128. a lv2:AudioPort, lv2:InputPort .
  129. <playback_1>
  130. lv2:index 6 ;
  131. lv2:name "Guitare - Sortie mod-ui" ;
  132. lv2:portProperty lv2:connectionOptional ;
  133. lv2:symbol "playback_1" ;
  134. a lv2:AudioPort, lv2:OutputPort .
  135. {additional_ports_ttl}
  136. <:bpb>
  137. ingen:value 4.0 ;
  138. lv2:index 0 ;
  139. a lv2:ControlPort, lv2:InputPort .
  140. <:bpm>
  141. ingen:value 120.0 ;
  142. lv2:index 1 ;
  143. a lv2:ControlPort, lv2:InputPort .
  144. <:rolling>
  145. ingen:value 0 ;
  146. lv2:index 2 ;
  147. a lv2:ControlPort, lv2:InputPort .
  148. <control_in>
  149. atom:bufferType atom:Sequence ;
  150. atom:supports midi:MidiEvent ;
  151. lv2:index 3 ;
  152. lv2:name "Control In" ;
  153. lv2:portProperty lv2:connectionOptional ;
  154. lv2:symbol "control_in" ;
  155. <http://lv2plug.in/ns/ext/resize-port#minimumSize> 4096 ;
  156. a atom:AtomPort, lv2:InputPort .
  157. <control_out>
  158. atom:bufferType atom:Sequence ;
  159. atom:supports midi:MidiEvent ;
  160. lv2:index 4 ;
  161. lv2:name "Control Out" ;
  162. lv2:portProperty lv2:connectionOptional ;
  163. lv2:symbol "control_out" ;
  164. <http://lv2plug.in/ns/ext/resize-port#minimumSize> 4096 ;
  165. a atom:AtomPort, lv2:OutputPort .
  166. <midi_separated_mode>
  167. ingen:value 0 ;
  168. lv2:index 7 ;
  169. a atom:AtomPort, lv2:InputPort .
  170. <midi_loopback>
  171. ingen:value 0 ;
  172. lv2:index 8 ;
  173. a atom:AtomPort, lv2:InputPort .
  174. <{nam_instance}>
  175. ingen:canvasX 160.0 ;
  176. ingen:canvasY 280.0 ;
  177. ingen:enabled true ;
  178. ingen:polyphonic false ;
  179. lv2:microVersion 0 ;
  180. lv2:minorVersion 0 ;
  181. mod:builderVersion 0 ;
  182. mod:releaseNumber 0 ;
  183. pedal:instanceLabel "NAM" ;
  184. pedal:instanceNumber {nam["instance"]} ;
  185. pedal:performanceVisible true ;
  186. pedal:performanceIndex 0 ;
  187. lv2:prototype <{nam["plugin_uri"]}> ;
  188. lv2:port <{nam_instance}/control>,
  189. <{nam_instance}/notify>,
  190. <{nam_instance}/input>,
  191. <{nam_instance}/output>,
  192. <{nam_instance}/input_level>,
  193. <{nam_instance}/output_level>,
  194. <{nam_instance}/quality_scale>,
  195. <{nam_instance}/:bypass> ;
  196. state:state [ <{nam_model_uri}> {turtle_string(str(nam_path))}^^atom:Path ] ;
  197. a ingen:Block .
  198. <{nam_instance}/control>
  199. atom:bufferType atom:Sequence ;
  200. atom:supports patch:Message ;
  201. lv2:designation lv2:control ;
  202. lv2:index 0 ;
  203. lv2:symbol "control" ;
  204. a atom:AtomPort, lv2:InputPort .
  205. <{nam_instance}/notify>
  206. atom:bufferType atom:Sequence ;
  207. atom:supports patch:Message ;
  208. lv2:designation lv2:control ;
  209. lv2:index 1 ;
  210. lv2:symbol "notify" ;
  211. a atom:AtomPort, lv2:OutputPort .
  212. <{nam_instance}/input>
  213. a lv2:AudioPort, lv2:InputPort .
  214. <{nam_instance}/output>
  215. a lv2:AudioPort, lv2:OutputPort .
  216. <{nam_instance}/input_level>
  217. ingen:value 0.0 ;
  218. a lv2:ControlPort, lv2:InputPort .
  219. <{nam_instance}/output_level>
  220. ingen:value {output_level} ;
  221. a lv2:ControlPort, lv2:InputPort .
  222. <{nam_instance}/quality_scale>
  223. ingen:value 1.0 ;
  224. a lv2:ControlPort, lv2:InputPort .
  225. <{nam_instance}/:bypass>
  226. ingen:value 0 ;
  227. a lv2:ControlPort, lv2:InputPort .
  228. <{ir_instance}>
  229. ingen:canvasX 620.0 ;
  230. ingen:canvasY 280.0 ;
  231. ingen:enabled true ;
  232. ingen:polyphonic false ;
  233. lv2:microVersion 0 ;
  234. lv2:minorVersion 0 ;
  235. mod:builderVersion 0 ;
  236. mod:releaseNumber 0 ;
  237. pedal:instanceLabel "Cabinet IR" ;
  238. pedal:instanceNumber {ir["instance"]} ;
  239. pedal:performanceVisible true ;
  240. pedal:performanceIndex 1 ;
  241. lv2:prototype <{ir["plugin_uri"]}> ;
  242. lv2:port <{ir_instance}/control>,
  243. <{ir_instance}/notify>,
  244. <{ir_instance}/in>,
  245. <{ir_instance}/out>,
  246. <{ir_instance}/:bypass> ;
  247. state:state [ <{ir_file_uri}> {turtle_string(str(ir_path))}^^atom:Path ] ;
  248. a ingen:Block .
  249. <{ir_instance}/control>
  250. atom:bufferType atom:Sequence ;
  251. atom:supports patch:Message ;
  252. lv2:designation lv2:control ;
  253. a atom:AtomPort, lv2:InputPort .
  254. <{ir_instance}/notify>
  255. atom:bufferType atom:Sequence ;
  256. atom:supports patch:Message ;
  257. lv2:designation lv2:control ;
  258. a atom:AtomPort, lv2:OutputPort .
  259. <{ir_instance}/in>
  260. a lv2:AudioPort, lv2:InputPort .
  261. <{ir_instance}/out>
  262. a lv2:AudioPort, lv2:OutputPort .
  263. <{ir_instance}/:bypass>
  264. ingen:value 0 ;
  265. a lv2:ControlPort, lv2:InputPort .
  266. <>
  267. doap:name "Rigforge - Guitare NAM/IR, Basse, Micro, Synthé" ;
  268. pedal:unitName "Rigforge" ;
  269. pedal:unitModel "Generic" ;
  270. pedal:width 1200 ;
  271. pedal:height 700 ;
  272. pedal:addressings <addressings.json> ;
  273. pedal:screenshot <screenshot.png> ;
  274. pedal:thumbnail <thumbnail.png> ;
  275. pedal:formatVersion 2 ;
  276. pedal:version 1 ;
  277. ingen:polyphony 1 ;
  278. ingen:arc _:b1, _:b2, _:b3, {additional_arcs_list} ;
  279. ingen:block <{nam_instance}>, <{ir_instance}> ;
  280. lv2:port <:bpb>, <:bpm>, <:rolling>,
  281. <control_in>, <control_out>,
  282. <capture_1>, <playback_1>,
  283. {additional_ports_list},
  284. <midi_separated_mode>, <midi_loopback> ;
  285. lv2:extensionData <http://lv2plug.in/ns/ext/state#interface> ;
  286. a lv2:Plugin, ingen:Graph, pedal:Pedalboard .
  287. _:b1 ingen:tail <capture_1> ;
  288. ingen:head <{nam_instance}/input> .
  289. _:b2 ingen:tail <{nam_instance}/output> ;
  290. ingen:head <{ir_instance}/in> .
  291. _:b3 ingen:tail <{ir_instance}/out> ;
  292. ingen:head <playback_1> .
  293. {additional_arcs_ttl}
  294. """
  295. files = {
  296. "manifest.ttl": (
  297. "@prefix ingen: <http://drobilla.net/ns/ingen#> .\n"
  298. "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
  299. "@prefix pedal: <http://moddevices.com/ns/modpedal#> .\n"
  300. "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\n"
  301. "<rigforge-guitar.ttl>\n"
  302. " lv2:prototype ingen:GraphPrototype ;\n"
  303. " a lv2:Plugin, ingen:Graph, pedal:Pedalboard ;\n"
  304. " rdfs:seeAlso <rigforge-guitar.ttl> .\n"
  305. ).encode("utf-8"),
  306. "rigforge-guitar.ttl": ttl.encode("utf-8"),
  307. "addressings.json": b"{}\n",
  308. "snapshots.json": b'{"current":0,"snapshots":[]}\n',
  309. }
  310. files.update(plugin_state_files(nam, nam_path))
  311. files.update(plugin_state_files(ir, ir_path))
  312. for image_name in ("screenshot.png", "thumbnail.png"):
  313. image = asset_root / image_name
  314. if not image.is_file():
  315. raise FileNotFoundError(f"mod-ui default board image is missing: {image}")
  316. files[image_name] = image.read_bytes()
  317. return files
  318. def write_bundle(output, files, overwrite=False):
  319. output = Path(output)
  320. if output.exists():
  321. if output.is_symlink() or not output.is_dir():
  322. raise RuntimeError(f"pedalboard output is not a regular directory: {output}")
  323. existing = {}
  324. for path in output.rglob("*"):
  325. if path.is_symlink():
  326. raise RuntimeError(f"refusing symlink in pedalboard output: {path}")
  327. if path.is_file():
  328. existing[path.relative_to(output).as_posix()] = path.read_bytes()
  329. if existing == files:
  330. return
  331. if not overwrite:
  332. raise RuntimeError(f"pedalboard output already exists and differs: {output}")
  333. output.parent.mkdir(parents=True, exist_ok=True)
  334. temporary = Path(tempfile.mkdtemp(prefix=f".{output.name}.", dir=output.parent))
  335. try:
  336. for relative, content in files.items():
  337. path = temporary / relative
  338. path.parent.mkdir(parents=True, exist_ok=True)
  339. path.write_bytes(content)
  340. if output.exists():
  341. backup = output.with_name(output.name + ".rigforge-backup")
  342. if backup.exists():
  343. raise RuntimeError(f"pedalboard recovery path already exists: {backup}")
  344. os.replace(output, backup)
  345. try:
  346. os.replace(temporary, output)
  347. except OSError:
  348. os.replace(backup, output)
  349. raise
  350. else:
  351. os.replace(temporary, output)
  352. finally:
  353. if temporary.exists():
  354. shutil.rmtree(temporary)
  355. def main(argv=None):
  356. parser = argparse.ArgumentParser(description=__doc__)
  357. parser.add_argument("--state", type=Path, default=ROOT / "config" / "desired-state.yaml")
  358. parser.add_argument("--repo-root", type=Path, default=ROOT)
  359. parser.add_argument("--output", type=Path)
  360. parser.add_argument("--force", action="store_true", help="replace an existing differing generated bundle")
  361. args = parser.parse_args(argv)
  362. try:
  363. state = yaml.safe_load(args.state.read_text(encoding="utf-8"))
  364. files = generate_bundle_files(state, args.repo_root)
  365. output = args.output
  366. if output is None:
  367. digest = hashlib.sha256()
  368. for name, content in sorted(files.items()):
  369. digest.update(name.encode("utf-8") + b"\0" + content + b"\0")
  370. reference_directory = state["deployment"]["mod_ui"]["reference_directory"]
  371. output = (
  372. Path.home()
  373. / reference_directory
  374. / f"rigforge-guitar-{digest.hexdigest()[:16]}.pedalboard"
  375. )
  376. write_bundle(output, files, overwrite=args.force)
  377. except (OSError, ValueError, RuntimeError, KeyError, TypeError, yaml.YAMLError) as error:
  378. print(f"ERROR: {error}", file=sys.stderr)
  379. return 1
  380. print(f"Generated mod-ui pedalboard: {output}")
  381. return 0
  382. if __name__ == "__main__":
  383. raise SystemExit(main())