#!/usr/bin/env python3 """Generate Rigforge's four-source reference pedalboard bundle for mod-ui.""" import argparse import hashlib import json import os import shutil import sys import tempfile from pathlib import Path, PurePosixPath import yaml from validate_desired_state import safe_relative_path, validate_state ROOT = Path(__file__).resolve().parents[1] def turtle_string(value): return json.dumps(str(value), ensure_ascii=False) def resolved_asset(repo_root, relative): if not safe_relative_path(relative): raise ValueError(f"unsafe pedalboard asset path: {relative!r}") path = (repo_root / Path(*PurePosixPath(relative).parts)).resolve() if not path.is_relative_to(repo_root.resolve()) or not path.is_file(): raise FileNotFoundError(f"pedalboard asset is missing or outside repository: {path}") return path def generate_bundle_files(state, repo_root=ROOT, asset_root=None, nam_model_path=None): errors = validate_state(state) if errors: raise ValueError("invalid desired state: " + "; ".join(errors)) repo_root = Path(repo_root).resolve() asset_root = Path(asset_root or repo_root / "artifacts" / "mod-ui" / "arm64" / "current" / "app" / "default.pedalboard") routing = state["routing"]["mod_host_chains"]["guitar"] nam, ir = routing["processors"] nam_source_path = resolved_asset(repo_root, nam["asset_path"]) nam_path = Path(nam_model_path).resolve() if nam_model_path else nam_source_path if not nam_path.is_file(): raise FileNotFoundError(f"NAM model file is missing: {nam_path}") ir_path = resolved_asset(repo_root, ir["asset_path"]) output_level = nam["parameters"]["output_level"] nam_instance = nam["mod_ui_instance"].removeprefix("/graph/") ir_instance = ir["mod_ui_instance"].removeprefix("/graph/") nam_model_uri = nam["file_property"] ir_file_uri = ir["file_property"] source_labels = { "guitar": "Guitare", "bass": "Basse", "voice": "Micro", "synth": "Synthé", } source_ids = {source["id"] for source in state["sources"]} passthrough_channels = [ (index, source_labels[source_id]) for index, source_id in enumerate(("guitar", "bass", "voice", "synth"), start=1) if source_id != "guitar" and source_id in source_ids ] additional_ports_ttl = "\n\n".join( f''' lv2:index {9 + (index - 2) * 2} ; lv2:name "{label} - Entrée mod-ui" ; lv2:portProperty lv2:connectionOptional ; lv2:symbol "capture_{index}" ; a lv2:AudioPort, lv2:InputPort . lv2:index {10 + (index - 2) * 2} ; lv2:name "{label} - Sortie mod-ui" ; lv2:portProperty lv2:connectionOptional ; lv2:symbol "playback_{index}" ; a lv2:AudioPort, lv2:OutputPort .''' for index, label in passthrough_channels ) additional_ports_list = ",\n ".join( f"<{symbol}_{index}>" for index, _label in passthrough_channels for symbol in ("capture", "playback") ) additional_arcs_list = ", ".join( f"_:b{index + 2}" for index, _label in passthrough_channels ) additional_arcs_ttl = "\n\n".join( f"_:b{index + 2} ingen:tail ;\n" f" ingen:head ." for index, _label in passthrough_channels ) ttl = f"""\ @prefix atom: . @prefix doap: . @prefix ingen: . @prefix lv2: . @prefix midi: . @prefix mod: . @prefix patch: . @prefix pedal: . @prefix rdfs: . @prefix state: . @prefix xsd: . lv2:index 5 ; lv2:name "Guitare - Entrée mod-ui" ; lv2:portProperty lv2:connectionOptional ; lv2:symbol "capture_1" ; a lv2:AudioPort, lv2:InputPort . lv2:index 6 ; lv2:name "Guitare - Sortie mod-ui" ; lv2:portProperty lv2:connectionOptional ; lv2:symbol "playback_1" ; a lv2:AudioPort, lv2:OutputPort . {additional_ports_ttl} <:bpb> ingen:value 4.0 ; lv2:index 0 ; a lv2:ControlPort, lv2:InputPort . <:bpm> ingen:value 120.0 ; lv2:index 1 ; a lv2:ControlPort, lv2:InputPort . <:rolling> ingen:value 0 ; lv2:index 2 ; a lv2:ControlPort, lv2:InputPort . atom:bufferType atom:Sequence ; atom:supports midi:MidiEvent ; lv2:index 3 ; lv2:name "Control In" ; lv2:portProperty lv2:connectionOptional ; lv2:symbol "control_in" ; 4096 ; a atom:AtomPort, lv2:InputPort . atom:bufferType atom:Sequence ; atom:supports midi:MidiEvent ; lv2:index 4 ; lv2:name "Control Out" ; lv2:portProperty lv2:connectionOptional ; lv2:symbol "control_out" ; 4096 ; a atom:AtomPort, lv2:OutputPort . ingen:value 0 ; lv2:index 7 ; a atom:AtomPort, lv2:InputPort . ingen:value 0 ; lv2:index 8 ; a atom:AtomPort, lv2:InputPort . <{nam_instance}> ingen:canvasX 160.0 ; ingen:canvasY 280.0 ; ingen:enabled true ; ingen:polyphonic false ; lv2:microVersion 0 ; lv2:minorVersion 0 ; mod:builderVersion 0 ; mod:releaseNumber 0 ; pedal:instanceLabel "NAM" ; pedal:instanceNumber {nam["instance"]} ; pedal:performanceVisible true ; pedal:performanceIndex 0 ; lv2:prototype <{nam["plugin_uri"]}> ; lv2:port <{nam_instance}/control>, <{nam_instance}/notify>, <{nam_instance}/input>, <{nam_instance}/output>, <{nam_instance}/input_level>, <{nam_instance}/output_level>, <{nam_instance}/quality_scale>, <{nam_instance}/:bypass> ; state:state [ <{nam_model_uri}> {turtle_string(str(nam_path))}^^atom:Path ] ; a ingen:Block . <{nam_instance}/control> atom:bufferType atom:Sequence ; atom:supports patch:Message ; lv2:designation lv2:control ; lv2:index 0 ; lv2:symbol "control" ; a atom:AtomPort, lv2:InputPort . <{nam_instance}/notify> atom:bufferType atom:Sequence ; atom:supports patch:Message ; lv2:designation lv2:control ; lv2:index 1 ; lv2:symbol "notify" ; a atom:AtomPort, lv2:OutputPort . <{nam_instance}/input> a lv2:AudioPort, lv2:InputPort . <{nam_instance}/output> a lv2:AudioPort, lv2:OutputPort . <{nam_instance}/input_level> ingen:value 0.0 ; a lv2:ControlPort, lv2:InputPort . <{nam_instance}/output_level> ingen:value {output_level} ; a lv2:ControlPort, lv2:InputPort . <{nam_instance}/quality_scale> ingen:value 1.0 ; a lv2:ControlPort, lv2:InputPort . <{nam_instance}/:bypass> ingen:value 0 ; a lv2:ControlPort, lv2:InputPort . <{ir_instance}> ingen:canvasX 620.0 ; ingen:canvasY 280.0 ; ingen:enabled true ; ingen:polyphonic false ; lv2:microVersion 0 ; lv2:minorVersion 0 ; mod:builderVersion 0 ; mod:releaseNumber 0 ; pedal:instanceLabel "Cabinet IR" ; pedal:instanceNumber {ir["instance"]} ; pedal:performanceVisible true ; pedal:performanceIndex 1 ; lv2:prototype <{ir["plugin_uri"]}> ; lv2:port <{ir_instance}/control>, <{ir_instance}/notify>, <{ir_instance}/in>, <{ir_instance}/out>, <{ir_instance}/:bypass> ; state:state [ <{ir_file_uri}> {turtle_string(str(ir_path))}^^atom:Path ] ; a ingen:Block . <{ir_instance}/control> atom:bufferType atom:Sequence ; atom:supports patch:Message ; lv2:designation lv2:control ; a atom:AtomPort, lv2:InputPort . <{ir_instance}/notify> atom:bufferType atom:Sequence ; atom:supports patch:Message ; lv2:designation lv2:control ; a atom:AtomPort, lv2:OutputPort . <{ir_instance}/in> a lv2:AudioPort, lv2:InputPort . <{ir_instance}/out> a lv2:AudioPort, lv2:OutputPort . <{ir_instance}/:bypass> ingen:value 0 ; a lv2:ControlPort, lv2:InputPort . <> doap:name "Rigforge - Guitare NAM/IR, Basse, Micro, Synthé" ; pedal:unitName "Rigforge" ; pedal:unitModel "Generic" ; pedal:width 1200 ; pedal:height 700 ; pedal:addressings ; pedal:screenshot ; pedal:thumbnail ; pedal:formatVersion 2 ; pedal:version 1 ; ingen:polyphony 1 ; ingen:arc _:b1, _:b2, _:b3, {additional_arcs_list} ; ingen:block <{nam_instance}>, <{ir_instance}> ; lv2:port <:bpb>, <:bpm>, <:rolling>, , , , , {additional_ports_list}, , ; lv2:extensionData ; a lv2:Plugin, ingen:Graph, pedal:Pedalboard . _:b1 ingen:tail ; ingen:head <{nam_instance}/input> . _:b2 ingen:tail <{nam_instance}/output> ; ingen:head <{ir_instance}/in> . _:b3 ingen:tail <{ir_instance}/out> ; ingen:head . {additional_arcs_ttl} """ files = { "manifest.ttl": ( "@prefix ingen: .\n" "@prefix lv2: .\n" "@prefix pedal: .\n" "@prefix rdfs: .\n\n" "\n" " lv2:prototype ingen:GraphPrototype ;\n" " a lv2:Plugin, ingen:Graph, pedal:Pedalboard ;\n" " rdfs:seeAlso .\n" ).encode("utf-8"), "rigforge-guitar.ttl": ttl.encode("utf-8"), "addressings.json": b"{}\n", "snapshots.json": b'{"current":0,"snapshots":[]}\n', } for image_name in ("screenshot.png", "thumbnail.png"): image = asset_root / image_name if not image.is_file(): raise FileNotFoundError(f"mod-ui default board image is missing: {image}") files[image_name] = image.read_bytes() return files def write_bundle(output, files, overwrite=False): output = Path(output) if output.exists(): if output.is_symlink() or not output.is_dir(): raise RuntimeError(f"pedalboard output is not a regular directory: {output}") existing = {} for path in output.rglob("*"): if path.is_symlink(): raise RuntimeError(f"refusing symlink in pedalboard output: {path}") if path.is_file(): existing[path.relative_to(output).as_posix()] = path.read_bytes() if existing == files: return if not overwrite: raise RuntimeError(f"pedalboard output already exists and differs: {output}") output.parent.mkdir(parents=True, exist_ok=True) temporary = Path(tempfile.mkdtemp(prefix=f".{output.name}.", dir=output.parent)) try: for relative, content in files.items(): path = temporary / relative path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(content) if output.exists(): backup = output.with_name(output.name + ".rigforge-backup") if backup.exists(): raise RuntimeError(f"pedalboard recovery path already exists: {backup}") os.replace(output, backup) try: os.replace(temporary, output) except OSError: os.replace(backup, output) raise else: os.replace(temporary, output) finally: if temporary.exists(): shutil.rmtree(temporary) def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--state", type=Path, default=ROOT / "config" / "desired-state.yaml") parser.add_argument("--repo-root", type=Path, default=ROOT) parser.add_argument("--output", type=Path) parser.add_argument("--force", action="store_true", help="replace an existing differing generated bundle") args = parser.parse_args(argv) try: state = yaml.safe_load(args.state.read_text(encoding="utf-8")) files = generate_bundle_files(state, args.repo_root) output = args.output if output is None: digest = hashlib.sha256() for name, content in sorted(files.items()): digest.update(name.encode("utf-8") + b"\0" + content + b"\0") reference_directory = state["deployment"]["mod_ui"]["reference_directory"] output = ( Path.home() / reference_directory / f"rigforge-guitar-{digest.hexdigest()[:16]}.pedalboard" ) write_bundle(output, files, overwrite=args.force) except (OSError, ValueError, RuntimeError, KeyError, TypeError, yaml.YAMLError) as error: print(f"ERROR: {error}", file=sys.stderr) return 1 print(f"Generated mod-ui pedalboard: {output}") return 0 if __name__ == "__main__": raise SystemExit(main())