Skip to content

Granite improvements - #46

Merged
danigb merged 6 commits into
mainfrom
granite
Sep 7, 2026
Merged

danigb merged 6 commits into
mainfrom
granite

Conversation

@danigb

@danigb danigb commented Sep 7, 2026

Copy link
Copy Markdown
Owner

Made with Claude

Replaces the stutter effect with Bencina's delay-line granulator, built on
scripts/_delay.ts: a grain playhead is a moving delay, so the masked wrap and
the Hermite read carry a cloud of up to 64 independent playheads unchanged.

- createGranulator(sampleRate, config) is a pure closure - no worklet globals,
  so dsp.test.ts runs in node. The old file reached for the sampleRate global
  despite taking it as a parameter, which is why it had no tests.
- Per-sample interonset scheduler: grains start at the exact sample their
  counter reaches zero, lifting the ceiling from one grain per render quantum
  (345/s, and 30/s as declared) to a measured 2,000/s.
- Preallocated pool, maxGrains 64 and bufferSeconds 4 via processorOptions,
  nothing allocated in process(). No free grain means no grain: nothing playing
  is ever stolen.
- rate, duration, position, pitch, shape, wet replace speed, density, spread.
  wet defaults to 1. Every range commented and justified.
- Clouds' causality clamp, asserted against an instrumented read at every
  corner of pitch x duration x position, for both a default and a short buffer.
- Envelope morphs EC2's asymmetry axis, expodec to bell to reversed expodec,
  from one table. Its mean square is 3/8 at every shape, so the morph is
  level-neutral; normalising it to unit RMS is what makes one grain of overlap
  unity rather than -4.26 dB.
- Clouds' smoothed 1/sqrt(n-1) gain normalisation.

Deterministic throughout - no randomness at all, which ticket 03 adds.

Measured: 2,000 grains/s with none dropped and 40 concurrent, at 0.031x real
time; pitch exact to 0.00 cents per grain and within 3.3 cents through the
stream; unity at one overlap (-0.06 dB) and within 0.11 dB across every shape;
level flat within 3.30 dB over a rate sweep of decorrelated grains; wet 0
bit-identical to the input.
Truax's (centre, spread) control model, eight parameters, every one drawn once
per grain at activation into the grain's own fields - EC2's argument that
heterogeneity belongs at the micro time scale rather than in a shared effects
chain. It is an API decision as much as a feature: strata inherits the names.

- durationSpread, spray, pitchSpread, reverse, pan, panSpread, level,
  levelSpread. Fourteen params, and the update() order changes with them.
- One seeded mulberry32 in the closure, processorOptions.seed. The library's
  idiom is Math.random(), which wavetable-oscillator argues for in as many
  words; three criteria here are distributions over thousands of grains, which
  a global stub cannot make reproducible.
