cignal 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cignal/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Compile DSP kernels written in static Python to C99."""
2
+
3
+ from .kernel import Array, Delay, Kernel, f32, f64, i32, param, table
4
+
5
+ __all__ = ["Array", "Delay", "Kernel", "f32", "f64", "i32", "param", "table"]
cignal/build.py ADDED
@@ -0,0 +1,229 @@
1
+ """Write generated C, render host shims, and invoke the C compiler."""
2
+
3
+ import functools
4
+ import os
5
+ import shutil
6
+ import subprocess
7
+ import sys
8
+ from collections.abc import Sequence
9
+ from importlib import resources
10
+ from pathlib import Path
11
+ from string import Template
12
+
13
+ from .compiler import CKernel, Target, compile_kernel
14
+
15
+ STRICT_FLAGS = ("-std=c99", "-O2", "-Wall", "-Wextra", "-Wpedantic", "-Wconversion", "-Wdouble-promotion", "-Werror")
16
+ # Reference builds must not fuse a*b+c, or they stop matching CPython's rounding.
17
+ REFERENCE_FLAGS = ("-ffp-contract=off",)
18
+
19
+
20
+ class BuildError(Exception):
21
+ """The C compiler failed. The message includes its stderr."""
22
+
23
+
24
+ def cc() -> str:
25
+ return os.environ.get("CC", "cc")
26
+
27
+
28
+ def cxx() -> str:
29
+ return os.environ.get("CXX", "c++")
30
+
31
+
32
+ def write_kernel(kernel: CKernel, out_dir: Path) -> tuple[Path, Path]:
33
+ """Write the kernel's header and source into `out_dir`."""
34
+ out_dir.mkdir(parents=True, exist_ok=True)
35
+ header = out_dir / kernel.header_name
36
+ source = header.with_suffix(".c")
37
+ header.write_text(kernel.header)
38
+ source.write_text(kernel.source)
39
+ return header, source
40
+
41
+
42
+ def pd_object_name(kernel: CKernel) -> str:
43
+ """Default Pd object name. It can collide with a Pd built-in (`biquad~`), which then wins silently."""
44
+ return kernel.name.lower() + "~"
45
+
46
+
47
+ def sc_ugen_name(kernel: CKernel) -> str:
48
+ """Default SuperCollider UGen name. The prefix keeps it clear of core UGens such as `Delay1`."""
49
+ return "Cignal" + kernel.name
50
+
51
+
52
+ def render_shim(shim: str, kernel: CKernel, pd_name: str | None = None, sc_name: str | None = None) -> str:
53
+ """Fill a shim template (`driver`, `pd` or `sc`) for `kernel`."""
54
+ filename = "sc.cpp.in" if shim == "sc" else f"{shim}.c.in"
55
+ template = resources.files("cignal.shims").joinpath(filename).read_text()
56
+ pd_name = pd_name or pd_object_name(kernel)
57
+ if not pd_name.endswith("~") or not pd_name[:-1].replace("_", "a").isalnum():
58
+ raise BuildError(f"Pd object name {pd_name!r} must be an identifier followed by `~`")
59
+ sc_name = sc_name or sc_ugen_name(kernel)
60
+ if not (sc_name.isidentifier() and sc_name[0].isupper() and sc_name.isascii()):
61
+ raise BuildError(f"SuperCollider UGen name {sc_name!r} must be an ASCII identifier starting with a capital")
62
+ ftz = resources.files("cignal.shims").joinpath("ftz.h.in").read_text()
63
+ return Template(template).substitute(
64
+ ftz=ftz,
65
+ sc_name=sc_name,
66
+ name=kernel.c_name or kernel.name,
67
+ header=kernel.header_name,
68
+ sample=kernel.sample_ctype,
69
+ n_inputs=kernel.n_inputs,
70
+ n_outputs=kernel.n_outputs,
71
+ n_params=len(kernel.params),
72
+ pd_name=pd_name,
73
+ c_prefix=pd_name.replace("~", "_tilde"),
74
+ )
75
+
76
+
77
+ def run_cc(args: Sequence[str | Path], compiler: str | None = None) -> None:
78
+ command = [compiler or cc(), *map(str, args)]
79
+ proc = subprocess.run(command, capture_output=True, text=True)
80
+ if proc.returncode != 0:
81
+ raise BuildError(f"{' '.join(command)}\n{proc.stderr}")
82
+
83
+
84
+ def compile_object(source: Path, flags: Sequence[str] = STRICT_FLAGS) -> Path:
85
+ """Compile one C file to an object next to it."""
86
+ obj = source.with_suffix(".o")
87
+ run_cc([*flags, "-c", source, "-o", obj])
88
+ return obj
89
+
90
+
91
+ def build_driver(
92
+ path: str | Path,
93
+ out_dir: Path,
94
+ kernel: str | None = None,
95
+ target: Target | None = None,
96
+ extra_flags: Sequence[str] = (),
97
+ compiled: CKernel | None = None,
98
+ ) -> Path:
99
+ """Compile `kernel` and the standalone driver into an executable. `compiled` skips recompiling."""
100
+ ck = compiled or compile_kernel(path, kernel, target)
101
+ _, source = write_kernel(ck, out_dir)
102
+ driver = out_dir / f"{ck.header_name[:-2]}_driver.c"
103
+ driver.write_text(render_shim("driver", ck))
104
+ exe = out_dir / f"{ck.header_name[:-2]}_driver"
105
+ run_cc([*STRICT_FLAGS, *extra_flags, "-I", out_dir, source, driver, "-o", exe, "-lm"])
106
+ return exe
107
+
108
+
109
+ def pd_extension() -> str:
110
+ return ".pd_darwin" if sys.platform == "darwin" else ".pd_linux"
111
+
112
+
113
+ def _mac_pd_apps() -> list[Path]:
114
+ """Pd bundles in /Applications or one folder below it, newest name first. A recursive glob took 10 s."""
115
+ apps = [*Path("/Applications").glob("Pd*.app"), *Path("/Applications").glob("*/Pd*.app")]
116
+ return sorted(apps, reverse=True)
117
+
118
+
119
+ @functools.cache
120
+ def find_pd_include() -> Path | None:
121
+ """Locate `m_pd.h`: `$PD_INCLUDE`, then standard install locations."""
122
+ candidates = [os.environ.get("PD_INCLUDE", ""), "/usr/include/pd", "/usr/local/include/pd"]
123
+ candidates += [str(app / "Contents/Resources/src") for app in _mac_pd_apps()]
124
+ return next((Path(c) for c in candidates if c and (Path(c) / "m_pd.h").is_file()), None)
125
+
126
+
127
+ @functools.cache
128
+ def find_pd_binary() -> Path | None:
129
+ """Locate the `pd` executable: `$PD`, then `PATH`, then macOS application bundles."""
130
+ candidates = [os.environ.get("PD", ""), shutil.which("pd") or ""]
131
+ candidates += [str(app / "Contents/Resources/bin/pd") for app in _mac_pd_apps()]
132
+ return next((Path(c) for c in candidates if c and Path(c).is_file()), None)
133
+
134
+
135
+ def build_pd_external(
136
+ path: str | Path,
137
+ out_dir: Path,
138
+ kernel: str | None = None,
139
+ pd_include: Path | None = None,
140
+ pd_name: str | None = None,
141
+ extra_flags: Sequence[str] = (),
142
+ compiled: CKernel | None = None,
143
+ ) -> Path:
144
+ """Compile `kernel` as a Pd external. Returns the path of the loadable binary."""
145
+ include = pd_include or find_pd_include()
146
+ if include is None:
147
+ raise BuildError("m_pd.h not found; set PD_INCLUDE or pass --pd-include")
148
+ ck = compiled or compile_kernel(path, kernel)
149
+ _, source = write_kernel(ck, out_dir)
150
+ pd_name = pd_name or pd_object_name(ck)
151
+ shim = out_dir / f"{pd_name.replace('~', '_tilde')}.c"
152
+ shim.write_text(render_shim("pd", ck, pd_name))
153
+ binary = out_dir / f"{pd_name}{pd_extension()}"
154
+ link = ["-bundle", "-undefined", "dynamic_lookup"] if sys.platform == "darwin" else ["-shared"]
155
+ run_cc(["-std=c99", "-O2", "-fPIC", "-Wall", *extra_flags, "-I", include, "-I", out_dir, source, shim, *link,
156
+ "-o", binary]) # fmt: skip
157
+ return binary
158
+
159
+
160
+ def sc_extension() -> str:
161
+ return ".scx" if sys.platform == "darwin" else ".so"
162
+
163
+
164
+ @functools.cache
165
+ def find_sc_include() -> Path | None:
166
+ """Locate the SuperCollider headers (the directory holding `plugin_interface/` and `common/`)."""
167
+ candidates = [os.environ.get("SC_INCLUDE", ""), "/usr/include/SuperCollider", "/usr/local/include/SuperCollider"]
168
+ return next((Path(c) for c in candidates if c and (Path(c) / "plugin_interface/SC_PlugIn.h").is_file()), None)
169
+
170
+
171
+ @functools.cache
172
+ def find_scsynth() -> Path | None:
173
+ """Locate `scsynth`: `$SCSYNTH`, then `PATH`, then the macOS application bundle."""
174
+ candidates = [os.environ.get("SCSYNTH", ""), shutil.which("scsynth") or ""]
175
+ candidates += [str(p / "Contents/Resources/scsynth") for p in Path("/Applications").glob("SuperCollider*.app")]
176
+ return next((Path(c) for c in candidates if c and Path(c).is_file()), None)
177
+
178
+
179
+ def sc_class_file(kernel: CKernel, sc_name: str) -> str:
180
+ """The sclang class that makes the UGen usable from SuperCollider code."""
181
+ inputs = [f"in{k}" for k in range(kernel.n_inputs)]
182
+ params = [f"{name} = {default!r}" for name, _, _, default in kernel.params]
183
+ args = ", ".join([*inputs, *(name for name, *_ in kernel.params)])
184
+ signature = ", ".join([*inputs, *params])
185
+ base = "MultiOutUGen" if kernel.n_outputs > 1 else "UGen"
186
+ call = ", ".join(["'audio'", *([args] if args else [])])
187
+ lines = [
188
+ f"// Generated by cignal for kernel {kernel.name}. Do not edit.",
189
+ f"{sc_name} : {base} {{",
190
+ f" *ar {{ |{signature}|",
191
+ f" ^this.multiNew({call})",
192
+ " }",
193
+ ]
194
+ if kernel.n_outputs > 1:
195
+ lines += [" init { |... theInputs|", " inputs = theInputs;",
196
+ f" ^this.initOutputs({kernel.n_outputs}, rate)", " }"] # fmt: skip
197
+ return "\n".join([*lines, "}", ""])
198
+
199
+
200
+ def build_sc_plugin(
201
+ path: str | Path,
202
+ out_dir: Path,
203
+ kernel: str | None = None,
204
+ sc_include: Path | None = None,
205
+ sc_name: str | None = None,
206
+ extra_flags: Sequence[str] = (),
207
+ compiled: CKernel | None = None,
208
+ ) -> Path:
209
+ """Compile `kernel` as a SuperCollider UGen plugin, and write its sclang class file next to it.
210
+
211
+ The kernel is compiled as C and the shim as C++: the generated C uses compound literals, which C++ lacks.
212
+ """
213
+ include = sc_include or find_sc_include()
214
+ if include is None:
215
+ raise BuildError("SuperCollider headers not found; set SC_INCLUDE or pass --sc-include")
216
+ ck = compiled or compile_kernel(path, kernel)
217
+ _, source = write_kernel(ck, out_dir)
218
+ sc_name = sc_name or sc_ugen_name(ck)
219
+ shim = out_dir / f"{sc_name}.cpp"
220
+ shim.write_text(render_shim("sc", ck, sc_name=sc_name))
221
+ (out_dir / f"{sc_name}.sc").write_text(sc_class_file(ck, sc_name))
222
+ obj = out_dir / f"{source.stem}.o"
223
+ run_cc(["-std=c99", "-O2", "-fPIC", "-Wall", *extra_flags, "-c", source, "-o", obj])
224
+ binary = out_dir / f"{sc_name}{sc_extension()}"
225
+ link = ["-bundle", "-undefined", "dynamic_lookup"] if sys.platform == "darwin" else ["-shared"]
226
+ headers: list[str | Path] = ["-I", include / "plugin_interface", "-I", include / "common", "-I", out_dir]
227
+ run_cc(["-std=c++17", "-O2", "-fPIC", "-Wall", *extra_flags, *headers, shim, obj, *link, "-o", binary],
228
+ compiler=cxx()) # fmt: skip
229
+ return binary
cignal/cli.py ADDED
@@ -0,0 +1,71 @@
1
+ """Command-line interface: `cignal check` and `cignal build`."""
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from .build import BuildError, build_driver, build_pd_external, build_sc_plugin, write_kernel
8
+ from .compiler import compile_kernel
9
+ from .diagnostics import CompileError, Diagnostic, diagnostics_to_json
10
+
11
+
12
+ def main(argv: list[str] | None = None) -> int:
13
+ parser = argparse.ArgumentParser(prog="cignal", description="Compile Python DSP kernels to C99.")
14
+ commands = parser.add_subparsers(dest="command", required=True)
15
+
16
+ check = commands.add_parser("check", help="validate a kernel without writing output")
17
+ check.add_argument("file", type=Path)
18
+ check.add_argument("--kernel")
19
+ check.add_argument("--format", choices=("text", "json"), default="text")
20
+
21
+ build = commands.add_parser("build", help="write C for a kernel, and optionally build a shim")
22
+ build.add_argument("file", type=Path)
23
+ build.add_argument("--kernel")
24
+ build.add_argument("-o", "--output", type=Path, default=Path("build"))
25
+ build.add_argument("--shim", choices=("none", "driver", "pd", "sc"), default="none")
26
+ build.add_argument("--pd-include", type=Path, help="directory containing m_pd.h")
27
+ build.add_argument("--pd-name", help="Pd object name (default: lowercased kernel name + `~`)")
28
+ build.add_argument("--sc-include", type=Path, help="SuperCollider header directory (holds plugin_interface/)")
29
+ build.add_argument("--sc-name", help="SuperCollider UGen name (default: Cignal + kernel name)")
30
+ build.add_argument("--prefix", default="", help="prefix for every generated C identifier, e.g. `mylib_`")
31
+
32
+ args = parser.parse_args(argv)
33
+ try:
34
+ if args.command == "check":
35
+ ck = compile_kernel(args.file, args.kernel)
36
+ if args.format == "json":
37
+ print(diagnostics_to_json(ck.warnings))
38
+ else:
39
+ _report(ck.warnings, args.file)
40
+ return 0
41
+ ck = compile_kernel(args.file, args.kernel, prefix=args.prefix)
42
+ _report(ck.warnings, args.file)
43
+ if args.shim == "driver":
44
+ print(build_driver(args.file, args.output, compiled=ck))
45
+ elif args.shim == "pd":
46
+ print(build_pd_external(args.file, args.output, pd_include=args.pd_include, pd_name=args.pd_name,
47
+ compiled=ck)) # fmt: skip
48
+ elif args.shim == "sc":
49
+ print(build_sc_plugin(args.file, args.output, sc_include=args.sc_include, sc_name=args.sc_name,
50
+ compiled=ck)) # fmt: skip
51
+ else:
52
+ for written in write_kernel(ck, args.output):
53
+ print(written)
54
+ return 0
55
+ except CompileError as exc:
56
+ if args.command == "check" and args.format == "json":
57
+ print(diagnostics_to_json(exc.diagnostics))
58
+ else:
59
+ print(exc, file=sys.stderr)
60
+ return 1
61
+ except (BuildError, ValueError) as exc:
62
+ print(f"cignal: build failed:\n{exc}", file=sys.stderr)
63
+ return 1
64
+
65
+
66
+ def _report(warnings: list[Diagnostic], path: Path) -> None:
67
+ for warning in warnings:
68
+ print(warning.format(str(path)), file=sys.stderr)
69
+
70
+
71
+ __all__ = ["main"]