Skip to content

Render pipeline chunk 3: stems and mixes render in the daemon - #54

Merged
ninjudd merged 8 commits into
mainfrom
render/stems-and-mixes
Aug 8, 2026
Merged

ninjudd merged 8 commits into
mainfrom
render/stems-and-mixes

Conversation

@ninjudd

@ninjudd ninjudd commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Render pipeline chunk 3. track-render and mix now call field-audiod --render, so the daemon is the executor for everything the graph renders.

Shape

The plan grows an op discriminant — effects, stem, mix — and RENDER_PLAN_VERSION goes to 2. Each op carries the schema's own objects verbatim: inserts, PlacedClips, faders. There is still no translation layer to drift.

Summing lives in native/audiod/src/dsp/mixdown.cpp: placed clips into a stem, stems through their faders into a mix, then master gain, master chain, and the declared length — in that order, which is the decision in effects.md §5 (gain drives into the limiter, and the length applies after the chain so a tail the chain grew still respects the bar line).

Musical time stays where decision 7 put it. Clips arrive already resolved to sample offsets, so mixdown.cpp has no idea what a bar is — the sentence the daemon's design keeps true.

Byte-identical again, so no rule_version bump

Same result as chunk 2, and it holds through the awkward paths rather than just the easy ones: clip fades, negative read offsets, reads running past a source's end, mono content on a stereo stem, overlapping windows, constant-power pan, master gain, and loop folding past the declared length. Verified against the old TypeScript path directly, comparing whole files.

So no cached artifact is invalidated and nothing re-renders. Stem and mix goldens join the effects one, since the summing paths are new arithmetic the effects golden says nothing about.

What deliberately did not move

The rate and channel-count checks stay in the control plane. They read WAV headers now rather than decoding whole files — wav.ts grows readWavHeader, and wavFrameCount shares its chunk walk. The reason is that those two messages are user-facing diagnostics, and diagnostics belong where every other diagnostic lives rather than duplicated into C++ where they would drift out of step. The daemon does arithmetic; the control plane does explaining.

One hazard worth naming

applyDeclaredLength folds the overhang by striding through the buffer in declared-sized steps. A zero-length declaration would advance by nothing and spin forever, so it is guarded — a hang is the worst way to discover a degenerate input.

After this

src/audio/insert-chain.ts and the DSP beneath it execute nothing. They are dead code with passing tests, which is exactly the state chunk 4 exists to clear.

Verification

  • macOS — 343 passed, including the two new goldens.
  • pnpm typecheck passes; the native build is warning-free in our own sources.
  • Stem and mix output compared against the old TypeScript implementation over a fixture built to hit the awkward cases; both byte-identical.

One caveat, stated because the last two PRs did better: Docker is not running on this machine right now, so unlike #52 and #53 I could not do a local Linux container run before opening. CI's Linux job is the check, and the two new goldens are precisely the assertion that would catch a cross-platform divergence — but this was not pre-verified locally.


Note

Medium Risk
Core offline render path for stems and mixes moves to native C++ with a new plan protocol version; regressions would affect all track/mix builds, though byte-identical verification and golden hashes mitigate cross-platform drift.

Overview
Stem and mix builds now run in field-audiod, alongside standalone effects. Generators spawn --render with an op discriminant (effects, stem, mix) and RENDER_PLAN_VERSION 2.

Summing is implemented in mixdown.cpp: clip placement into stems, stem summing through faders (constant-power pan), then for mixes master gain, master insert chain, and declared length with optional loop folding—in the order required by effects.md §5.

Control plane still validates sample rate and channel count via readWavHeader (no full decode); stem/mix generators delegate arithmetic to the daemon.

Two new SHA-256 golden tests lock stem and mix bytes cross-platform; existing effects tests use op: 'effects'. Output matches the prior TypeScript path, so no rule_version bump and cached artifacts stay valid. insert-chain.ts is unused until chunk 4 removes it.

Reviewed by Cursor Bugbot for commit b340df9. Configure here.

track-render and mix call field-audiod --render, so the plan grows an op
discriminant (effects, stem, mix) and RENDER_PLAN_VERSION goes to 2.
Summing lives in native/audiod/src/dsp/mixdown.cpp: placed clips into a
stem, stems through faders into a mix, then master gain, master chain and
the declared length in that order.

Byte-identical again, including the awkward paths — clip fades, negative
read offsets, reads past a source's end, mono content on a stereo stem,
constant-power pan, and loop folding past the declared length. So no
rule_version bump and no re-render, as with chunk 2. Stem and mix goldens
join the effects one.

What did not move: the rate and channel-count checks stay in the control
plane, reading WAV headers rather than decoding. Their messages are
user-facing diagnostics and belong with every other diagnostic rather
than duplicated into C++ where they would drift. wav.ts grows
readWavHeader for that, and wavFrameCount now shares its chunk walk.

Musical time stays where decision 7 put it. Clips arrive already resolved
to sample offsets, so mixdown.cpp has no idea what a bar is.

One hazard worth naming: applyDeclaredLength folds the overhang by
striding backwards through the buffer, and a zero-length declaration
would advance by nothing and spin forever. Guarded, because a hang is the
worst way to discover a degenerate input.

After this, src/audio/insert-chain.ts and the DSP beneath it execute
nothing — dead code with passing tests, which is what chunk 4 clears.

macOS 343/343. Docker is not running on this machine at the moment, so
unlike #52 and #53 the Linux check is CI's rather than a local container
run; the two new goldens are exactly the assertion that would catch a
divergence.
Comment thread native/audiod/src/dsp/mixdown.cpp Resolved
Two review findings, the first of them a repeat of the one #53 fixed.

sumClips skipped a clip naming an input outside the source list, and
sumStems skipped a stem with no channels. Both wrote plausible audio and
exited 0, cached under an action key still describing what was dropped —
exactly the fail-closed rule decision 6 states and the unknown-effect and
unknown-band-type checks already follow. I wrote the silent version one
PR after fixing the same class of bug.

Worth naming why it looked ordinary: three lines below the bad continue
sits a legitimate one, where reads outside a source are silence so slip
never errors (project-core.md §3.2). The legitimacy of the second made
the first read as normal. Both comments now say which is which, and there
are tests for both — the rejection and the slip that must still render.

The 15 committed clangd index files came in with git add -A after
CMAKE_EXPORT_COMPILE_COMMANDS was enabled in #53. Removed, and
native/audiod/.cache/ is ignored so they do not return.

All three goldens are unchanged, confirming the fix touches only paths
that previously produced wrong output. macOS 345/345.
Comment thread native/audiod/src/render.cpp Resolved
Third finding of the same class, and the reviewer drew the line precisely:
reject an absent or non-array `clips`, but keep allowing an explicitly
empty one.

Reproduced, and one case was worse than reported. A missing `clips`
rendered a zero-frame stem at exit 0, as reported; a non-array `clips`
did the same, which was not covered. The mix had the twin: `faders`
missing was caught only incidentally by the count check, so it slipped
through whenever `inputs` was also empty.

The rule now has a name in the code. Required-by-schema arrays — clips,
inputs, faders — must be present and be arrays, empty allowed. Optional
ones — inserts, master — stay conditional, because they are genuinely
omitted when they have no entries so insert-less stems keep their
pre-inserts action keys. That is the distinction the three bugs blurred:
optionality of the schema, not convenience at the call site.

Two tests, again for both sides: malformed plans rejected, and an
explicitly empty clip list still rendering a valid zero-frame stem. The
second is there so a later tightening cannot turn a legitimate state into
an error and look like a fix.

macOS 347/347. Docker is back, so this head also ran the full suite in an
ubuntu:24.04 container: 337 passed, 10 skipped, 0 failed — the three
goldens among them, which is the cross-platform check #54 originally had
to leave to CI.
Comment thread native/audiod/src/render.cpp Resolved
Fourth finding of the same class, in the one function I left untouched
while fixing its siblings. applyChain still used the permissive
if-getArray pattern, so all four malformed shapes rendered as though the
chain were absent: an effects plan with no inserts at all (they are
required there), and a present-but-not-an-array inserts or master on any
op.

