audio

@audio/plugin-vst0.0.2

Compile audio.js processors to native VST3 and CLAP plugins with JZ

Status
pending calibration
Updated
Family
plugin, 2 packages under it
Category
build
Licence
MIT
Dependencies
none
Tests
at least 152 in audiojs/plugin's CI at 6f0ae92

Compile audio.js atoms to native VST3 and CLAP plugins with JZ. The compiler is a build-time choice; Porffor is planned and build({ compiler: 'porffor' }) refuses until it lands.

The same factory-with-metadata that @audio/plugin-wam runs as an AudioWorklet becomes a .vst3 or a .clap bundle. The plugin's identity, parameters, buses, latency and tail come from the manifest exactly as the contract specifies (one derivation, manifest.js, serves both formats); the DSP is the atom itself, compiled ahead of time and linked into a fixed native shell, one per format, over the same boundary, native/dsp-abi.h. What a shell owes the processor between the host and that boundary (values, calls, input, transport, tail, state) is one file both shells link, native/calls.c: the VST3 and the CLAP build keep the same duties by the same code.

Use

Experimental. Builds compile with jz 1.0.x through its public options; jz is an optional peer dependency (^1.0.3), so install it to build (npm install jz). The tests here have passed against a jz development checkout; verify a build from the installed package before treating it as release evidence, and do not pin an interim compiler snapshot. No third-party host, validator (clap-validator, pluginval) or DAW has loaded a build yet: the only host that has is the sibling @audio/host.

import { toVst3 } from '@audio/plugin-vst'
import { gain } from '@audio/plugin-wam/examples/gain.js'
import { fileURLToPath } from 'node:url'

const plugin = toVst3(gain)          // synchronous: derivation only, no file or process access
plugin.id                            // 'gain'
plugin.native.vst3                   // the class id, derived from vendor + id unless native.vst3 is pinned
plugin.paramSpecs                    // normalized parameter specs, host-facing stable ids included

await plugin.build({
  atom: fileURLToPath(import.meta.resolve('@audio/plugin-wam/examples/gain.js')),
  out: './dist',
  compiler: 'jz',
  jz: fileURLToPath(new URL('./', import.meta.resolve('jz')))
})   // macOS: writes a .vst3 bundle in dist

import { toClap } from '@audio/plugin-vst'
const clap = toClap(gain)            // the same derivation
clap.native.clap                     // 'org.audiojs.gain': <vendor>.<id>, unless native.clap is pinned
await clap.build({ atom: fileURLToPath(import.meta.resolve('@audio/plugin-wam/examples/gain.js')), out: './dist' })   // gain.clap

toVst3 and toClap refuse what they cannot ship faithfully instead of guessing: an atom without a vendor (the class id derived from it is permanent), streaming: false, declared events (no event transport yet), a number parameter without a finite range, bus layouts beyond mono and stereo, and every parameter-metadata collision the contract names. curve, unit and step are display hints, as the contract says; the wire value always maps linearly.

The real-time gate

Before anything native runs, the JZ backend drives the compiled atom through hundreds of blocks in plain Node with every host import replaced by a stub that throws. The heap cursor (__jz_heap) and memory size must not move, no byte past the cursor may be written, no stub may fire, and every output sample must be finite. Short, repeated, zero-length and full callbacks are included, each further input bus fed and not, and a transport set before each call. The compiled module makes, once at setup, a view of each channel for every callback length up to the block size, and of the buses for each further input bus fed or not, so the atom reads its frame count as inputs[0][0].length and an unfed bus as one with no channels, as the contract says; no buffer is resized. These views cost memory in proportion to the block size: for a stereo input with a stereo key at 8192 frames, setup takes 3.1 MB of the module's memory, 0.46 MB of it the buses with the key unfed (56 bytes a callback length). A build that fails the gate does not link.

latency, tail and frames functions are planning (CONTRACT.md § Latency, tail): they may allocate, and are called outside the block loop with { sampleRate, params, buffers, transport }. The shim takes latency and tail as the instance is built (dsp_start, where the factory runs too), with the values then in force, no buffers (a native build takes none) and the transport of a host with no tempo; a shell reports those. The gate then calls a tail function on its own, with random values: one that allocates nothing, grows nothing and returns is also read live, on the audio thread after the values move (realtime.tailLive true), and the shell reports the tail with the values in force. One that allocates (an object or array literal, a spread, a typed array made in it, as the reverb family's tail functions do) is reported as taken at each new instance; the build is not refused for it. Install JZ explicitly (npm install jz), or select an exact checkout with build({ jz: '/path/to/jz', ... }) / JZ_ROOT. The compiler version must include the fixes your atom needs; an ambient sibling checkout is a development fallback.

jz's static proof, memory: { fixed: ['process'] }, is asked for alongside and reported as realtime.fixed: true, or the reason jz gives. With jz 1.0.x it cannot pass for any atom, because process calls the atom's closure through the closure table, which the public options keep exported; host: 'native', proposed for jz 1.1.0, closes it. Until the proof passes, the run above is the binding check.

The tests that compile with jz fail when jz cannot be loaded. Set SKIP_NATIVE_LANE=1 to say the native lane is not under test (CI does, on Linux); the bundle tests also skip, saying why, where macOS, wabt, clang++ or the sibling @audio/host is missing.

Traps

A wasm trap in the compiled atom (an out-of-range access, call-stack exhaustion, a stubbed host import, a throw nothing catches) is caught with the wasm2c runtime's own wasm_rt_impl_try(). From that block on the instance writes silence and runs no more module code; dsp_failed() in native/dsp-abi.h returns the trap code so a shell can report it. The host process keeps running. Both shells silence the whole block the trap happened in, frames before the trap included, and every block after: VST3 sets each output channel's silenceFlags bit, CLAP its constant_mask bit and returns CLAP_PROCESS_ERROR ("the output buffer must be discarded", clap/process.h). A new instance starts healthy: a new plugin instance, the host's next setupProcessing or, once the instance has heard audio, setActive(true) (VST3), or the next activate (CLAP); CLAP's reset puts the failed instance's memory back and leaves it failed. A factory, latency or tail function that traps as the instance is built fails setupProcessing or setActive(true) (VST3) or activate (CLAP).

What both shells do

native/calls.c, C11, compiled once per processor beside dsp-jz.c, is the part of a plugin that needs nothing of its format; it mirrors audio's batch.js (held, sourceAt, valuesAt) so that a plugin's calls, and the values each reads, are toBatch's for the same automation. Each shell turns its format's events into jumps and lines, its buffers and its transport into the splitter's, and its state stream into bytes. Shown by test/clap.test.js, test/build.test.js, test/transport.test.js and test/catalogue.test.js:

  • Values. A value is held as its parameter holds it: clamped, a number put on its step (the nearest from min, a tie upward), an enum an index of its values. A value changes only between calls: a block is split where one jumps, and while one moves (a smoothing ramp, a line) no call is longer than 32 frames; a call carries at most 8192 frames, so a longer block is split and ctx.maxBlockSize says so. The first values after a build or a reset snap; a later jump of a number with smoothing is reached by a linear ramp of that length from the value in force, while what the host sent goes on. A restart value never reaches the running instance: it asks for a new one. A value changed before an instance has heard its first block asks for one too, so ctx.params holds the values in force there (as audio and toWam, which build at the first block, give it). A host's block of 0 frames takes its values and calls nothing; it is not heard, so a value it brings before the first block asks for a new instance too.
  • Input. A NaN or Infinity coming in reaches the processor as 0, and the output is made finite. Input bus 0 always carries its channels, silent where the host gives none. A further input bus (a key) that nothing feeds reaches the processor with no channels (CONTRACT.md § process), so a keyed processor keys itself, as in toBatch: a bus is unfed when the host says so (VST3 activateBus, CLAP audio-ports-activation) or gives it no channels. The compiled module has a view of the buses for each further bus fed or not, made at setup (the gate above), so switching allocates nothing.
  • Transport. ctx.transport is set before each call, in the contract's shape { playing, bpm, beat, barStart, timeSig }: the host's at the block's first frame (CLAP clap_process.transport, VST3 ProcessContext), its beat moved on by the frames to the call while it plays and its bar's start by the bars passed; what the host leaves out (no transport, a field marked invalid) the contract's default, { playing: false, bpm: 120, beat: 0, barStart: 0, timeSig: [4, 4] }. A transport the host sends inside a block (CLAP's CLAP_EVENT_TRANSPORT) is not read.
  • Tail. The value taken as the instance was built, or, for a tail function the gate shows allocation-free, read again after the values move, on the audio thread; the CLAP host is told by the tail's changed.
  • State. Every value under its stableId, numbers in their unit, enums by label (CONTRACT.md § State), in a blob named by the plugin, little-endian: AJSP, u32 version 1, u16 length and the plugin's id (the CLAP id; the VST3 class id in hex), u32 count, then per value a u32 id, a u8 kind (0 number, 1 enum, 2 bool) and an f64, or a u16 length and the label for an enum. Loading skips an id it does not know, gives a missing one (or a NaN) its default and an undeclared label the enum's default, and refuses a blob that ends early, of another magic, version or plugin, or with an unknown kind, before any value changes. A state loaded while an instance runs reaches it whole at one block boundary (a sequence lock: a block takes all of it or waits for the next). The version stays 1: no blob of the layout before the id was published.
  • Threads. The audio thread allocates nothing, locks nothing and calls the host for nothing but a shell's notices (CLAP request_restart, [thread-safe], and the tail's changed, [audio-thread]); the values asked for and a loaded state cross threads as atomics.

