API typings
  1. Start here
  2. API typings
    1. What runs where
    2. process(frame)
    3. Block process()
    4. PluginAPI
    5. Components and $api
    6. The generics
    7. Params
    8. State
    9. Frame generics
    10. Asset and sample ids
    11. Type reference
  3. Audio processing
  4. PluginAPI
  5. UI components
  6. Assets
  7. AI

API typings

What each method of your plugin receives, which thread runs it, and how the two type arguments you give the class reach every one of them.

What runs where

A plugin runs on two threads. The audio thread makes the sound and must never wait: it cannot load a file, touch the network or redraw anything. The UI thread draws the window and does everything that can take time. Which object a method receives tells you which thread it is on:

WhereThreadWhat you get
process(frame)Audio, per sampleframe: AudioFrame<Params>
Block process(…)Audio, per blockapi: AudioAPI<Params>, context: ProcessContext, and a synth's midi: MidiEvent[]
reset(api, context)Audioapi, of which only getAudioState works
init, render, event handlers, your own methodsUIapi: PluginAPI<Params> (or this.api), this.getParam, this.setParam, this.state
A component you writeUIthis.$api: BasePluginAPI, this.props

In process(), the build refuses the window's calls: this.state, this.setState, this.getParam, this.setParam, api.assets, api.samples and undo. Read parameters there with frame.getParam, or api.getParam in block mode, and pass data between the threads through audio-thread state.

process(frame)

Give process exactly one parameter and the plugin is per-sample: it is called once for every sample, and frame is that sample, going in and coming out. This is the usual way to write a plugin, and the build turns it into a tight loop over each block.

Per-sample: one parameter
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI, TypedParameterDefinition } from '@the-plug/core';

type Params = { drive: number };

export default class Fuzz extends EffectPlugin<Params> {
  static id = 'com.example.fuzz';
  static pluginName = 'Fuzz';
  static parameters = [{ id: 'drive', name: 'Drive', default: 0.5 }] satisfies TypedParameterDefinition<Params>[];

  // One parameter, so the plugin is per-sample: frame is this sample, in and out.
  process(frame: AudioFrame<Params>) {
    const k = 1 + frame.getParam('drive') * 30;
    frame.outL = frame.softclip(frame.inL * k);
    frame.outR = frame.softclip(frame.inR * k);
  }

  render(api: PluginAPI<Params>) {
    return <div />;
  }
}

The frame's type comes from your annotation alone, so write AudioFrame<Params> and its getParam checks your ids. AudioFrame lists every member.

Block process()

Give process any other number of parameters and it runs once per block, with whole buffers. An effect takes (inputs, outputs, api, context) and a synth takes (outputs, api, context, midi).

Block: an effect
import { EffectPlugin } from '@the-plug/core';
import type { AudioAPI, AudioBus, PluginAPI, ProcessContext, TypedParameterDefinition } from '@the-plug/core';

type Params = { gain: number };

export default class BlockGain extends EffectPlugin<Params> {
  static id = 'com.example.block-gain';
  static pluginName = 'Block Gain';
  static parameters = [{ id: 'gain', name: 'Gain', default: 1 }] satisfies TypedParameterDefinition<Params>[];

  // Four parameters, so the plugin processes whole blocks. Keep the names api and context:
  // the native build finds them by name.
  process(inputs: AudioBus, outputs: AudioBus, api: AudioAPI<Params>, context: ProcessContext) {
    const gain = api.getParam('gain');
    for (let ch = 0; ch < outputs.length; ch++) {
      for (let i = 0; i < context.sampleFrames; i++) {
        outputs[ch][i] = inputs[ch][i] * gain;
      }
    }
  }

  render(api: PluginAPI<Params>) {
    return <div />;
  }
}
Block: a synth
import { SynthPlugin } from '@the-plug/core';
import type { AudioAPI, AudioBus, MidiEvent, PluginAPI, ProcessContext } from '@the-plug/core';

type Params = { level: number };

export default class Clicker extends SynthPlugin<Params> {
  static id = 'com.example.clicker';
  static pluginName = 'Clicker';
  static parameters = [{ id: 'level', name: 'Level', default: 0.5 }];

