Overview
render(api) gets a PluginAPI<Params>, and the plugin's other methods reach the same object as this.api. The plugin class wraps the calls you make most, so they need no api: this.getParam, this.setParam, this.getAudioState, this.setAudioState and the job calls. The same four calls on api are marked deprecated, so use the this. forms. Timers are the ordinary setTimeout and setInterval.
None of this runs on the audio thread, and the build refuses each call inside process(). What runs where lists both sides, and the PluginAPI type maps every namespace to its type.
Parameters
this.getParam('id') reads a parameter and this.setParam('id', value) moves it. Both are typed against your Params, so a misspelt id is an error before you build. A move made from the window reaches the host like any other move of that control. api.resetParam('id') returns a parameter to its default.
import { Knob } from '@the-plug/ui';
<div>
<Knob value={this.getParam('cutoff')} onChange={(v) => this.setParam('cutoff', v)} label="Cutoff" />
<button onClick={() => api.resetParam('cutoff')}>Reset</button>
</div>Parameters are declared in static parameters; Start here lists the fields.
UI state
this.state holds what the window shows, and this.setState({ … }) changes it and redraws; a change to equal values does nothing. State is saved with the project. Fields named in static transientState start clean on every load instead, which suits a drag in progress. A component you write keeps its state with the plugin's the same way, and names its own static transientState.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
type Params = { mix: number };
type State = { tab: number; dragFrom: number; notes: string };
export default class Notes extends EffectPlugin<Params, State> {
static id = 'com.example.notes';
static pluginName = 'Notes';
static parameters = [{ id: 'mix', name: 'Mix', default: 1 }];
// Saved with the project, except what is listed here: a half-finished drag should start clean.
static transientState = ['dragFrom'];
state: State = { tab: 0, dragFrom: -1, notes: '' };
process(frame: AudioFrame<Params>) {
frame.outL = frame.inL;
frame.outR = frame.inR;
}
render(api: PluginAPI<Params>) {
return (
<div>
<button onClick={() => this.setState({ tab: (this.state.tab + 1) % 3 })}>Tab {this.state.tab + 1}</button>
</div>
);
}
} Parameters and state are saved for you. For anything else, such as a pattern kept in a field, write saveState() and loadState(data); presets and projects carry what they return.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
type Params = { mix: number };
export default class Steps extends EffectPlugin<Params> {
static id = 'com.example.steps';
static pluginName = 'Steps';
static parameters = [{ id: 'mix', name: 'Mix', default: 1 }];
pattern: number[] = [1, 0, 0, 1, 0, 1, 0, 0];
process(frame: AudioFrame<Params>) {
frame.outL = frame.inL;
frame.outR = frame.inR;
}
// Parameters are saved for you. Anything else you want back goes through these two.
saveState() {
return { pattern: this.pattern };
}
loadState(data: any) {
this.pattern = data?.pattern ?? this.pattern;
}
render(api: PluginAPI<Params>) {
return <div>{this.pattern.join(' ')}</div>;
}
} The host learns of parameter moves and of the user's edits to this.state by itself. When something saveState() writes changes, or a change lands later, such as a sample that finished loading, call api.markStateChanged() so the host marks the project as modified.
Audio state
The window and the audio thread share static dspState buffers. this.getAudioState('name') returns a read-only snapshot of one, or of a slot a DSP factory publishes, such as an FFT's <slot>_mag. this.setAudioState('name', data) sends new contents without blocking the audio thread, which sees them from the next block. Instead of an array you can pass the id of a buffer this instance holds, such as an impulse response: the slot then becomes that audio.
api.copyBufferToDsp(bufferId) copies a decoded file or a loaded sample into the playback slots that frame.samplePlayer plays, and the plugin remembers the choice in the project. Audio-thread state shows both ends.
fetch
api.fetch is an HTTP client in the style of axios. Call it with a request, or use get, post, put, delete, patch, head or options. The response has data (JSON is parsed for you), status, statusText and headers; a failed request rejects with an error that carries a code and, when the server answered, its response.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
type Params = { mix: number };
type State = { news: string };
type Release = { version: string; notes: string };
export default class News extends EffectPlugin<Params, State> {
static id = 'com.example.news';
static pluginName = 'News';
static parameters = [{ id: 'mix', name: 'Mix', default: 1 }];
state: State = { news: '' };
process(frame: AudioFrame<Params>) {
frame.outL = frame.inL;
frame.outR = frame.inR;
}
async init(api: PluginAPI<Params>) {
// Await it: the native build needs the result before the next line runs.
const res = await api.fetch.get<Release>('https://example.com/latest.json');
if (res.status === 200) this.setState({ news: `${res.data.version}: ${res.data.notes}` });
}
render(api: PluginAPI<Params>) {
return <div>{this.state.news}</div>;
}
}Files
import { SynthPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
type Params = { level: number };
type State = { fileName: string };
export default class OneShot extends SynthPlugin<Params, State> {
static id = 'com.example.one-shot';
static pluginName = 'One Shot';
static parameters = [{ id: 'level', name: 'Level', default: 0.8 }];
// The playback slots samplePlayer reads: 10 s at 48 kHz.
static dspState = {
audioDataL: new Float32Array(480000),
audioDataR: new Float32Array(480000),
dspInfo: new Float32Array(4),
};
state: State = { fileName: '' };
pos = -1;
process(frame: AudioFrame<Params>) {
for (let i = 0; i < frame.midiCount; i++) {
if (frame.getMidiEvent(i).type === 0x90) this.pos = 0;
}
if (this.pos < 0 || this.pos >= frame.samplePlayer.getSampleFrames()) return;
const level = frame.getParam('level');
frame.outL = frame.samplePlayer.readSample(0, this.pos) * level;
// A mono file is copied into both slots, so channel 1 always plays.
frame.outR = frame.samplePlayer.readSample(1, this.pos) * level;
this.pos++;
}
async openFile() {
const file = await this.api.promptForFile({ extensions: ['wav', 'aif', 'aiff', 'flac', 'mp3'] });
if (!file) return; // cancelled
const audio = await this.api.decodeAudioData(await file.arrayBuffer());
this.api.copyBufferToDsp(audio.id);
this.setState({ fileName: file.name });
}
render(api: PluginAPI<Params>) {
return <button onClick={() => this.openFile()}>{this.state.fileName || 'Open a sample'}</button>;
}
}| Call | What it does |
|---|---|
promptForFile({ extensions }) | Opens the system's file panel. Resolves with { name, size, type, arrayBuffer() }, or null when the user cancels. |
decodeAudioData(bytes) | Decodes audio into a buffer this instance holds: { id, duration, numberOfChannels, sampleRate, length }. Pass the id to a waveform display, to copyBufferToDsp or to an export. |
saveFile({ defaultName, extensions }, bytes) | Resolves true once the file is written and false when the user cancels; a failure rejects with the reason. In the browser preview the save is a download. |
exportBufferWithDialog(id, name?) | Saves a buffer as an audio file the user places. The extension picks the format: .wav, .aif, .flac, .mp3 or .m4a. |
exportRegionWithDialog(id, start, end, name?) | The same for part of a buffer, with start and end from 0 to 1. |
exportRegionsWithDialog(id, starts, ends, names) | Several regions under one save panel, such as every slice of a loop. |
api.samples
Sample banks are folders of audio that ship with the plugin, such as a drum kit or a multisampled instrument. api.samples lists and loads them. It is a SampleLibraryAPI, and its bank and sample ids are checked against what the plugin declares (typed ids).
| Call | What it does |
|---|---|
getBanks() | The banks the plugin declares. |
getSamples(bankId) | A bank's samples: id, name, path and root note. |
loadSample(bankId, sampleId) | Loads one sample and resolves with it, including the bufferId the other calls take. A sample that cannot load resolves with an empty bufferId and logs why; it never rejects. |
preloadBank(bankId, onProgress?) | Loads a whole bank ahead of time, for an instrument that has to answer every note at once. |
isLoaded(bankId, sampleId), getLoadedSample(bufferId), hasBuffer(bufferId) | What is loaded. |
unloadSample(bufferId) | Frees a loaded sample. |
loadFromArrayBuffer(bytes, name, ext?) | Decodes audio you already hold, such as a dropped or downloaded file, into a buffer named name. |
unloadBuffer(bufferId) | Frees a buffer loadFromArrayBuffer made. It also leaves the next saved project, which keeps every buffer the instance holds. |
exportRegion(bufferId, start, end, filename) | Saves part of a buffer as a file, with start and end from 0 to 1. |
Loading a sample does not play it. Copy it into the playback slots with api.copyBufferToDsp(sample.bufferId), and frame.samplePlayer plays it. Assets walks through declaring a bank, loading it and playing it. In the browser preview, loadSample reads WAV files only.
api.assets
Asset folders hold files the plugin reads as data rather than plays straight: wavetables, impulse responses, presets, MIDI. api.assets is an AssetLibraryAPI. An asset's id is its file name without the extension, and a load that fails resolves empty rather than rejecting.
| Call | What it does |
|---|---|
getFolders() | The asset folders the plugin declares. |
listAssets(folderId) | A folder's files: id, name, path, size and type. |
loadAsset(folderId, assetId) | The file's bytes. |
loadWavetable(folderId, assetId, tableSize?) | A WAV file's first channel as a table of 2048 samples, or the size you ask for. |
loadImpulseResponse(folderId, assetId) | Loads an impulse response and resolves with its id, for setAudioState('<slot>_ir', id). |
getContentStatus() | Where the plugin's live content stands: checking, downloading (with bytes received), ready, offline or an error. |
Assets covers where these files go and how an impulse response reaches a convolver.
api.blobStore
api.blobStore keeps large audio data, such as a recorded take, on the user's computer so it is still there when the project opens again. Keys are up to 64 letters, digits, dots, dashes and underscores, and do not start with a dot. write resolves false when the disk refuses, so tell the user; remove deletes a key.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
type Params = { mix: number };
export default class Capture extends EffectPlugin<Params> {
static id = 'com.example.capture';
static pluginName = 'Capture';
static parameters = [{ id: 'mix', name: 'Mix', default: 1 }];
process(frame: AudioFrame<Params>) {
frame.outL = frame.inL;
frame.outR = frame.inR;
}
async keep(take: Float32Array, sampleRate: number) {
const saved = await this.api.blobStore.write('last-take', take, sampleRate);
if (!saved) console.log('The disk refused the take');
}
async restore(): Promise<Float32Array | null> {
const take = await this.api.blobStore.read('last-take');
// Check the length, not the value: a miss is null in the browser and an empty buffer natively.
if (!take || take.length === 0) return null;
return take;
}
render(api: PluginAPI<Params>) {
return <div />;
}
}api.liveAudio
api.liveAudio.input and api.liveAudio.output name the audio entering and leaving the plugin, refreshed every block. Hand them to a display such as AudioMarquee.
import { AudioMarquee, MarqueeMode } from '@the-plug/audio-marquee';
<AudioMarquee
width={480}
height={120}
sourceInput={api.liveAudio.input}
sourceOutput={api.liveAudio.output}
mode={MarqueeMode.Peak}
/>Background jobs
A job runs heavy work, such as normalizing, analysing or stretching a take, off the window's thread, so the window stays responsive. this.startJob(fn, buffers, numbers) runs a top-level function whose parameters are the buffers, then the numbers, then a one-element progress cell, and returns a job id: 0 when that function already has a job running. Poll jobProgress, jobDone and jobResult. jobCancel sets the progress cell to -1, so check it and return early.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
type Params = { mix: number };
type State = { progress: number };
// A job is a top-level function: the input buffers, then the numbers, then a progress cell.
function normalize(audio: Float32Array, target: number, progress: Float32Array): Float32Array {
let peak = 0.0;
for (let i = 0; i < audio.length; i++) {
peak = Math.max(peak, Math.abs(audio[i]));
if (progress[0] < 0) return new Float32Array(0); // cancelled
if (i % 65536 === 0) progress[0] = (0.5 * i) / audio.length;
}
const out = new Float32Array(audio.length);
let gain = 1.0;
if (peak > 0) gain = target / peak;
for (let i = 0; i < audio.length; i++) out[i] = audio[i] * gain;
return out;
}
export default class Normalizer extends EffectPlugin<Params, State> {
static id = 'com.example.normalizer';
static pluginName = 'Normalizer';
static parameters = [{ id: 'mix', name: 'Mix', default: 1 }];
state: State = { progress: 0 };
process(frame: AudioFrame<Params>) {
frame.outL = frame.inL;
frame.outR = frame.inR;
}
run(audio: Float32Array) {
const job = this.startJob(normalize, [audio], [0.9]);
const poll = setInterval(() => {
this.setState({ progress: this.jobProgress(job) });
if (!this.jobDone(job)) return;
clearInterval(poll);
const result = this.jobResult(job); // null if it was cancelled
if (result) console.log('normalized', result.length, 'samples');
}, 100);
}
render(api: PluginAPI<Params>) {
return <div>{Math.round(this.state.progress * 100)}%</div>;
}
}Automation menus
api.makeAutomationOptions('id') gives a control's right-click menu the host's own entries for that parameter, such as automation and MIDI learn. Hosts that offer such a menu through VST3 show their entries; AU has no way to ask, so the entry is left out there rather than shown doing nothing. In the browser preview, the builder adds its own. api.restoreDefault('id') returns a parameter to its default.
import { Knob } from '@the-plug/ui';
<Knob
value={this.getParam('cutoff')}
onChange={(v) => this.setParam('cutoff', v)}
label="Cutoff"
contextMenu={[
{ label: 'Restore default', onClick: () => api.restoreDefault('cutoff') },
...api.makeAutomationOptions('cutoff'),
]}
/>Editor size
static width and static height set the editor's size. With static resizable, minSize and maxSize, the user can resize it. api.getEditorSize() is the size now, and api.requestEditorSize(width, height) asks the host for another, kept within your limits; it returns whether the host agreed.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
import { ResizeGrip } from '@the-plug/ui';
type Params = { mix: number };
export default class Roomy extends EffectPlugin<Params> {
static id = 'com.example.roomy';
static pluginName = 'Roomy';
static parameters = [{ id: 'mix', name: 'Mix', default: 1 }];
static width = 640;
static height = 360;
static resizable = true;
static minSize = { width: 480, height: 270 };
static maxSize = { width: 1280, height: 720 };
process(frame: AudioFrame<Params>) {
frame.outL = frame.inL;
frame.outR = frame.inR;
}
render(api: PluginAPI<Params>) {
const size = api.getEditorSize();
return (
<div style={{ width: size.width, height: size.height, position: 'relative' }}>
{/* The grip asks the host for a new size, so it works in hosts that draw no frame to drag. */}
<ResizeGrip api={api} />
</div>
);
}
}Presets
static presets lists the presets that ship with the plugin, and hosts show them in their own preset menus too. Give values in each parameter's own units, as in default, and a choice by its option name if you like. The build refuses an unknown parameter, a value out of range and a repeated name. <PresetManager api={api} /> is a ready-made menu over all of it (Presets components).
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI, TypedParameterDefinition } from '@the-plug/core';
import { PresetManager } from '@the-plug/ui';
type Params = { drive: number; tone: number };
export default class Drive extends EffectPlugin<Params> {
static id = 'com.example.drive';
static pluginName = 'Drive';
static parameters = [
{ id: 'drive', name: 'Drive', default: 0.3 },
{ id: 'tone', name: 'Tone', default: 0.5 },
] satisfies TypedParameterDefinition<Params>[];
// Factory presets ship with the plugin; the user's own sit beside them.
static presets = [
{ name: 'Gentle', params: { drive: 0.15, tone: 0.6 } },
{ name: 'Crushed', params: { drive: 0.95, tone: 0.3 } },
];
process(frame: AudioFrame<Params>) {
const k = 1 + frame.getParam('drive') * 20;
frame.outL = Math.tanh(frame.inL * k);
frame.outR = Math.tanh(frame.inR * k);
}
render(api: PluginAPI<Params>) {
// A dropdown with Save, Save As and Delete, and the factory presets in their own section.
return <PresetManager api={api} width={220} />;
}
}| Call | What it does |
|---|---|
savePreset(name), loadPreset(name), getPresetList(), deletePreset(name) | The user's own presets of the whole plugin: every parameter and the editor's state. Every list of the user's presets comes back in one order (letter case set aside, numbers by value), and a name that is empty, over 64 bytes, starts with a dot or holds / \ : or a control character is refused. |
getFactoryPresetList(), loadFactoryPreset(name) | The presets that ship in static presets. A factory preset is read-only, and loading one sets only the parameters it names. |
exportPreset(), importPreset(json) | The whole state as text, for copy and paste or a file. |
savePresetScope(scope, name), applyPresetScope(scope, name), getPresetScopeList(scope), deletePresetScope(scope, name) | Presets for one group of parameters, named in static presetScopes. |
isPresetScopeDirty(scope, name) | Whether the group has moved since that preset, for a modified marker. |
saveSlicePreset(scope, name, sliceIndex), getSlicePresetNames(scope), deleteSlicePreset(scope, name) | Presets for some fields of one slice of state.slices, named in static sliceScopes. |
applySlicePreset(scope, name, target) | Applies a slice preset to one slice, or to each slice of a list in one state change. An index with no slice is skipped. |
isSlicePresetDirty(scope, name, sliceIndex) | Whether the slice differs from that preset in a field the preset holds. A slice that is not there is at no preset. |
getFactorySlicePresetNames(scope), applyFactorySlicePreset(scope, name, target) | The slice presets that ship in static sliceFactoryPresets, read-only, in the order you declared them. |
storeSlicePreset(scope, name, values) | Stores a slice preset from values you give, for example presets your plugin kept somewhere else. Returns whether it was stored. |
Slice presets
A slicer keeps its slices in state.slices. static sliceScopes names the fields of a slice that a slice preset saves and applies, and static sliceFactoryPresets ships read-only ones per scope. A factory preset sets only the fields it names, each a field its scope saves, as a number, true or false, or a string written out; the build refuses anything else.
Give <PresetManager> a scope and a sliceIndex and it is the slice preset menu: the factory presets first, then the user's. A pick applies to every slice in sliceIndices at once, or to sliceIndex alone. The menu shows the preset the slice at sliceIndex is at, and nothing once that slice is edited. It has Save As and Delete but no Save, because the preset it shows is one the slice already holds. onBeforeApply runs before each apply, where you record the undo step, and onApplied after it.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
import { PresetManager } from '@the-plug/ui';
type Params = { mix: number };
type Slice = { start: number; end: number; pitch: number; volume: number; reverse: boolean };
type State = { slices: Slice[]; shown: number; selection: number[] };
export default class Chopper extends EffectPlugin<Params, State> {
static id = 'com.example.chopper';
static pluginName = 'Chopper';
static parameters = [{ id: 'mix', name: 'Mix', default: 1 }];
// The fields of a slice that a preset of each scope saves and applies.
static sliceScopes = { sound: ['pitch', 'volume', 'reverse'] };
// Read-only presets that ship with the plugin. Each sets only the fields it names.
static sliceFactoryPresets = {
sound: { 'Octave down': { pitch: -12 }, 'Reverse': { reverse: true } },
};
state: State = {
slices: [
{ start: 0, end: 0.5, pitch: 0, volume: 1, reverse: false },
{ start: 0.5, end: 1, pitch: 0, volume: 1, reverse: false },
],
shown: 0,
selection: [0, 1],
};
process(frame: AudioFrame<Params>) {
frame.outL = frame.inL;
frame.outR = frame.inR;
}
render(api: PluginAPI<Params>) {
// The menu shows the preset the shown slice is at; a pick applies to the whole selection as one undo step.
return (
<PresetManager
api={api}
scope="sound"
sliceIndex={this.state.shown}
sliceIndices={this.state.selection}
onBeforeApply={() => api.pushUndo('Slice preset')}
width={220}
/>
);
}
}Undo
For edits that are not parameter moves, such as a drawn pattern or a moved point, give the plugin its own undo. A component makes the same calls on this.$api.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
type Params = { mix: number };
type State = { steps: number[] };
export default class Sequencer extends EffectPlugin<Params, State> {
static id = 'com.example.sequencer';
static pluginName = 'Sequencer';
static parameters = [{ id: 'mix', name: 'Mix', default: 1 }];
state: State = { steps: [0, 0, 0, 0, 0, 0, 0, 0] };
process(frame: AudioFrame<Params>) {
frame.outL = frame.inL;
frame.outR = frame.inR;
}
clearAll(api: PluginAPI<Params>) {
api.pushUndo('Clear pattern'); // snapshot first, then change
this.setState({ steps: [0, 0, 0, 0, 0, 0, 0, 0] });
}
render(api: PluginAPI<Params>) {
return (
<div>
<button onClick={() => this.clearAll(api)}>Clear</button>
<button disabled={!api.canUndo} onClick={() => api.undo()}>Undo {api.undoLabel ?? ''}</button>
<button disabled={!api.canRedo} onClick={() => api.redo()}>Redo</button>
</div>
);
}
}| Call | What it does |
|---|---|
pushUndo(label) | Records the plugin's state before an edit. Call it first, then change things. |
undo(), redo() | Step back and forward. Each returns false when there is nothing to do. |
canUndo, canRedo, undoLabel, redoLabel | For the buttons. |
beginUndoGroup(label), endUndoGroup() | Many changes, such as randomizing every step, undone as one. |
clearUndoHistory() | Forget both stacks, for example after loading a preset. |
License
api.license, also this.license, says whether this copy is licensed. status is 'valid', 'grace', 'invalid' or 'pending'; isValid is true when it is valid or in grace; trial holds a trial's days left. It updates as the answer comes in. The browser preview always reads valid.
<div>{api.license.isValid ? 'Licensed' : api.license.trial ? 'Trial' : 'Not licensed'}</div>api.modules
Importing an extension module registers its calls on api.modules under the module's name; each module documents its own. In the browser preview, a module that is not loaded answers with a failure rather than throwing. What you import lists the modules.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
import '@the-plug/onnx-splitter'; // importing a module registers api.modules.onnxSplitter
type Params = { mix: number };
export default class Stems extends EffectPlugin<Params> {
static id = 'com.example.stems';
static pluginName = 'Stems';
static parameters = [{ id: 'mix', name: 'Mix', default: 1 }];
process(frame: AudioFrame<Params>) {
frame.outL = frame.inL;
frame.outR = frame.inR;
}
render(api: PluginAPI<Params>) {
return <div>{api.modules.onnxSplitter ? 'Stem splitting is available' : ''}</div>;
}
}this.daw
this.daw is the host's transport as the window sees it. Read in render(), it redraws the window as it changes; Transport and timing has an example.
| Member | What it is |
|---|---|
tempo, timeSigNumerator, timeSigDenominator | The tempo and time signature. |
ppqPosition, barPosition, beatPosition | Where the playhead is, in quarter notes and in the bar. |
isPlaying, isRecording, isLooping, loopStartPpq, loopEndPpq | The transport and the loop. |
phase(division) | From 0 to 1 once per division, locked to the host, with the same divisions as frame.phase(). A bare phase() is a quarter note here, where frame.phase() is a whole bar. |