VST3

toVst3(processor, opts) makes the derivation and the class id (derived from vendor and id, or native.vst3); .build({ atom, out }) links native/plugin.cpp over calls.c and writes <Title>.vst3, signed ad hoc. One class is component, processor and controller. What it does beyond what both shells do:

  • Parameter queues. Each point is a knot of a line, from the block's previous point or from the block's first frame and the value in force there; a point at most one frame after the previous one is a step (smoothed where the parameter says): the SDK sends a jump as "two points: one with the old value and one with the new value at the next sample position", and a point at offset 0 is one frame after position -1; after the last point the value holds; an enum's or a bool's point is a jump at its offset. The SDK's text (ivstparameterchanges.h) starts a block's first line at position -1, the previous block's last sample, with the last value sent: a shell can no longer cut a call there, so it starts the line at 0. Its value then reaches each point at the point, as the SDK's does; inside a block's first segment it trails the SDK's line by at most |v - x| / (o + 1) (from x to a point v at offset o). toBatch given the curve through the same knots, one at each such block's first frame, makes the same calls with the same values: shown to the bit by test/catalogue.test.js.
  • Buses. A further input bus is not active until the host activates it (activateBus; "By default a bus is inactive", ivstcomponent.h), and is not marked kDefaultActive.
  • Lifecycle. The instance is built in setupProcessing; the factory hands out no instance when memory runs out as one is made (createInstance says kOutOfMemory); setActive(true) builds a new one when a restart value changed, when the parameter flush (a process call of 0 samples) brought a value before the first block or once the instance has heard audio (a host's reset is setActive off and on), so it gives a just-built instance with the values in force. A value in the first block's queue comes in that block: the live value has it, ctx.params the one the instance was built with. A restart value waits for setActive(true): the vendored interface holds no component handler, and restartComponent is the UI thread's. getLatencySamples and getTailSamples read what the instance took, never module code off the audio thread. The controller's setParamNormalized changes what it reports and what the next instance is built with; the processor hears values through process's parameter queues.
  • Not built: a value's text (getParamStringByValue, getParamValueByString), a bypass the adapter adds, a hand-over, events, buses beyond mono and stereo, a component handler.

CLAP

toClap(processor, opts) makes the derivation toVst3 makes and adds the CLAP plugin id, <vendor>.<id> (or native.clap where the processor pins one). .build({ atom, out }) links native/clap.c, one C11 file over calls.c and dsp-abi.h, against the same DSP objects and writes <Title>.clap, signed ad hoc. The CLAP headers, release 1.2.10 (MIT, Alexandre Bique), are vendored unchanged in native/clap with their LICENSE; files ships them with the rest of native.

What the plugin does beyond what both shells do, each shown by test/clap.test.js through the sibling @audio/host's CLAP backend, or by a C host in the same file where host-clap cannot show it:

  • Descriptor and ports. Name, vendor, version, description; features audio-effect (analyzer with no output bus, none for a generator: CLAP has no word for one), then mono or stereo of the main output bus. One audio port per bus, CLAP_PORT_MONO or CLAP_PORT_STEREO; bus 0 is CLAP_AUDIO_PORT_IS_MAIN, a further input bus (a key) is not. audio-ports-activation, while inactive only: a further input port deactivated is a bus with no channels in the instance the next activate builds. A host that never calls it leaves every port active, as the header says ports start, and the shell feeds a key port what the host gives it: host-clap 0.2.0 gives an unrouted key port silence, so through it a keyed processor is keyed by silence.
  • Parameters. One CLAP parameter per manifest parameter, its id the contract's stableId, its values plain: a number in its own range, an enum by index (CLAP_PARAM_IS_ENUM), a bool 0 or 1. Stepped (CLAP_PARAM_IS_STEPPED, "integer values only") for an enum, a bool and a number whose step and min are whole; automatable unless hidden or restart; CLAP_PARAM_IS_BYPASS for a bool marked bypass. A value the host sends is cast where stepped (as CLAP says), then held. Each event is a jump at its frame; one whose header says it is shorter than clap_event_param_value_t is skipped; events are taken in the order the host lists them (sorted, clap/process.h says), one out of order with the events before it. value_to_text writes the number and its unit, an enum's label, on or off; text_to_value takes a label, a bool's word, or a number with a suffix of the same dimension and moves its decimal point as audio's inUnit does (250ms to a parameter in s is 0.25), both in the C locale whatever the host's. flush works while active (on the audio thread: the value reaches the processor at the next call's first frame) and while inactive (it is what the next activation builds with).
  • Restart. A restart value, or any value before the instance's first block, asks the host for a new instance (host->request_restart()), built with it at the next activate.
  • Lifecycle. activate builds the instance off the audio thread and takes its latency and tail; reset, on the audio thread, puts back the processor's memory as its factory left it (dsp_reset, a copy made at dsp_start; the contract's "the old one's memory put back") and writes the values asked for again. The tail is reported through clap_plugin_tail; INT32_MAX frames or more is infinite. process returns CLAP_PROCESS_TAIL for an effect (go by the tail once the input is quiet), CLAP_PROCESS_CONTINUE for a generator, CLAP_PROCESS_ERROR once trapped.
  • Not built: note events (toClap refuses events as toVst3 does: the compiled module has no event path), emissions, ctx.buffers, buses beyond mono and stereo, a hand-over to a replacing instance, a bypass the adapter adds, the render, note-ports, thread-check and gui extensions, Windows and Linux.