  // A synth's block process has no inputs and gets the block's MIDI, each event with its sample offset.
  process(outputs: AudioBus, api: AudioAPI<Params>, context: ProcessContext, midi: MidiEvent[]) {
    for (const ch of outputs) ch.fill(0);
    for (const e of midi) {
      if (e.type === 0x90 && e.velocity > 0) {
        for (const ch of outputs) ch[e.sampleOffset] = api.getParam('level');
      }
    }
  }

  render(api: PluginAPI<Params>) {
    return <div />;
  }
}

Keep the names api and context: the native build recognises them by name, not by type. For the transport in block mode, use the api's getters, such as api.getTempo(), api.getPpqPosition(), api.getBeatPosition() and api.isPlaying(). AudioAPI also declares factories such as createADSR and createCompressor, but no build implements them yet; use the @the-plug/dsp slots instead.

PluginAPI

PluginAPI<Params> is the window's whole toolbox. render(api) and init(api) receive it, and every other method on the UI thread reaches the same object as this.api.

PluginAPI in the editor
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';

type Params = { mix: number };

export default class Editor extends EffectPlugin<Params> {
  static id = 'com.example.editor';
  static pluginName = 'Editor';
  static parameters = [{ id: 'mix', name: 'Mix', default: 1 }];

  process(frame: AudioFrame<Params>) {
    frame.outL = frame.inL * frame.getParam('mix');
    frame.outR = frame.inR * frame.getParam('mix');
  }

  // render() gets the api; every other UI-thread method reaches the same object as this.api.
  render(api: PluginAPI<Params>) {
    return (
      <button onClick={() => this.resetMix()}>
        Mix {Math.round(this.getParam('mix') * 100)}%
      </button>
    );
  }

  resetMix() {
    this.api.resetParam('mix');
  }
}
NamespaceWhat it holds
api.fetchHTTP requests.
api.samplesThe plugin's sample banks: list, load, play.
api.assetsThe plugin's asset folders: impulse responses, wavetables, any file.
api.blobStoreAudio kept on disk between sessions.
api.liveAudioThe signal going in and coming out, for displays.
api.licenseWhether this copy is licensed.
api.modulesThe APIs of the extension modules the plugin imports.

Parameters, files, presets, background jobs, the editor's size and undo are methods on api itself; the PluginAPI page covers each. There is no api.transport: the window reads the host's transport from this.daw.

Components and $api

A component you write extends PluginComponent<Props, State>. It gets this.props, its own this.state and setState, and this.$api: a BasePluginAPI, the part of the plugin API that does not depend on any one plugin's parameters. Its getParam and setParam take any string, and it has undo.

Its state is saved with the plugin's and put back with it, every field but those the class names in static transientState, such as a text field that is open. A prop the plugin does not pass is undefined where the component tests for it, with === undefined, == null or ??, in a built plugin as in the browser. Read any other way, an absent number is 0 in a built plugin, an absent string '' and an absent boolean false, so give a default with ??.

A component of your own
import { PluginComponent } from '@the-plug/core';

type Props = { label: string; onPick: (value: number) => void };
type State = { picked: number };

// A component gets this.$api: the untyped base of PluginAPI, shared by every plugin.
export class StepPicker extends PluginComponent<Props, State> {
  state: State = { picked: 0 };

  render() {
    return (
      <div style={{ display: 'flex', gap: 4 }}>
        {[1, 2, 3, 4].map((n) => (
          <button
            key={n}
            onClick={() => {
              this.$api.pushUndo('Pick step');
              this.setState({ picked: n });
              this.props.onPick(n);
            }}
          >
            {this.props.label} {n}
          </button>
        ))}
      </div>
    );
  }
}

The generics

EffectPlugin<Params, State> and SynthPlugin<Params, State> take two type arguments, and both are optional.

  • Params types every parameter read and write: PluginAPI<Params> in the window, this.getParam and this.setParam, and AudioAPI<Params> in block mode. In per-sample mode it reaches the frame through your AudioFrame<Params> annotation.
  • State types this.state and setState.

