Prerequisites: Petri Nets as a Music Sequencer for the token-ring construction; Declarative Differential Models for incidence matrices and P-invariants.
In beats.bitwrap.io today, a transition fires in a Web Worker, a transition-fired message crosses to the main thread, and a Tone.js instrument is triggered. The net decides when; a graph of AudioNodes decides what it sounds like. We have been building the other reading: the audio as a function of the marking, evaluated sample by sample inside an AudioWorklet. It lives in public/wave-engine/, now merged to main and served at beats.bitwrap.io behind ?engine=wave. The default engine is unchanged.
This post is the theory that engine is built on, and where that theory stops being exact.
Every music net the composer emits is a single-token cycle p_i → t_i → p_(i+1). We probed compose() for techno, ambient and jazz at seed 42, plus techno with the standard structure (NOTES.md records the probe): every music net is one cycle with exactly one token, no branching place, no inhibitor arc. Euclid and Markov both run at compose time. Euclid decides which places carry weight; the Markov and motif grammars decide which pitch each transition binds. Neither runs at play time.
Such a ring has state but no beginning or end. It is live: every transition fires again within n ticks. It is 1-bounded: the token count is conserved. It is reversible: the initial marking is reachable from every reachable marking, because after n more ticks you are back where you started. Firing advances phase, not progress. After k ticks the token sits on p_(k mod n), and nothing about the net records how many laps it has run.
The conserved quantity is a P-invariant. The all-ones vector y satisfies yᵀC = 0 for the ring's incidence matrix, so y·M is constant across every firing. The engine's executor (net.js) computes incidenceMatrix and pInvariants directly, and scripts/test-wave-engine.mjs checks them (make test-wave; every figure below is from the results table in the engine's README, not re-run for this post). On techno seed 42 every music ring has the all-ones invariant (40 of 40), and y·M stays constant at every tick of every net across a full standard song: 928 ticks, 60 nets, zero drift. The invariant is what makes the trajectory a closed orbit rather than a walk.
A single-token ring of length n is a concrete copy of the cyclic group Z_n. Its reachable markings are its n places, and one tick is the generator +1. A track is many rings ticking in lockstep. The Stage visualizer's default, the mandala (labelled "Constellation" in the UI), draws exactly this ring-of-rings. With r independent rings of lengths n_1, …, n_r, the joint marking is an element of
Z_n1 × Z_n2 × … × Z_nr
which is a discrete torus. A tick is the diagonal action (1, 1, …, 1). The orbit of the initial marking under it has length lcm(n_1, …, n_r). That is the period after which the whole texture repeats. Polyrhythm is what you hear when the ring lengths share few factors and the orbit is long. The dnb preset's polyrhythm setting shortens the hat ring to 6 steps. Against any 16-step ring, a 6-ring closes after lcm(6, 16) = 48 ticks, not 16.
The irreducible characters of Z_n are χ_k(p) = e^{2πi k p / n}: roots of unity, which is to say sines and cosines sampled on n points. Any function on the ring decomposes into them. The function we care about is the gate. Give t_p the weight w_p = velocity/127, or 0 for a rest, and let one pulse P sound per firing at tick length Δ:
g(t) = Σ_p w_p · P(t − p·Δ), periodic with T = n·Δ
Its Fourier coefficients factor:
c_k = P̂(k) · (1/n) Σ_p w_p · e^{−2πi k p / n}
The second factor is the DFT of the place weights. The ring's spectrum is the DFT of its weights, shaped by the transform of a single pulse. Because the weight DFT is n-periodic in k, the pulse transform P̂ acts as the envelope: it carries the high harmonics, and the ring only decides which ones survive. Four-on-the-floor, E(4,16), has weight-DFT magnitude 1/4 at every k ≡ 0 (mod 4) and exactly zero elsewhere. The tresillo, E(3,8), spreads its energy over every bin.
In the engine, P is two exponentials, a 1 ms attack and a decay, so onsets don't click. ringSpectrum in synth.js evaluates the sampled form of P̂ exactly. The test renders a hi-hat ring with ghost notes (n = 8, 48 bins), takes a DFT of the rendered gate, and compares it with the predicted c_k. The maximum relative error is 4.5×10⁻¹⁰.
A minimal sketch, not the engine's code (ringSpectrum is the real one, for the two-exponential pulse sampled at the audio rate). It uses one exponential pulse P(t) = e^{−t/τ}, which has the closed form P̂(k) = (τ/Δ) / (1 + 2πi·kτ/T):
// Harmonic amplitudes |c_k| of a ring's gate from its place weights.
// weights: w_p per place (velocity/127, 0 = rest); tickSec: Δ; tau: pulse decay.
function ringHarmonics(weights, tickSec, tau, K = weights.length) {
const n = weights.length, T = n * tickSec, out = [];
for (let k = 0; k < K; k++) {
let re = 0, im = 0; // (1/n) Σ w_p e^{-2πi k p/n}
for (let p = 0; p < n; p++) {
const a = -2 * Math.PI * k * p / n;
re += weights[p] * Math.cos(a);
im += weights[p] * Math.sin(a);
}
re /= n; im /= n;
const x = 2 * Math.PI * k * tau / T; // P̂(k) = (τ/Δ) / (1 + i x)
const pMag = (tau / tickSec) / Math.hypot(1, x);
out.push({ k, hz: k / T, weightDFT: Math.hypot(re, im), amp: pMag * Math.hypot(re, im) });
}
return out;
}
// Tresillo at 120 BPM, sixteenth-note ticks (Δ = 0.125 s), 40 ms decay.
// weightDFT is 0.375 at k = 0 and 0.125 at k = 4.
console.table(ringHarmonics([1, 0, 0, 1, 0, 0, 1, 0], 0.125, 0.04));
Look at the hz column before reading anything into it.
The tempting conclusion is that a ring is an oscillator whose timbre is the DFT of its rhythm. It isn't. The worker's clock fixes PPQ at 4, so a tick is a sixteenth note: 125 ms at 120 BPM. An 8-ring has period 1 s and fundamental 1 Hz. The 64-place bass and melody rings run 8 s per lap. Every k/T that the weight DFT controls is sub-audio. The audible content of g is the pulse shape, not the ring. A gate is an envelope.
So each voice is a product:
y_i(t) = g_i(t) · carrier_i(t)
The gate supplies when and how loud; the carrier supplies the pitch and the timbre. In the engine, the kick is a sine swept down to f1 using the same octave constants as each kit in tone-engine.js. The snare is band-passed noise plus a 180 Hz body, the clap is band-passed noise, and the hats are high-passed noise. Melodic rings use a band-limited wavetable at the pitch bound to the transition that just fired. Pitch is therefore also a function of the marking: the token's place determines which transition fired, and the transition carries the note. Each melodic ring gets a small deterministic voice pool (4, or 6 for harmony) so strummed pads can overlap.
A ring of rings is then nested modulation. If an outer ring's gate scales an inner one, that is AM, and the spectrum is the convolution of the two harmonic combs. If it bends the inner carrier's frequency, that is FM. On the torus this is just the statement that characters of a product group are products of characters. The engine exposes it as opts.mods = [{target, source, kind: 'am'|'fm', depth}]. An AM-nested ring matches inner × outer gate to 1×10⁻⁷. Nothing the composer emits uses it yet.
The output is Σ_i y_i(t): every lane summed inside one AudioWorklet node. The executor, the gates, the carriers and the mix all run in the same process() call. The net is the source of truth and the waveform is a projection of it. The worklet's ticks are replayed to the canvas and the Stage as transition-fired and state-sync messages, so the visualizers read the marking the audio is computed from.
The product-of-cyclic-groups picture is exact only for independent single-token rings. Shared transitions, inhibitor arcs and choice points break periodicity, and the Markov chain picture people expect, a stochastic choice at play time, would break stationarity outright.
In the composer's output those features appear only in control nets. These are the struct-* chains with inhibitor arcs and drained delay places, firing mute-track, unmute-track and activate-slot at section boundaries. They are not conservative: seven of them have no P-invariant at all, because their delay tokens drain and the last gate is a sink. They do not live on the torus. They move the torus around.
So we treat them as switches. At a tick boundary, a control firing replaces one set of ring weights with another, which amounts to switching Fourier coefficients. A muted ring makes no new onsets, and what is already sounding decays. Conflicts are resolved with the worker's own rule, deterministicRand(tick, strHash(place)). The engine's resolution matches the worker's over 400 ticks, and its compiled executor produces identical markings and audible fires over 896 ticks of a full song. The signal is piecewise stationary: each section is a closed orbit, and the arrangement is a seeded, deterministic path through a small set of them.
None of the signal processing here is ours, and the theory isn't either.
Running the sequencer at audio rate is an old pattern. In Max/MSP and Pure Data, a phasor~ ramp drives a patch sample-accurately and step indices are derived from its phase. SuperCollider's demand-rate UGens do the same job. Moving the executor into an AudioWorklet is that pattern ported to the browser.
Music as a single function of time is old too. Bytebeat writes a whole piece as one expression in t. Faust compiles instruments as pure signal functions. Cyclic time with no start or end is how TidalCycles and Strudel work: a pattern is a function from cycle-time to events. That is the closest philosophical cousin of the ring picture, with the cycle as a primitive rather than as a property derived from a net.
The Fourier side is an established field in music theory. Lewin took the DFT of pitch-class sets. Emmanuel Amiot's Music Through Fourier Space develops the DFT of pitch-class sets and rhythms at book length, and Milne's work on balanced rhythms uses the same coefficients. Toussaint's work on Euclidean rhythms, which is what our composer's Bjorklund step produces, connects to it through maximal evenness, which shows up as a large Fourier magnitude. The c_k weight factor above is their formula, applied to velocity-weighted onsets.
What we claim is narrower. The spectrum is read off the net's structure: a ring is Z_n because the net is a single-token cycle, and the P-invariant is a conserved coordinate the executor can check rather than an assumption about the input. The output is fully deterministic and content-addressed by (genre, seed, structure). The contribution is the correspondence between those things, not the DSP.
For independent rings, the engine is pre-processing, literally. With no choice at play time, the output is exactly periodic with period lcm(n_1, n_2, …) ticks. One hyperperiod can be rendered once and looped. That is the cheapest possible mobile playback, cheaper than the worklet, because playback becomes a buffer read.
Take dnb in loop mode. The genre table in composer.js gives a 16-step kick and an 8-step snare, polyrhythm: 6 makes the hat ring 6 steps, and the bass and melody rings are 64 places. The drums alone repeat after lcm(16, 8, 6) = 48 ticks. With the 64-place rings the hyperperiod is lcm(64, 6) = 192 ticks. At 174 BPM a tick is 86.2 ms, so the whole loop repeats every 16.6 s. As 48 kHz stereo float32 that is about 6.4 MB. These lengths come from reading the composer, not from a probe of a rendered track.
Two caveats keep it from being byte-exact. The exponential tails carry over from the previous lap, so the buffer has to be rendered after one warm-up hyperperiod. And the noise carriers and oscillator phases run free, so a looped buffer repeats one realization of the hats and isn't bit-identical to what the worklet would produce over the same span. The gates are periodic, but the samples aren't.
It stops being pre-processing once the net makes choices at play time. Markov choice between transitions (today's Markov runs at compose time), or rings that share transitions, make the output aperiodic, so it has to be computed online or per seeded segment. Structure mode is the in-between case. Its control nets make the signal piecewise stationary, so each section is its own closed orbit and could be rendered as its own loop.
A hybrid would cache rendered deterministic stretches keyed by (marking, seed state), and compute live only at choice points. Content addressing already supplies the cache key, because the same marking and seed state always produce the same stretch. The engine does none of this today. Every block is computed live in the worklet. Caching is an option the model opens up, not a feature.
The worklet is the general path, and its practical motive is beats-bitwrap-io#2, the mobile performance problem. The Tone path has three costs that grow with density. Timer-driven scheduling on the main thread contends with layout and input. Per-note AudioNode graphs are built and torn down. Both add garbage-collection pressure.
Running the executor in the worklet removes all three by construction. There is no message per note and no node per note. The per-sample loop keeps every mutable number in typed arrays, because V8 boxes a double written to an object field. That path allocates about 0.2 B per block, effectively nothing. Tick-boundary work, firing plus note onsets about eight times a second, still allocates a bounded amount: 66 B per tick on Node 25, 193 B on Node 22.
The cost doesn't disappear. It moves into per-sample JavaScript arithmetic, and that is where the discipline has to go. Use phase accumulators and wavetables, not Math.sin of absolute time per sample. One-pole IIR states realise the exponential pulses in O(1) per sample instead of re-evaluating the closed form. Tonal voices already read wavetables. The kick sweep and the snare body still call Math.sin on an accumulated phase, which is the next thing to table.
On valoper, a desktop x86 box, make wave-bench puts a 128-sample block at a mean of 43–102 µs across six genre/structure cases (10–53 lanes). The budget at 48 kHz is 2667 µs. The worst p99 is 365 µs, for ambient/extended. None of that has been measured on a phone. The bench's phone column multiplies by an assumed 6× slowdown, which would put the worst p99 at roughly a third to four-fifths of budget. That is an estimate to check on a device. The comparison that matters for #2 is the Tone path on the same handset, and it hasn't been run yet. We expect the wave engine to help on mobile. We have not shown that it does, and #2 stays open.
Scope is also narrower than the theory. The wave engine converts the six drum kits, approximately. Every other instrument currently plays as a generic family voice. Wave mode still borrows Tone's AudioContext and master chain downstream of the worklet. Macros, loop/seek, swing, humanize and live transpose are not yet wired. The roadmap generalises gate × carrier to a per-hit impulse response, y(t) = Σ_i w_i · h_v(t − iΔ). Output stays linear in the place weights, so c_k = Ĥ(k) · DFT(w) keeps holding with Ĥ computed numerically. Whether Tone.js leaves entirely is a decision for after the measurements, not an assumption.
What doesn't change is determinism. (genre, seed, structure) → compose → project JSON → WaveRunner gives byte-identical WAVs within one process and across two separate processes. There is no Math.random and no wall clock on the render path, and noise is a per-lane seeded xorshift. Because Math.sin, exp and tanh aren't bit-specified across JS engines, cross-browser byte identity is not claimed. The net already was a pure function of the seed. Now the waveform is one too.
Source: github.com/stackdump/beats-bitwrap-io, public/wave-engine/ on the wave-engine branch. Start with NOTES.md and README.md there.