Equality with the reference host

Two equalities, of two things. The shell's: a build writes what its own compiled module writes when that module is run in V8 on toBatch's calls, to the bit, for any processor (onCalls in test/live.js shows it for FET). The compiler's: the compiled module against the JavaScript it was compiled from, which is what a comparison of a build with toBatch also reads. That one is measured on the processors compared here, not a property of every build, and on them it holds in one of two ways, by what process reaches in the compiled module:

  • To the bit, for a processor that only adds, multiplies, divides and takes square roots: jz's arithmetic is JavaScript's at the options a build compiles with (the default level, no relaxedFloat; jz's README, "Where behaviour differs from JS", "Float results at 'speed'": "The other levels … keep JavaScript's results").
  • Within 1 float32 ulp a sample, for one that calls exp, log, pow or the trigonometric functions (the hyperbolic ones and hypot too): jz computes these with its own kernels, a few double ulps from V8's (jz's README, "Where behaviour differs from JS": "Math within 50 ulp of V8"), so a sample can round to the neighbouring float32.

Neither bound holds for every processor. A value fed back through one of those kernels carries its last bits to any size: a map s = 18 s e^-s compiled at a build's options differs from V8 at 47945 of 48000 samples, by up to 45 million float32 ulps. And jz writes x ** n for a whole n of 16 or under as multiplications, which leaves no kernel to find and is not what V8's ** gives (for n = 3, 44882 of 200000 doubles differ), so a map s = 2.9 s - s ** 3 is classed "to the bit" and differs at 47971 of 48000. A kernel reached only as the instance is made (a coefficient from Math.cos) is not walked either. On such a processor the comparison with toBatch fails, by the compiler's arithmetic and not the shell's; the shell's equality above is the one to test it by.