Params

Describe your parameters with a type. Then satisfies TypedParameterDefinition<Params>[] checks every id in static parameters, so a typo is an error where you made it.

Params: a type, or an interface that extends PluginParams
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI, PluginParams, TypedParameterDefinition } from '@the-plug/core';

// A type alias works with everything.
type Params = { gain: number; tone: number };

// An interface works with the plugin classes, but TypedParameterDefinition, EffectFrame and
// SynthFrame need it to extend PluginParams.
interface ToneParams extends PluginParams {
  gain: number;
  tone: number;
}

export default class Tone extends EffectPlugin<Params> {
  static id = 'com.example.tone';
  static pluginName = 'Tone';

  // satisfies checks every id against Params: a typo is an error here, not a silent knob.
  static parameters = [
    { id: 'gain', name: 'Gain', default: 1 },
    { id: 'tone', name: 'Tone', default: 0.5 },
  ] satisfies TypedParameterDefinition<Params>[];

  process(frame: AudioFrame<Params>) {
    frame.outL = frame.inL * frame.getParam('gain');
    frame.outR = frame.inR * frame.getParam('gain');
  }

  render(api: PluginAPI<Params>) {
    return <div />;
  }
}

export const sameIds: TypedParameterDefinition<ToneParams>[] = Tone.parameters;

An interface works with the plugin classes too, but TypedParameterDefinition, EffectFrame and SynthFrame accept one only when it extends PluginParams. Doing that lets getParam accept any string, so a type is the better choice.

State

The second argument is the shape of this.state. setState takes part of it and redraws the window, and skips the redraw when nothing changed.

State: the second type argument
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';

type Params = { mix: number };
type State = { page: 'main' | 'settings'; selectedBand: number };

export default class Eq extends EffectPlugin<Params, State> {
  static id = 'com.example.eq';
  static pluginName = 'EQ';
  static parameters = [{ id: 'mix', name: 'Mix', default: 1 }];

  state: State = { page: 'main', selectedBand: 0 };

  process(frame: AudioFrame<Params>) {
    frame.outL = frame.inL;
    frame.outR = frame.inR;
  }

  render(api: PluginAPI<Params>) {
    // this.state is a State; setState takes part of one and redraws.
    return (
      <button onClick={() => this.setState({ page: this.state.page === 'main' ? 'settings' : 'main' })}>
        {this.state.page}
      </button>
    );
  }
}

Frame generics

AudioFrame<Params, DspState, AuxIn, AuxOut> takes up to four. For a plugin with sidechain or aux buses, EffectFrame<Params, AuxIn, AuxOut> types frame.aux and frame.auxOut by bus id. SynthFrame takes the outputs first: SynthFrame<Params, AuxOut, AuxIn>.

A sidechain: EffectFrame<Params, AuxIn>
import { EffectPlugin } from '@the-plug/core';
import type { AuxInputDefinition, EffectFrame, PluginAPI, TypedParameterDefinition } from '@the-plug/core';

type Params = { threshold: number };
type AuxIn = { sidechain: 2 }; // bus id -> channel count

export default class Ducker extends EffectPlugin<Params> {
  static id = 'com.example.ducker';
  static pluginName = 'Ducker';
  static parameters = [{ id: 'threshold', name: 'Threshold', default: 0.2 }] satisfies TypedParameterDefinition<Params>[];
  static auxInputs = [{ id: 'sidechain', name: 'Sidechain', channels: 2 }] satisfies AuxInputDefinition<AuxIn>[];

  // EffectFrame<Params, AuxIn, AuxOut> types frame.aux and frame.auxOut by bus id.
  // SynthFrame takes the outputs first: SynthFrame<Params, AuxOut, AuxIn>.
  process(frame: EffectFrame<Params, AuxIn>) {
    const key = Math.max(Math.abs(frame.aux.sidechain.inL), Math.abs(frame.aux.sidechain.inR));
    let duck = 1.0;
    if (key > frame.getParam('threshold')) duck = 0.3;
    frame.outL = frame.inL * duck;
    frame.outR = frame.inR * duck;
  }

