# Effect API

An effect is a machine that listens. It is one plain JavaScript file that calls `FM.define` once, with
`kind: 'effect'`, and it is written against the same kit as the machines: everything in the Machine API
(`docs/MACHINE_API.md`: screens, knobs, colours, the clock, seeded randomness, `m.keep`, the performance budget)
works here too. This page is only what is different.

```js
FM.define({
  kind: 'effect',
  title: 'Tape Moth',                  // 1–4 words
  blurb: 'What it does to a sound and how to play it, 2–4 sentences. Say what touching the screen does.',
  thoughts: ['3–5 short, wry lines for its gallery label.', '…'],
  mix: 0.5,                            // optional: where the kit's Mix knob starts (0 dry … 1 wet). Default 1.
  skin: 'bakelite',                    // optional: the colour scheme it is born in
  build(m) {
    const d = m.ac.createDelay(2);
    m.input.connect(d);                // sound comes in here
    d.connect(m.out);                  // what you make of it goes out here, all of it wet
  },
});
```

## Sound in, sound out

| | |
|---|---|
| `m.input` | an `AudioNode`: the sound coming in, in stereo (the host's track, or in the app a Machine playing as the source). Connect it into your own nodes. |
| `m.out` | where your result goes: **only the effect, no dry sound**. `m.verb` and `m.echo` (the kit's reverb and delay sends) are there too. |
| Mix, Level | **the kit adds these two knobs itself**, in an Output section after your own controls: Mix crossfades what came in with what you send to `m.out`, Level trims the result. Never make a Mix, Wet or Level knob of your own (the bench refuses it); set the starting point with `mix:` in `FM.define`. |
| power | off is bypass: all dry, in time. Your nodes keep running, so nothing clicks when it comes back. |
| `m.inLevel`, `m.outLevel` | how loud it is going in and coming out, 0…1, smoothed: read them in `m.frame` to make the screen move with the sound. |
| `m.wave(float32Array)`, `m.outWave(float32Array)` | fills your array (up to 256 samples) with the waveform going in / coming out, to draw. `m.inAnalyser` and `m.analyser` are the `AnalyserNode`s behind them. |
| `m.bpm` | the tempo everything follows (the host's, or the app's). `60 / m.bpm` is a beat in seconds. Read it when you need it; it changes. `m.clock` works as in machines and lands on the host's beat. |

An effect gives back what it is given: no auto level and no compressor sit behind it. So **stage your gains**:
with every knob at its default, a full-scale sound going in should come out about as loud as it went in.
Feedback paths need a ceiling below 1 (and a filter or a soft clip inside the loop is what makes them sing
instead of scream). The engine ends in a limiter just under 0 dBFS, as a seat belt, not as a sound.

## What the engine can do

Effects only live in the iOS and macOS app and the AUv3, where Web Audio is rebuilt natively. With `m.ac` use
only: Gain, Oscillator (all types, and `createPeriodicWave`), BufferSource, BiquadFilter, IIRFilter,
StereoPanner, Delay (up to 10 s), WaveShaper, DynamicsCompressor, Convolver, Analyser, ConstantSource,
ChannelSplitter / ChannelMerger (two channels). There is **no AudioWorklet and no ScriptProcessor**: you
cannot touch samples one by one. An effect is a graph of those nodes, and the invention is in how they are
wired and what moves them:

- **Modulation is a connection.** An oscillator (or looped buffer, or ConstantSource) through a Gain into an
  `AudioParam` (`lfo.connect(depth); depth.connect(delay.delayTime)`) is a chorus, a vibrato, a flanger, a tremolo,
  an auto-pan, a wah. A buffer you fill yourself and loop is an LFO of any shape, a step sequence, a random walk.
- **Feedback is a loop through a Delay** (a loop must contain a DelayNode): echoes, combs, resonators,
  Karplus-Strong strings that the input plucks, flangers, shimmer-less shimmers, feedback networks of four
  delays crossed into each other.
- **Ring and amplitude modulation**: connect a signal into another Gain's `gain` (set that gain's own value to 0
  for a true ring modulator). The input itself can be the modulator: connect `m.input` into a param.
- **An envelope follower without code**: `m.input` → WaveShaper with a curve of `Math.abs(x)` (a rectifier) →
  a low-pass BiquadFilter at 5–30 Hz → a Gain → any `AudioParam`. Now the sound's own loudness opens a filter,
  bends a delay, pushes a pan, ducks the wet. This is how an effect listens.
- **Distortion and folding** are WaveShaper curves you compute once: tanh, hard clip, wavefold (a sine of the
  input), bit-crush steps (a staircase), rectify, octave-up (abs), asymmetric tube curves, a Chebyshev.
- **Filters in banks**: formants, combs of bandpasses tuned to the key (`m.freq`), phasers (all-pass chains
  with a modulated frequency), vocoder-ish bands each with its own follower.
- **Rooms**: a Convolver with an impulse you compute (noise with any envelope, reversed, gated, a staircase, a
  ping-pong, a room tuned to chord notes by adding decaying sines).
- **Granular without samples**: several Delay taps whose `delayTime` is swept by sawtooth LFOs, each windowed
  by a Gain driven by a matching window LFO, is a pitch shifter, a harmoniser, a freeze, a cloud.
- **Rhythm**: `m.clock` (follows the host) scheduling `setValueAtTime` / `setTargetAtTime` on gains, filters and
  delay times is a gate, a stutter, a sequenced filter, a tape stop.

What you move from `m.frame` or a pointer handler should be moved with `setTargetAtTime` (never set a param to
`NaN`; never `exponentialRampToValueAtTime(0)`). A change of a `Delay`'s time is heard as pitch: use that on
purpose, or crossfade between two taps.

## Performance comes first

An effect lives inside someone else's song: in Logic, AUM or Loopy Pro, next to forty other plugins, on a phone.
Its sound is rendered natively on the host's audio thread, so what costs is **how many nodes it has** and how much
the page does:

- **Build the whole graph once, in `build`.** Never create nodes while it runs (the bench refuses an effect that
  does). Afterwards only parameters move.
- **Few nodes.** Aim for 15–40; the bench warns above 48 and refuses above 90. Every node costs on every block,
  whether sound passes or not.
- **One Convolver at most**, with an impulse of 2 seconds or less. Often a few delays and all-passes make a
  better room for a tenth of the cost. `m.verb` and `m.echo` (the kit's sends) cost nothing until you touch them;
  touching `m.verb` adds a Convolver, so don't reach for it out of habit.
- **Parameters move when something changed**, not every frame: call `setTargetAtTime` from a knob, a pointer
  handler or a tempo change, not unconditionally in `m.frame`. Each call crosses a bridge to the engine.
  Follow the tempo like this: `let bpm = 0; m.every(0.5, () => { if (m.bpm !== bpm) { bpm = m.bpm; apply(); } });`
- **A WaveShaper curve is computed rarely** (a knob, the end of a drag; at most a few times a second), 1024 points
  or fewer.
- **Light drawing**: a few hundred canvas calls per frame at most (the bench warns above 700). When the
  plugin's window is closed the kit stops calling `m.frame` and stops measuring levels by itself, so everything
  that matters to the sound must live in the graph, a clock or `m.every`, never in `m.frame`.
- **A low-pass or high-pass filter's `Q` is in decibels**, not the usual linear Q: `Q.value = 0` already has a resonant
  bump above unity gain, and 0.5 or 1 more so. Inside a feedback loop that bump multiplies on every pass and the
  loop blows up (it took a whole effect down). Use `Q.value = -3` (flat, Butterworth) for any low-pass or high-pass
  in a loop, and keep resonance (a positive Q) for filters outside loops. Band-pass and all-pass filters peak at
  exactly 1, so their (linear) Q is safe anywhere. Count a loop's gain at its loudest frequency, with every knob at
  its far end: it must stay under 1, or the loop must pass a soft clip that brings it back.
- **A Delay is never shorter than 128 samples** (2.7 ms at 48 kHz) in this engine. Combs and plucked strings tuned
  by a delay reach up to about 350 Hz (`m.ac.sampleRate / 128`); for higher notes use resonant band-pass filters.

## The screen

The screen is the biggest part and it is **played**: pressing and dragging on it changes the sound (drag a
tap, bend the curve, throw the echo, pull the resonator, smear the room), and it shows what the effect is
doing to the sound right now, driven by `m.inLevel`, `m.outLevel`, `m.wave` and your own state. `flex: true`,
laid out from `scr.w` / `scr.h` every frame, theme colours only (`m.color`), a short hint drawn on it. What a
visitor made on the screen goes through `m.keep(save, load)`.

It keeps drawing with no sound coming in (an effect is often opened before anything plays): idle, breathing,
waiting. And it must never make sound of its own when nothing comes in, except a tail of what did (a
self-oscillating filter or a feedback loop at the edge is allowed to be a knob's far end, never its default).

## Controls

- 3–8 knobs and menus of its own, in sections laid out like a synth panel (`cols` = the number of controls up
  to 5, or even rows; knobs first, then menus, then switches). The first eight knobs you create are Macro 1–8
  in the host, automatable and named after them: make the most expressive ones first.
- Time knobs that could follow the beat should offer it: a Sync select (`Free`, `1/4`, `1/8`, `1/8.`, `1/16`, …)
  read against `m.bpm`.
- Where an effect has pitch (resonators, combs, shifters), take it from the key (`m.freq`, `m.quantize`) and
  offer the Scale menu (`select({ label: 'Scale', options: m.scaleNames, value: m.scale, onChange: (v) => m.setScale(v) })`),
  created after its other controls. An effect with no pitch has none.
- `m.onNote` is optional: in a host an effect gets no notes.

## Making your own

Open the [Workbench](https://forevermachines.net/workbench.html) and choose **Start from → A blank effect**, or
start from any effect in the collection. It notices from your code that it is an effect (`kind: 'effect'`):

- the **preview** plays a sound into it: pick a beat, a bass line, chords, a public-domain voice or a file of your
  own under **Source**;
- **Run & test** runs it on the bench below, with an effect's budget (its node count against 90);
- **Docs** opens this page first, then the Machine API;
- **Write it with AI** has a *Make an effect* choice that puts this page, the rules and the collection's
  effects into the brief;
- **Add to my effects** keeps it in this browser, numbered from No. 1001. It plays on
  [/effects](https://forevermachines.net/effects/) under *Yours*, and as an insert on any channel of the Mixer on
  forevermachines.net.

**In the apps**, save the file (Export in the Workbench, or any `.js` file you wrote) and add it:

- **Forever Effects** (iPhone, iPad, Mac): **⋯ → Yours → Add a file…**. It runs on the same bench; if it passes it
  is kept under *Yours* (No. 1001 on), in the app and in its AUv3 plugin alike (Logic, AUM, Loopy Pro…). Add a new
  version of the same file (same title) and it keeps its number. Remove it from its info card (**i**).
- **Forever Machines**: add it as you add a machine (**＋**): it becomes one of your effects in the mixer's FX menu,
  and goes on the machine you are playing.

Your effects stay on the device: in a file the app and its plugin share, never uploaded, kept through app updates.

An AI agent can do all of it through the Forever Machines MCP server (`get_effect_api`, `list_effects`,
`test_machine`, `open_in_workbench`, `keep_machine`).

## The test bench

**Run & test** in the Workbench (and `node effects/scripts/invent.mjs --install <file> --check` for the weekly
inventor) runs the same bench as the machines, with the effect rules: it must use `m.input`, send to `m.out`, have knobs, have a screen that answers the pointer, no
Mix/Level of its own, nothing the native engine lacks, no crashes or NaNs over three seeds with every control
fuzzed, inside the performance budget.
