← Home
petri-nets music beats-bitwrap

A browser music sequencer where every note is a Petri-net transition firing

Live at beats.bitwrap.io. Source: github.com/stackdump/beats-bitwrap-io.

The readout at the bottom of that picture says 8/17 nets · 248 places · 248 transitions · 496 arcs, and 496 is exactly two arcs per transition, which is what a ring has. Each small ring on the big ring is one net, a track's pattern or one of its riff variants, drawn from the project the worker ticks; dimmed panels are muted, and muted hit-pad nets are left off the display. The streaks toward the centre are the Pulse and Flame layers reacting to firings. An activate-slot action mutes a riff's siblings, so you hear one variant per slot, chosen from the denser structure on screen.

The thing I wanted to share is the implementation choice underneath it, since plenty of people have built beat generators: the sequencer is a Petri net executor. The worker keeps no event list and has no "schedule note at tick N." A drum pattern is a ring of places with one token circulating (the first writeup walks through the rings); every step fires a transition, and the ones carrying a MIDI binding are the notes. Polyrhythm is two rings of different length sharing a tempo (the dnb preset's hat ring is 6 steps). Song structure is a control net that fires mute-track / unmute-track / activate-slot actions at section boundaries. Mute macros are short linear-chain control nets injected at runtime with a restore action on the terminal transition.

We should be exact about where that stops. Control actions flip a mute table in the worker instead of moving tokens. Loop wrap and seek replay silently from tick 0. FX-style macros are animation loops on the sliders, off the net entirely. The main thread schedules each fire onto the audio clock with an 80 ms lookahead. The engine notes list what sits outside the net.

What the seed pins

Same (genre, seed) composes the same nets. Per the engine notes, compose seeds one mulberry32 generator and draws every choice from it in a fixed order (chords, motif, instruments, variants, fills), with drums hashing the genre name instead.

We have a Go port of the composer, and what CI checks across the two languages is narrower than that sentence suggests. A Go test and a JS script assert the motif for techno, seed 42 against one pinned vector; the script says plainly that it can't byte-compare whole projects, so past the motif it checks JS structure only (feel-curve net, melody place counts, bass hit counts). TestArrangeSeeded_Deterministic runs the Go arranger three times and byte-compares, which is Go against itself. The one live diff between the languages is model_cid_parity_test: both producers parse one fixture model, and their canonical bytes and CID must match. We found no test comparing whole arrangements across the languages, and rendered audio isn't compared at all. (These were read for this revision, not re-run.)

Playback adds more on top. In the default Drift loop mode the worker's driftMidi jitters velocity and can drop ghost notes, seeded by loop iteration, and applyPhaseDrift occasionally shifts a token on loop wrap. Its conflict resolver calls Math.random(), though the engine notes record a probe of generated techno, ambient and jazz nets with no contested place for it to act on. Set the loop mode to Deterministic and those go quiet. The main thread still adds humanize jitter with Math.random() whenever humanize is above zero, which the dnb preset sets to 15, and Auto-DJ picks its macros the same way. The worker ticks on a setInterval of 60000 / (BPM × PPQ) ms with PPQ fixed at 4, and a throttled tab advances state silently to catch up, so notes can go missing there too. Two listeners on one envelope get the same nets, not the same samples.

The address

A track is a small JSON envelope (@context + @type + v + genre + seed + optional overrides; schema, minimal example), canonicalized, sha-256'd, encoded as a CIDv1 in base58btc. The URL is ?cid=z…. Same canonical bytes ⇒ same CID, always, and PUT /o/{cid} re-hashes the body and writes it only when the CID matches the path, so different bytes can't pretend to be an existing one. There's also a ?cid=…&z=<base64url-gzip> form that inlines the gzipped envelope so the link works offline, from a local copy, or after the share store is purged. ~80 chars for the short form, ~1.5 kB for the self-contained form, 10–100 kB once an envelope carries hand-authored nets.

What the CID addresses is the recipe. It doesn't cover the audio, and it doesn't name a generator version; the schema has no such field. When cohesion v2 became the default, links sealed earlier would have regenerated with a different sound, so an envelope without the field is pinned to v1. That pin handles that one change, and a composer change that didn't get its own pin would change what an old CID sounds like. The Go tests pin the CID computation and the canonical round-trip against a fixture shaped like a browser payload; they don't run the JS codec.

The screen

Press M and the app turns into a Petri-net display, one sub-net per track in a ring, each showing the active variant for its slot. The panels and the default layers run off the same worker messages the audio does: transition-fired reaches the visuals on receipt and the audio 80 ms later, and the marking arrives by state-sync every 6 ticks. Token particles pulse toward the composition core on each fire; per-panel flames ignite on every transition. It's the first time I've shipped a music tool where the thing on screen is literally the data structure making the sound, with two exceptions. The big ring joining the panels is layout: its connector places aren't in the project and nothing fires them, and past 16 panels it isn't drawn at all, so the picture above, at 17 nets, doesn't show one. Songs are composed by the control nets. And the optional wave and spectrum layers do read the audio, through an analyser on the master chain.

Where the audio comes from

No bundler, no npm install, no React. Vanilla ES modules, Tone.js from a CDN with a pinned version and SRI hash, and a single Go binary that serves the static files and the share store. Once an envelope reaches the studio, every sound is generated in the listener's tab and the audio path never touches the server. The studio does send anonymous playback diagnostics unless you opt out, which has nothing to do with the audio. /feed is different: its cards play the cached .webm in an <audio> element.

Production runs no audio renderer. A browser can upload a render with PUT /audio/{cid}.webm; the handler requires the CID to exist in the share store, rate-limits, refuses an upload that arrives sooner after sealing than the track could have played or that runs over 6 MiB, and keeps the first write. It can't check the bytes against the CID, because the CID covers the envelope, and its own comment calls the trust model "treat as a hint." A browser render also captures that listener's mixer state, so an off-host render farm authenticates with a secret, overwrites, and sweeps browser uploads so the feed converges on its renders. The site still doesn't transcode; it stores bytes produced elsewhere. That farm's output later outgrew this app.

There's a /feed gallery, a Winamp-flavoured sidebar player, an Auto-DJ that picks random macros every N bars, and a regen mode that cross-fades through a transition macro into a newly generated track, pre-rendered one bar early so the swap is a pointer flip. They sit on top of the runtime model. The longer launch post with screenshots and details is at /posts/beats-launch-jambox, and the native Mac version is the same sequencer built for performing.

We still haven't added a piano-roll editor. The Scope tab now draws fired events as a piano roll under the waveform, but that's a view of what fired.

Code, generator, share-store sealing, and the Go/JS parity tests are all in the repo.

Open questions

The three things I asked when this went up. Is "Petri net as canonical sequencer IR" a known pattern in computer music? I haven't seen it in the literature I've read; the closest neighbours feel like Max/MSP patcher graphs or SuperCollider proxy spaces, but those are dataflow, not place/transition. Is anyone else doing music tooling where the share URL is the complete spec, given the generator, and not a pointer to a server-stored timeline? And for a content-addressed audio store, what would you do differently for serving .webm at scale beyond "stick a CDN in front"? The naive disk + nginx setup is fine until it isn't.

What Changed

For readers of the April version:

  1. Determinism. The post said same (genre, seed) gave byte-identical output and that there wasn't a non-deterministic codepath. Both the worker and the main thread call Math.random() during playback. What holds is that the seed composes the same nets, and the cross-language checks are the motif plus one model-CID fixture.
  2. The address. "The address is the track" overstated it: the CID covers the envelope, with no generator version in it.
  3. Uploads. "Hash-checked" was wrong; the handler has no way to hash audio against an envelope CID. "Bytes other browsers produced" no longer describes the feed, which converges on render-farm output.
  4. The picture. Muted hit slots aren't on the ring, the streaks to the centre aren't connector places, and connector places are drawn by the layout, not fired by the net. "Nine sub-nets" was the launch-era track; the count varies.
  5. Smaller fixes. Only mute macros are control nets. Only firings with a MIDI binding are notes. /feed plays cached audio. The Scope tab now draws a piano roll.

Discussion: Hacker News

Related: Petri Nets as a Music Sequencer · beats.bitwrap.io is a Jambox Now · From Petri-net toy to jambox: 38 days of beats.bitwrap.io · cdn.stackdump.com Is a Polydocument Host · beats-btw-dj

×

Follow on Mastodon