- Three spread conventions, each pinned rather than chosen: a total width for
  durationSpread and pitchSpread (12 semitones is one octave, which is the
  ticket's own criterion), a half width for panSpread (pan is already bipolar,
  so a total width could not reach the field's ends), and one-sided for spray
  and levelSpread (Truax's "average or minimum value", and level is his
  per-grain maximum amplitude).
- The causality clamp is applied after the duration and pitch draws, and a
  reversed grain gets its own available: its delay grows by 1 + ratio where a
  forward grain's moves by 1 - ratio, so the two heads run apart.
- Constant power for a mono input, L/R balance for a stereo one; process()
  takes the flag because it cannot see it. pan 0 with panSpread 0 bypasses the
  law exactly rather than landing an ulp off unity.

Every spread is neutral at 0, bit for bit: three FNV digests of ticket 02's own
output, captured at 3726675 before this was written, are asserted byte for byte.

Measured: pitchSpread 12 spans 1.9996 of an octave, uniform to within 14% in the
worst decile; spray 1 covers [0.0013, 0.9996] of the buffer with no causality
violation over 343,692,064 instrumented reads; reverse 0.5 gives 50.90%
backwards; pan power is flat to 0.000 dB across the field; every parameter at
once peaks at 1.053 where the coherent case peaked at 10.49. And the finding
this ticket exists for: ticket 02's rate sweep collapses from 16.00 dB to
2.93 dB with a spray of 0.02, which is the empirical argument for its gain law.
Two scheduler parameters, both defaulting to 0.

`jitter` draws the next interonset from `mean * (1 +- jitter)` - Bencina's
Direct Interonset Specification over Truax's mean-preserving `[0, 2*mean]`
range - so the onsets dissolve off the grid while the density stays put.
`intermittency` rolls a skip at the moment of activation, before the grain
takes a pool slot or any of its six draws, so it lowers the density and the
cost together. EC2's Figure 6 is exactly that distinction, and it is why they
are two parameters rather than one.

The scheduler draws from a second generator of its own. Two more draws from
ticket 03's would displace every grain's draws and change every sample at every
setting, including at 0 where this ticket owes bit-identity with ticket 03; a
conditional draw would fix that by abandoning ticket 03's unconditional-draw
rule. A second generator keeps both, and makes the two parameters independent
by construction: the nth scheduled onset sees the same skip roll whatever
`jitter` is.

The preemption clamp now compares against `interonset * (1 + jitter)` rather
than the mean, which is Bencina's clause read literally. Without it `update()`
would cap every above-mean interval at the next block boundary and raise the
density by about a third.

Measured against the ticket's own thresholds:

- density preserved: 501 -> 503 grains over 10 s at rate 50, +0.399% (<= 2%)
- interonset sd 505.70 samples against the predicted mean/sqrt(3) = 509.22,
  0.69% low (<= 5%); 0.04 samples at jitter 0
- comb at the grain rate drops 17.45 dB at one grain of overlap (>= 15 dB).
  The ticket's rate 100 at the default 60 ms grain is six overlaps of a Hann
  window, which is COLA and has no comb to remove - measured -70.82 dB before
  and after; the whole duration sweep is logged
- intermittency 0.5 keeps exactly 50.00% of grains (+-3%); 1.0 emits none and
  the output is exactly silent
- the same intermittency keeps the same count at jitter 0 and 1 to +0.41%
  (<= 3%)
- bit-identical to ticket 03 at 0, by three FNV-1a digests of both channels

58 tests in dsp.test.ts, dsp.ts at 296 lines of code.
The two parameters that exist only because granite has a write head, and which
strata can therefore never have.

`freeze > 0` stops the head. That is the whole of it: a grain's delay is the
distance *behind* the head, so a head that stops moving is already the frozen
addressing, and the render loop subtracts a hoisted `advance` rather than
carrying a second mode. The same subtraction covers forward and reversed
grains, because both need exactly `delayStep - 1`.

The read is now clamped to `[1, ...]`. Live it returns the delay untouched and
is bit-exact; frozen, a forward grain's delay falls to about `ratio/2` in the
last samples of a grain born at `position: 0`, and a stated invariant that
holds only while the head is moving is not one.

Only the *leaving* edge needs a crossfade, and the asymmetry is derived rather
than assumed: entering freeze changes no sample already in the buffer and
leaves every grain's read index continuous, so there is nothing to splice.
Leaving it writes new audio against the last pre-freeze sample and sends that
join travelling outward through the buffer, where every grain crosses it. 100
samples, raised cosine, against the held last sample - fading into what the
buffer already holds there would replace one step with two, since that content
is the far side of the very splice being fixed.

`feedback` sums the wet grain sum back into the line ahead of the dry input,
through `clip-amp`'s `Math.tanh` blended in by `feedback` (digital-delay's
form, and what keeps 0 exactly neutral) and a one-pole high-pass at Clouds'
`20 + 100*feedback^2` Hz. The high-pass sits on everything the loop contributed
- saturation included - rather than on the raw feedback ahead of the saturator:
a soft clip is odd, but the grain sum it is fed is not symmetric over any short
window, and high-passing first leaves that DC to reach the buffer. Worth 52 dB
of output mean. Feedback is inert while frozen because it lives inside the
write.

Measured against the ticket's thresholds:

- freeze holds: RMS over the 30 s after the input is silenced is 0.136 dB from
  its value at the freeze, worst single second also 0.136 dB (<= 1 dB)
- freeze does not click: entering <= +0.07 dB and leaving <= +2.37 dB over the
  unfrozen baseline across four signals x four settings (<= 3 dB). With the
  fade disabled the leaving edge reaches +9.82, +7.23, +5.90 and +3.40 dB in
  four of the sixteen; the entering edge is unchanged either way
- feedback stable at 0.95 over 60 s: finite, last-30 s peak buckets not
  monotonic (first 3.2380, last 3.1191), peak 3.3761 - *below* the 3.7074 at
  0.5, which is the saturator. The "below 0 dBFS" clause is not about feedback
  and cannot be met: at feedback 0 the same 60 s already peaks at 2.1824, and
  the peak at 0.95 is 3.38/3.22/3.23/3.16 across inputs from -4.7 to
  -30.8 dBFS RMS - the same number whatever the input, because at 0.95 the loop
  gain is near unity and the saturator alone sets the ceiling
- stacks transpositions: 440/880/1760 Hz at 108.30/103.94/101.12 dB above the
  floor from a 220 Hz sine at pitch +12 (>= 20 dB), against 109.34/12.89/-19.32
  at feedback 0 - one transposition, not three
- no DC accumulation: -102.75 dBFS after 60 s at feedback 0.95 on a zero-mean
  input, against -102.80 at feedback 0 (<= -60 dBFS). The suite's own noise
  carries -40.43 dBFS of its own bias, which comes out at -31.03 dBFS at every
  feedback setting including 0
- bit-identical to ticket 04 at 0, by two new FNV-1a digests captured from
  d410330 with jitter and intermittency up, and by the five from 02 and 03

70 tests in dsp.test.ts, dsp.ts at 353 lines of code in 835.
Ships the package the rewrite made. granite is framed as what it is: the
third delay after digital-delay and analog-delay, all three over the same
scripts/_delay.ts, split on what the read head does - a tap, a glide, a
cloud.