The fix carries the schema's own optionality into the call rather than
inferring it from the value: effects always serializes inserts, while a
stem's inserts and a mix's master are omitted when empty — and that
omission is exactly what keeps insert-less stems on their pre-inserts
action keys, so it has to stay legal. Optional therefore means absent is
allowed; present-but-wrong is a shape mismatch on every op.

One test covering both directions across all three ops: four malformed
plans rejected, and both optional chains still rendering when omitted.

macOS 348/348; ubuntu:24.04 container 338 passed, 10 skipped, 0 failed.
Comment thread native/audiod/src/render.cpp Resolved
Comment thread native/audiod/src/dsp/mixdown.cpp Resolved
Two P1s from an exhaustive audit, sharing one root: the plan was consumed
without ever being validated.

The parser failed open everywhere it had not been patched. juce::var
coerces freely, so ceiling_db: {} became a 0 dB limiter and clip.duration:
{} a zero-frame stem; version: 2.9 passed the exact gate by truncation;
unknown keys were ignored, which is precisely the additive-field hazard
decision 6 names; an EQ with bands: [] was a byte-identical no-op;
length_samples: -1 read as absent; loop without a length was dropped. 126
of 263 mutations were accepted.

And one was memory-unsafe rather than merely wrong: start: -1 allocated
for the clip's end, then indexed before the output buffer. Reproduced
under AddressSanitizer — heap-buffer-overflow, 4-byte read before a
16-byte allocation — and it now throws instead.

So validation happens once, in plan.cpp, before dispatch: types that
reject coercion, allowed keys, required and optional fields per op and per
effect, collection sizes, the unsafe-value domains, and the one
cross-field rule. Downstream code consumes only a plan already proven to
match.

Two lines drawn on purpose. It does not mirror zod's user-input ranges —
frequency within 10-24000 is zod's job on the way in, and duplicating
every bound would create the drift this exists to prevent. And
read_offset stays unbounded, because reads outside a source are declared
silence; that is what slip is.

sumClips keeps a negative-placement check as well. Unlike most such pairs
that redundancy earns its place: the consequence there is not a wrong
render but a write outside the allocation, so a future parser regression
should produce an error rather than corruption.

The five earlier rejection tests now fail in the validator with
path-prefixed messages, and are updated to expect them. A new test walks
the audit's own matrix.

macOS 349/349; ubuntu:24.04 container 339 passed, 10 skipped, 0 failed.
Comment thread native/audiod/src/plan.cpp Resolved
ninjudd added 2 commits August 7, 2026 17:17
Review was right and my line was wrong. The validator enforced structure
but left the numeric ranges to the control plane, arguing a second copy
would drift. The rebuttal is decisive: the file already mirrored names,
types, cardinalities and some bounds, so a partial copy carried the same
drift risk with none of the coverage.

And the omitted ranges were not merely odd values. bandwidth: 0 makes a
bell an identity filter; ceiling_db: 1 leaves audio untouched. Both
rendered byte-identical to their input under action keys naming an EQ and
a limiter — the exact failure the validator was added to close.

So the bounds are generated. scripts/gen-plan-limits.ts reads the zod
schemas through z.toJSONSchema and emits
native/audiod/src/plan-limits.h; a test regenerates and compares, so a
widened range cannot land without the daemon following it. zod stays the
single source of truth project-core.md §5 already says it is. The drift
objection was real — generating answers it, omission did not.

Now rejected, each verified individually: all three EQ band ranges, band
count outside 1-8, all three limiter ranges, all four reverb ranges,
sample rates outside the supported set, zero-length clips, fractional
fades, fades exceeding their clip, and a zero declared length under loop.

read_offset stays unbounded, and that one is principled: reads outside a
source are declared silence. Bounding it would break slip while looking
like rigour.

macOS 352/352; ubuntu:24.04 container 342 passed, 10 skipped, 0 failed.
The plan still carried the reasoning review overturned: that mirroring
zod's ranges would drift, so the validator should enforce structure only.
A partial mirror had the same drift risk with none of the coverage, and
the omitted ranges were the ones that rendered no-ops under keys
describing real work. Generation is what answers the drift objection.
Comment thread native/audiod/src/plan.cpp Resolved
The validator required length_samples >= 1, which rejected a zero-length
bounce whether or not it looped. Only looping needs it positive: that is
where the fold stride would be zero and spin. A declared length of zero is
an empty bounce, and the reference produced exactly that — so rejecting it
narrowed behaviour while looking like rigour.

length_samples is now >= 0, and the cross-field rule checks for a positive
length rather than merely a present one, so loop at zero is still refused.

Tests for both sides, as with the other pairs in this file: the looping
case rejected, the non-looping zero-length mix still writing its
zero-frame WAV.

macOS 353/353; ubuntu:24.04 container 343 passed, 10 skipped, 0 failed.

@ninjudd ninjudd left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 3775066 as a fresh protocol-validation head. No findings.

Verification:

  • Rebuilt and froze the exact native binary.
  • Reran the complete 298-case plan matrix: all 264 malformed cases rejected, all 34 valid controls accepted, zero crashes/timeouts.
  • Confirmed the two sides of the corrected rule: length_samples: 0 renders when not looping; looping with absent or zero length rejects.
  • Native build and typecheck pass.
  • Focused render/generator suite passes: 18/18; regenerating plan-limits.h leaves the committed header unchanged.
  • Both GitHub jobs are green and all review threads are resolved.

