generate_mod_ui_pedalboard.py 11 KB

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