  render(api: PluginAPI<Params>) {
    return <div />;
  }
}

The second argument of AudioFrame types frame.dspState. It defaults to a record of Float32Arrays, which is what static dspState holds.

Asset and sample ids

AssetIdIn<'irs'> is an asset id in the folder irs, and SampleIdIn<'drums'> a sample id in the bank drums. The builder fills these in from your plugin's own files, so ids complete as you type them, and any string still compiles, because ids are often worked out at run time. api.fetch.get<T>() types the response's data as T.

Asset and sample ids
import { EffectPlugin } from '@the-plug/core';
import type { AssetIdIn, AudioFrame, PluginAPI, SampleIdIn } from '@the-plug/core';

type Params = { mix: number };

// In the builder these complete with the ids your plugin's files have. Any string still compiles.
const room: AssetIdIn<'irs'> = 'room';
const kick: SampleIdIn<'drums'> = 'kick-c2';

export default class Ids extends EffectPlugin<Params> {
  static id = 'com.example.ids';
  static pluginName = 'Ids';
  static parameters = [{ id: 'mix', name: 'Mix', default: 1 }];

  process(frame: AudioFrame<Params>) {
    frame.outL = frame.inL;
    frame.outR = frame.inR;
  }

  async init(api: PluginAPI<Params>) {
    await api.assets.loadImpulseResponse('irs', room);
    await api.samples.loadSample('drums', kick);
    // api.fetch.get<T>() types the body it returns.
    const res = await api.fetch.get<{ presets: string[] }>('https://example.com/presets.json');
    console.log(res.data.presets.length);
  }

  render(api: PluginAPI<Params>) {
    return <div />;
  }
}

Type reference

The types you will meet most, all from @the-plug/core:

TypeWhat it is
AudioFrame<Params>One sample on the audio thread: inputs, outputs, parameters, MIDI, timing, helpers.
EffectFrame<Params, AuxIn, AuxOut>An effect's frame with typed sidechain and aux buses.
SynthFrame<Params, AuxOut, AuxIn>A synth's frame with typed buses; note the outputs come first.
AudioAPI<Params>The block process's api: parameters, transport getters, MIDI out, buffers.
ProcessContextThe block's size, channel count and sample rate.
AudioBusOne Float32Array per channel.
MidiEventA block's MIDI event: type, note, velocity, channel and its sampleOffset in the block.
FrameMidiEventA frame's MIDI event: type, note, velocity, channel, status, data1, data2.
PluginAPI<Params>Everything the window can call.
BasePluginAPIWhat a component gets as this.$api: untyped parameters and undo.
PluginComponent<Props, State>The base of a component you write.
TypedParameterDefinition<Params>A parameter definition whose id is checked against Params.
ChannelsDeclarationThe channel layouts a plugin runs on: 'stereo', 'mono', '5.1', a list of them, or { process, offer }.
ChannelLayoutOne side's layout: mono, stereo, the surround and immersive beds from 'lcr' to '9.1.6', ambisonics to third order, or { discrete: N }, which builds for AU alone.
ChannelRoleNameWhat frame.channelRole(ch) returns: 'L', 'R', 'C', 'LFE', 'Ls', 'Rs' and the rest of VST3's speakers, or 'ACN0' and up for ambisonics.
AuxInputDefinition<AuxIn>A sidechain or aux input bus, its width (1, 2 or a layout) checked against AuxIn.
PluginAssetConfigstatic assets: sample banks, asset folders, defaults.
LoadedSampleWhat api.samples.loadSample resolves to, with the bufferId to play.
AssetEntryOne file of an asset folder, as api.assets.listAssets lists it.
FileHandleA file the user picked: name, size, type and arrayBuffer().
AudioBufferInfoA decoded file: id, duration, numberOfChannels, sampleRate, length.
FetchResponse<T>An HTTP response: data (a T), status, statusText, headers.
ContentStatusWhere the plugin's live content stands: downloading, ready, offline…
DAWStateWhat this.daw holds in the window: tempo, time signature, playhead position, transport and loop.

CurvePoint, the point type of the curve editors, comes from @the-plug/ui.