@ninjudd
ninjudd merged commit 7589c0a into main Aug 8, 2026
2 checks passed
ninjudd added a commit that referenced this pull request Aug 8, 2026
…convert retires (#57)

Chunk 5, and the last of this plan. Sample-rate conversion moves into
the daemon's built-in tier, `normalize` renders through it, `say` is
deleted, and nothing in the build shells out to a macOS binary any more.

## The resampler

Fixed-ratio polyphase FIR, Kaiser-windowed sinc prototype, 128 taps per
phase. The six project rates are pairwise rational with small
denominators — 44.1→48k is exactly 160/147 — so every conversion field
supports has precomputable per-phase coefficient rows. The stopband edge
sits at the **lower** of the two Nyquist frequencies, which is the one
detail that makes a single routine correct in both directions.

Measured on the built binary:

| | |
| --- | --- |
| Passband 100 Hz – 19 kHz | flat to ±0.0000 dB |
| Passband at 20 kHz | −0.009 dB |
| Downsample 96→44.1k, image rejection | −103 dB at 23 kHz, −113 to −119
above |
| Length, 2 s at 44.1k → 48k | 88200 → 96000 exactly |
| Same-rate conversion | bit-exact identity (1:1 ratio returns the
input, it does not filter it) |

**JUCE's `WindowedSinc` was rejected on evidence, not preference.**
`interpolateImpl` advances `pos += speedRatio` against a kernel whose
width never depends on `speedRatio`. Downsampling therefore filters at
the *input* Nyquist and folds everything above the output Nyquist back
into the band — not a quality difference but aliasing, and disqualifying
for half the conversions the schema permits. The §3 table said "probably
usable"; it now says why it is not.

## The one rule that is not byte-identical

Every prior chunk transliterated a TypeScript reference and could prove
equality against it, so all of them landed with no `rule_version` bump
and no re-render. This one displaced a macOS binary there was never any
way to diff against, so `normalize` goes to `version: 2` and its
artifacts re-render once. That is the cost chunks 2 and 3 priced and did
not incur, arriving here instead.

## With no oracle, the properties are the specification

So they were mutation-tested before being believed. Six properties,
measured through the build rules:

| Mutation in `resample.cpp` | Result |
| --- | --- |
| filter at the input Nyquist (the JUCE failure mode) | 30 kHz folds
into a 44.1k file at 14.1 kHz and **0 dB** — aliasing property fails,
five stay green |
| `tpdf = 0.0` (no dither) | sub-LSB signal quantizes to digital black —
dither property fails, five stay green |

Each mutation is caught by exactly one property, which is what says they
carry distinct weight rather than overlapping.

The normalize golden downsamples 96k→44.1k at 24-bit deliberately: that
is the direction with the anti-alias filter engaged, and it puts the
dither sequence in the hashed bytes. Designing the prototype calls libm
`sin` several thousand times, so the digest is also the check that
Apple's libm and glibc still agree.

## `say` is deleted

`say.ts` held the second `afconvert` call — the AIFF macOS `say` emits,
converted to a WAV at the project rate. Our reader does not read AIFF,
so keeping the rule meant teaching the daemon a second container format
for one macOS-only rule, or keeping `afconvert` for that rule alone.
Either way the dependency survives.

This overturns `voice-generation.md` decision 1, which had `say` staying
as the hermetic in-graph recipe opposite the generated tier, so §5 there
records what changed rather than diverging quietly — **including the
cost, which is real**: that plan is deferred and not started, so bloom's
creek loses the source for its two `lead-vocal` clips and its
`vocal-96k` normalize until something replaces it. An imported recording
is the stopgap, which is what a scratch vocal is anyway.

Deleting it means **all nine** platform-guarded tests retire rather than
the three a resampler alone would have freed. `src/testing/platform.ts`
goes with them: both probes had no callers left, and a file of nothing
but tombstones is worse than none.

## Also

The bit-depth set is generated from zod alongside the rate set rather
than copied, following #54's rule that a partial copy of a schema is
itself schema drift. And the pre-existing `-Wfloat-equal` in
`validateSampleRate` is fixed rather than duplicated — `checkObject` has
already proved the value is an integer, so set membership is an integer
question. The native build is warning-free in our own sources again.

## Review round (7 findings, all correct)

**P1 — `bit_depth: 32` had regressed from integer PCM to IEEE float.**
`afconvert` was asked for `LEI32`, and linux-portability decision 1 says
that float-to-integer conversion stands, so writing format tag 3 changed
the meaning of an existing schema value under a version bump that only
claims to change bytes. `writeWavInt` handles 32 now, undithered — its
step is ~186 dB down, finer than the float32 input can resolve.

It slipped because a decoded sample sits on the same grid whichever
writer ran, so the grid test could not see the writer selection at all.
`WavHeader` now exposes `format` and `bitsPerSample` and the properties
assert both.

**Four coverage holes**, each reproduced before fixing, each now failing
exactly one property while the other eight stay green:

| Mutation | Was | Now |
| --- | --- | --- |
| 16-bit through the float writer | 6/6 passed | format property fails |
| `tapsPerPhase` 128 → 32 | 6/6 passed (19 kHz fell 16 dB) | passband
property fails |
| input replaced by dither alone | 6/6 passed | dither property fails |
| `outN` floored | 6/6 passed | short-source property fails |

**Two more in the code.** A two-frame 96 kHz source floored to an empty
44.1 kHz file — a one-shot vanishing under a successful action key,
where afconvert produced one frame; the rule is now round-half-up with a
one-frame floor for any non-empty source. And odd `data` chunks went
unpadded, which only 24-bit mono with an odd frame count can reach — our
own reader already advanced by `size + (size % 2)`, so the writer was
out of step with its own reader.

**Two doc findings**, both stale in opposite directions: the plan's open
questions contradicted its own Shipped status, and `stem.ts` told users
to fix a rate mismatch with `afconvert` — a tool this PR deletes and
Linux never had.

The golden is unchanged, which is expected rather than lucky: it is
24-bit stereo at an integral length, so it touches none of the three
paths that moved.

## Verification

346 tests pass, `pnpm typecheck` clean, native build clean and
warning-free in our own sources. `RENDER_PLAN_VERSION` is 3.
@ninjudd
ninjudd deleted the render/stems-and-mixes branch September 28, 2026 04:11
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