README to the karplus-strong standard, all nine sections. The parameter
table is eighteen rows, not the sixteen the ticket asked for: it was
written before jitter/intermittency and freeze/feedback landed. Every row
is checked against params.ts for name, default, min, max and rate.

"Measured quality" quotes only numbers dsp.test.ts produces, and states
all three criteria that were not met as written, with the threshold, the
measured value and the reason:

- the gain rate sweep is 3.30 dB against "below 3", and the whole excess
  is Clouds' `activeCount > 2` clause - two decorrelated grains are
  +3.01 dB by arithmetic. `> 1` would meet it and depart from the
  reference
- "jitter dissolves the comb at rate 100" is unmeetable at the default
  60 ms grain, because Hann is COLA at six overlaps and the output is a
  pure delay with -70.82 dB of modulation. Asserted at one grain of
  overlap instead: 17.45 dB against the unweakened 15 dB
- feedback's "peak below 0 dBFS" and "DC below -60 dBFS" both fail at
  feedback 0, before feedback exists. Restated as finite, non-monotonic,
  and peak 3.3761 at 0.95 below 3.7074 at 0.5 - the saturator's
  signature - with DC asserted on a zero-mean input at -102.75 dBFS

Attribution replaces "Original granular engine" with the papers (Bencina
2001, Truax 1986/1988/1994, Roads 2001, Roads et al. 2021), the five
Clouds citations by file and line, and the in-repo reuse. It also
corrects a licence error the ticket folder carried: Clouds is MIT, not
GPL-3.0 - every file read here has Emilie Gillet's MIT notice and there
is no GPL text under clouds/. No source was copied either way.

The site was broken from ticket 02 onward and nothing in the workspace
compiled it. site/examples/GraniteExample.tsx replaces the bespoke
/demos/granite route, following FlexAudioBufferSourceExample: the same
track14.mp3, sliders bound to the real AudioParams within their declared
ranges, freeze as a checkbox, dispose on unmount, and the track credit
carried over. The docs page is rewritten around the eighteen parameters
and documents none that does not exist.

dsp.test.ts is consolidated from four appended per-ticket blocks into one
suite: every helper hoisted into one section, describes grouped by
subject. Not one assertion, threshold or measured number changed - the
sorted set of non-comment lines is byte-identical before and after, and
the count is still 70.

Granite.descriptors now asserts the gate shape for `freeze` in
descriptors.test.ts's TRIGGERS table, where generic well-formedness could
not.

package.json: 0.1.0 -> 0.2.0 with real keywords and a real description,
and a CHANGELOG naming every breaking change - speed/density/spread
removed, wet 0.5 -> 1, and why no existing patch reproduces.

npm test 50 suites / 1280 tests, npm run build clean with processors
unchanged, prettier clean, and the site typechecks and builds with no
errors.
@danigb
danigb merged commit de70c97 into main Sep 7, 2026
1 check passed
@danigb
danigb deleted the granite branch September 7, 2026 06:29
danigb added a commit that referenced this pull request Sep 7, 2026
Brings in #46 (Granite improvements) and #47 (FlexAudioBufferSource ->
TimestretchAudioSource). Three conflicts, all in files this branch also
rewrote.

**`packages/granite/src/params.ts`** - main replaced the four-parameter engine
with an eighteen-parameter one, so ticket 06's pass on the old `wet`/`speed`/
`density`/`spread` had nothing left to describe. Took main's file and re-applied
the convention to it.

Its header carried a cost argument this branch disproves: "not worth 128 floats
per parameter per block". `benchmarks/automation-rate/` measured that and it is
wrong twice over - declaring a parameter costs ~0.30 us/node/block with the rate
free, and an a-rate parameter with nothing varying connected still arrives as a
single value, so the 128 floats only exist once somebody has patched something
in, at which point k-rate renders the modulator and discards the samples.
Replaced with the honest ground: fifteen of the eighteen are read once per grain
at activation, which is (b). `freeze` is (a). `wet` and `feedback` are applied
per sample and are marked **A bet**, joining the folder's candidate list.

**`packages/synthlet/src/descriptors.test.ts`** - main added
`["Granite", "freeze", "k-rate"]` to the trigger-like table, against this
branch's claim that every trigger-like param is now a-rate.

Kept `freeze` k-rate. It is not an event: it borrows the gate shape (`> 0`, so a
scaled control still opens it) to latch a *mode*, and `dsp.ts` crossfades 100
samples across each edge - so the splice is what a listener hears, not the
sample the edge landed on, and placing it exactly would buy nothing the fade
does not already cover. Narrowed the claim the test pins from "every
trigger-like param" to "every param that places an *event*", and said why
`freeze` is the exception.

**`packages/synthlet/src/worklet-copies.test.ts`** - both sides added a package
to `spectrumPackages`. Kept both: `granite`, `lfo`.

Verified on the merged tree: 60 suites, 1519 tests, 42 snapshots pass;
`npm run build` leaves every generated bundle unchanged; `npm run check:rates`
and `prettier --check` pass. The two lockfiles are byte-identical to main's.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant