Claudio Pietronik

The language reference

266 entries, exported from the build: the signatures come from the standard library's source, so a function cannot be documented as something it is not.

Basics

The language

abit-code is a small C-like language that runs ONCE PER SAMPLE, PER VOICE. Read the inputs, write the outputs. It is procedural, NOT object-oriented.

in1..in4 / out1..out4

Read the four inputs, write the four outputs. An output you don't write passes its input through.

out1 = in1 * 0.5;   // half volume
out2 = in2;
float x = ...;

A per-sample local variable. It resets every sample.

float y = in1 + in2;
out1 = y * 0.5;
state float z = 0;

A variable that PERSISTS across samples - the basis of every filter, oscillator, counter, anything with memory. The initializer must be a constant.

state float ph = 0;               // a phase
ph += 220 / sr; if (ph >= 1) ph -= 1;
out1 = sin(2 * pi * ph);
array a[N];

An ARRAY of N floats (N a constant). Arrays always PERSIST across samples (they live in the state memory, max 512 slots total) - use them for SMALL control data: notes, patterns, coefficients. Use a[i]; a[i] += x works too; the index is clamped to 0..N-1. (The older `state float a[N];` form is still accepted.) For thousands of samples use `buffer`.

array notes[3];
notes[0] = 48; notes[1] = 55; notes[2] = 60;
out1 = notes[2];
buffer b[N];

A LARGE indexable sample store (N a constant, up to 96000 samples shared with the delay lines). Free b[i] read/write, persistent, starts zeroed - for hand-rolled sample capture, wavetables, loopers. For a plain echo/comb prefer `delay` (it has the moving write head built in); a buffer gives you FULL control of where you read and write.

buffer wave[48000];
state float w = 0;
wave[w] = in1;                     // record
float r = w - 24000; if (r < 0) r += 48000;
out1 = wave[r];                    // play 0.5 s late
w += 1; if (w >= 48000) w = 0;
.size .lerp(pos) .wave(ph) .lookup(x) .mix(pos, v);

