AudioFrame
A per-sample process(frame) gets one AudioFrame for every sample. It holds this sample's input and takes its output, and carries everything else the audio thread may read: parameters, the MIDI that lands on this sample, the host's timing, and the plugin's state and DSP slots. Use it only inside process: it describes this one sample.
Inputs and outputs
frame.inL and frame.inR are this sample's input, and you write frame.outL and frame.outR. On a mono track, inR reads the same as inL. For other channel counts, declare the layouts the plugin accepts in static channels and loop over frame.numChannels with getInput(ch) and setOutput(ch, value).
A synth's frame has the same members, but a built synth has no main input, so its inL and inR read 0. The frame's typing is AudioFrame.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, ChannelsDeclaration, PluginAPI } from '@the-plug/core';
type Params = { gain: number };
export default class AnyWidth extends EffectPlugin<Params> {
static id = 'com.example.any-width';
static pluginName = 'Any Width';
static parameters = [{ id: 'gain', name: 'Gain', default: 1 }];
// Run on stereo and on mono tracks.
static channels: ChannelsDeclaration = ['stereo', 'mono'];
process(frame: AudioFrame<Params>) {
const gain = frame.getParam('gain');
for (let ch = 0; ch < frame.numChannels; ch++) {
frame.setOutput(ch, frame.getInput(ch) * gain);
}
}
render(api: PluginAPI<Params>) {
return <div />;
}
} A layout wider than stereo works the same way. Declare it (static channels = ['5.1'], or '7.1.4', 'ambisonic1' and the rest of ChannelLayout), and every channel reaches process in the layout's canonical order: '5.1' runs L R C LFE Ls Rs, and ambisonics run in ACN order. frame.channelRole(ch) names each output channel, and frame.inputLayout and frame.outputLayout name each side's layout, so find a channel by its role rather than its index. Only mono and stereo convert into each other, so hosts are offered a wider layout exactly as you declare it. The browser preview folds it to stereo for you to listen to; a built plugin plays every channel.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, ChannelsDeclaration, PluginAPI } from '@the-plug/core';
type Params = { gain: number };
export default class SurroundTrim extends EffectPlugin<Params> {
static id = 'com.example.surround-trim';
static pluginName = 'Surround Trim';
static parameters = [{ id: 'gain', name: 'Gain', default: 1 }];
// 5.1 in and 5.1 out: hosts are offered 5.1 alone.
static channels: ChannelsDeclaration = ['5.1'];
process(frame: AudioFrame<Params>) {
const gain = frame.getParam('gain');
for (let ch = 0; ch < frame.numChannels; ch++) {
// '5.1' runs L R C LFE Ls Rs. Find a channel by its role, not its index.
const role = frame.channelRole(ch);
if (role === 'LFE') {
frame.setOutput(ch, frame.getInput(ch));
} else {
frame.setOutput(ch, frame.getInput(ch) * gain);
}
}
}
render(api: PluginAPI<Params>) {
return <div />;
}
}History and lookahead
static inputHistory = N gives an effect frame.previousL and frame.previousR: the last N input samples, oldest first, with this sample last. static lookahead = N gives frame.nextL and frame.nextR: the next N samples. Lookahead delays the output by N samples, and the host is told so it can line the track up.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
type Params = { ceiling: number };
export default class Smoother extends EffectPlugin<Params> {
static id = 'com.example.smoother';
static pluginName = 'Smoother';
static parameters = [{ id: 'ceiling', name: 'Ceiling', default: 0.9 }];
static inputHistory = 16; // frame.previousL/R: the last 16 input samples, oldest first, this one last
static lookahead = 32; // frame.nextL/R: the next 32 samples; adds 32 samples of latency, reported to the host
process(frame: AudioFrame<Params>) {
// Ahead: turn both channels down before a peak arrives.
let peak = 0.0;
for (let i = 0; i < frame.nextL.length; i++) {
peak = Math.max(peak, Math.abs(frame.nextL[i]));
peak = Math.max(peak, Math.abs(frame.nextR[i]));
}
const ceiling = frame.getParam('ceiling');
let gain = 1.0;
if (peak > ceiling) gain = ceiling / peak;
// Behind: a 16-sample moving average softens the top end.
let sumL = 0.0;
let sumR = 0.0;
for (let i = 0; i < frame.previousL.length; i++) {
sumL += frame.previousL[i];
sumR += frame.previousR[i];
}
frame.outL = (sumL / frame.previousL.length) * gain;
frame.outR = (sumR / frame.previousR.length) * gain;
}
render(api: PluginAPI<Params>) {
return <div />;
}
}Parameters
frame.getParam('id') and frame.params.id read the same value. Write the id out: the audio thread has no way to look one up from a variable. A parameter can jump between blocks, so smooth anything that would click.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
type Params = { volume: number };
export default class Volume extends EffectPlugin<Params> {
static id = 'com.example.volume';
static pluginName = 'Volume';
static parameters = [{ id: 'volume', name: 'Volume', default: 0, min: -60, max: 12, units: 'dB' }];
static dspState = { volumeRamp: new Float32Array(1) };
process(frame: AudioFrame<Params>) {
// frame.getParam('volume') and frame.params.volume read the same value.
// smooth() ramps toward it over 20 ms, so a fast knob move does not click.
const db = frame.smooth(frame.dspState.volumeRamp, frame.params.volume, 0.02);
const gain = frame.dbToGain(db);
frame.outL = frame.inL * gain;
frame.outR = frame.inR * gain;
}
render(api: PluginAPI<Params>) {
return <div />;
}
}Timing
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
type Params = { depth: number };
export default class SyncTrem extends EffectPlugin<Params> {
static id = 'com.example.sync-trem';
static pluginName = 'Sync Trem';
static parameters = [{ id: 'depth', name: 'Depth', default: 0.6 }];
process(frame: AudioFrame<Params>) {
// phase('1/8') runs 0 to 1 once per eighth note, following the host's tempo and position.
const wave = 0.5 + 0.5 * Math.sin(2 * Math.PI * frame.phase('1/8'));
const gain = 1 - frame.getParam('depth') * wave;
frame.outL = frame.inL * gain;
frame.outR = frame.inR * gain;
}
render(api: PluginAPI<Params>) {
return <div />;
}
}| Member | What it is |
|---|---|
sampleRate | The session's sample rate, in Hz. |
blockSize | The size of the block this sample is in. |
sampleIndex | How many samples this instance has processed. It never resets: it keeps counting while the transport is stopped, and a seek does not move it. |
currentTimeSec | The host's position, in seconds. |
tempo | Beats per minute. |
ppq | The position in quarter notes. |
beat, barPosition | The position within the bar. |
timeSigNumerator, timeSigDenominator | The time signature. |
isPlaying, isRecording, isLooping, isOffline | The transport's state. isOffline is true while the host bounces; isRecording always reads false in the browser preview. |
loopStartPpq, loopEndPpq | The loop, in quarter notes. |
transportJumped | True on the sample playback starts, seeks while playing, or wraps a loop. |
phase(division) | Runs 0 to 1 once per division, counted from the bar line and locked to the host. The divisions are '1/1' (one bar), '1/2' (half a bar), '1/4', '1/8', '1/16', '1/32', dotted '1/4d' and '1/8d', and triplet '1/4t' and '1/8t'; any other string runs as '1/4'. A bare phase() is one bar. |
Helpers
The frame carries the common maths, so per-sample code needs no imports for it:
| Helper | What it does |
|---|---|
lerp(a, b, t), cubic_interp(…) | Interpolation. |
softclip(x), hardclip(x, threshold) | Saturation and clipping. |
smooth(state, target, seconds) | Ramps toward a target, so a jumpy value does not click. Keep a Float32Array of your own for state: smooth reads and writes its first element. |
dryWet(dry, wet, mix) | A mix between two signals. |
gainToDb(g), dbToGain(db) | Level conversion. |
flushDenormal(x) | Rounds tiny values to zero, which keeps a decaying tail from eating CPU. |
readDspState, writeDspState, accumulateDspState | Read, write or add into a dspState buffer as a ring: the offset counts from this sample's sampleIndex. Adding suits overlap-add. |
getPrevSlice(channel, start, length) | A run of earlier input samples; start is negative for the past. |
Sample player
frame.samplePlayer plays the sample the window copied into the plugin's playback slots: readSample(channel, frame), readSampleInterp(channel, position) for playing at another pitch, and getSampleFrames(), getSampleChannels() and getSampleRate(). A mono sample reads the same on both channels.
import { SynthPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
type Params = { volume: number };
export default class OneShot extends SynthPlugin<Params> {
static id = 'com.example.oneshot';
static pluginName = 'One Shot';
static parameters = [{ id: 'volume', name: 'Volume', default: 0.8 }];
static assets = { sampleBanks: ['kits/acoustic'] };
// The playback slots. process() plays only what the editor copied in here.
static dspState = {
audioDataL: new Float32Array(480000),
audioDataR: new Float32Array(480000),
dspInfo: new Float32Array(4),
voice: new Float32Array(2), // [playing, position]
};
state = { status: 'Pick a sound' };
async choose(api: PluginAPI<Params>, sampleId: string) {
const loaded = await api.samples.loadSample('acoustic', sampleId);
if (loaded.bufferId === '') {
this.setState({ status: `Could not load ${sampleId}` });
return;
}
api.copyBufferToDsp(loaded.bufferId);
this.setState({ status: sampleId });
}
process(frame: AudioFrame<Params>) {
const voice = frame.dspState.voice;
for (let m = 0; m < frame.midiCount; m++) {
const e = frame.getMidiEvent(m);
if (e.type === 0x90 && e.velocity > 0) {
voice[0] = 1;
voice[1] = 0;
}
}
if (voice[0] === 0) {
frame.outL = 0;
frame.outR = 0;
return;
}
const gain = frame.getParam('volume');
frame.outL = frame.samplePlayer.readSampleInterp(0, voice[1]) * gain;
frame.outR = frame.samplePlayer.readSampleInterp(1, voice[1]) * gain;
// Step by the file's rate over the session's, so it plays at its own pitch.
voice[1] += frame.samplePlayer.getSampleRate() / frame.sampleRate;
if (voice[1] >= frame.samplePlayer.getSampleFrames()) voice[0] = 0;
}
render(api: PluginAPI<Params>) {
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, padding: 12 }}>
{api.samples.getSamples('acoustic').map((s) => (
<button onClick={() => this.choose(api, s.id)}>{s.name}</button>
))}
<span>{this.state.status}</span>
</div>
);
}
}Assets explains the playback slots and the other ways a sample gets there.
Block processing
A process with any number of parameters other than one runs once per block, with whole buffers. It suits code that works on a block at a time, such as an FFT. The typings page shows both signatures; the block's transport comes from the api's getters, for example api.getTempo() and api.isPlaying().
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 />;
}
}@the-plug/dsp
Stateful building blocks such as filters, envelopes and dynamics are declared once in static dsp. Each entry is a slot with its own memory, and you call it as frame.dsp.<slot>(…) once per sample. Give every channel and every job its own slot: a slot run on two signals mixes their histories.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
import { compress, dryWet, lfo, smooth, svf } from '@the-plug/dsp';
type Params = { mix: number };
export default class AutoFilter extends EffectPlugin<Params> {
static id = 'com.example.auto-filter';
static pluginName = 'Auto Filter';
static parameters = [{ id: 'mix', name: 'Mix', default: 1 }];
// One slot per job and per channel: a slot keeps its own state between samples.
static dsp = {
wobble: lfo(),
glide: smooth(),
filterL: svf(),
filterR: svf(),
compL: compress(),
compR: compress(),
};
process(frame: AudioFrame<Params>) {
const mod = frame.dsp.wobble('1/4', 'tri'); // -1..1, one cycle per beat
const cutoff = frame.dsp.glide(300 + 1500 * (mod + 1), 0.01);
const l = frame.dsp.compL(frame.dsp.filterL(frame.inL, cutoff, 0.9, 'lp'), -18, 3, 0.005, 0.12);
const r = frame.dsp.compR(frame.dsp.filterR(frame.inR, cutoff, 0.9, 'lp'), -18, 3, 0.005, 0.12);
frame.outL = dryWet(frame.inL, l, frame.getParam('mix'));
frame.outR = dryWet(frame.inR, r, frame.getParam('mix'));
}
render(api: PluginAPI<Params>) {
return <div />;
}
}| Factory | Slot call (name the slot anything) | What it is |
|---|---|---|
adsr() | env(gate, attack, decay, sustain, release) | An ADSR envelope from 0 to 1; gate is 1 while the note is held, and 0 starts the release. |
compress() | comp(input, thresholdDb, ratio, attackSec, releaseSec) | A compressor. compress.detect() takes the same arguments and returns only the gain reduction, so a sidechain key can duck another signal. |
limit() | lim(input, ceilingDb, attackSec, releaseSec) | A brickwall limiter. |
gateProcess() | gate(input, thresholdDb, attackSec, releaseSec) | A noise gate. |
meter() | lvl(input, windowSec) | An RMS level. |
svf() | filt(input, freq, q, type) | A state-variable filter. type is 'lp', 'hp', 'bp', 'notch', 'peak' or 'allpass'. |
ladder() | moog(input, freq, resonance, saturation) | A four-pole ladder filter. |
biquad() | eq(input, freq, q, type, gainDb?) | A biquad. type is 'lowpass', 'highpass', 'bandpass', 'notch', 'peak', 'lowshelf' or 'highshelf'; peaks and shelves take gainDb. |
onepoleLp(), onepoleHp() | lp(input, coefficient) | One-pole filters, for gentle tone and smoothing. |
crossover() | xover(input, freq) | Splits a signal at freq and returns { low, high }; the two bands sum to the input. The editor's types still give it a number, so it underlines .low and .high; the plugin builds and runs regardless. |
smooth() | sm(target, rampTimeSec) | Glides toward a target value. |
ballistics() | bal(input, attackMs, releaseMs) | A meter-style level follower, with its times in milliseconds. |
envelopeFollower() | env(input, attackCoeff, releaseCoeff) | Follows a signal's level, with its attack and release as coefficients rather than times. |
lfo() | wobble('1/8', 'tri') or trem(5.0, 'sine') | An LFO from -1 to 1: a division ('1/8', '1/4d', '1/16t'…) locks it to the tempo, a number runs it free in Hz. Shapes: 'sine', 'tri', 'saw', 'square'. |
random() | rng() | A random number from 0 up to 1. |
convolver(length) | cab(input) | Convolves with an impulse response the window loads into <slot>_ir (see Assets). Every sample costs the whole length, so keep it near 256 samples. |
fft(size) | spec(input) | A spectrum for a display, read in the window as <slot>_mag. fft.process() lets you change the spectrum itself. |
capture(seconds) | rec(input, gate) | Records while gate is on, until the time you declared is full, and returns the seconds recorded. The window can draw the take from <slot>_buf. |
varispeed('rec') | a(rate, gate?) | Loops what a capture slot recorded at any rate: 1 as recorded, 0.5 an octave down, negative backwards. Any number can read one capture. |
The pure functions keep no state. Import them from @the-plug/dsp and call them in process(): lerp, cubic_interp, softclip, hardclip, fold, waveshape, dryWet, pan, gainToDb, dbToGain, flushDenormal, clamp, rsqrt, fmod, gain_computer, and the oscillators sine, saw, square and triangle, which take a phase from 0 to 1.
Audio-thread state
The audio thread and the window share no variables. What has to pass between them goes in static dspState: named Float32Arrays that the audio thread reads and writes as frame.dspState.name, and the window reads with this.getAudioState('name') and writes with this.setAudioState('name', data). A meter, a playhead and a drawn curve all travel this way.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
type Params = { gain: number };
type State = { level: number };
export default class Meter extends EffectPlugin<Params, State> {
static id = 'com.example.meter';
static pluginName = 'Meter';
static parameters = [{ id: 'gain', name: 'Gain', default: 1 }];
static dspState = { peak: new Float32Array(1) };
state: State = { level: 0 };
process(frame: AudioFrame<Params>) {
frame.outL = frame.inL * frame.getParam('gain');
frame.outR = frame.inR * frame.getParam('gain');
const now = Math.max(Math.abs(frame.outL), Math.abs(frame.outR));
const held = frame.readDspState('peak', 0) * 0.9995; // fall back slowly
frame.writeDspState('peak', 0, Math.max(now, held));
}
init(api: PluginAPI<Params>) {
// Twenty times a second, copy the level into the editor's state, which redraws it.
setInterval(() => this.setState({ level: this.getAudioState('peak')[0] }), 50);
}
render(api: PluginAPI<Params>) {
return (
<div style={{ width: 160, height: 8, background: '#222' }}>
<div style={{ width: Math.min(1, this.state.level) * 160, height: 8, background: '#3ddc84' }} />
</div>
);
}
}this.state belongs to the window, and the build refuses it in process(). Values the audio thread keeps between samples go in static dspState or in a plain field of the plugin, such as phase = 0.
MIDI
frame.midiCount events land on this sample; read each with frame.getMidiEvent(i). An event has type (0x90 note on, 0x80 note off, 0xb0 a controller), note, velocity and channel, plus status, data1 and data2 as raw bytes. A note on with velocity 0 is a note off.
import { SynthPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
import { sine } from '@the-plug/dsp';
type Params = { level: number };
export default class SineVoice extends SynthPlugin<Params> {
static id = 'com.example.sine-voice';
static pluginName = 'Sine Voice';
static category = 'Instrument';
static parameters = [{ id: 'level', name: 'Level', default: 0.5 }];
freq = 0;
amp = 0;
phase = 0;
vibrato = 0;
process(frame: AudioFrame<Params>) {
for (let i = 0; i < frame.midiCount; i++) {
const e = frame.getMidiEvent(i);
if (e.type === 0x90 && e.velocity > 0) {
this.freq = 440 * Math.pow(2, (e.note - 69) / 12);
this.amp = e.velocity / 127;
} else if (e.type === 0x80 || e.type === 0x90) {
this.amp = 0;
} else if (e.type === 0xb0 && e.data1 === 1) {
this.vibrato = e.data2 / 127; // the mod wheel
}
}
const wobble = 1 + 0.01 * this.vibrato * Math.sin(2 * Math.PI * 5 * frame.currentTimeSec);
this.phase = (this.phase + (this.freq * wobble) / frame.sampleRate) % 1;
const out = sine(this.phase) * this.amp * frame.getParam('level');
frame.outL = out;
frame.outR = out;
}
render(api: PluginAPI<Params>) {
return <div />;
}
} To send MIDI, use frame.noteOn(channel, note, velocity), frame.noteOff(channel, note), frame.cc(…) or frame.sendMidi(status, data1, data2). A block-processing synth gets the block's events in its midi argument, each with its sampleOffset inside the block. Both event shapes, FrameMidiEvent and MidiEvent, are in the type reference.
Sidechain and aux buses
Declare extra inputs in static auxInputs, and read them as frame.aux.<bus>.inL and inR. Typing the frame as EffectFrame<Params, AuxIn> checks the bus names.
A bus's channels is 1, 2 or a layout name such as '5.1'. Read a wider bus with frame.aux.<bus>.getInput(ch), in its layout's canonical order. Its numChannels is how many channels are routed to it this block, never more than it declares and 0 while nothing is, and a channel past that reads 0.
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 />;
}
} Extra outputs work the same way: declare them, then write frame.auxOut.<bus>.outL and outR, or setOutput(ch, value) for each channel of a wider one. The browser preview does not play aux outputs yet; a built plugin does.
Transport and timing
The audio thread reads the host's transport from the frame (see Timing), and the window reads the same facts from this.daw, which is kept up to date for you.
import { EffectPlugin } from '@the-plug/core';
import type { AudioFrame, PluginAPI } from '@the-plug/core';
type Params = { mix: number };
export default class Beat extends EffectPlugin<Params> {
static id = 'com.example.beat';
static pluginName = 'Beat';
static parameters = [{ id: 'mix', name: 'Mix', default: 1 }];
process(frame: AudioFrame<Params>) {
// In process(), the same facts are on the frame: frame.tempo, frame.ppq, frame.isPlaying.
frame.outL = frame.inL;
frame.outR = frame.inR;
}
// In the editor, this.daw holds the host's transport, refreshed for you.
render(api: PluginAPI<Params>) {
const beat = Math.floor(this.daw.beatPosition) + 1;
return (
<div>
{this.daw.isPlaying ? 'Playing' : 'Stopped'} at {Math.round(this.daw.tempo)} BPM, beat {beat} of {this.daw.timeSigNumerator}
</div>
);
}
}this.daw.phase() defaults to a quarter note, while frame.phase() defaults to a whole bar, so pass the division you mean to both. Both take the same ten divisions.