The tests class each compared processor from jz's own output (kernelsOf in test/reference.js): the WAT of the same shim and sources at the build's options with the optimizer off, where each Math kernel is a function named $math.<name> (at the build's level jz inlines some into their callers), its functions walked from the export process through every call and, at an indirect call, the closure table. A processor whose process reaches one of those kernels is held to 1 ulp, any other to the bit; each comparison prints the samples that differ and the largest difference. The compared processors are classed so: gain (plugin-wam's example, 10 **) reaches math.pow; the ducker and FET math.exp and math.log; freeverb none (its tail function's Math.log10 is not reached from process). A shell that moves one sample by 1 ulp fails the tests of freeverb and of the CLAP test's probe, each at its first comparison, and passes gain's and the ducker's; one that moves it by 2 ulps fails them all (measured on deliberately wrong builds, not part of the tests).

Each comparison renders one second of a fixed signal through the plugin (via the sibling @audio/host) and through toBatch, at 44.1 and 48 kHz in blocks of 128 and 333 (the last one short):

  • test/clap.test.js: gain and freeverb 1.0.5 as CLAP, at their defaults and with jumps inside blocks.
  • test/catalogue.test.js, sources read from a commit with git: freeverb 1.0.5 (reverb 29597c9, mix smoothed) as VST3, and the ducker (dynamics 505d0da, keyed) as VST3 and as CLAP, at its defaults, with two values set before the first block, with moves inside blocks (a line, a step, a smoothed step), and the ducker with no key routed. 0 of 96000 samples differ in each of 44 comparisons, the ducker's as well. The dynamics family has no commit whose FET builds (at 505d0da the gate refuses it: plugin-vst: fet allocated during processing).
  • npm run test:catalogue (test/live.js, not part of npm test): freeverb, the ducker and FET read from the families' working trees, as VST3 and CLAP, the same comparisons, and a tail function's value reported at the defaults: a tripwire that says which processor's tree no longer builds, or no longer equals the reference host, and why. It pins the case where a build was first seen 1 ulp from toBatch: FET as VST3 at 48 kHz in blocks of 1024, keyed, its makeup moved by a curve as @audio/host sends one; frame 23261 of the right channel is -0.07131026685 in the build and -0.07131027430 in toBatch, and the compiled module run in V8 on toBatch's own calls gives the build's value for every sample, so the difference is the compiled code's, not the shell's.

No external validator and no DAW has loaded a VST3 or a CLAP build. which clap-validator pluginval finds neither on the machine this was built on, and nothing was downloaded; the only hosts are the sibling @audio/host (its CLAP backend 0.2.0, CLAP 1.2.10, and its VST3 backend) and the C hosts in the tests.

The fixture suite, against both builds

conformance.js, the 18 duties audio's hosts and toWam pass, run against the CLAP and the VST3 build the same way by test/conformance.test.js: each probe built from its own source with toClap and with toVst3, loaded through @audio/host (host-clap, host-vst), rendered by its process with the latency taken off and the tail the plugin reports rendered, the suite's tempo passed on (none: no transport at all). A native build takes buses of one or two channels, fixed as it is built, no events and no buffers; the host function refuses those options by name, as conformance.js lets a host do. In each format: 2 kept, 1 kept in part, 1 not kept, 14 not run. The test asserts every row of both columns.

Ten duties ask the same probe, which reports through an emission (zero, a call of 0 frames) and writes 18 output channels: a native build refuses the first (… declares events; plugin-vst v1 carries no event transport) and would refuse the second. Asking them would take emissions in both adapters (a read-only parameter: CLAP CLAP_PARAM_IS_READONLY with its value in out_events, VST3 kIsReadOnly in outputParameterChanges) handed back by @audio/host, and output buses of more than two channels, which the adapters refuse rather than guess (buses.js), and a probe that holds what it reads: this one reads two names of conformance.js outside itself (zero, its count of calls of 0 frames, and MODES), so written out from its own source it does not build (jz: 'zero' is not in scope); until then native/calls.c and the package's own tests show what those duties ask, as the sections above say.

Duty toClap toVst3 What the run shows
calls carry 1 to maxBlockSize frames not run not run the probe that reports through an emission (above)
ctx.maxChannels is the widest bus not kept not kept its first case feeds 5 channels to an 'any' bus, which a native build fixes at stereo as it is built: refused, input bus 0 carries 2 channels in a native build, not the 5 fed. Keeping it would take an instance built for the channel count the host negotiates (CLAP audio-ports-config, VST3 setBusArrangements of other counts)
input bus 0 always carries its channels not run not run the same probe
a NaN or Infinity reaches the processor as 0 not run not run the same probe
a jump falls on a call boundary not run not run the same probe
≤ 32 frames while a value moves not run not run the same probe
smoothing ramps a jump linearly not run not run the same probe
no automation reaches a restart parameter not run not run the same probe: the duty passes only because the probe is refused, which shows nothing
clamped, enums refused, text converted not run not run the same probe
a stepped number on its step not run not run the same probe
notes sorted, ids assigned, offs paired not run not run its probe declares notes in: refused, … declares events; it would take note ports, an event path into the compiled module's ctx.events and an output bus of the 10 channels it writes
ctx.transport set before each block not run not run the same probe
emissions are passed on not run not run its probe declares emissions: refused, … declares events; it would take the emissions above
latency taken as built, output lined up not run not run its one case hands the probe a buffer, which a native build cannot take: a native build has no buffers: pad cannot be given (a latency taken as built is asked again two rows down). The probe also calls delay, a function of conformance.js outside it, so written out from its own source it does not build (the compiled atom imports global.delay)
a tail rendered as declared kept kept the ring of 480 frames rendered by the instance that heard the input, its ring set before the first block
a tail handed the transport, a latency the one built with kept in part kept in part the latency part passes, with no tempo and at 600 bpm: a latency function is handed the transport the instance is built with. The tail part fails: at 100 bpm the output ends 8 frames after the input; its tail is one beat of the transport it is handed, 4800 frames. The shells take a tail as the instance is built, with the transport of a host with no tempo, and read a live one again after a value moves, never when the tempo does (native/calls.c, retail)
buffers there at construction not run not run its probe's output bus of 4 channels is refused (… output channel count 4 is not supported), and a native build takes no buffers: it cannot be asked of one
a whole-signal processor in one call kept kept by refusal, which the duty asks of a real-time target: … declares streaming: false

Other native shells

The VST3 and CLAP bundles are two shells around the compiled atom. buildDsp from @audio/plugin-vst/dsp runs the same gate and compile, and returns the objects and compiler flags behind native/dsp-abi.h for any host to link. The calls a host makes per block are declared nonblocking, so a Core Audio IOProc can call them under clang's realtime checks. @audio/tap links them into a Core Audio process tap.

import { buildDsp } from '@audio/plugin-vst/dsp'
const { objects, flags } = await buildDsp(toVst3(gain), { atom: './gain.js', out: './dsp' })

Scope of v1

macOS bundles built with JZ; mono and stereo buses, negotiated independently for each input and output bus, a further input bus present or not; number, enum and bool parameters, a value read at each call's first frame (contract 1.0 has no per-sample values, so a manifest's older rate: 'sample' changes nothing), automation inside a block a line between the host's points (VST3) or a jump at each event (CLAP), both split into calls as toBatch splits them; ctx.transport from the host's; latency taken once per instance, and tail taken once per instance or, where its function allocates nothing, read with the values in force; restart: true (or flags: ['restart']) applied at the host's next setupProcessing or setActive(true) in VST3, since the vendored interface holds no component handler to request one, and asked of the host in CLAP; default parameter ids in [0, 0x7FFFFFFF]. Events and wider speaker layouts are refused rather than silently ignored; ctx.buffers holds none. build() compiles the processor's file with every module it reaches by static import and export ... from, each resolved as Node resolves it for import (a path names its file in full; a package resolves through its exports under the conditions import and default, else its module, then its main; a # specifier through its package's imports). Departures from Node, kept: node and module-sync, which Node's import also matches (the second since 22.12 and 20.19), are not taken, both being Node's own (a node target may reach Node's modules, which jz cannot compile); and module is read, which Node does not read. A dynamic import(), a Node builtin, a JSON, wasm or other non-JavaScript file, a path with a query or fragment (Node loads ./a.js?x as a module apart from ./a.js), and a file or package that is not there are refused, with the importing file and the specifier named. Not built yet: AU and LV2 targets, Windows and Linux builds, and validation by a third-party host.