Every builtin effect is a small program that runs once per sample. process lets you write that program yourself: a function from one sample to the next output sample, compiled to bytecode and run by the same engine on the desktop and in the browser. This lesson turns a builtin distortion into five words of your own.
process (\x -> tanh (x * 4.0)) hands every sample x of the signal to your lambda and plays what it returns. tanh squashes big values toward ±1 and leaves small ones alone — that curve is a soft-clipping distortion. A lambda used like this is called a kernel, and the formula is its law.
The law may use numbers, + - * /, comparisons, if … then … else, let, and the math builtins abs min max tanh sin cos floor sqrt exp ln pow. It may call other lambdas you define (they are inlined). It may not read another signal, pitch or a patch field directly — a kernel sees its input sample, its own arguments and macros.
That last one is the reason to write your own: a macro used inside the law becomes a live parameter of the kernel, read every sample. process (\x -> tanh (x * (1.0 + grit * 8.0))) puts the drive knob inside the curve — something a fixed builtin cannot offer.
Output is safe by construction: a division by zero gives 0, a NaN becomes silence, and the output is soft-limited at ±2. Experiment freely.
The starting point#
The lesson opens with this song in the editor. Every edit recompiles and plays.
-- Your first kernel. This lead is distorted by the builtin `drive`;
-- you are about to write that curve yourself.
lead = patch {
source = saw (freq pitch) |> drive 0.5,
ampEnv = adsr 5ms 150ms 0.6 120ms,
gain = vel * 0.2
}
riff = play lead !"c3 eb3 g3 bb3 g3 eb3 c3 ~"
What to watch#
Watch the scope as you raise the drive inside your law: the saw's ramp bends into a rounded plateau, then into a near-square as tanh flattens the top and bottom.
Goals#
The workbench checks these as you work; the solution is there when you want it.
- Write the distortion as a law:
process (\x -> …) - Retire the builtin
drive - Stretch: put a knob inside the law
Make it yours#
Write three different laws and switch between them: a hard clip (max (0.0 - 0.5) (min 0.5 x)), a wavefolder (sin (x * 3.0)), and an asymmetric tube-ish curve (tanh (x + 0.3) - tanh 0.3). Hear which ones add even harmonics.
Further reading#
Write a custom audio processor in the reference.