Documentation / Development
Codebase Architecture and Schemas
eurorack-js is a browser-based modular synthesizer. Modules exchange voltage buffers, but only modules marked as audio outputs send sound to Web Audio. The codebase separates rack ownership, browser UI, and real-time DSP. A module keeps its DSP and UI definition together, but the definition is instantiated differently on the main thread and in the audio worklet.
Mental Model#
EurorackApp (DOM and user interaction)
└── RackHost (authoritative runtime API)
├── RackState (modules, rows, params, cables, MIDI mappings)
├── PluginRegistry (trusted plugin and module definitions)
├── UI mirrors (stable main-thread instances for custom renderers)
└── AudioWorkletEngine
└── EurorackProcessor (audio thread)
├── Worklet plugin registry
├── DSP instances
└── Compiled signal graph
RackHost owns module lifecycle, parameters, patch loading, cables, runtime state, and audio activation. EurorackApp renders DOM and delegates these operations to the host; it also updates row layout and module positions through RackState. Use the public createRackHost() API when embedding the instrument.
Audio requires AudioWorklet in a secure context. There is no ScriptProcessor, timer-based fallback, or duplicate main-thread DSP engine.
From Patch to Sound#
EurorackAppturns DOM, cable, patch, and MIDI interactions into host commands.RackHostmutatesRackState, validates plugin ownership, and sends a versioned topology toAudioWorkletEngine. Ordinary structural edits update visible state immediately; full patch loading snapshots the prior state and waits for activation.EurorackProcessorcreates the worklet DSP instances and compiles cable routes withcompileGraph().- Each audio block copies source voltages into stable destination buffers, processes non-output modules in dependency order, and commits every feedback delay at the block boundary.
- Modules marked
role: 'audio-output'are routed but not processed as ordinary DSP modules. Their inputs are sanitized, volume-scaled, summed, converted from Eurorack voltage, and hard-limited into the browser's stereo output. - Bounded telemetry returns LEDs and display state to stable main-thread UI mirrors.
Worklet topology activation is atomic: a compilation failure leaves the previous audio graph active. Ordinary rack edits publish revisions asynchronously and report activation errors without rolling back visible state. RackHost.loadPatch() is transactional: it waits for the replacement revision, emits patch-loaded only after acknowledgement, and restores the prior rack and worklet topology on failure.
Audio Measurements#
The rack's Analysis panel and the optional measure_audio WebMCP tool share one analysis service. Both capture the final stereo output for 0.5–10 seconds. audio/audio-analysis.js owns request cancellation, host mutation checks and a disposable analysis Worker. AudioWorkletEngine.captureOutput() allocates and transfers bounded capture buffers to the processor, which copies final samples after limiting and returns those owned buffers at the exact requested frame count.
app/rack-activity.js tracks in-flight calls, up to 16 completed calls and the latest successful measurement in tab memory. Older entries expire sooner when the JSON history exceeds four million characters. The UI reads capture phases and results from those same calls. The present_step tool holds a caption over the rack for a requested interval and can highlight a module instance. Its timer runs on the main thread independently of audio processing. See the live walkthrough.
audio/analysis-worker.js loads the content-hashed program from wasm/audio-analysis/manifest.js and runs Rust/WASM off the realtime thread. Rust source lives in the repository's wasm/audio-analysis/ crate. The Worker returns JSON metrics and is terminated; captured PCM is not uploaded or persisted. Live playback is required and is never started by the tool. Parameter/topology edits, audio suspension/stop, tool cancellation and timeouts invalidate the measurement.
Run npm run build:audio-analysis after changing the Rust implementation or its locked dependencies. The normal app build verifies the committed generated assets against their source and file checksums; it does not compile Rust on Vercel. WASM assets load only on demand. See the crate README for the report definitions and build prerequisites.
Module Instances#
Each rack module has a main-thread instance, and a second instance while audio is running:
- UI mirror: created on the main thread as soon as the module enters
RackState. Its identity remains stable before, during, and after audio playback. Custom renderers capture this instance. - DSP instance: created inside
EurorackProcessor. It alone processes routed voltage buffers and produces sound.
Parameter changes are validated against the module's declared UI control and state paths, written to RackState, reflected in the UI mirror, and sent to the worklet. The processor repeats validation before mutation. The worklet sends bounded telemetry back at approximately 30 Hz. A UI mirror is not a second production DSP path and must never be processed by the browser app.
Plugin Registration#
Plugins are trusted JavaScript, not sandboxed extensions. Registration is atomic: all definitions validate before any module becomes visible. Plugin IDs and module IDs cannot collide.
This API supports local development and embedding. Hosted account and public patches accept built-in modules only. New modules must be tested locally and submitted through a GitHub PR, then reviewed, merged and deployed before hosted use.
The main-thread manifest is:
{
id: 'my-plugin',
name: 'My Plugin',
version: '1.0.0',
apiVersion: 1,
patchVersion: 1,
workletUrl: new URL('./my-plugin.worklet.js', import.meta.url).href,
modules: [{ id: 'mymodule', definition: myModule }]
}
Register it with registerPlugin(manifest). A plugin cannot be unregistered while a live RackHost contains one of its module types.
The audio engine loads a plugin's worklet URL when preparing a topology that declares it. It must register matching ownership and patch contracts:
globalThis.registerEurorackWorkletPlugin({
id: 'my-plugin',
apiVersion: 1,
patchVersion: 1,
modules: new Map([['mymodule', myModule]])
});
The processor rejects a topology when its plugin is missing, its patch contract differs, or a module resolves to a different owner.
Core modules have two registration lists so the worklet graph can use static imports:
rack/module-manifest.js: lazy main-thread imports and deterministic default order.rack/core-definitions.js: static worklet imports in the same order.
Contract tests require both lists to match exactly.
Module Schema#
Every module definition includes metadata, createDSP(), a declarative ui contract, and optionally render, telemetry, runtime-state hooks, and a worklet-event handler.
export default {
id: 'mymodule',
name: 'My Module',
hp: 4,
color: 'module-color-six',
category: 'utility',
createDSP({ sampleRate = 44100, bufferSize = 512, services = {} } = {}) {
const input = new Float32Array(bufferSize);
const output = new Float32Array(bufferSize);
return {
params: { gain: 0.5 },
inputs: { input },
outputs: { output },
leds: { active: 0 },
process() {},
reset() {}
};
},
ui: {
leds: ['active'],
knobs: [{ id: 'gain', label: 'Gain', param: 'gain', min: 0, max: 1, default: 0.5 }],
state: [],
inputs: [{
id: 'input', label: 'In', port: 'input', signal: 'audio',
voltage: { min: -5, max: 5, normal: 0 }
}],
outputs: [{ id: 'output', label: 'Out', port: 'output', signal: 'audio' }]
}
};
Visible parameters are declared by knobs, switches, buttons, or actions. ui.state declares patch-persisted finite values that have no direct control, such as learned scale tables. These state paths are accepted by patch/worklet validation but are not rendered or MIDI-learnable. Runtime-only bulk data remains separate and uses the runtime-state hooks.
The worklet presents each press and release of a trigger or momentary action to
DSP for at least one audio block. Two presses arriving in one block therefore
produce two rising edges. Actions with editState apply their saved-state
change immediately on each rising edge.
Port Contract#
At registration the rack checks every input's normal against its inclusive voltage limits. Live parameter messages must satisfy the control's declared range, step or enumerated choices on both sides of the worklet boundary. The compiled ARP sequence and the range checks share their implementation with the Bend specifications.
Ordinary jacks carry one DC-coupled voltage. Their signal labels (audio, cv, gate, trigger, and any) are freely patchable between types. The built-in OCTO pair also has a dedicated octo-link connector for eight lanes. Send's LINK output mates with Receive's LINK input.
Default voltage contracts are:
| Signal | Minimum | Maximum | Input normal |
|---|---|---|---|
audio | -5V | 5V | 0V |
cv | -5V | 5V | 0V |
gate | 0V | 10V | 0V |
trigger | 0V | 10V | 0V |
any | -10V | 10V | 0V |
Use voltage to override known hardware behavior. The DSP input buffer must initialize to its declared normal. Input and output Float32Array identities are immutable for the DSP lifetime. Routing overwrites connected destination buffers each block; unconnected buffers retain their normal, and topology disconnection explicitly restores it. The worklet calls optional onInputConnected(port) and onInputDisconnected(port) lifecycle hooks when topology connections change. Modules must not replace input arrays or implement their own cable cleanup methods.
Custom Renderer Telemetry#
A module with render() must declare what additional UI state crosses from its worklet DSP to the stable UI mirror:
telemetry: {
fields: ['displayBuffer'],
methods: ['getStats'],
history: { field: 'history', maxEntries: 300 }
}
- LEDs synchronize on every snapshot. By default every DSP parameter is observed.
telemetry.paramscan select the parameter paths changed on the audio thread. Useparams: []when all edits originate in the host. Gate Seq uses this for its working pattern and eight preset memories. - The browser receives the full selected parameters at the first periodic update of each topology revision, followed by changed values at the same paths. In-place edits to nested patch data are detected. A skipped revision or an in-flight host edit that suppresses part of a packet requests another complete parameter update. Explicit runtime capture always reports the declared DSP-owned paths. Worklet clients that do not acknowledge periodic telemetry retain full snapshots.
- Host edits still update the rack state, UI mirror and worklet immediately. Select every DSP-modified parameter the UI or saved patch needs to observe.
fieldsare structured-cloned snapshots and must stay bounded.methodsare evaluated in the worklet; the mirror exposes a zero-argument function returning the latest result.historysends the latest entry when its identity changes and maintains a bounded mirror-side history. Entries produced between telemetry updates can be skipped; this is a display feed, not a complete recording.
Custom controls must call onParamChange(). Writing directly to instance.dsp only changes the mirror and cannot control audio. Display code may read the mirror, but must tolerate telemetry latency.
Worklet Module Events#
DSP code cannot access DOM APIs. A DSP can expose drainEvents() to return infrequent, structured-cloneable events. The processor forwards them as module-event messages and transfers included typed-array buffers. A definition may handle them on the main thread:
handleWorkletEvent(event, { moduleId, instance, services, audioCtx }) {
// Browser-only work such as file export.
}
This path is for command-boundary data such as completed recordings, not continuous telemetry.
The core recorder stores one-second stereo chunks and emits recording-complete with buffersL, buffersR, sampleRate, and the exact valid sampleCount. The final chunk may be padded; main-thread WAV encoding must stop at sampleCount.
Local sampler media#
Slice Sampler decodes a selected WAV on the main thread. Its panel sends the decoded PCM through its instance-bound onRuntimeCommand(command, transfer) callback. In a stopped rack the host applies the command to the UI instance and saves a runtime snapshot. During playback the worklet checks the active graph revision, module ID and type before the module validates the command and replaces one slot. Successful delivery is acknowledged. A cable edit retains both running voices. Stopping audio captures local takes and restores the stopped panel from that snapshot.
Patch v3 stores the source choice and slice markers. Sample bytes and filenames stay in runtime memory for the current rack. The player's Factory choice reconstructs its original phrase on a fresh load. Control snapshots carry a graph revision and the serial of the latest applied panel edit so a delayed worklet message cannot undo a newer edit.
MIDI Timing#
MIDI OUT returns timestamped note edges in one module event per active block. The browser MIDI service maps their times to the output clock, tracks held notes by module and sends them to the tab’s selected MIDI output. MIDI port selections belong to the local session. MIDI input and output guide
The main thread maps each raw MIDI message to an AudioContext timestamp before forwarding it. At the start of each render quantum, the worklet MIDI service maps due timestamps to sampleOffset and exposes non-destructive note and clock/transport event arrays. Every MIDI module sees the same block events; late events use offset zero and future events remain queued. CC, mod wheel, and pitch bend are block-rate state. DSP modules receive this service through createDSP({ services }) and must not read browser globals.
Worklet Profiling#
AudioWorkletEngine.setProfiling(enabled, { reset }) enables bounded, opt-in timing capture. requestProfilingReport() returns the render deadline, mean, p50/p95/p99 block and module times in milliseconds, and p99 utilization. On browsers with integer worklet clocks, use the mean for attribution and a Chrome audio trace for sub-millisecond percentiles. Profiling is disabled by default and its machine-dependent values are diagnostic, not CI pass/fail thresholds.
Compiled Signal Graph#
Topology activation validates every module, endpoint, direction, and block buffer before replacing the active graph. The worklet acknowledges the topology revision; RackHost.loadPatch() does not commit until that revision is active.
Routing rules:
- One source per input. Creating or moving a cable to an occupied input is rejected and leaves the existing connections intact.
- One output may fan out to any number of inputs.
- OCTO LINK cables are saved and drawn as ordinary endpoint pairs. Before ordering DSP modules, the compiler traces each numbered lane back to its source. Sending a clock or a feedback path through a snake preserves direct-cable timing. A physically patched Receive output supplies 0 V when its LINK or upstream lane is open.
- Imported patches with duplicate destinations are rejected rather than silently rewritten.
- Sources process before destinations outside feedback components, using a topological ordering.
- Manifest order, rack order, then instance ID provide deterministic tie breaks.
- Every edge inside a feedback strongly connected component uses an explicit one-block delay, including self-feedback.
- Removing a cable restores the destination's declared normal voltage when the replacement worklet topology activates.
- Cable endpoint moves are transactional: clicks, Escape, focus loss, and incompatible-jack drops restore the original connection; a valid drop commits the move, while an actual drag to empty space explicitly removes it.
- Dragging a connected socket moves that cable end. Shift-drag starts an additional cable from a connected socket, while repeated Ctrl/Command drags cycle through cables sharing that socket. Outputs may fan out, but an occupied input rejects another cable and preserves both existing connections.
- Valid endpoint moves replace the cable in rack state atomically and publish one topology revision, so the running AudioWorklet never receives a disconnected intermediate patch.
If a module throws during process(), that instance is disabled and its outputs are zeroed while the rest of the graph continues. Topology compilation errors reject the revision and leave the prior graph active.
The production render order is: adapt to a changed render quantum if necessary; clear the browser output; begin the MIDI block; route and process modules in compiled order while deferring audio-output sinks; call commitFeedback(); end the MIDI block; sanitize, meter, volume-scale, and sum output sinks; scale ±5V to Web Audio ±1 and hard-limit both channels; publish declared telemetry when its approximately 30 Hz interval is due; record optional profiling; return.
Patch Schema v3#
Canonical patch state is:
{
version: 3,
plugins: { core: 1 },
modules: [
{ id: 'osc_1', type: 'vco', row: 1, index: 0 },
{ id: 'out_1', type: 'out', row: 1, index: 1 }
],
params: {
osc_1: { coarse: 0.35 }
},
cables: [
{ fromModule: 'osc_1', fromPort: 'triangle', toModule: 'out_1', toPort: 'L' }
],
midiMappings: {}
}
plugins maps plugin IDs to their patch contract versions, not package versions. Every module type must belong to a declared plugin. Missing plugins reject the whole patch; placeholder modules are not created.
Only schema version 3 is accepted. Every parameter group must name an existing module, every parameter path must be declared by that module's UI control or state contract, and numeric leaves must be finite. Plugin patch contracts must match exactly; the application does not migrate older patch or plugin schemas.
Bulk runtime state such as Looper audio buffers and CV Recorder lane buffers is separate from persisted patch state. RackHost captures supported state when audio stops, retains it with the live module state, and supplies it when the corresponding worklet DSP instance is recreated. Patch serialization and shared URLs exclude this data.
Topology acknowledgements and runtime-state requests have a five-second timeout by default, configurable through requestTimeoutMs. Processor failure or shutdown rejects and clears all pending requests. Runtime-state capture failure is reported but cannot prevent audio shutdown.
MIDI and Output#
Raw MIDI messages are timestamped against the AudioContext on the main thread and forwarded to the worklet, where the shared MIDI service exposes note and clock events with per-block sample offsets plus CC, pitch-bend, and modulation state.
Modules marked role: 'audio-output' are worklet sinks. The processor routes their inputs but skips their ordinary process() method. It replaces non-finite samples with zero, constrains volume and meter values to 0…1, sums every sink, scales Eurorack ±5V to Web Audio ±1, and hard-limits the final stereo channels to −1…1. Main-thread UI mirrors never create or connect audio nodes.
Repository Map#
| Area | Responsibility |
|---|---|
src/js/app/app.js | Rack bootstrap, audio start/stop UI, and coordination across rack-dom.js, cable-controller.js, module-drag-controller.js, patch-io.js, and midi-controller.js |
src/js/patch-library/ | Patch gallery views, navigation/history routing, patch actions, previews, viewer list caching, save/choice dialogs, account session, and pre-auth draft recovery |
src/js/patches/ | Account API client, local patch store, catalogue URL state, patch detail page, and email sign-in |
src/js/previews/ | Offscreen rack preview renderer (patch-preview-frame.js, patch-preview.js) and preview cache |
src/js/site/ | SEO/social page metadata, playable demos, and background catalogue/guide preloading |
src/styles/ | Industrial palette, rack core stylesheet partials (src/styles/rack/, minified and inlined at build time), and feature/page stylesheets bundled into content-hashed immutable CSS assets by scripts/lib/build-styles.mjs |
scripts/lib/ | Internal build and audit libraries (build-rack.mjs, build-styles.mjs, build-docs.mjs, module-guides.mjs, static-page-manifest.mjs, dsp-audit.js) |
src/midi-*.html, src/js/midi/, src/styles/midi-tools.css | Standalone MIDI performance tools and shared MIDI manager/output modules |
src/js/app/rack-host.js | Authoritative module, parameter, cable, patch, runtime-state, and audio lifecycle API |
src/js/app/rack-state.js | Serializable modules, rows, params, cables, and MIDI mappings |
src/js/app/patch-format.js, patch-url-codec.js | Strict patch v3 validation and compact gzip/base64url shared-link codec |
src/js/patch-script/ | Patch Script compiler, sandboxed evaluator, and workbench (workbench.js, workbench-console.js, workbench-completions.js) |
src/js/rack/registry.js | Atomic trusted-plugin registration and module ownership |
src/js/rack/module-contract.js | Module, port, buffer, voltage, and telemetry validation |
src/js/rack/module-manifest.js | Lazy core imports, category taxonomy, and deterministic module order |
src/js/rack/core-definitions.js | Static core imports used by the AudioWorklet bundle |
src/js/audio/worklet-engine.js | Main-thread AudioWorklet node and message controller |
src/js/audio/worklet/ | Production DSP processor (processor.js), MIDI service (midi-service.js), telemetry/profiling (telemetry.js), and plugin registry |
src/js/audio/graph.js | Compiled routing, dependency order, input normals, and feedback delays |
src/js/modules/{moduleId}/index.js | Self-contained module DSP, UI contract, renderer, and optional telemetry/hooks |
src/js/ui/renderer.js, declarative-panel.js, cable-geometry.js | Module panel lifecycle, declarative control/jack layout rendering, and SVG cable geometry helpers |
src/js/ui/toolkit/ | Shared controls, layout helpers, and interactions |
src/js/utils/math.js | Clamp and exponential parameter mapping with explicit range contracts |
src/js/utils/oscillator.js | Optional normalized phase wrapping and PolyBLEP primitives |
src/js/utils/interpolation.js | Optional linear and fixed circular-buffer interpolation primitives |
src/js/utils/slew.js | Optional stateful RC smoothing primitive |
src/js/utils/voltage.js | Optional documented soft voltage rails |
src/js/utils/fft.js | Optional preallocated, calibrated real FFT analysis |
src/js/utils/color.js | Internal theme-token and fallback color handling |
src/js/utils/nested-access.js | Internal validated parameter/port path access with stable-buffer copying |
src/js/config/patches/ | Retained test and musical example source files |
src/js/config/test-patches.js | Standalone catalogue for the Module demos directory |
src/js/config/patches/index.js | Complete built-in patch regression aggregate (TEST_PATCHES plus Introduction) |
src/js/config/factory-patches.js | Re-exports TEST_PATCHES and FACTORY_PATCHES for regression checks and profiling |
src/js/index.js | Public host, plugin, contract, renderer, toolkit, and utility exports |
tests/dsp/ | Focused module behavior and voltage-contract tests |
tests/audio/ | Graph and AudioWorklet integration tests |
Where to Make Changes#
- Add a built-in module: create
modules/{moduleId}/index.js, register it in bothmodule-manifest.jsandcore-definitions.jsin matching order, preserve the sequentialm0throughmNaliases, and bump the synchronized core worklet graph revision using the ordered-module digest described increating-modules.md. - Add an external plugin: register its main-thread manifest and provide a matching worklet entry point; do not edit core registration lists.
- Change cable or feedback behavior: edit
audio/graph.jsand its graph/worklet tests. - Change production block processing: edit
audio/worklet/processor.js. - Change rack ownership or lifecycle: edit
app/rack-host.js. - Change the patch schema or persistence: edit
app/patch-format.js, app import/export handling, and patch tests together. - Change module panels: edit the module's
ui/renderdefinition and shared renderer/toolkit only when the behavior is reusable. - Add a DSP primitive: add a focused utility with boundary tests, migrate only behaviorally equivalent call sites, export module-facing APIs from
src/js/index.js, and update the module creation guide. - Add a test patch: add one file under
config/patches/and register it inconfig/test-patches.jsfor the Module demos directory and complete regression catalogue. - Change the public API: edit
src/js/index.jsand update the architecture/module-authoring documentation.
Playback load and rack profiling#
While audio runs, the worklet times one in sixteen quanta and publishes a mean DSP load about once per second. The transport shows an overload warning for missed playout, slow audio-clock progress or sustained processing above budget. Activating a topology starts a fresh worklet sampling window and clears the previous rack’s load and recovery history. Browser underruns can trigger a warning before the first DSP percentage for the new revision arrives. The optional device underrun counter belongs to the browser. The measured load covers work inside the callback. get_rack and a completed measure_audio expose the latest playbackHealth sample. UI telemetry uses one outstanding periodic snapshot so a stalled view can resume with current meter and playhead values. Gesture ticks deliver their ordered panel and MIDI changes together.
To profile any exported built-in rack or a factory patch offline, run npm run profile:rack -- path/to/patch.json or npm run profile:rack -- "Test - Shimmer" --modules. The command warms the production processor, replays its actual cables, and reports high-resolution whole-block timings including telemetry construction and a synchronous clone. --sample-rate, --block-size and --blocks set the measurement conditions. Optional per-instance profiling adds measurement overhead. For a live release check, record the browser and hardware, take device underrun deltas after warmup, and measure control round trips and animation frames alongside callback timing.