The INTERPOLATED accesses of an array/buffer (gen~'s dim/sample/wave/lookup/splat). .size = the length. .lerp(pos) reads at a FRACTIONAL position (clamped to the table). .wave(ph) treats the whole table as ONE WAVEFORM CYCLE: phase 0..1, wraps last->first - wavetable synthesis. .lookup(x) maps x in -1..1 across the table - a drawn waveshaper. .mix(pos, v); is a STATEMENT: adds v split between the two cells around pos (interpolated overdub). Raw b[i] stays the exact-index form.

array wt[64];
state float init = 0;
if (init < 1) { init = 1; for (i = 0; i < 64; i += 1) { wt[i] = sin(2 * pi * i / 64) + sin(2 * pi * 3 * i / 64) * 0.3; } }
state float ph = 0;
ph += 110 / sr; ph = fract(ph);
out1 = wt.wave(ph) * 0.4;
delay d(N); d.write(x); d.read(t);

A delay line. N = a CONSTANT number of samples. Write the signal, then read `t` samples ago (t may be fractional = interpolated).

delay d(24000);                   // 0.5 s at 48k
d.write(in1);
out1 = in1 + d.read(12000) * 0.4;
param name = def [lo, hi];

Declares a MACRO INPUT. Reading `name` in the code gives a value ALREADY in [lo, hi] - so `param cutoff = 800 [80, 15000]` lets you use `cutoff` DIRECTLY as Hz, no scaling. The 0..1 lives only on the CABLE: the Nth `param` = channel N of the node's PARAMS input, where 0..1 spans [lo, hi] (merge control sources into a poly cable with Merge/Poly and feed PARAMS). To sweep the full range with a bipolar source (an LFO is -1..1), offset it: e.g. lfo(2)*0.5+0.5. Unpatched, `name` is its default `def`. [lo, hi] is optional (defaults to [0, 1]).

param cutoff = 800 [50, 12000];
import filter;
out1 = svf_lp(in1, cutoff, 0.5);
struct Voice { float ph; float note; }

Groups named fields into a TYPE; then `state Voice v;` is one instance and `state Voice v[8];` is a BANK of 8. Access v.ph / v[i].ph (+= works too); every field starts at 0 and persists. Compile-time only (fields live in state memory) - no methods, behaviour stays in functions. THE way to build polyphony, grain clouds and particles inside one program.

struct Voice { float ph; float note; }
state Voice v[4];
v[0].note = 45; v[1].note = 52; v[2].note = 57; v[3].note = 60;
float mix = 0;
for (i = 0; i < 4; i += 1) {
  v[i].ph += midi2freq(v[i].note) / sr;
  if (v[i].ph >= 1) v[i].ph -= 1;
  mix += sin(2 * pi * v[i].ph);
}
out1 = mix * 0.2;
if (cond) { } else { }

Conditionals. Compare with < > <= >= == != ; combine with && || ! .

if (in2 > 0.5) out1 = in1;
else out1 = 0;
for (i = 0; i < N; i += 1) { }

A loop. Keep N a small constant - the whole program runs every sample.

float sum = 0;
for (i = 0; i < 4; i += 1) sum += saw(110 * (i + 1));
out1 = sum * 0.25;   // needs: import osc;
float f(float a){ return ..; }

Define your own function and call it f(x). It can be defined ANYWHERE - before or after the call site (definitions are hoisted). Inlined at compile time (no recursion). A body is ISOLATED: it keeps its OWN state/arrays/buffers per call site and CANNOT see top-level variables - pass values in as parameters, and declare pattern arrays INSIDE the function.

out1 = soft(in1);
float soft(float x){ return tanh(x * 2); }
void process(){ ... }

The entry point: its body is your per-sample program. (You can also just write statements at the top level, without a process() wrapper.)

void process(){
  out1 = tanh(in1 * 1.5);
}
import osc; (and the other libraries)

Pulls in a library so its functions become callable. Call them BARE - saw(440), NOT osc.saw(440). The blocks are functions, not objects: never `state osc.block x;`, never `x.method()`.

import osc; import filter;
out1 = ladder(saw(110), 900, 0.4);
440hz 2khz 10ms 2s -6db C3 A3 F#4

Unit literals - write a value in its musical unit and the compiler converts it to a plain compile-time constant. Frequency: hz / khz. Time: ms / s -> seconds. Gain: db -> linear (so -6db = 0.5). NOTE names -> frequency in Hz, with C3 = middle C (so A3 = 440). For a pitch that ARRIVES on an input (not a fixed literal) use midi2freq(x) or pitch2freq(x).

import osc; import env;
out1 = saw(A3) * -6db;
out2 = saw(C4) * adsr(in2, 10ms, 50ms, 0.7, 200ms);
// ==== SECTION: name ====

Splits the program into named SECTIONS: the editor shows each one as a collapsible CARD (fold what you're not working on), and the order top-to-bottom is the compile order. It is just a comment line - the program still compiles as one plain text. Functions may be defined in ANY section (order-free), so you can keep 'Voices', 'FX', 'Helpers' apart.

// ==== SECTION: Voices ====
import osc;
float v = supersaw(A2, 0.03);
// ==== SECTION: FX ====
import verb;
out1 = v + plate(v, 0.8, 0.4) * 0.4;
// line comment /* block */ sr, pi

Comments are ignored. Handy constants: sr = the sample rate (e.g. 48000), pi = 3.14159...

// a 1-second ramp
state float t = 0; t += 1 / sr; if (t > 1) t = 0;
out1 = t;

Core

Math builtins (always available, no import)

sin(x) cos(x) tan(x) tanh(x) exp(x) log(x) log2(x) log10(x) sqrt(x) abs(x) floor(x) ceil(x) round(x) sign(x) atan(x) asin(x) acos(x) sinh(x) cosh(x) asinh(x) acosh(x) atanh(x) exp2(x) trunc(x) fract(x) degrees(x) radians(x) pow(x,y) min(a,b) max(a,b) fmod(a,b) atan2(y,x) hypot(x,y) clamp(x,lo,hi). Out-of-domain inputs are clamped to the edge (asin(2) = asin(1)), never NaN. Random: rand() = [0,1), rand(hi) = [0,hi), rand(lo,hi) = [lo,hi). Constants: sr, pi. Each one is also a placeable BLOCK - see the Operators tab.

Prelude - always available, no import needed

phasor(freq)

The wheel every oscillator turns on: a ramp that climbs from nothing to full and snaps back, over and over, at the rate you set. Feed it to a shaper and it becomes any waveform; read a table with it and it becomes a player. Phase IS the raw material of motion, and this is phase, bare.

out1 = phasor(220) * 2 - 1;   // ramp -> saw
noise()

Every frequency at once, none of them twice: pure chance, sample by sample. Filtered it is wind and surf; sampled it is random voltages; struck through an envelope it is the snare's white burst.

out1 = noise() * 0.2;
snh(x, trig)

The camera shutter for signals: on every trigger it photographs the input and holds the picture until the next shot. Aimed at noise it is the classic random stepper; aimed at anything it freezes moments a clock chooses. Its cousins: sah carries its own clock, latch holds while a gate is open.

out1 = snh(noise(), in1);   // latch when in1 rises
slew(x, rate)

A speed limit for a value: the output chases the input but may only move so many units a second, so jumps become slopes. Glide for pitches, de-click for switches, suspension for any control that arrives in steps.

out1 = slew(in1, 5);   // max 5/sec
dcblock(x)

Recentres a signal on zero: any constant lean - from a wavefolder, an asymmetric shaper, a feedback loop gone one-sided - is gently removed while everything audible passes. Cheap insurance at the end of a chain that bends waves.

out1 = dcblock(in1);
midi2freq(m)

Note numbers into Hertz: the language the Composer and the scale tools speak, turned into the language an oscillator wants. One step is one semitone, sixty is middle C. The last block before the oscillator in nearly every melodic patch.

import osc;
out1 = saw(midi2freq(in1));   // in1 = MIDI note
freq2midi(f)

Hertz back into note numbers - the return ticket. It is how a measured frequency becomes something a scale tool can quantise: detect, convert, snap, convert back.

import conv;
out1 = freq2midi(440);   // 69
pitch2freq(v)

The modular world's pitch into Hertz: one unit is one OCTAVE, zero is middle C - the volt-per-octave convention the app's PITCH cables carry. Its sibling midi2freq is for note NUMBERS, where one unit is a semitone: feed a pitch cable to the wrong one and everything lands an octave-scale off, which is how you will know.

import osc;
out1 = saw(pitch2freq(in1));   // in1 = PITCH

Synth

Oscillators - import osc

saw(freq)

The raw shape of a synthesiser: a ramp that climbs and drops straight back, carrying every harmonic there is. It is what most bright, buzzing sounds are built from - and what a filter is usually there to tame.

import osc;
out1 = saw(110) * 0.3;
sine(freq, phase)

One frequency, alone: no harmonics, nothing to filter away. It runs two ways, and both are useful: give it a frequency and it oscillates on its own, or leave the frequency at nothing and drive its phase with a ramp, and the ramp becomes the motion. Give it both and the two speeds add, which is the short road to vibrato and FM.

import osc;
float x = sine(0, phasor(110));   // the phase drives it: 110 Hz
float y = sine(220, 0.25);        // or a frequency, phase offsets a quarter turn
out1 = (x + y) * 0.3;
square(freq, pw)

The hollow, woody tone of a pulse wave, built from the odd harmonics only. How wide the pulse is decides how hollow it sounds: even halves give the true square, and pushing it toward either end thins the tone to a reedy buzz.

import osc;
out1 = square(110, 0.5) * 0.3;
tri(freq)

Almost a sine, with just enough edge to be heard through a mix. Its harmonics fall away quickly, so it stays soft with no filter at all - the usual choice for a flute-ish voice or a clean sub.

import osc;
out1 = tri(110) * 0.3;
chirp(f0, f1, secs)

A sweep with a beginning and an end: it starts at one pitch, slides to another over the time you give it, and then holds there. Sonar pings and laser zaps, and the test signal a room is measured with.

import osc;
out1 = chirp(100, 2000, 1) * 0.3;
pulse(freq, pw)

The square wave's family, written to be driven: a rectangle whose width you move while it plays. Narrow it and the tone thins toward a nasal buzz; sweep the width slowly and you have the shimmer every string patch leans on.

import osc;
out1 = pulse(110, 0.25) * 0.3;
supersaw(freq, detune)

Seven sawtooths at once, spread slightly apart in pitch - the sound of a trance lead in one block. The spread IS the instrument: barely open it thickens a single note, wide open it drifts and beats against itself.

import osc;
out1 = supersaw(110, 0.03) * 0.2;
fm2(freq, ratio, index)

Two oscillators, one bending the other's pitch thousands of times a second: the sound of an FM synth, all bells, basses and electric pianos. The ratio between them decides whether the result rings harmonic or clangorous, and the depth decides how far it goes - none at all is a plain sine, plenty is metal.

import osc;
out1 = fm2(110, 2, 5) * 0.3;
pd(freq, amount)

Phase distortion: a sine whose phase is squeezed as it turns, so the wave leans toward a sawtooth or grows a resonant peak with no filter involved. The trick Casio built the CZ synths on, and here it is one control.

import osc;
out1 = pd(110, 0.6) * 0.3;
hardsync(freq, syncf)

One oscillator restarted by another, over and over: the wave never gets to finish, and the tear that leaves is the sound. Sweep its own pitch against the one resetting it and you get the screaming lead no filter can make.

import osc;
out1 = hardsync(110, 260) * 0.3;
trishape(ph, duty)

A shaper rather than an oscillator: feed it a phase and it hands back a triangle, with the peak wherever you put it. Centred it is a symmetric triangle; pushed to one end it becomes a rising ramp, to the other a falling one - one control that travels the whole way from triangle to sawtooth.

import osc; import util;
out1 = trishape(phasor(110), 0.2 + lerp(0, 0.6, in1));
rate(ph, mul)

A gearbox for a phase: it follows the ramp you feed it but runs at a fraction or a multiple of its speed, staying locked to the original's turns. This is how one clock drives something at half or double time without ever drifting away from it.

import osc;
float ph = phasor(2);
out1 = rate(ph, 0.5);   // half-speed ramp, locked
triphase(ph, duty)

Bends a phase into a triangle that still runs from nothing to full, so it can drive anything a plain ramp could. Where you put the peak decides whether it rises slowly and falls fast, or the other way about.

import osc;
out1 = (triphase(phasor(220), 0.5) * 2 - 1) * 0.3;   // triangle
phasewrap(x)

Folds an angle back into a single turn. Phase and FM arithmetic accumulate without limit and eventually lose their precision; wrapping keeps the number small while the sound stays exactly the same.

import osc;
state float ph = 0;
ph = phasewrap(ph + 220 * 2 * pi / sr);
out1 = sin(ph) * 0.3;

Physical models - import phys

impulse(trig)

A rising edge becomes the sharpest sound there is: one sample, full height, gone. The hammer of the physical models - a perfect click carries every frequency, which is exactly what you want to strike a resonator with.

import phys;
out1 = impulse(in1);
pluck(freq, trig)

A string, plucked: a burst of noise trapped in a tuned loop, losing its brightness the way a real string does. Karplus and Strong found a whole guitar in four lines of DSP; here it is as one block, retuned per note.

import phys;
out1 = pluck(220, in1);   // in1 = trigger
reson(x, freq, decay)

A single resonance: strike it, it rings at its pitch and dies away. It is the body every excitation is looking for - one is a tuned tom, a few in parallel are a marimba bar, a bank of them is modal synthesis.

import phys;
out1 = reson(in1, 440, 0.99);
bell(trig, freq, decay)

Metal, struck: a clutch of partials deliberately OUT of tune with each other, because that inharmonic argument is what ears call a bell. Long decays gong, short ones chime.

import phys;
out1 = bell(in1, 800, 0.995);   // in1 = trig

Granular - import gran

gran(x, pitch, grainms)

Pitch-shift by scissors and glue: the signal is chopped into little grains, each replayed faster or slower, the seams crossfaded. The grain size is the character knob - short grains track cleanly, long ones smear into texture.

import gran;
out1 = gran(in1, 2, 80);   // up an octave
shimmer(x, pitch, fb)

The cathedral trick: what comes back from the feedback loop comes back an octave up, so every repeat climbs. A pad in, a sky out - the sound Eno and Lanois built a decade on.

import gran;
out1 = shimmer(in1, 2, 0.6);

Filter

Filters - import filter

onepole(x, cutoff)

The gentlest low-pass there is: one pole, no resonance, six decibels an octave. Too soft to be a voice's filter and perfect for everything else - smoothing a control, taking the fizz off a signal, keeping a feedback loop from getting brighter every time round.

import filter;
out1 = onepole(in1, 800);
svf_lp(x, cutoff, q)

The everyday low-pass: it lets the low end through and rolls the top away, with a resonant peak at the corner you can lean on. Open the corner as a note plays and you have the sound the synthesiser is famous for.

import filter;
out1 = svf_lp(in1, 1200, 3);
svf_hp(x, cutoff, q)

The same filter looking the other way: the top passes and the low end goes. Its everyday job is cleaning - lifting rumble out of a mix, thinning a pad so the bass has room - and, wound up, it sings at the corner like its twin.

import filter;
out1 = svf_hp(in1, 400, 2);
svf_bp(x, cutoff, q)

Keeps a band around the corner and lets everything else fall away, so the corner frequency becomes a pitch you can hear. Sweep it over noise for wind and waves; ring it hard for a bell.

import filter;
out1 = svf_bp(in1, 900, 6);
ladder(x, cutoff, res)

The Moog cascade: four poles instead of two, so it falls away twice as fast, and a resonance that thickens the sound before it whistles. Push the resonance to the end and it oscillates on its own - a sine you can play.

import filter;
out1 = ladder(in1, 900, 0.4);
polezero(x, b0, b1, b2, a1, a2)

The raw-coefficient filter: two zeros (b0 b1 b2), two poles (a1 a2), direct form 1, output clamped +-100 against blow-ups. The door for filters carried in from the papers.

import filter;
out1 = polezero(in1, 0.2, 0.4, 0.2, -0.6, 0.2);

Drive / distortion - import drive

softclip(x, drive)

Saturation with no corners: as the signal gets louder the curve leans over and the peaks round off instead of snapping. It is the warm end of distortion - drive it gently for glue, hard for a fuzz that never crackles.

import drive;
out1 = softclip(in1, 5);
wavefold(x, amt)

Instead of flattening a peak that goes too far, it folds it back on itself, again and again. Harmonics appear that were never in the sound, and they move as the signal moves - the west-coast noise every Buchla patch leans on.

import drive;
out1 = wavefold(in1, 3);
bitcrush(x, bits)

Throws away resolution: the signal is rounded to a coarse ladder of levels, and the error you hear is the grit. A little is old sampler, a lot is broken toy - and paired with a rate reducer it is the whole lo-fi sound.

import drive;
out1 = bitcrush(in1, 6);
decimate(x, factor)

Sample-rate REDUCER: holds each value for `factor` samples. With bitcrush (which crushes bits) it is the whole lo-fi pair.

import drive;
out1 = decimate(in1, 12);   // ~4 kHz grit at 48k

Env+Mod

Envelopes - import env

slope(trig, rise, fall, curve, out eoc)

The function generator of the Maths and Buchla 281 tradition: a trigger starts a rise, the rise tips over into a fall, and one control bends both curves from logarithmic through straight to exponential. Its second output ticks once when the fall lands - feed that tick back into the trigger and the envelope chases its own tail, which is the whole trick the 281 is famous for: the same block is an envelope, an LFO, or anything between.

import env; import osc;
float eoc = 0;
out1 = sine(220) * slope(in1, 5ms, 400ms, 0.5, eoc);
out2 = eoc;
ar(gate, atk, rel)

The simplest envelope there is: while the gate is open it climbs, when the gate closes it falls away. Two times, nothing else - which is exactly what a pluck, a hat or a sidechain duck needs, and why it ends up in every patch.

import env;
out1 = in1 * ar(in2, 0.01, 0.2);   // in2 = gate
adsr(gate, a, d, s, r)

The classic four-stage envelope every synthesiser taught: a strike up, a fall to a held level, the hold for as long as the gate stays open, and a tail when it lets go. The held level is a LEVEL, not a time - the one thing about an ADSR everyone forgets once.

import env;
out1 = in1 * adsr(in2, 0.01, 0.1, 0.7, 0.3);

Modulators / LFOs - import mod

lfo(rate, shape)

An oscillator meant to be felt, not heard: a slow wave that swings between minus one and one, for wobbling whatever you wire it into - a cutoff, a pitch, a level. It carries five shapes in one block, from smooth sine to stepped random, so trying another movement is a number and not a rebuild.

import mod;
out1 = in1 * (0.5 + 0.5 * lfo(4, 0));   // tremolo
envfollow(x, atk, rel)

Listens to how LOUD a signal is and hands that loudness back as a slow control signal. It is how audio gets to drive things: a kick opening a filter, a voice ducking a pad - any place the music itself should turn the knob.

import mod;
out1 = envfollow(in1, 0.01, 0.1);
sah(x, rate)

Sample and hold with its own clock built in: so many times a second it looks at the input, grabs the value, and holds it until the next look. Aimed at noise it is the classic stepped-random voltage. Its cousins: snh grabs on an incoming trigger, latch tracks while a gate is open.

import mod;
out1 = sah(noise(), 8);
glide(x, time)

Portamento: the value never jumps, it slides. Put it after a pitch and every new note bends in from the last one; put it after any control and the moves become fingers on a real knob instead of switch flicks.

import mod;
out1 = glide(in1, 0.1);
randlfo(rate, smooth)

A random wander instead of a repeating wave: it drifts to a new place at its own rate, smoothed as much as you ask, from stepped jumps to a slow breathing drift. The movement that keeps a patch from sounding like a machine.

import mod;
out1 = randlfo(3, 0.5);
latch(x, gate)

Track and hold: while the gate is open the signal passes straight through, and the moment it closes the last value freezes and stays. The freeze-frame of signals. Its edge-triggered cousin is snh, which grabs on a trigger instead.

import mod;
out1 = latch(in1, in2);   // in2 nonzero = track, 0 = hold
slide(x, up, dn)

A smoother with two speeds: one for the way up, one for the way down. That asymmetry is the useful part - an instant rise with a slow fall is an envelope follower's decay, and a slow rise with an instant drop softens only the attacks.

import mod;
out1 = slide(abs(in1), 0.001, 0.2);   // fast up, slow down

FX

Effects - import fx

comb(x, dt, fb)

A delay short enough that you stop hearing an echo and start hearing a pitch: the repeats reinforce some frequencies and cancel others, and the notches that leaves are the comb it is named after. Short and fed back it rings like a plucked string; longer it is the body of a reverb.

import fx;
out1 = comb(in1, 300, 0.7);
allpass(x, dt, g)

Lets every frequency through at the same loudness but delays some more than others, so the sound is smeared without being coloured. On its own it is almost inaudible; several in a row are what turns a bank of echoes into the smooth wash of a reverb.

import fx;
out1 = allpass(in1, 220, 0.6);
delayfx(x, dt, fb)

The echo: the signal comes back later, and part of what comes back goes round again. Short repeats thicken a sound, long ones answer it, and turning the feedback up near the top gives a tail that hangs for a very long time.

import fx;
out1 = delayfx(in1, 12000, 0.4);   // ~0.25 s
delayline(x, ms)

A delay with nothing else in it: the signal comes out later, and that is all. Its length can be moved every single sample and the tap slides smoothly between them, which is what makes chorus, doppler and tape wobble possible by hand. Nothing is fed back inside - you close that loop yourself with a delayed cable, and then the sound is yours rather than the block's.

import fx; import osc;
out1 = (in1 + delayline(in1, 8 + sine(0.4) * 6)) * 0.6;   // hand-made chorus
freqshift(x, hz)

Moves every partial by the SAME number of Hertz, rather than by the same ratio - so the harmonic ladder of a sound stops being a ladder and it turns into a bell. Small shifts on a feedback loop keep it from ringing on one note; large ones are the barberpole that seems to rise forever. Harald Bode's box, if you want the history.

import fx; import osc;
out1 = freqshift(sine(220), 7);   // slow inharmonic beating
chorus(x, rate, depth)

A copy of the signal, delayed by a few milliseconds and wobbling slowly against the original: two players, never quite in tune, never quite together. It widens anything thin, and it arrives here as a stereo pair, so the two sides drift apart on their own.

import fx;
out1 = chorus(in1, 0.6, 0.5);
flanger(x, rate, depth, fb)

The same wobbling copy as a chorus, but close enough to interfere: the cancellation sweeps up and down the spectrum and you hear a jet going over. Feeding it back sharpens the swoosh into a metallic whistle.

import fx;
out1 = flanger(in1, 0.3, 0.7, 0.5);
phaser(x, rate, depth)

Notches that move: a stack of allpasses shifts part of the sound out of step with itself, and where the two cancel a hole travels through the spectrum. It is the flanger's smoother cousin - swirl rather than jet.

import fx;
out1 = phaser(in1, 0.4, 0.7);
tremolo(x, rate, depth)

The volume, going up and down. Slow it breathes, fast it flutters, and past a certain speed it stops being a wobble and starts adding sidebands of its own. The oldest effect on the list, and still the one nothing replaces.

import fx;
out1 = tremolo(in1, 5, 0.6);
reverb(x, decay)

A room, made of echoes dense enough to stop being echoes. It hands back the WET signal only, so you decide how much of it sits behind the dry - and if you want a good room rather than a quick one, the Reverbs collection has plate and hall built properly.

import fx;
out1 = reverb(in1, 0.7);
chorusL(x, rate, depth)

The LEFT half of the stereo chorus. You do not place these: dropping `chorus` in Forge gives one block with two outputs that calls this pair, decorrelated (the R half runs half a cycle later, on a longer base delay). Callable in a Code box.

chorusR(x, rate, depth)

The RIGHT half of the stereo chorus - see chorusL.

reverbL(x, decay)

The LEFT half of the stereo reverb: four combs on one set of primes. The R half uses different ones, so the two tails are decorrelated. For ONE shared stereo network (the sides feeding each other) use verb's plate_st instead.

reverbR(x, decay)

The RIGHT half of the stereo reverb - see reverbL.

Reverbs - import verb

vap(x, dt, g)

A building brick of the plate's diffusion, exposed for the curious: one of the allpasses it is made of. You would normally reach for the plate itself.

import verb;
out1 = vap(in1, 512, 0.7);
plate(x, decay, damp)

The studio classic that never was a room: a sheet of steel ringing, dense from the first instant, smooth all the way down. It hands back the WET signal only, so you decide how far behind the dry it sits - and how dark it gets as it fades is its second personality control.

import verb;
out1 = plate(in1, 0.8, 0.4);
plate_st(x, decay, damp, out r)

A TRUE stereo plate: one reverb network with two outputs, its delay lines cross-mixed every sample so each side is fed by the other. That crossing is what makes a FIELD rather than two mono tails that happen to match - drop it once and wire both pins.

import verb;
float r = 0;
out1 = plate_st(in1, 0.85, 0.35, r);
out2 = r;   // one network, both sides
room(x, size, damp)

A room instead of a plate: early reflections you can almost see the walls in, then a tail. Size takes it from a cupboard to a hall; the damping is the furniture. Wet only, like the others - the dry stays yours.

import verb;
out1 = room(in1, 0.5, 0.3);

EQ - import eq

peakeq(x, freq, q, gainDb)

A bell on the spectrum: pick a spot, decide how wide, then raise or lower it. This is the surgical tool of mixing - find the resonance that annoys and pull it down, find the body that is missing and lift it in.

import eq;
out1 = peakeq(in1, 1000, 2, 6);   // +6 dB @ 1k
lowshelf(x, freq, gainDb)

Everything below the corner rises or falls together, like the bass knob on an amplifier. Gentler than a filter: the lows are turned, not removed.

import eq;
out1 = lowshelf(in1, 200, 4);
highshelf(x, freq, gainDb)

Everything above the corner rises or falls together - the treble knob. A few decibels up is 'air', a few down takes the edge off a harsh source.

import eq;
out1 = highshelf(in1, 4000, -3);
notch(x, freq, q)

The opposite of a bell: a narrow cut that removes one frequency and leaves the neighbours alone. Hum, whistle, a resonant sting - things you delete rather than turn down.

import eq;
out1 = notch(in1, 60, 8);   // kill 60 Hz
bandlow(x, hz)

The crossover's LOW half at `hz` (2-pole). Its twin bandhigh is EXACTLY the rest: bandlow + bandhigh = the input, sample for sample.

import eq; import drive;
out1 = softclip(bandlow(in1, 300), 3) + bandhigh(in1, 300);   // drive the lows only
bandhigh(x, hz)

The crossover's HIGH half at `hz` - the exact complement of bandlow. Two blocks = two bands; four = three bands.

import eq;
out1 = bandhigh(in1, 2000) * 0.5;   // just the air

Dynamics - import dyn

denv(x, atk, rel)

The ear the dynamics blocks share: a peak follower, exposed for the curious. You would normally reach for the compressor, gate or limiter built on it.

import dyn;
out1 = denv(in1, 0.01, 0.1);   // envelope
compressor(x, thresh, ratio, atk, rel)

Turns the loud parts down so the whole thing can come up: past the threshold, every extra decibel in becomes a fraction of a decibel out. Slow attack keeps the punch, fast attack tames it - the attack IS the sound of a compressor.

import dyn;
out1 = compressor(in1, -18, 4, 0.01, 0.1);
limiter(x, ceiling)

The wall: nothing gets past the ceiling, however hard it is hit. On a master it is safety; pushed hard on purpose it is a sound of its own - the pumping flatness every loud record wears.

import dyn;
out1 = limiter(in1, 0.9);
gate(x, thresh, atk, rel)

Silence, unless the signal earns its way through: below the threshold the output is closed, above it it opens. It cleans bleed and hiss between notes - and gated against a rhythm it becomes the chopped-pad trick.

import dyn;
out1 = gate(in1, 0.05, 0.005, 0.1);
expander(x, thresh, ratio, atk, rel)

The gate's diplomatic cousin: instead of slamming shut below the threshold, it turns the quiet parts down by a ratio. Breath, room and hum recede without the on/off flutter a hard gate leaves on soft material.

import dyn;
out1 = expander(in1, -40, 3, 0.01, 0.1);

Seq+Rnd

Sequencing - import seq

clockdiv(trig, n)

The clock divider: it lets one tick through and swallows the rest, so a fast clock becomes a slower one that stays perfectly in step with it. Half notes from quarters, a kick every fourth hat - one block per division.

import seq;
out1 = clockdiv(in1, 4);   // in1 = clock
euclid(trig, steps, pulses)

The rhythm you DECLARE instead of draw: say how many hits and how many steps, and they spread as evenly as the circle allows - which happens to be how half the world's rhythms are built. Advanced by whatever clock you feed it, so it locks to anything.

import seq;
out1 = euclid(in1, 8, 5);   // 5 hits / 8
counter(trig, reset, lo, hi)

Counts whole numbers, one per rising edge of `trig`: it starts at `lo`, climbs to `hi`, and the next edge takes it back to `lo`. A trigger on `reset` sends it home at once - which is how two counters are kept in step. It gives the NUMBER itself, not a ramp, so it can address a table or pick a note straight away. Type the range the way you think of it; if `lo` is above `hi` it counts the span between them all the same.

import seq; import trig;
out1 = counter(in1, metro(0.5), 1, 8);   // 1..8, home every 2 s
trig2gate(trig, len)

Stretches a click into a held note: the trigger opens a gate, the gate stays open for the time you give it, then closes on its own. The bridge between the world of ticks and the world of envelopes.

import seq;
out1 = trig2gate(in1, 0.1);
walk(trig, len, mode, reset)

A sequencer's footsteps: on every tick it moves one place along a row and hands you the place it stands on - forward, backward, bouncing off the ends, or at random, one mode number away. It gives the INDEX itself, ready to address a table or pick a note; this is the counter grown up, for when forward-only is not enough.

import seq; import trig; import osc;
array notes[4];
notes[0] = 48; notes[1] = 55; notes[2] = 60; notes[3] = 67;
float step = walk(metro(6), 4, 2, 0);   // 2 = pendulum
out1 = saw(midi2freq(notes[step])) * 0.3;
clockperiod(trig)

A stopwatch on someone else's clock: it measures the time between the last two ticks it was fed and keeps saying it. That number is how a patch derives times FROM a clock - an echo that follows the tempo, an envelope that fills exactly one beat. Half a second until it has heard two ticks.

import seq; import trig;
float clk = metro(2);
out1 = clockperiod(clk);   // 0.5
metromul(trig, beats, swing, shift)

The clock multiplier: feed it a beat and ONE number turns it into any figure - halves, eighths, triplets, dotted notes - because the same number both multiplies and divides, so nothing musical is a special case. It can swing the off-steps and slide the whole grid, and it stays silent until the clock actually ticks. Figures faster than the beat are predicted from the last one measured: exact on a steady clock, a beat behind through a tempo ramp - the way every clock multiplier behaves.

import seq; import trig; import phys;
float clk = metro(2);          // the beat
out1 = pluck(A3, metromul(clk, 1.0/3, 0, 0)) * 0.4;   // eighth triplets of it

Clocks / triggers - import trig

metro(hz)

The heartbeat: a clock that runs by itself and ticks so many times a second, no input needed. Nearly every generative patch starts here - one metro, and everything downstream has a sense of time.

import trig;
out1 = metro(4);   // 4 ticks/sec
clockgate(hz, width)

A clock that holds instead of ticking: each cycle it is ON for the part you choose and off for the rest. Where metro pokes an envelope, this one holds it open - a pulse-width for events.

import trig;
out1 = clockgate(2, 0.5);
burst(trig, count, rate)

One trigger in, a machine-gun out: a fixed count of ticks at their own rate, then silence until the next trigger. The ratchet, the drum roll, the stutter - fired from a single hit.

import trig;
out1 = burst(in1, 4, 20);   // ratchet
toggle(trig)

The light switch: every trigger flips it, on stays on until the next one. It turns momentary things into lasting ones - a button into a mute, a beat into an every-other-beat.

import trig;
out1 = toggle(in1);

Random - import rnd

dust(density)

Rain on a tin roof: random clicks scattered in time, averaging out to the density you ask for but never falling in a pattern. Triggers without a grid - the anti-metro, and grains and crackle by the handful.

import rnd;
out1 = dust(10);   // 10 clicks/sec
prob(trig, p)

The coin toss: every trigger that arrives either gets through or it doesn't, at the odds you set. Feed it a steady clock and out comes a broken one - which is the fastest way to make a rhythm human.

import rnd;
out1 = prob(dust(20), 0.6);   // a broken random clock
drunk(step)

The drunkard's walk: every step is small and random, so the value wanders instead of jumping, and the walls keep it in the room. Aim it at a pitch or a cutoff for movement that noodles rather than teleports.

import rnd;
out1 = drunk(0.02);
chaos(rate)

Not random, not periodic: a tiny equation folded on itself until it never repeats. It hovers around patterns, almost settles, escapes again - movement with a memory, where true noise has none.

import rnd;
out1 = chaos(8);
randh(rate)

A new random value held flat until the next one: the classic stepped voltage of every vintage sample-and-hold patch. Slow, it picks notes; fast, it staircases a cutoff into gritty motion.

import rnd;
out1 = randh(6);
pinknoise()

Noise with the low end restored: white noise spends its energy up high, pink spreads it evenly across the octaves, the way rooms and rain and most of nature actually sound. The gentler bed, and the honest test signal.

import rnd;
out1 = pinknoise() * 0.3;

Musical scales - import scale (indices = the app's 48-scale dictionary)

scalemask(s)

A building brick of the scale tools, exposed for the curious: the bit pattern of which pitch classes a scale contains. You would normally reach for scaleq or degree, which are built on it.

inscale(m, root, scl)

The yes-or-no of harmony: does this note belong to that scale? It answers one when it does, zero when it does not - which makes it a gate, a filter for wrong notes, or the condition an if hangs a decision on.

import scale;
out1 = inscale(64, 0, 0);   // E in C major -> 1
scaleq(m, root, scl)

The safety net: whatever note arrives, out comes the nearest one that belongs to the scale. Put it after anything reckless - a random walk, a drunk LFO, a hand on a pad - and the wrong notes simply stop existing. Ties snap downward, the same choice the Quantize module makes; the scales are the app's own dictionary, the one every scale menu shows.

import scale; import osc;
out1 = saw(midi2freq(scaleq(in1, 9, 5)));   // snap to A minor
scalelen(scl)

How many notes the scale holds in one octave - five for a pentatonic, seven for the church modes. The number you need to walk degrees without running off the end.

import scale;
out1 = scalelen(21);   // 5 (major pentatonic)
degree(root, scl, n)

The melody builder: ask for the first, third, fifth degree of a scale and get the note itself, octaves wrapping as the count climbs. Feed the count from a counter or a walk and a number series becomes a line that cannot leave the key.

import scale; import osc; import trig; import seq;
state float st = 0;
if (metro(4) > 0) st += 1;
float deg = floor(fmod(st, 8));
out1 = saw(midi2freq(degree(48, 21, deg))) * 0.3;   // pentatonic walk

Util

Utility - import util

quant(x, steps)

A smooth value becomes a ladder: however many rungs you ask for, evenly spaced. It is bitcrush for controls, steps for a glide - anywhere motion should click instead of slide.

import util;
out1 = quant(in1, 8);
semitone(p)

Snaps a pitch signal to the nearest semitone, so a bend or a wobble lands on real notes. The chromatic little brother of the scale quantizer.

import util;
out1 = semitone(in1);
scale(x, inlo, inhi, outlo, outhi)

The unit converter of patching: a value living in one range comes out living in another. An LFO's minus-one-to-one becomes a cutoff's Hertz, a fader's zero-to-one becomes anything at all - half the wires in a patch pass through one of these.

import util;
out1 = scale(in1, -1, 1, 0, 1);
lerp(a, b, t)

The straight-line blend: at zero the first value, at one the second, and a proportional mix anywhere between. The plainest way to travel between two numbers.

import util;
out1 = lerp(in1, in2, 0.5);
xfade(a, b, t)

The crossfade a MIXER would make: as one side comes up the other goes down along an equal-power curve, so the middle does not dip the way a straight blend does. For fading between two SOUNDS, this one.

import util;
out1 = xfade(in1, in2, 0.5);
wrap(x, lo, hi)

Values that leave through one wall come back through the other: the range is a loop, not a room. Phases live on it - and a melody wrapped instead of clamped folds into itself rather than parking at the edge.

import util;
out1 = wrap(in1, -1, 1);
dbgain(db)

Decibels into the multiplier they mean, so gain math can be spoken in the unit ears use: minus six is half the amplitude, minus twelve a quarter.

import util;
out1 = in1 * dbgain(-6);
select(c, a, b)

The if-else of signals: a condition picks which of two values passes, sample by sample. Every decision a patch makes eventually goes through one of these.

import util;
out1 = select(in2 > 0, in1, 0);   // gate by in2
gate2(which, x, out b)

One signal, two doors, one open: the chooser sends the input out of one side while the other holds a clean zero - never yesterday's value. Routing as a thing you can point at.

import util;
float b = 0;
out1 = gate2(in2 > 0.5, in1, b);
out2 = b;
gate4(which, x, out b, out c, out d)

The four-way switchyard: one signal in, four destinations, exactly one alive at a time and the rest silent. Drive the chooser from a counter and the signal tours your effects in turn.

import util;
float b = 0; float c = 0; float d = 0;
out1 = gate4(in2 * 3, in1, b, c, d);
out2 = b;
out3 = c;
out4 = d;
split2(x, out b)

A tee: the signal leaves through both outputs, untouched. Nothing two wires from one pin would not do - except that here the fork is a thing you can see and grab.

import util;
float b = 0;
out1 = split2(in1, b);
out2 = b;
selector4(i, a, b, c, d)

The gate turned around: four inputs, one output, and an index that says who speaks. A hand-built bank of sources, switched however fast you drive it.

import util; import osc; import mod;
out1 = selector4(floor(lfo(0.5, 2) * 2 + 2), saw(220), sine(220), tri(220), pulse(220, 0.5)) * 0.3;
selector8(i, a, b, c, d, e, f, g, h)

The eight-way version of the input picker: eight sources, one index, one voice at a time on the output.

import util; import osc;
out1 = selector8(in2 * 7, sine(220), sine(247), sine(262), sine(294), sine(330), sine(349), sine(392), sine(440)) * 0.3;
fold(x, lo, hi)

Instead of clipping at the walls, the value bounces off them - again and again if it must. This is the wavefolder's arithmetic exposed: aim a growing signal at a narrow room and harmonics bloom.

import util;
out1 = fold(in1 * 3, -1, 1);   // fold the overshoot
smoothstep(e0, e1, x)

A ramp with manners: flat below the low edge, flat above the high one, and a smooth S between - no corners for the ear to catch. The shape every soft threshold wants.

import util;
out1 = in1 * smoothstep(0.2, 0.8, in2);
cbrt(x)

Cube root, sign preserved - a gentler companion to sqrt for shaping.

import util;
out1 = cbrt(in1);   // a soft, sign-true bend
coslerp(a, b, t)

The blend with soft landings: it travels a cosine arc instead of a straight line, so it leaves and arrives without a corner. For motion that should breathe rather than snap.

import util;
out1 = coslerp(in1, in2, 0.5);
cublerp(a, b, c, d, t)

Reads BETWEEN two values the way a good sampler does: it looks at the neighbours on both sides and draws the curve through all four, so the in-between points bend naturally instead of kinking. The interpolation a wavetable read slowly deserves.

import util;
out1 = cublerp(0, in1, in2, 0, 0.5);
scalex(x, inlo, inhi, outlo, outhi, curve)

The range remapper with a bent middle: same journey as scale, plus a curve that makes the travel start slow and finish fast, or the other way round. What a volume fader or a filter sweep actually wants - straight lines rarely sound straight.

import util;
out1 = scalex(in1, 0, 1, 20, 8000, 3);   // perceptual sweep

Stereo - import pan

panL(x, pos)

The LEFT half of an equal-power pan: place a mono signal anywhere on the stage and this is what the left speaker gets. In Forge you drop `pan` once and the block arrives with both sides wired.

import pan;
out1 = panL(in1, -0.5);   // left
panR(x, pos)

The RIGHT half of the equal-power pan - see panL. Equal-power means the loudness holds steady as the sound travels: a straight-line pan dips in the middle, this one does not.

import pan;
out2 = panR(in1, -0.5);   // right
widenL(l, r, amt)

The width knob, LEFT half: the stereo image stretches past itself or narrows toward the centre, by lifting or ducking what the two sides disagree on. All the way down is mono; past one the room grows wider than the speakers.

import pan;
out1 = widenL(in1, in2, 1.5);
widenR(l, r, amt)

The width knob's RIGHT half - see widenL.

import pan;
out2 = widenR(in1, in2, 1.5);
mono(l, r)

The two sides folded into one. It is also the honest CHECK: whatever vanishes when you listen through this was built on phase tricks, and the club PA will do the same folding for you.

import pan;
out1 = mono(in1, in2);
msenc(l, r, out side)

Stereo taken apart: MID is what the two channels agree on, SIDE is what they argue about. Once apart they can be treated differently - compress the centre, brighten the edges - and put back with msdec. For plain width, widen is already one block.

import pan;
float side = 0;
out1 = msenc(in1, in2, side);
out2 = side;
msdec(mid, side, out r)

MID/SIDE back to stereo, the exact inverse of msenc: left is the return, right the second output.

import pan;
float r = 0;
out1 = msdec(in1, in2, r);   // in1 = mid, in2 = side
out2 = r;
haas(x, ms)

Width from a trick of hearing: one ear gets the sound a few thousandths of a second late, and the head reads space instead of an echo. Cheap, wide, and worth checking in mono - the trick can fold badly.

import pan;
out1 = in1;
out2 = haas(in1, 15);   // widen
haasL(x, ms)

The LEFT half of the Haas widener: the signal, untouched (the delay is all on the right).

haasR(x, ms)

The RIGHT half of the Haas widener: the signal, delayed by `ms`.

Conversions - import conv (units, dB, polar; gen~'s Convert family)

gain2db(x)

An amplitude turned back into decibels - the meter's language for the mixer's number. The inverse of dbgain, floored so silence reads as a very quiet number instead of forever.

import conv;
out1 = gain2db(abs(in1));
ms2samps(ms)

Milliseconds into samples at whatever rate the engine is running - so a time you can say out loud becomes the count a delay line wants, and it stays right when the sample rate changes.

samps2ms(n)

Samples back into milliseconds at the current rate - the return ticket, for reading a measured count as a time.

t60(secs)

Say how long a tail should last and get the per-sample factor that makes it so: multiply a feedback or an envelope state by it every sample and the sound dies away in exactly that many seconds. The reverb designer's number, handed over.

import conv;
state float env = 0;
if (in2 > 0) env = 1;
env = env * t60(0.5);
out1 = in1 * env;   // 60 dB fade in 0.5 s
t60time(g)

The same law read backwards: given a per-sample factor, how many seconds its tail lasts. For measuring a feedback loop you already have.

import conv;
out1 = t60time(0.9999);   // ~ seconds to -60 dB
cartopolr(x, y)

A point's DISTANCE from the centre - half of the cartesian-to-polar pair (cartopola is the angle). Polar is the language of orbits and spectral tricks: radius is energy, angle is phase.

import conv;
out1 = cartopolr(in1, in2);   // radius
cartopola(x, y)

A point's ANGLE around the centre, in radians - the other half of the cartesian-to-polar pair (cartopolr is the radius).

import conv;
out1 = cartopola(in1, in2);   // angle
poltocarx(r, a)

From radius-and-angle back to a flat X - half of the polar-to-cartesian pair (poltocary is the Y). The way home from orbit language.

import conv;
out1 = poltocarx(in1, in2 * pi);
poltocary(r, a)

From radius-and-angle back to a flat Y - the other half of the polar-to-cartesian pair.

import conv;
out2 = poltocary(in1, in2 * pi);

Signal tools - import sig (delta/change/accum/elapsed)

delta(x)

How much the signal moved since last sample - the slope, sample by sample. Zero means still; big means fast. It is how edges are found, and the first half of building your own phasor arithmetic.

import sig;
out1 = delta(in1) * sr / 1000;   // slope per ms
fixnan(x)

A broken number becomes 0: NaN and infinity stop here instead of infecting everything downstream. Put it INSIDE a feedback loop you are torturing.

import sig;
out1 = fixnan(in1 / in2);   // a division that cannot explode
change(x)

Only the DIRECTION of movement: rising, falling, or still, as one, minus one, zero. The signal's gesture with the size thrown away - perfect for detecting turns.

import sig;
out1 = change(in1);   // 1 rising, -1 falling
accum(x, reset)

The running total: every sample is added to everything that came before, until a reset empties the jar. Integration by the spoonful - ramps, envelopes and phasors are all an accumulator wearing clothes. It grows without limit unless you wrap or clamp it yourself.

import sig;
out1 = fract(accum(440 / sr, 0)) * 2 - 1;   // a phasor by hand
mulaccum(x, reset)

The running product: instead of adding, every sample MULTIPLIES what is stored. Fed a factor just under one it is an exponential decay with an exact length - hand it t60's number and the tail lasts precisely that long.

import sig; import conv; import trig; import osc;
out1 = sine(220) * mulaccum(t60(0.4), metro(2));   // a 0.4 s decay, retriggered
elapsed()

The voice's own age, counted in samples from the moment it started. The raw clock one-shot envelopes, fade-ins and anything once-only hang their timing on.

import sig;
out1 = (elapsed() < sr) * in1;   // only the first second

The project's CLOCK - import sync (beats, bars, tempo-locked delays and LFOs)

beatsecs()

How long one beat lasts right now, in seconds, straight from the project's tempo. The bridge between musical time and every tool that thinks in seconds.

import sync;
out1 = beatsecs();
beats2samps(beats)

Beats into samples at the project's tempo - say a musical length and get the count a delay line wants. Change the tempo and the number follows.

import sync; import fx;
out1 = delayfx(in1, beats2samps(0.5), 0.4);   // half-beat echo
samps2beats(n)

Samples back into beats at the project's tempo - for reading a measured length as music.

import sync;
out1 = samps2beats(24000);
beats2ms(beats)

Beats into milliseconds at the project's tempo - for the tools that want their time in thousandths.

import sync;
out1 = beats2ms(0.25);
beathz(beats)

The frequency of something that repeats every `beats` beats: 1 gives a cycle per beat, 4 a cycle per bar. Feed it to any oscillator or LFO to lock it to the music.

import sync; import osc;
out1 = sine(beathz(4)) * 0.3;   // one cycle per bar
beatphase()

Where we are inside the current beat, as a ramp the PROJECT drives: it climbs with the playhead and snaps back on every beat. An oscillator phase whose oscillator is the song itself.

import sync;
out1 = beatphase() * 2 - 1;
barphase()

The same ramp one level up: where we are inside the current bar. Four beats of travel, snapped back at the barline - the phase for anything that breathes once a measure.

import sync;
out1 = barphase() * 2 - 1;
divphase(div)

The beat's ramp cut into faster ones: a phase per eighth, sixteenth or triplet, still locked to the playhead. The clockwork for arps and stutters that must never drift.

import sync;
out1 = divphase(4) * 2 - 1;   // sixteenths
divtrig(div)

A trigger on every subdivision boundary - the metronome of the project rather than one of your own, so it never drifts against the music.

import sync; import env;
out1 = in1 * ar(divtrig(2), 2ms, 90ms);   // chop on eighths
synclfo(beats, shape)

An LFO that reads the playhead instead of running free: its cycle is measured in beats, so a filter sweep lands in the same place on every playthrough - automation you never had to draw. Four shapes in the second inlet.

import sync; import filter;
out1 = svf_lp(in1, 400 + 3000 * (synclfo(4, 0) * 0.5 + 0.5), 2);
syncdelay(x, beats, fb)

The delay that thinks in music: its time is a number of beats, so a dotted-eighth echo is still a dotted-eighth echo after the tempo change. About two seconds of tape at most, so long figures want slow tempos - and the feedback is the tail.

import sync;
out1 = in1 + syncdelay(in1, 0.75, 0.45) * 0.6;   // dotted eighth

Operators

Math

These are BLOCKS, for Forge: a patcher cannot draw a plus sign, so `add` IS the +. In a Code box keep writing the symbol (a + b, a > b, a && b) - it is clearer and compiles to exactly the same thing. No import: they are always in scope.

sin(x)

Sine of x, x in RADIANS (one full cycle = 2*pi).

out1 = sin(2 * pi * phasor(220)) * 0.3;
cos(x)

Cosine of x, in radians.

out1 = cos(2 * pi * phasor(220)) * 0.3;
tan(x)

Tangent of x, in radians.

out1 = tanh(tan(in1)) * 0.3;
asin(x)

Arc sine: the angle whose sine is x (x clamped to -1..1).

out1 = asin(in1) * 0.3;
acos(x)

Arc cosine: the angle whose cosine is x (x clamped to -1..1).

out1 = acos(in1) * 0.3;
atan(x)

Arc tangent of x, in radians.

out1 = atan(in1);
atan2(y, x)

The ANGLE of the point (x, y), in radians - the full-circle arc tangent.

out1 = atan2(in2, in1);
sinh(x)

Hyperbolic sine (input clamped to +/-20, so it can never blow up).

out1 = sinh(in1) * 0.2;
cosh(x)

Hyperbolic cosine (input clamped to +/-20).

out1 = cosh(in1) * 0.1;
tanh(x)

Hyperbolic tangent - the S-curve every soft clipper is built on.

out1 = tanh(in1 * 4) * 0.5;
asinh(x)

Inverse hyperbolic sine.

out1 = asinh(in1);
acosh(x)

Inverse hyperbolic cosine (x below 1 gives 0).

out1 = acosh(in1);
atanh(x)

Inverse hyperbolic tangent - steep near +/-1, and clamped so it stays finite.

out1 = atanh(in1 * 0.9) * 0.3;
exp(x)

e to the power x.

out1 = exp(0 - in1);
exp2(x)

2 to the power x - one per OCTAVE, the musical exponential.

import osc;
out1 = saw(440 * exp2(in1));
log(x)

Natural logarithm (x <= 0 gives 0).

out1 = log(abs(in1) + 1);
log2(x)

Logarithm base 2 - how many octaves x is.

out1 = log2(abs(in1) + 1);
log10(x)

Logarithm base 10 - the decibel's own log.

out1 = 20 * log10(abs(in1) + 0.00001);
pow(x, y)

x raised to the power y.

out1 = pow(abs(in1), 2) * sign(in1);
sqrt(x)

Square root (negative gives 0).

out1 = sqrt(abs(in1)) * sign(in1);
hypot(x, y)

Length of the vector (x, y) - sqrt(x*x + y*y) without overflowing.

out1 = hypot(in1, in2);
abs(x)

Distance from zero: the sign is dropped.

out1 = abs(in1);
sign(x)

1 when positive, -1 when negative, 0 at zero.

out1 = sign(in1) * 0.3;
floor(x)

Down to the whole number below.

out1 = floor(in1 * 8) / 8;
ceil(x)

Up to the whole number above.

out1 = ceil(in1 * 8) / 8;
round(x)

To the NEAREST whole number.

out1 = round(in1 * 8) / 8;
trunc(x)

Toward ZERO: 2.7 becomes 2, -2.7 becomes -2 (floor would say -3).

out1 = trunc(in1 * 8) / 8;
fract(x)

Just the fractional part, always positive: x - floor(x). A phase wrapper.

out1 = fract(in1) * 2 - 1;
clamp(x, lo, hi)

Holds x inside lo..hi - anything beyond stops at the edge.

out1 = clamp(in1, -0.5, 0.5);
degrees(x)

Radians -> degrees.

out1 = degrees(atan2(in2, in1));
radians(x)

Degrees -> radians.

out1 = sin(radians(in1 * 180));
rand(lo, hi)

A new random number every sample, between lo and hi. rand() alone gives 0..1.

out1 = rand(-1, 1) * 0.2;
add(a, b)

a + b - and on the canvas, the MIXER: drop as many cables as you like on either inlet and the block sums them all, no modifier, the Max way. The one block a filter's input usually wants in front of it. In a Code box just write a + b.

out1 = add(in1, in2);        // in code: in1 + in2
sub(a, b)

a - b (the block form of the minus sign).

out1 = sub(in1, in2);        // in code: in1 - in2
mul(a, b)

a * b (the block form of the multiply sign).

out1 = mul(in1, in2);        // ring modulation
div(a, b)

a / b. Dividing by 0 gives 0 - it can never blow up.

out1 = div(in1, 2);          // half
mod(a, b)

The remainder of a / b (fmod). By 0 gives 0.

out1 = mod(in1, 1);          // wrap into 0..1
neg(x)

Flips the sign: -x.

out1 = neg(in1);             // phase flip
absdiff(a, b)

How far apart two values are, always positive: abs(a - b).

out1 = absdiff(in1, in2);
rsub(a, b)

b - a - subtraction with the operands swapped (when the SECOND inlet carries the signal).

out1 = rsub(1, in1);         // 1 - in1
rdiv(a, b)

b / a - division with the operands swapped.

out1 = rdiv(in1, 1);         // 1 / in1
rmod(a, b)

The remainder of b / a - modulo with the operands swapped.

out1 = rmod(1, in1);

Compare

min(a, b)

The smaller of the two.

out1 = min(in1, 0.5);
max(a, b)

The larger of the two.

out1 = max(in1, 0 - 0.5);
fmod(a, b)

The remainder of a / b (by 0 gives 0).

out1 = fmod(in1, 1);
lt(a, b)

1 when a is less than b, else 0.

out1 = lt(in1, 0.5) * in2;   // pass in2 only while in1 < 0.5
gt(a, b)

1 when a is greater than b, else 0.

out1 = gt(in1, 0.5) * in2;
lte(a, b)

1 when a is less than or equal to b, else 0.

out1 = lte(in1, in2);
gte(a, b)

1 when a is greater than or equal to b, else 0.

out1 = gte(in1, in2);
eq(a, b)

1 when the two are equal, else 0.

out1 = eq(round(in1), 3);
neq(a, b)

1 when the two are different, else 0.

out1 = neq(in1, 0) * in2;    // mute when in1 is exactly 0
step(a, b)

0 while a is below b, 1 from there up - a threshold.

import env;
out1 = ar(step(in1, 0.5), 5ms, 200ms);   // a threshold becomes a gate
gtp(a, b)

Passes a through when it is greater than b, otherwise 0 (a gate that keeps the value).

out1 = gtp(in1, 0.2);        // only what is above 0.2
gtep(a, b)

Passes a through when it is greater than or equal to b, otherwise 0.

out1 = gtep(in1, 0.2);
ltp(a, b)

Passes a through when it is less than b, otherwise 0.

out1 = ltp(in1, 0 - 0.2);    // only what is below -0.2
ltep(a, b)

Passes a through when it is less than or equal to b, otherwise 0.

out1 = ltep(in1, 0);
eqp(a, b)

Passes a through when it equals b, otherwise 0.

out1 = eqp(round(in1), 3);
neqp(a, b)

Passes a through when it differs from b, otherwise 0.

out1 = neqp(in1, 0);

Logic

and(a, b)

1 when BOTH are nonzero, else 0.

out1 = and(gt(in1, 0.1), gt(in2, 0.1)) * in1;
or(a, b)

1 when EITHER is nonzero, else 0.

out1 = or(gt(in1, 0.5), gt(in2, 0.5));
not(x)

1 when x is zero, 0 when it is anything else.

out1 = not(in2) * in1;       // pass in1 only while in2 is 0
xor(a, b)

1 when exactly ONE of the two is nonzero.

out1 = xor(gt(in1, 0), gt(in2, 0));
bool(x)

Anything nonzero becomes 1; zero stays 0.

out1 = bool(in1) * 0.5;

Constants

bpm()

The PROJECT'S TEMPO, in beats per minute. 120 when nothing is driving the transport, so a module auditioned on its own still has a sane clock. gen~ has no idea what a tempo is; this is the door to `import sync`.

import sync; import fx;
out1 = delayfx(in1, beats2samps(0.5), 0.4);   // half a beat, at any tempo
beat()

The playhead in BEATS since the start, fractional - so fract(beat()) is a phasor the project drives, and it lands in the same place every time you press play.

import sync;
out1 = beatphase() * 2 - 1;
bar()

The playhead in BARS, fractional (4/4).

import sync;
out1 = barphase() * 2 - 1;
playing()

1 while the transport is running, 0 when it is stopped.

import env;
out1 = in1 * ar(playing(), 5ms, 200ms);   // fade in with the transport
samplerate()

The engine's sample rate right now (48000 at 48k). In code it is `sr`.

out1 = in1 / samplerate();   // in code: in1 / sr
nyquist()

Half the sample rate - the highest frequency that exists here.

import filter;
out1 = svf_lp(in1, nyquist() * 0.4, 0.7);
twopi()

2*pi = 6.28318 - one full turn in radians.

out1 = sin(twopi() * phasor(220)) * 0.3;
halfpi()

pi/2 = 1.5708 - a quarter turn.

out1 = sin(halfpi()) * in1;
invpi()

1/pi = 0.31831.

out1 = atan(in1 * 4) * invpi() * 2;   // atan drive, normalised
euler()

e = 2.71828, the base of the natural logarithm.

out1 = log(euler());   // 1
phi()

The golden ratio, 1.61803.

import osc;
out1 = (saw(220) + saw(220 * phi())) * 0.2;   // inharmonic pair
sqrt2()

The square root of 2, 1.41421.

out1 = in1 * sqrt2();
invsqrt2()

1/sqrt(2) = 0.70711 - the -3 dB point, and the Butterworth Q.

import filter;
out1 = svf_lp(in1, 1000, invsqrt2());   // Butterworth Q
ln2()

The natural log of 2, 0.69315.

out1 = log(in1 + 1) / ln2();   // log base 2 by hand
ln10()

The natural log of 10, 2.30259.

out1 = log(abs(in1) + 1) / ln10();
log2e()

Log base 2 of e, 1.44270.

out1 = log(in1 + 1) * log2e();
log10e()

Log base 10 of e, 0.43429.

out1 = log(abs(in1) + 1) * log10e();
degtorad()

Multiply by this to turn degrees into radians.

out1 = sin(in1 * 180 * degtorad());
radtodeg()

Multiply by this to turn radians into degrees.

out1 = atan2(in2, in1) * radtodeg();   // the angle in degrees

Voices

voice()

WHICH copy of this program is running: 0, 1, 2 … A cable's channels are independent clones of the same patch, and this is how a clone tells itself apart - the way you detune or spread a unison from INSIDE the patch.

import osc;
float spread = (voice() - (voicecount() - 1) * 0.5) * 0.02;
out1 = saw(220 * (1 + spread)) * 0.2;
voicecount()

How many copies are running (the channel count of the cable feeding it). 1 when the patch is playing on its own.

out1 = in1 / voicecount();   // keep the sum level as voices come and go
vsum(x)

THE LANE CROSSING: every lane deposits x, and every lane reads the TOTAL all of them deposited - one sample late, the same declared z-1 the canvas gives a cycle. After a mask it is the mix of the live voices, inside the patch. Each written vsum is its own crossing (two never smear), and the cable after it honestly reads width 1. vavg(x) is the averaged sister.

import osc;
out1 = vsum(saw(110 * (lane() + 1)) * 0.1);   // the stack, summed
voices(n)

THE DECLARED POLYPHONY: lanes at index n and above DO NOT RUN - no CPU, their time simply stops, and when n rises they resume where they stopped (adopted at the next block; lane 0 never sleeps). It returns the number, so one idiom masks AND declares. A plain comparison mask keeps every lane running - and paying - so its clocks stay true; voices(n) is for lanes you want off the bill.

import osc;
out1 = saw(110 * (lane() + 1)) * 0.1 * (lane() < voices(2));
alive()

Does THIS lane exist next block? 1 while inside the width voices(n) is asking for, 0 the moment it has asked for fewer - one block of warning, so a copy about to pause can FADE instead of stopping mid-sample (and a newborn one can fade in). With nobody declaring anywhere it is simply 1. A paused lane never runs, so alive() is the goodbye, not the obituary.

import env;
out1 = in1 * ar(alive(), 2ms, 8ms);   // click-free birth and pause
MERGE

Cables CONCATENATE: each pin owns a range of output lanes as wide as the cable on it - 8 voices on one pin and 6 on another become 14. An unfed pin is one silent lane. All-mono merges are instant; ANY wide pin makes the whole merge one declared sample late (the crossing's price, worn on the cable), uniformly across every lane. Width out = the sum, capped at 16.

SPLIT

ONE lane out of a wide cable: `lane` picks which (whole, 0 = the first; wire it and it becomes a voice scanner). Crossing lanes costs the declared one sample, like vsum - the out-cable wears the z-1 badge and honestly reads width 1.

ROTATE

The lanes TURN by `step`: lane i reads lane (i+step), wrapping. Round-robin distribution, canons, voice ping-pong - width preserved, one declared sample late, and the out-cable says so.

ALLOC

A mono stream becomes VOICES: every rising edge on `trig` goes to the NEXT lane, round-robin. Two wide outs: `val` holds each lane's last value, `trig` reaches ONLY the assigned lane - and stays hers until the next event steals it, so her envelope attacks while the others ring out. The lane count (1..16) lives in the inspector and IS the width out. Deterministic, zero delay - no busy, no mute, no thispoly~.

lane()

WHICH clone this is, counted from zero. The program runs once per voice, so the index is a question you ask, never a number routed to you - and one multiplication later every lane has its own harmonic, its own pan, its own anything.

out1 = phasor(55 * (lane() + 1)) * 0.1;   // a harmonic per lane
lanes()

How many clones are running - the patch's width in one number. With the lane index beside it, anything spreads evenly across the voices, however wide the cable happens to be.

out1 = phasor(220) * (lane() < lanes() / 2);
vspread(lo, hi)

The even spread, done for you: the first lane gets the low end, the last the high, everyone between their fair share. A whisker apart is unison detune, minus-one-to-one is a pan fan across the stage.

out1 = phasor(220 * vspread(0.99, 1.01)) * 0.2;   // a detuned stack
vavg(x)

The average across the lanes - the sum crossing divided by the head count, so every voice reads the same mean. One declared sample late, like every lane crossing.

out1 = in1 - vavg(in1);   // each lane minus the chorus mean (one sample late, declared)