feat(studio): the geometry and plumbing behind automation lanes (#3023)

* feat(core): audio FX registry

One declarative description of every effect that can be applied to an audio
track: fourteen across filters, dynamics, non-linear and time, each exposing
its full parameter surface rather than a curated subset.

Parameters carry the range, step, unit and scale a control needs, so a panel
can generate its UI from this rather than hard-coding a form per effect, and a
value that survives `normalizeAudioFxParams` is always safe to realise.
Everything is declared in the units a person thinks in — dB, ms, Hz.

Parsing rejects an unknown effect id rather than skipping the node. A chain
that quietly loses an effect renders something other than what was authored,
which is worse than refusing to load it.

Data only: no audio is produced here. The graph that realises each effect is
referenced by the `web` id and lands in the next change, which keeps this
module free of browser globals so the engine and the linter can import it.

* fix(core): stop declaring knobs that move nothing

Three parameters were declared with ranges, defaults and hints, and read by no
builder — dials an author could turn with no audible result.

- `chorus.decay` and `bitcrush.aa`: removed. FFmpeg's chorus feeds a decay back
  into its delay line and a bitcrusher's anti-alias needs a real filter; adding
  either is new DSP, not a fix, so the honest move is to stop advertising them.
- `lowshelf.q` / `highshelf.q`: removed. The Web Audio spec leaves Q unused for
  shelving filters, so the control moved nothing — and because the shared Q
  helper marks it automatable, an author could draw an envelope on it and hear
  nothing at all.

`phaser.decay` and `gate.knee` stay: the first drives the sweep depth, and the
second is now read by the gate's processor.

A test asserts each of these directly, since the existing exposure invariant only
checks that a flagged parameter reaches an AudioParam — a parameter the node then
ignores passes it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(core): Web Audio graphs for the FX registry

One graph builder per `web` id, turning the registry's declarations into
running audio.

Every node exposes `update`, so turning a dial re-parameterises the live graph
rather than rebuilding it: an AudioParam change lands on the next 128-sample
quantum, about 2.7 ms at 48 kHz. `buildFxChain` reports whether an update could
be applied in place — adding or bypassing an effect, or switching a filter
between one and two poles (which changes the node type from BiquadFilterNode to
IIRFilterNode), changes the graph's shape and returns false so the caller
rebuilds.

Four effects have no native node and run as AudioWorklet processors:
compressor, limiter, gate and bitcrush. The module is registered from a data:
URL rather than a blob:, because a blob inherits the page origin and is opaque
on a file:// page, where it fails with an unhelpful AbortError.

Reverb has no single node either. `synthesizeReverbImpulse` generates a tail
from the room parameters, seeded so the same room sounds the same on every
machine, and the ConvolverNode uses it.

Tests cover the wiring — which nodes get built, how they connect, parameter
application and clamping, in-place update versus rebuild, disposal — against a
fake AudioContext, since happy-dom has no Web Audio.

* fix(core): reverb level, phaser wiring, per-channel dynamics, one-pole rebuild

Four defects in the graph builders, all found by review rather than by ear.

**Reverb was unusable at its own defaults.** A ConvolverNode applies the
impulse's gain whole — the graph sets `normalize = false` so a room is
deterministic rather than browser-defined — but the impulse was raw decaying
noise. Measured L2 at the registry default (size 0.7 / damping 0.5): 46.4, or
+33.3 dB, putting the wet path ~24 dB over dry at the default `wet: 0.35`. It is
now normalised to unit energy, so the wet knob means what it says. Preview and
render both convolve this buffer, so they stayed identical throughout — equally
deafening before, equally correct now.

**Phaser in_gain/out_gain trim the signal entering and leaving the effect**, not
a wet/dry pair. Wired to the wet and dry legs, "Input" muted the dry path and
the two defaults summed to 1.14, so inserting a phaser raised the track level.
They are now input and output trims with the legs summed at unity. Its declared
waveform is also honoured: `lfo.type` was never assigned, so the default
"Triangular" was silently a sine.

**The dynamics worklets held one envelope across a channel-major loop.** The
followers advance per sample, so on stereo a 20 ms attack behaved as 10 ms, and
the right channel's gain came from an envelope that had already traversed the
left — the two ducked differently from the same input and the image pumped.
State is now per channel, as is the gate's smoothed gain and bitcrush's
sample-hold counter, which previously advanced only on the last channel and left
every earlier one frozen for a whole quantum. The gate also honours the knee it
declares instead of chattering on material sitting at the threshold.

**A one-pole filter's cutoff was swallowed in preview.** Its coefficients are
fixed at construction, so `update` cannot push a new frequency — but the shape
signature carried only type and pole count, so a cutoff change looked like a
values-only edit and went into a no-op updater. Preview kept filtering at the
old frequency while the render used the new one: a preview/render divergence in
exactly the two effects that do not use a BiquadFilterNode.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(engine): render audio FX in an OfflineAudioContext

Reads `data-fx-chain` off an audio element and runs the chain over the trimmed
WAV before volume automation is baked in — effects should see the raw signal,
and the envelope belongs on their output.

The processing happens in an OfflineAudioContext inside the headless browser
the engine already drives, running the same graph builders the studio previews
with. That is the point of the approach: one implementation per effect, so the
render agreeing with the preview is a property of the architecture rather than
a tolerance to police. Reimplementing each effect as an FFmpeg filter would
mean two implementations to keep in step, and for the dynamics processors and
modulated delays there is no filter that behaves the same way.

`build:audio-fx-runtime` bundles the graph builders into an injectable IIFE,
following the same pattern as the existing runtime artifacts, so the browser
runs exactly the code the studio does.

The page loads from a file:// URL rather than about:blank because AudioWorklet
is only exposed in a secure context — the compressor, limiter, gate and
bitcrush processors would otherwise fail to register with an opaque error.
file:// qualifies and needs no listening socket.

The chain is serialised into the attribute the way colour grading carries its
config, so there is no side-car file to resolve or lose.

An FX failure is fatal for the whole mix rather than a per-track soft failure.
Every other audio failure mode degrades gracefully — the track drops, siblings
continue — but substituting the dry signal for a processed one ships a render
that sounds plausible and is not what the author set up. Since the per-element
work races under Promise.all, an internal AbortController chained off the
caller's signal aborts in-flight siblings before workDir is removed.

* feat(core): voiceover carve analysis

Finds the bands a voice occupies so a music bed can be dipped there, letting
the voice sit in front without ducking the whole track.

Carve is a relationship between two tracks rather than an effect on one, so it
stays out of the FX chain. What it emits is an ordinary chain of peaking
filters, so a carve composes with whatever else is on the track and needs no
separate rendering path.

Selection is weighted toward intelligibility rather than raw voice energy.
Ranking purely by power lands on the fundamental almost every time, because
that is where a voice is loudest — but the masking that actually hurts a
voiceover happens higher up, and dipping 160 Hz mostly just thins the bed. The
bias is a control, not a constant: at 0 it follows raw energy, at 1 it weights
toward 1-3 kHz.

Ranking happens in dB, which matters more than it looks. Speech spreads 20-30 dB
across these bands — it falls off roughly 6 dB per octave above the fundamental
— so a weighting has to be on that scale to move anything at all. A
multiplicative weight of `1 - bias + bias * shaped` is bounded below by
`1 - bias`, capping its influence at 10*log10(1/(1 - bias)): 5.2 dB at the 0.7
default, 3 dB at 0.5. That is no influence against a real voice — every bias
short of ~0.95 would rank exactly like bias 0 and carve the fundamental, the
outcome the bias exists to prevent, while looking decisive against a fixture
whose bands sit 2 dB apart. So the bias is a dB penalty, zero at 2 kHz and worth
up to 30 dB at full strength, and relative cut depths come from a dB difference
rather than a ratio of weighted linear powers.

The bias reweights ranking without overriding the spectrum — a band the voice
has no energy in is not worth carving, and scores -Infinity rather than
competing — so a strongly low-pitched voice can still select low at full bias.
What the tests hold is that biasing never selects lower than the unbiased
ranking, that the DEFAULT bias reaches the presence region on a voice with a
realistic tilt, and that bias 0 still follows raw power exactly.

Includes a radix-2 FFT rather than a dependency; one Welch-style averaged
spectrum over third-octave bands does not justify pulling in a DSP library.

* fix(engine): keep the FX render 16-bit, stereo, and correctly sized

Three defects in the offline FX path, none of which any test could see.

**Float output silently disabled sample-accurate volume automation.** The writer
emitted 32-bit IEEE float; the very next mixer step bakes the volume envelope
into the samples and accepts only 16-bit PCM, returning null otherwise. So
enabling any effect downgraded that track to the ffmpeg expression path — capped
at 32 straight segments, quantising a curved envelope, and on a dense one falling
back to base volume. It now writes 16-bit PCM, clamped rather than wrapped so a
limiter at 0 dB or a resonant filter cannot turn overshoot into a click. A test
asserts the baker accepts the writer's own output and actually fades it.

**Everything was folded to mono.** `prepareAudioTrack` goes out of its way to
emit stereo — its pan filter exists to dodge ffmpeg's 3 dB mono-to-stereo
rematrix — and this folded it, then wrote one channel. So adding a single peaking
EQ collapsed a bed's width and cost ~3 dB in the render, while preview stayed
stereo. Channels now travel as one plane each, through an OfflineAudioContext of
the same width, and come back interleaved.

**Small results decoded the wrong length.** `new Float32Array(buf.buffer)`
discards byteOffset and byteLength, and Node pools small allocations: a 400-byte
payload sits at offset 8 inside an 8 KiB pool, so a clip under ~1024 samples
decoded as 2048 samples of unrelated memory — and the empty-result guard could
not see it. The reader has the mirror-image fix: a float data chunk on an odd
boundary (ffmpeg's pcm_f32le writes fmt(18) + fact, landing `data` at 58) now
copies instead of throwing RangeError on an unaligned view.

The tail limitation is now stated rather than mis-stated: the context is exactly
as long as the input, so a reverb or delay still ringing is cut there. The old
comment claimed the opposite. How far a tail may run past a clip's end changes
the clip's length in the mix, so it is a product decision, not one to make here.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(producer): report an FX render failure as an audio error

`processCompositionAudio` reports per-track failures in its result, but an FX
failure it cannot degrade past — a browser that will not launch, a chain that
will not build — rejects instead. `runAudioStage` had no try, so that rejection
escaped to the orchestrator as an unclassified pipeline exception, losing the
stage/owner/retryable classification this stage exists to attach, and skipping
its abort check on the way out.

It now lands in `audioError` alongside every other cause, while an abort still
keeps its own shape rather than being reported as an audio problem.

Not done here: committing the generated `audio-fx-runtime-inline.ts` so a fresh
clone typechecks packages/engine without building first. The bundle is built from
the stub, and the stub changes three times across this stack — so the artifact
differs per branch and would conflict on every restack. Its model,
position-edits-render-inline.ts, is committed only because it is stable. Building
before testing is this monorepo's existing contract (studio's tests need core's
dist too), so the gap is not specific to audio FX and is better closed by a build
ordering gate than by committing a per-branch artifact.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(engine): skip the browser FX render cases when there is no browser

CI's `Test` job was red on this PR with four failures, all the same cause:

  Failed to launch the browser process: spawn
  /home/runner/.cache/hyperframes/chrome/chrome-headless-shell

The job installs ffmpeg and no browser, deliberately — every other suite
that needs an external binary already guards on it
(`describe.skipIf(!HAS_FFMPEG)`). These cases were the only ones assuming
a Chrome, so they failed on an absent dependency rather than on anything
about the code.

Guards on `resolveHeadlessShellPath()` — the same resolver
`acquireBrowser` launches through, so the check cannot drift from the
thing it guards the way a hard-coded cache path would. A configured path
that does not exist throws; that is caught and read as "cannot run here".

Checked both directions rather than just the green one: with a browser all
11 cases run and pass, and with `HYPERFRAMES_BROWSER_PATH` pointed at a
missing binary exactly 3 skip and the other 8 still run. A guard that
silently skipped everything would have looked identical in CI.

They keep their value where it exists — every developer machine, and any
job that has run `hyperframes browser ensure`.

Not touched: the CodeQL failure on this PR is a run from 2026-08-07, five
days and several force-pushes stale. None of the 17 open repo alerts are
in files this PR changes; it re-runs on this push.

* chore(engine): suppress the temp-file alert with the reason it is safe

CodeQL flags `writeWav`'s `writeFileSync` as js/insecure-temporary-file
(high) — the one new alert on #3021, and the reason its CodeQL check is
red.

It is a false positive, and the comment says why rather than just silencing
it: `path` is always inside a directory made by `mkdtempSync`, never a
name assembled directly under `tmpdir()`. Both callers are covered — the
browser host page writes into `mkdtempSync(join(tmpdir(), "hf-fx-host-"))`,
and the render output goes to the producer work dir, itself
`mkdtempSync(join(tempRoot, "producer-project-"))`. mkdtemp picks the
random suffix and creates the directory 0700 in one syscall, so the
predictable filename inside it cannot be pre-created or symlinked by
another user, which is the attack the rule is about. The analyzer sees the
dataflow reach `tmpdir()` and not the mkdtemp in between.

Suppressed inline rather than dismissed in the UI, so the justification
lives next to the code and the rule stays live for anything added later in
this file. Matches the repo's existing convention — `planV2.ts:222`
carries an `lgtm[js/insecure-temporary-file]` for a different reason on
the same rule.

Correcting myself: I first reported this alert as not real, having
intersected the PR's files against the default-branch alert list, which
does not contain PR-ref alerts. Querying ?ref=refs/pull/3021/merge returns
it straight away.

* feat(core): register the audio-fx-rack canary at 0%

Lands the rollout switch dark, per the registry's own procedure: "Start at
percentage: 0 and merge that — a canary at 0 is dead code you can land
safely and ramp without a code review."

Declared at the bottom of the stack so every branch above can read it. The
gate itself goes in at wa-4-fx-panel, where the rack first appears.

Scope is deliberate and stated in the description: it gates the AUTHORING
surface only. A composition that already carries `data-fx-chain` still
plays and renders it. A canary should stage who can REACH a feature, not
make an attribute somebody already wrote silently inert — an agent that
writes a chain through the skill would otherwise produce a file whose audio
processing vanishes with no error.

* feat(studio): audio FX panel generated from the registry

Controls for the whole chain: add, remove, reorder, bypass, and every knob each
effect declares.

Nothing in the panel knows what a compressor is. The registry supplies each
parameter's range, step, unit and scale and the panel renders what it finds, so
adding an effect or a knob upstream needs no change here, and the panel cannot
offer a value the renderer would reject — a typed-in figure is clamped into the
declared range on the way through.

Frequency and time controls span three or four decades, so those declare a log
scale and the slider maps exponentially; a linear slider would spend most of
its travel somewhere useless.

Reorder is a first-class control because chain order changes the sound: a
reverb before a compressor is not the same as after.

Carve gets its own block rather than an entry in the add menu, with a picker
for the voice track to listen to. It processes this track based on another one,
which is how a sidechain control works — it lives on the track that changes,
and names the source.

* feat(studio): show the Audio FX section on audio tracks

Adds `audioFx` to the editing-affordances contract and renders the FX panel in
the inspector when an `<audio>` element is selected.

The section is audio-only. A `<video>` carries its sound on a separate
`<audio>` element, so an FX chain on the video would have nothing to process.

Chain and carve settings are written straight back onto the element as
serialised attributes, the way colour grading carries its config, so
persistence is an ordinary attribute write and needs no new server route. A
chain that cannot be parsed renders as empty rather than breaking the panel,
and the attribute is left untouched until the user changes something.

The collapsed group summarises what is on the track ("2 effects + carve") so
the state is visible without expanding it.

Wired into PropertyPanelFlat rather than PropertyPanel: STUDIO_FLAT_INSPECTOR_ENABLED
defaults to true, so the flat inspector is what actually renders.

* refactor(studio): lift audioFxSummary out of PropertyPanelFlat

`PropertyPanelFlat.tsx` is 612 lines here against the repo's 600-line cap,
so the required File size check is red — the sole reason this PR is
blocked. The review says as much: "mechanical fix (~5 min), not a design
problem. Code itself is LGTM."

Moves `audioFxSummary` to `audioFxSummary.ts`, the same file a later
branch creates for it. Deliberately the smallest cut that clears the cap
rather than the whole `AudioFxGroup` extraction: every later commit in the
stack edits AudioFxGroup, so moving it here would collide with each of
them, while almost nothing touches this function.

595 lines.

* feat(studio): put the audio FX rack behind its canary

Gates the rack on `isCanaryEnabled("audio-fx-rack")`, which is registered
at 0% — so the whole 47-PR stack can land without showing anyone a feature
that has not been measured yet.

The gate sits on the AUTHORING surface and nowhere else. The runtime and
the render still honour a `data-fx-chain` already on an element, so a
composition written through the skill or by `carve.mjs` keeps its
processing rather than going silently dry for anyone outside the cohort. A
canary should stage who can REACH a feature, not make an attribute somebody
already wrote stop working with no error.

Gated at the panel rather than in `resolveEditingSections`: the affordance
resolver is a pure function in core describing what an element CAN support,
and rollout state is not a property of an `<audio>` tag.

Pinned the 0% with a test, and checked it fails at 25 — a ramp should have
to break something that says "this ships dark" out loud.

One gap, stated rather than papered over: the gate itself has no unit test.
I wrote one and deleted it, because `PropertyPanel.test.tsx`'s harness
never renders the Audio FX group for its audio fixture even with the gate
removed — so the test passed for the wrong reason in the off case and could
not pass at all in the on case. A test that cannot fail for the right
reason is worse than none. Verifying the gate needs the panel harness to
mount that section first, which is its own change.

* feat(core,studio): hear the FX chain in preview, and run the carve analysis

Splices an element's FX chain into the playback graph so preview stops being
silent about effects, and wires the carve button that was previously inert.

The chain goes between the decoded source and its gain stage: effects see the
raw signal and volume automation rides on their output, matching the order the
offline render uses. Since preview and render call the same graph builders,
what is heard while scrubbing is what gets written.

The splice lives in the transport rather than on the `<audio>` element. The
transport plays each track from a decoded AudioBuffer and mutes the element to
avoid doubling, so capturing the element with createMediaElementSource would
have processed a stream nothing is listening to — it looked like it worked
because the call succeeded, and the audio was unchanged.

A chain that cannot be built plays dry rather than silencing the track, which
is the right failure in preview: the author keeps working and hears the source.
The render still refuses, because shipping the dry signal there would be wrong.

Carve now analyses for real: it decodes the chosen voice track, ranks its bands
and writes the resulting peaking filters onto this track. Generated nodes are
tagged `fromCarve`, so re-running replaces the previous carve instead of
stacking another set on top of hand-added effects.

Known limitation: the graph is built when a source is scheduled, so a knob
turned mid-playback takes effect on the next play or seek rather than
immediately. Live re-parameterisation needs the transport to hold the handle
and forward updates.

* fix(studio,core): stop parameter drags from restarting playback

Dragging a knob wrote the chain through the persisting attribute path on every
input event. That path refreshes the preview, which reloads the composition and
reschedules audio — so a single drag reloaded dozens of times and playback
stuttered the whole way.

Drags now go through `onSetAttributeLive`, the same path colour grading uses for
scrubs: it coalesces undo entries and sets `skipRefresh`, so no reload happens.
The persisting write fires once, when the gesture ends — pointer-up or blur for
a slider, Enter or blur for a typed value. A select commits immediately since
there is no drag to wait for.

While dragging, the control is driven from local state. Waiting for the value to
round-trip through the element attribute made the knob lag behind the pointer.

For the change to be audible without a reload, the graph now follows the
attribute: the chain installed by the transport observes the element and
re-parameterises itself in place, so a value change lands on the next
128-sample quantum. A shape change (effect added, bypassed, pole count) cannot
be patched into a running graph, so it still waits for the next schedule rather
than cutting the audio mid-play.

The regression test drags a slider through several values and asserts the
persisting handler is untouched until release.

* fix(core): register FX worklets before building nodes that need them

An AudioWorkletNode cannot be constructed before its processor is registered —
it throws, and the surrounding chain is lost with it. `attachElementFxChain`
built the chain first and only then called `ensureAudioFxWorklets`, so every
worklet-backed effect (compressor, limiter, gate, bitcrush) threw on
construction and the track fell back to dry. Instrumenting the preview showed
`hf-compressor: InvalidStateError` with addModule never called at all.

When the module has not landed yet the track now plays dry and the graph is
swapped in once registration resolves, so the effect arrives a moment late
instead of never.

Registration is also tracked per context rather than in one module-level
promise. A processor registered on one AudioContext does not exist on another,
so the shared promise made every context after the first believe it was ready
when it was not — the studio's transport owns its own context, which is exactly
that case.

With the worklets actually running, the compressor's per-sample log10 and pow
became real audio-thread work. Samples below the knee have a gain of exactly
unity and need neither, so the envelope is now compared in the linear domain
and the transcendentals only run for samples that are actually being
compressed.

* refactor(studio): split the FX node row out of FxSection

Clears the health findings the FX stack left behind: the chain-node render
callback was a 70-line closure over half of FxSection's state, and the two
reorder arrows were the same button written twice.

Also drops two exports with no consumers, and registers the audio FX runtime
stub as an entry point — it is bundled by file path, so nothing imports it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(studio): lift the audio FX group out of PropertyPanelFlat

`PropertyPanelFlat.tsx` was 672 lines against the repo's 600-line cap, so
the required File size check was red — the sole reason #3014 and #3022 are
blocked. Both reviews say the same thing: "mechanical fix, not a design
problem. Code itself is LGTM."

Moves `AudioFxGroup` and `audioFxSummary` into
`propertyPanelAudioFxGroup.tsx`, which is where a later branch puts them
anyway — done here so the file is under the cap from the point it first
crosses it, rather than ten branches later.

533 lines now. The four audio imports it no longer needs go with it.

Not fixed here: three `FxSection carve` tests fail on this branch with
"Cannot read properties of undefined (reading 'toFixed')". Confirmed
pre-existing by stashing this change and re-running — that is the separate
`Test` failure the review also flags.

* feat(core): automation envelope model for audio tracks

Adds the data model behind Ableton-style automation lanes: breakpoint
envelopes over track volume or one knob of one effect in the track's FX
chain, stored on the element as `data-automation`.

Times are clip-local, so an envelope travels with the clip when it moves —
the clip-envelope model rather than arrangement automation.

`sampleAutomationLane` is the single interpolator. The lane drawing, the
preview scheduler and the render bake all call it, so the picture and the
sound cannot disagree about the curve. Log-scaled parameters interpolate in
log space, matching what their own knob already promises.

FX nodes gain a stable `id`, minted by count rather than randomly so the
document is the same on every machine. Lanes address nodes by id, so
reordering a chain never re-points a lane at a different effect, and a lane
whose effect was deleted is dropped rather than left to reattach.

Also warns when a track carries both a volume lane and a GSAP volume tween,
since only the lane is heard and the tween silently does nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(core): expose the AudioParams behind automatable FX knobs

Marks the knobs an automation lane can drive and has each graph builder hand
back the AudioParam behind them, so a scheduler can write to a running effect
without knowing what the effect is.

A knob is not always one AudioParam. A wet/dry mix is two gains moving in
opposition, and a knob in milliseconds drives a delay time in seconds, so
each target carries the mapping out of the knob's own declared unit.

What stays unautomatable is stated where it is decided: a WaveShaper curve, a
convolution impulse and a one-pole filter's coefficients are all rebuilt
wholesale rather than scheduled, and the four worklet effects take values by
postMessage rather than through AudioParams.

The registry flag is written by hand, so a test builds every effect and
checks the exposure both ways — nothing flagged is missing, nothing exposed
is unflagged. A flag that lied would offer a lane that silently did nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(core): play automation envelopes in preview

Schedules each lane onto the AudioParams behind its knob using native ramps
and value curves. Nothing evaluates the envelope per frame: it is handed to
the audio thread once, so it stays sample-accurate however busy the main
thread is, and the offline render will schedule it the same way.

Timing comes from the transport, so an envelope survives seeking into the
middle of a clip, a clip that has not started yet, and a playback rate that
compresses clip seconds into context seconds.

A straight line is only scheduled as a ramp when nothing bends it — no
curvature, a linear parameter scale, and no unit mapping. Log-scaled
parameters and mapped ones are sampled instead, since a delay knob in
milliseconds and a wet/dry pair moving in opposition are not linear in the
parameter they drive.

Lanes with nowhere to write are skipped rather than reported: a one-pole
filter exposes no frequency param, and the worklet effects expose none at
all. Editing an envelope mid-playback re-aims it at the live playhead rather
than restarting the track.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(engine): bake automation envelopes into the render

The offline render schedules FX lanes with the same scheduler preview uses,
inside the OfflineAudioContext that already runs the same graph builders. The
input WAV is the clip's own audio from its first sample, so clip-local time
is offline time and the envelope needs no offset.

Volume lanes take the existing PCM bake rather than a second mechanism: the
lane is converted to keyframes, so a straight fade stays two of them and only
a bent segment is sampled — the baker interpolates linearly and would
otherwise quietly straighten the curve. A volume lane supersedes keyframes
probed from the timeline, which `lint` already warns about.

A browser test sweeps a lowpass from below a 2 kHz tone to well above it and
measures both ends. Parsing the envelope is not the same as scheduling it,
and only running the real thing tells the two apart.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(core): make the volume lane audible in preview

The envelope was scheduled onto the transport's gain AudioParam, but the
runtime rewrites that gain every tick from `data-volume` and the GSAP-seeked
value — so it was erased within a frame. Volume automation was correct in the
render and inaudible while previewing.

The lane now feeds the per-tick path where the probed volume keyframes already
sit, checked ahead of them so the two cannot fight, and the transport no
longer schedules volume at all: one mechanism instead of two racing.

The cost is honest — in preview the level steps per tick rather than per
sample, exactly as the existing keyframe path does. The render still bakes it
into the PCM sample-accurately, and FX parameters are still scheduled on their
own AudioParams, since nothing rewrites those.

Parsed lanes are cached by attribute text: the runtime asks once per tick per
track, and parsing there would run the JSON parser 60 times a second for a
value that only changes on an edit.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(core): apply chain edits to the running graph

A structural edit — an effect added, removed, bypassed, or a filter's pole
count switched — was dropped. `buildFxChain`'s update reports false when the
change is not merely new values, and the attribute observer ignored that, so
the edit only took hold when the persisting write reloaded the composition.
That reload restarted every playing track, which is what was heard as the
audio chopping.

The graph is now swapped in place: the old effects are detached, the new ones
built and connected between the same source and gain, and any lanes
re-scheduled onto the new nodes. The source node is never touched, so playback
does not restart.

A track with no chain is watched too, rather than wired through and forgotten,
so adding its first effect is heard the same way. That means the function
always returns a disposer instead of null for the empty case.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(studio): the geometry and plumbing behind automation lanes

Everything an automation lane needs before there is a lane to look at, kept
apart from the component so the maths can be read and tested without a pointer.

`automationLaneGeometry` is pure: which parameters a clip can automate (its
fader, then each automatable knob of each effect that carries a node id), how a
value maps to a position in the lane, and how a lane is edited. Two decisions
live here and are worth review:

- A log-read knob maps on its own log scale, so the middle of a 100 Hz–20 kHz
  lane is the geometric mean. Dragging and drawing then agree with what the
  knob's own scale already promises.
- `withLane` replaces a lane in place rather than appending. A lane with no
  explicitly chosen parameter shows whichever comes first, so moving the edited
  one to the end would switch the lane out from under the pointer on the first
  edit.

`automationLaneData` parses the two attributes, cached by their text so the
identity only changes when the text does — the lane holds an optimistic draft
while a point is dragged and compares against that identity, and a fresh object
on every playhead tick would throw the drag away. It binds automation to the
chain the way preview and the render bind it, so a lane whose effect was deleted
is dropped rather than drawn against the wrong axis.

`useAutomationLanes` routes edits through the DOM edit session, targeting the
selected element because that is what the attribute commit path writes to.

Row height reserves each lane at its own height rather than counting it as
another keyframe lane, and `TimelinePropertyLanes` gains a footer slot so the
lanes share the keyframe disclosure — and its `aria-controls`.

`TimelineElement` moves to its own module: playerStore had reached the 600-line
studio ceiling exactly and could not carry another field. It is re-exported from
there, so no importer changes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* fix(studio): make automationLaneData reviewable, and evict one entry not all

The cache key held a literal NUL byte instead of its escape, so git classified
the whole module as binary: it landed as `Bin 0 -> 2677 bytes` with zero
diffable lines, invisible to review, to grep, and to any textual merge. The
escape is behaviour-identical.

With the file readable, two things in it needed fixing.

Eviction cleared the entire map. Clearing changes the identity of every lane's
automation at once, and a lane compares its drag draft against that identity —
so one unrelated element arriving at the limit would release an in-progress drag
and snap the point back. It now drops the oldest entry, and a hit is re-inserted
so it counts as recently used.

Nothing tested this module, which is what let the binary blob through. Now
covered: identity stability, re-parsing when the chain changes but the
automation text does not, a hot entry surviving 40 evictions, and an unreadable
attribute reading as nothing.

The geometry module's exports are ignored for dead-code while its consumer sits
one PR upstack, following the convention already used for the fast-capture
stack.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(studio): carry the audio FX attributes onto every timeline row

Both element builders read `data-fx-chain` and `data-automation` off the host
element, and an expanded sub-composition child is built without one — so an audio
track inside a sub-composition reserved no automation height and drew no lanes,
while the property panel, which reads the live DOM selection rather than the row,
still showed its chain and its toggles. `hostElementState` exists to re-inherit
exactly this class of host-only field; it now covers these two alongside
`hidden`, `timelineLocked` and `timelineRole`.

`parseTimelineFromDOM` had the same gap and now reads both directly.

Also exempts the offline FX render's browser entry from the health gate: it runs
only inside the headless page the engine drives, so its CRAP score is
coverage-driven rather than complexity-driven, and its behaviour is covered by the
engine's real-browser render tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(engine): render audio FX in an OfflineAudioContext

Reads `data-fx-chain` off an audio element and runs the chain over the trimmed
WAV before volume automation is baked in — effects should see the raw signal,
and the envelope belongs on their output.

The processing happens in an OfflineAudioContext inside the headless browser
the engine already drives, running the same graph builders the studio previews
with. That is the point of the approach: one implementation per effect, so the
render agreeing with the preview is a property of the architecture rather than
a tolerance to police. Reimplementing each effect as an FFmpeg filter would
mean two implementations to keep in step, and for the dynamics processors and
modulated delays there is no filter that behaves the same way.

`build:audio-fx-runtime` bundles the graph builders into an injectable IIFE,
following the same pattern as the existing runtime artifacts, so the browser
runs exactly the code the studio does.

The page loads from a file:// URL rather than about:blank because AudioWorklet
is only exposed in a secure context — the compressor, limiter, gate and
bitcrush processors would otherwise fail to register with an opaque error.
file:// qualifies and needs no listening socket.

The chain is serialised into the attribute the way colour grading carries its
config, so there is no side-car file to resolve or lose.

An FX failure is fatal for the whole mix rather than a per-track soft failure.
Every other audio failure mode degrades gracefully — the track drops, siblings
continue — but substituting the dry signal for a processed one ships a render
that sounds plausible and is not what the author set up. Since the per-element
work races under Promise.all, an internal AbortController chained off the
caller's signal aborts in-flight siblings before workDir is removed.

* feat(core): voiceover carve analysis

Finds the bands a voice occupies so a music bed can be dipped there, letting
the voice sit in front without ducking the whole track.

Carve is a relationship between two tracks rather than an effect on one, so it
stays out of the FX chain. What it emits is an ordinary chain of peaking
filters, so a carve composes with whatever else is on the track and needs no
separate rendering path.

Selection is weighted toward intelligibility rather than raw voice energy.
Ranking purely by power lands on the fundamental almost every time, because
that is where a voice is loudest — but the masking that actually hurts a
voiceover happens higher up, and dipping 160 Hz mostly just thins the bed. The
bias is a control, not a constant: at 0 it follows raw energy, at 1 it weights
toward 1-3 kHz.

Ranking happens in dB, which matters more than it looks. Speech spreads 20-30 dB
across these bands — it falls off roughly 6 dB per octave above the fundamental
— so a weighting has to be on that scale to move anything at all. A
multiplicative weight of `1 - bias + bias * shaped` is bounded below by
`1 - bias`, capping its influence at 10*log10(1/(1 - bias)): 5.2 dB at the 0.7
default, 3 dB at 0.5. That is no influence against a real voice — every bias
short of ~0.95 would rank exactly like bias 0 and carve the fundamental, the
outcome the bias exists to prevent, while looking decisive against a fixture
whose bands sit 2 dB apart. So the bias is a dB penalty, zero at 2 kHz and worth
up to 30 dB at full strength, and relative cut depths come from a dB difference
rather than a ratio of weighted linear powers.

The bias reweights ranking without overriding the spectrum — a band the voice
has no energy in is not worth carving, and scores -Infinity rather than
competing — so a strongly low-pitched voice can still select low at full bias.
What the tests hold is that biasing never selects lower than the unbiased
ranking, that the DEFAULT bias reaches the presence region on a voice with a
realistic tilt, and that bias 0 still follows raw power exactly.

Includes a radix-2 FFT rather than a dependency; one Welch-style averaged
spectrum over third-octave bands does not justify pulling in a DSP library.

* fix(engine): keep the FX render 16-bit, stereo, and correctly sized

Three defects in the offline FX path, none of which any test could see.

**Float output silently disabled sample-accurate volume automation.** The writer
emitted 32-bit IEEE float; the very next mixer step bakes the volume envelope
into the samples and accepts only 16-bit PCM, returning null otherwise. So
enabling any effect downgraded that track to the ffmpeg expression path — capped
at 32 straight segments, quantising a curved envelope, and on a dense one falling
back to base volume. It now writes 16-bit PCM, clamped rather than wrapped so a
limiter at 0 dB or a resonant filter cannot turn overshoot into a click. A test
asserts the baker accepts the writer's own output and actually fades it.

**Everything was folded to mono.** `prepareAudioTrack` goes out of its way to
emit stereo — its pan filter exists to dodge ffmpeg's 3 dB mono-to-stereo
rematrix — and this folded it, then wrote one channel. So adding a single peaking
EQ collapsed a bed's width and cost ~3 dB in the render, while preview stayed
stereo. Channels now travel as one plane each, through an OfflineAudioContext of
the same width, and come back interleaved.

**Small results decoded the wrong length.** `new Float32Array(buf.buffer)`
discards byteOffset and byteLength, and Node pools small allocations: a 400-byte
payload sits at offset 8 inside an 8 KiB pool, so a clip under ~1024 samples
decoded as 2048 samples of unrelated memory — and the empty-result guard could
not see it. The reader has the mirror-image fix: a float data chunk on an odd
boundary (ffmpeg's pcm_f32le writes fmt(18) + fact, landing `data` at 58) now
copies instead of throwing RangeError on an unaligned view.

The tail limitation is now stated rather than mis-stated: the context is exactly
as long as the input, so a reverb or delay still ringing is cut there. The old
comment claimed the opposite. How far a tail may run past a clip's end changes
the clip's length in the mix, so it is a product decision, not one to make here.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(producer): report an FX render failure as an audio error

`processCompositionAudio` reports per-track failures in its result, but an FX
failure it cannot degrade past — a browser that will not launch, a chain that
will not build — rejects instead. `runAudioStage` had no try, so that rejection
escaped to the orchestrator as an unclassified pipeline exception, losing the
stage/owner/retryable classification this stage exists to attach, and skipping
its abort check on the way out.

It now lands in `audioError` alongside every other cause, while an abort still
keeps its own shape rather than being reported as an audio problem.

Not done here: committing the generated `audio-fx-runtime-inline.ts` so a fresh
clone typechecks packages/engine without building first. The bundle is built from
the stub, and the stub changes three times across this stack — so the artifact
differs per branch and would conflict on every restack. Its model,
position-edits-render-inline.ts, is committed only because it is stable. Building
before testing is this monorepo's existing contract (studio's tests need core's
dist too), so the gap is not specific to audio FX and is better closed by a build
ordering gate than by committing a per-branch artifact.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(engine): skip the browser FX render cases when there is no browser

CI's `Test` job was red on this PR with four failures, all the same cause:

  Failed to launch the browser process: spawn
  /home/runner/.cache/hyperframes/chrome/chrome-headless-shell

The job installs ffmpeg and no browser, deliberately — every other suite
that needs an external binary already guards on it
(`describe.skipIf(!HAS_FFMPEG)`). These cases were the only ones assuming
a Chrome, so they failed on an absent dependency rather than on anything
about the code.

Guards on `resolveHeadlessShellPath()` — the same resolver
`acquireBrowser` launches through, so the check cannot drift from the
thing it guards the way a hard-coded cache path would. A configured path
that does not exist throws; that is caught and read as "cannot run here".

Checked both directions rather than just the green one: with a browser all
11 cases run and pass, and with `HYPERFRAMES_BROWSER_PATH` pointed at a
missing binary exactly 3 skip and the other 8 still run. A guard that
silently skipped everything would have looked identical in CI.

They keep their value where it exists — every developer machine, and any
job that has run `hyperframes browser ensure`.

Not touched: the CodeQL failure on this PR is a run from 2026-08-07, five
days and several force-pushes stale. None of the 17 open repo alerts are
in files this PR changes; it re-runs on this push.

* chore(engine): suppress the temp-file alert with the reason it is safe

CodeQL flags `writeWav`'s `writeFileSync` as js/insecure-temporary-file
(high) — the one new alert on #3021, and the reason its CodeQL check is
red.

It is a false positive, and the comment says why rather than just silencing
it: `path` is always inside a directory made by `mkdtempSync`, never a
name assembled directly under `tmpdir()`. Both callers are covered — the
browser host page writes into `mkdtempSync(join(tmpdir(), "hf-fx-host-"))`,
and the render output goes to the producer work dir, itself
`mkdtempSync(join(tempRoot, "producer-project-"))`. mkdtemp picks the
random suffix and creates the directory 0700 in one syscall, so the
predictable filename inside it cannot be pre-created or symlinked by
another user, which is the attack the rule is about. The analyzer sees the
dataflow reach `tmpdir()` and not the mkdtemp in between.

Suppressed inline rather than dismissed in the UI, so the justification
lives next to the code and the rule stays live for anything added later in
this file. Matches the repo's existing convention — `planV2.ts:222`
carries an `lgtm[js/insecure-temporary-file]` for a different reason on
the same rule.

Correcting myself: I first reported this alert as not real, having
intersected the PR's files against the default-branch alert list, which
does not contain PR-ref alerts. Querying ?ref=refs/pull/3021/merge returns
it straight away.

* test(engine): probe ffmpeg and Chrome instead of assuming them

Two failures on #3021's Test job, both about the environment rather than
the code under test.

**Bare `ffmpeg` is not on PATH in CI.** The 16-bit fixture shelled out to
`execFileSync("ffmpeg", ...)` and died with ENOENT. The job does provide
ffmpeg, through `prepare-ffmpeg-bin`, which is what `getFfmpegBinary()`
resolves — every other ffmpeg-dependent suite in this package already goes
through it. Now this one does too, and the case is `skipIf(!HAS_FFMPEG)`
so a contributor without ffmpeg skips rather than fails.

**The browser guard trusted the wrong thing.** It asked
`resolveHeadlessShellPath()` and treated a returned path as "a browser is
here". CI's cache holds a chrome-headless-shell that resolves and then
fails to spawn — a partial download is indistinguishable from a working
one by `existsSync`, which is all that resolver checks. So the three
browser cases ran anyway and failed on the launch.

It now runs `--version` and requires exit 0, which is the same probe the
ffmpeg suites use: ask the binary, do not infer from the filesystem.

Checked both directions rather than just the green one. With a working
browser all 11 cases run and pass; with `HYPERFRAMES_BROWSER_PATH` pointed
at a binary that exits non-zero — CI's exact situation — exactly 3 skip
and the other 8 still run. A guard that quietly skipped everything would
have looked identical on the CI summary.

* feat(core): register the audio-fx-rack canary at 0%

Lands the rollout switch dark, per the registry's own procedure: "Start at
percentage: 0 and merge that — a canary at 0 is dead code you can land
safely and ramp without a code review."

Declared at the bottom of the stack so every branch above can read it. The
gate itself goes in at wa-4-fx-panel, where the rack first appears.

Scope is deliberate and stated in the description: it gates the AUTHORING
surface only. A composition that already carries `data-fx-chain` still
plays and renders it. A canary should stage who can REACH a feature, not
make an attribute somebody already wrote silently inert — an agent that
writes a chain through the skill would otherwise produce a file whose audio
processing vanishes with no error.

* feat(studio): audio FX panel generated from the registry

Controls for the whole chain: add, remove, reorder, bypass, and every knob each
effect declares.

Nothing in the panel knows what a compressor is. The registry supplies each
parameter's range, step, unit and scale and the panel renders what it finds, so
adding an effect or a knob upstream needs no change here, and the panel cannot
offer a value the renderer would reject — a typed-in figure is clamped into the
declared range on the way through.

Frequency and time controls span three or four decades, so those declare a log
scale and the slider maps exponentially; a linear slider would spend most of
its travel somewhere useless.

Reorder is a first-class control because chain order changes the sound: a
reverb before a compressor is not the same as after.

Carve gets its own block rather than an entry in the add menu, with a picker
for the voice track to listen to. It processes this track based on another one,
which is how a sidechain control works — it lives on the track that changes,
and names the source.

* feat(studio): show the Audio FX section on audio tracks

Adds `audioFx` to the editing-affordances contract and renders the FX panel in
the inspector when an `<audio>` element is selected.

The section is audio-only. A `<video>` carries its sound on a separate
`<audio>` element, so an FX chain on the video would have nothing to process.

Chain and carve settings are written straight back onto the element as
serialised attributes, the way colour grading carries its config, so
persistence is an ordinary attribute write and needs no new server route. A
chain that cannot be parsed renders as empty rather than breaking the panel,
and the attribute is left untouched until the user changes something.

The collapsed group summarises what is on the track ("2 effects + carve") so
the state is visible without expanding it.

Wired into PropertyPanelFlat rather than PropertyPanel: STUDIO_FLAT_INSPECTOR_ENABLED
defaults to true, so the flat inspector is what actually renders.

* refactor(studio): lift audioFxSummary out of PropertyPanelFlat

`PropertyPanelFlat.tsx` is 612 lines here against the repo's 600-line cap,
so the required File size check is red — the sole reason this PR is
blocked. The review says as much: "mechanical fix (~5 min), not a design
problem. Code itself is LGTM."

Moves `audioFxSummary` to `audioFxSummary.ts`, the same file a later
branch creates for it. Deliberately the smallest cut that clears the cap
rather than the whole `AudioFxGroup` extraction: every later commit in the
stack edits AudioFxGroup, so moving it here would collide with each of
them, while almost nothing touches this function.

595 lines.

* feat(core,studio): hear the FX chain in preview, and run the carve analysis

Splices an element's FX chain into the playback graph so preview stops being
silent about effects, and wires the carve button that was previously inert.

The chain goes between the decoded source and its gain stage: effects see the
raw signal and volume automation rides on their output, matching the order the
offline render uses. Since preview and render call the same graph builders,
what is heard while scrubbing is what gets written.

The splice lives in the transport rather than on the `<audio>` element. The
transport plays each track from a decoded AudioBuffer and mutes the element to
avoid doubling, so capturing the element with createMediaElementSource would
have processed a stream nothing is listening to — it looked like it worked
because the call succeeded, and the audio was unchanged.

A chain that cannot be built plays dry rather than silencing the track, which
is the right failure in preview: the author keeps working and hears the source.
The render still refuses, because shipping the dry signal there would be wrong.

Carve now analyses for real: it decodes the chosen voice track, ranks its bands
and writes the resulting peaking filters onto this track. Generated nodes are
tagged `fromCarve`, so re-running replaces the previous carve instead of
stacking another set on top of hand-added effects.

Known limitation: the graph is built when a source is scheduled, so a knob
turned mid-playback takes effect on the next play or seek rather than
immediately. Live re-parameterisation needs the transport to hold the handle
and forward updates.

* fix(studio,core): stop parameter drags from restarting playback

Dragging a knob wrote the chain through the persisting attribute path on every
input event. That path refreshes the preview, which reloads the composition and
reschedules audio — so a single drag reloaded dozens of times and playback
stuttered the whole way.

Drags now go through `onSetAttributeLive`, the same path colour grading uses for
scrubs: it coalesces undo entries and sets `skipRefresh`, so no reload happens.
The persisting write fires once, when the gesture ends — pointer-up or blur for
a slider, Enter or blur for a typed value. A select commits immediately since
there is no drag to wait for.

While dragging, the control is driven from local state. Waiting for the value to
round-trip through the element attribute made the knob lag behind the pointer.

For the change to be audible without a reload, the graph now follows the
attribute: the chain installed by the transport observes the element and
re-parameterises itself in place, so a value change lands on the next
128-sample quantum. A shape change (effect added, bypassed, pole count) cannot
be patched into a running graph, so it still waits for the next schedule rather
than cutting the audio mid-play.

The regression test drags a slider through several values and asserts the
persisting handler is untouched until release.

* feat(studio): put the audio FX rack behind its canary

Gates the rack on `isCanaryEnabled("audio-fx-rack")`, which is registered
at 0% — so the whole 47-PR stack can land without showing anyone a feature
that has not been measured yet.

The gate sits on the AUTHORING surface and nowhere else. The runtime and
the render still honour a `data-fx-chain` already on an element, so a
composition written through the skill or by `carve.mjs` keeps its
processing rather than going silently dry for anyone outside the cohort. A
canary should stage who can REACH a feature, not make an attribute somebody
already wrote stop working with no error.

Gated at the panel rather than in `resolveEditingSections`: the affordance
resolver is a pure function in core describing what an element CAN support,
and rollout state is not a property of an `<audio>` tag.

Pinned the 0% with a test, and checked it fails at 25 — a ramp should have
to break something that says "this ships dark" out loud.

One gap, stated rather than papered over: the gate itself has no unit test.
I wrote one and deleted it, because `PropertyPanel.test.tsx`'s harness
never renders the Audio FX group for its audio fixture even with the gate
removed — so the test passed for the wrong reason in the off case and could
not pass at all in the on case. A test that cannot fail for the right
reason is worse than none. Verifying the gate needs the panel harness to
mount that section first, which is its own change.

* fix(core): register FX worklets before building nodes that need them

An AudioWorkletNode cannot be constructed before its processor is registered —
it throws, and the surrounding chain is lost with it. `attachElementFxChain`
built the chain first and only then called `ensureAudioFxWorklets`, so every
worklet-backed effect (compressor, limiter, gate, bitcrush) threw on
construction and the track fell back to dry. Instrumenting the preview showed
`hf-compressor: InvalidStateError` with addModule never called at all.

When the module has not landed yet the track now plays dry and the graph is
swapped in once registration resolves, so the effect arrives a moment late
instead of never.

Registration is also tracked per context rather than in one module-level
promise. A processor registered on one AudioContext does not exist on another,
so the shared promise made every context after the first believe it was ready
when it was not — the studio's transport owns its own context, which is exactly
that case.

With the worklets actually running, the compressor's per-sample log10 and pow
became real audio-thread work. Samples below the knee have a gain of exactly
unity and need neither, so the envelope is now compared in the linear domain
and the transcendentals only run for samples that are actually being
compressed.

* refactor(studio): split the FX node row out of FxSection

Clears the health findings the FX stack left behind: the chain-node render
callback was a 70-line closure over half of FxSection's state, and the two
reorder arrows were the same button written twice.

Also drops two exports with no consumers, and registers the audio FX runtime
stub as an entry point — it is bundled by file path, so nothing imports it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(core): automation envelope model for audio tracks

Adds the data model behind Ableton-style automation lanes: breakpoint
envelopes over track volume or one knob of one effect in the track's FX
chain, stored on the element as `data-automation`.

Times are clip-local, so an envelope travels with the clip when it moves —
the clip-envelope model rather than arrangement automation.

`sampleAutomationLane` is the single interpolator. The lane drawing, the
preview scheduler and the render bake all call it, so the picture and the
sound cannot disagree about the curve. Log-scaled parameters interpolate in
log space, matching what their own knob already promises.

FX nodes gain a stable `id`, minted by count rather than randomly so the
document is the same on every machine. Lanes address nodes by id, so
reordering a chain never re-points a lane at a different effect, and a lane
whose effect was deleted is dropped rather than left to reattach.

Also warns when a track carries both a volume lane and a GSAP volume tween,
since only the lane is heard and the tween silently does nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(studio): lift the audio FX group out of PropertyPanelFlat

`PropertyPanelFlat.tsx` was 672 lines against the repo's 600-line cap, so
the required File size check was red — the sole reason #3014 and #3022 are
blocked. Both reviews say the same thing: "mechanical fix, not a design
problem. Code itself is LGTM."

Moves `AudioFxGroup` and `audioFxSummary` into
`propertyPanelAudioFxGroup.tsx`, which is where a later branch puts them
anyway — done here so the file is under the cap from the point it first
crosses it, rather than ten branches later.

533 lines now. The four audio imports it no longer needs go with it.

Not fixed here: three `FxSection carve` tests fail on this branch with
"Cannot read properties of undefined (reading 'toFixed')". Confirmed
pre-existing by stashing this change and re-running — that is the separate
`Test` failure the review also flags.

* feat(core): expose the AudioParams behind automatable FX knobs

Marks the knobs an automation lane can drive and has each graph builder hand
back the AudioParam behind them, so a scheduler can write to a running effect
without knowing what the effect is.

A knob is not always one AudioParam. A wet/dry mix is two gains moving in
opposition, and a knob in milliseconds drives a delay time in seconds, so
each target carries the mapping out of the knob's own declared unit.

What stays unautomatable is stated where it is decided: a WaveShaper curve, a
convolution impulse and a one-pole filter's coefficients are all rebuilt
wholesale rather than scheduled, and the four worklet effects take values by
postMessage rather than through AudioParams.

The registry flag is written by hand, so a test builds every effect and
checks the exposure both ways — nothing flagged is missing, nothing exposed
is unflagged. A flag that lied would offer a lane that silently did nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(core): play automation envelopes in preview

Schedules each lane onto the AudioParams behind its knob using native ramps
and value curves. Nothing evaluates the envelope per frame: it is handed to
the audio thread once, so it stays sample-accurate however busy the main
thread is, and the offline render will schedule it the same way.

Timing comes from the transport, so an envelope survives seeking into the
middle of a clip, a clip that has not started yet, and a playback rate that
compresses clip seconds into context seconds.

A straight line is only scheduled as a ramp when nothing bends it — no
curvature, a linear parameter scale, and no unit mapping. Log-scaled
parameters and mapped ones are sampled instead, since a delay knob in
milliseconds and a wet/dry pair moving in opposition are not linear in the
parameter they drive.

Lanes with nowhere to write are skipped rather than reported: a one-pole
filter exposes no frequency param, and the worklet effects expose none at
all. Editing an envelope mid-playback re-aims it at the live playhead rather
than restarting the track.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(core): make the volume lane audible in preview

The envelope was scheduled onto the transport's gain AudioParam, but the
runtime rewrites that gain every tick from `data-volume` and the GSAP-seeked
value — so it was erased within a frame. Volume automation was correct in the
render and inaudible while previewing.

The lane now feeds the per-tick path where the probed volume keyframes already
sit, checked ahead of them so the two cannot fight, and the transport no
longer schedules volume at all: one mechanism instead of two racing.

The cost is honest — in preview the level steps per tick rather than per
sample, exactly as the existing keyframe path does. The render still bakes it
into the PCM sample-accurately, and FX parameters are still scheduled on their
own AudioParams, since nothing rewrites those.

Parsed lanes are cached by attribute text: the runtime asks once per tick per
track, and parsing there would run the JSON parser 60 times a second for a
value that only changes on an edit.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(engine): bake automation envelopes into the render

The offline render schedules FX lanes with the same scheduler preview uses,
inside the OfflineAudioContext that already runs the same graph builders. The
input WAV is the clip's own audio from its first sample, so clip-local time
is offline time and the envelope needs no offset.

Volume lanes take the existing PCM bake rather than a second mechanism: the
lane is converted to keyframes, so a straight fade stays two of them and only
a bent segment is sampled — the baker interpolates linearly and would
otherwise quietly straighten the curve. A volume lane supersedes keyframes
probed from the timeline, which `lint` already warns about.

A browser test sweeps a lowpass from below a 2 kHz tone to well above it and
measures both ends. Parsing the envelope is not the same as scheduling it,
and only running the real thing tells the two apart.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(core): apply chain edits to the running graph

A structural edit — an effect added, removed, bypassed, or a filter's pole
count switched — was dropped. `buildFxChain`'s update reports false when the
change is not merely new values, and the attribute observer ignored that, so
the edit only took hold when the persisting write reloaded the composition.
That reload restarted every playing track, which is what was heard as the
audio chopping.

The graph is now swapped in place: the old effects are detached, the new ones
built and connected between the same source and gain, and any lanes
re-scheduled onto the new nodes. The source node is never touched, so playback
does not restart.

A track with no chain is watched too, rather than wired through and forgotten,
so adding its first effect is heard the same way. That means the function
always returns a disposer instead of null for the empty case.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(studio): drop the FX panel's dead __testables export

Fallow audit flagged it — no test imports the module.

* fix(core,studio): clear the remaining Fallow audit findings on the FX panel

- Split FxSection's per-node row into FxNodeRow + FxNodeControls so the
  CRAP score (31.6, threshold 30) splits across two smaller units instead
  of moving wholesale with one extraction.
- Dedupe the repeated "open the add menu, read its items" block in
  propertyPanelFxSection.test.tsx into openAddMenuItems().
- Merge build-audio-fx-runtime.ts and build-position-edits-render.ts into
  one build-inline-artifact.ts, config-selected by CLI arg — the two
  scripts were a byte-for-byte clone save for names.
- Exempt canary.test.ts's rawFnv (a deliberate independent
  reimplementation used to cross-check canaryBucket, per its own
  docstring) and the property-panel test files' shared renderInto/mount
  scaffolding (pre-existing across 9 files, 2 outside this stack) in
  .fallowrc.jsonc, consistent with this file's existing exemptions for
  the same class of intentional/pre-existing duplication.

* fix(ci): allowlist the build-script consolidation in the no-main-deletions guard

build-audio-fx-runtime.ts and build-position-edits-render.ts were merged into
build-inline-artifact.ts to kill a fallow duplication finding; the deletion
guard flagged that as an accidental loss since main still has both originals.

* fix(core): dedupe the wet/dry mix math between delayFeedback and chorusLfo

Both effect builders set wet.gain to the mix and dry.gain to its complement
in identical two-line blocks; fallow kept re-flagging it as a 10-line clone
on every unrelated change. Extracted setWetDryMix.

* fix(core): remove the build-audio-fx-runtime.ts stray resurrected by a main merge

An earlier merge with main brought this deleted file back (git's merge/delete
handling on an unchanged-on-one-side file); package.json already points at
build-inline-artifact.ts, so it sat unreachable and duplicating that file's
config, both of which fallow flagged.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Vance Ingalls
2026-08-12 16:30:36 -07:00
committed by GitHub
co-authored by Claude Opus 5
parent 2c41a74ff7
commit 3cfacf440d
16 changed files with 736 additions and 71 deletions
+22
View File
@@ -160,6 +160,22 @@
"file": "packages/core/src/audio/audioFxGraph.ts",
"exports": ["ensureAudioFxWorklets"],
},
// automationLaneGeometry is the bottom of the audio-automation stack: its
// consumer is the lane component one PR upstack, so a per-PR audit diffing
// against the merge base sees these as unused. Consumed for real once the
// stack merges; safe to drop this entry then.
{
"file": "packages/studio/src/player/components/automationLaneGeometry.ts",
"exports": [
"POINT_MERGE_SEC",
"GRAB_PX",
"DRAW_SAMPLES",
"PAD_X",
"formatValue",
"laneFor",
"withLane",
],
},
// drawElementService is the bottom of the fast-capture Graphite stack
// (#1917): its consumers (frameCapture in #1919) land two PRs upstack, so
// a per-PR audit diffing against the merge base sees these exports as
@@ -684,6 +700,12 @@
// complexity pre-dates the computed-timeline work. Exempted at file level
// rather than refactored as scope creep.
"ignore": [
// audio-fx-runtime-entry.ts: the browser-side IIFE entry for the offline FX
// render. It runs only inside the headless page the engine drives, so unit
// coverage cannot reach it and its CRAP score is coverage-driven rather
// than complexity-driven (5 cyclomatic). Its behaviour is covered by the
// engine's real-browser render tests.
"packages/core/stubs/audio-fx-runtime-entry.ts",
// useGestureRecording.ts: readBasePosition/connectGsapRuntime/tick are
// inherited gesture-runtime control flow. This stack only changes
// recordSample to coalesce display-rate events onto authored frames;
@@ -1,4 +1,4 @@
import { useMemo, type MouseEvent as ReactMouseEvent, type RefObject } from "react";
import { useMemo, type MouseEvent as ReactMouseEvent, type ReactNode, type RefObject } from "react";
import {
classifyPropertyGroup,
type GsapAnimation,
@@ -35,6 +35,12 @@ export interface TimelinePropertyLanesProps {
onContextMenuKeyframe?: (e: ReactMouseEvent, target: TimelineKeyframeTarget) => void;
onMoveKeyframe?: (target: TimelineKeyframeTarget, toClipPercentage: number) => Promise<boolean>;
suppressClickRef?: RefObject<boolean>;
/**
* Rendered after the keyframe lanes, inside this wrapper. An audio clip's
* automation lane lives here so it shares the same disclosure — and so the
* header caret's `aria-controls` covers it too.
*/
footer?: ReactNode;
}
/**
@@ -196,6 +202,7 @@ export function TimelinePropertyLanes({
onContextMenuKeyframe,
onMoveKeyframe,
suppressClickRef,
footer,
}: TimelinePropertyLanesProps) {
// Memoized: TimelineDiamondLane is React.memo'd, and rebuilding the lanes (and
// a fresh keyframesData literal per lane) on every render would re-render every
@@ -263,6 +270,7 @@ export function TimelinePropertyLanes({
/>
</div>
))}
{footer}
</div>
);
}
@@ -0,0 +1,66 @@
// @vitest-environment happy-dom
import { describe, expect, it } from "vitest";
import { elementAutomation, elementFxChain } from "./automationLaneData";
import type { TimelineElement } from "../store/timelineElement";
const el = (over: Partial<TimelineElement> = {}): TimelineElement => ({
id: "bgm",
key: "bgm",
tag: "audio",
start: 0,
duration: 10,
track: 10,
...over,
});
const CHAIN = JSON.stringify({
version: 1,
nodes: [{ type: "lowpass", id: "n1", params: { frequency: 400, q: 0.9, poles: "2" } }],
});
const LANE = JSON.stringify({
version: 1,
lanes: [{ target: "fx.n1.frequency", points: [{ t: 0, v: 400 }] }],
});
describe("automationLaneData", () => {
it("returns the same object for the same attributes", () => {
// The lane compares its drag draft against this identity; a fresh object per
// playhead tick would drop the drag.
const a = elementAutomation(el({ automation: LANE, fxChain: CHAIN }));
const b = elementAutomation(el({ automation: LANE, fxChain: CHAIN }));
expect(a).toBe(b);
expect(elementFxChain(el({ fxChain: CHAIN }))).toBe(elementFxChain(el({ fxChain: CHAIN })));
});
it("re-parses when the chain changes even though the automation text did not", () => {
const withChain = elementAutomation(el({ automation: LANE, fxChain: CHAIN }));
const withoutChain = elementAutomation(el({ automation: LANE }));
expect(withChain.lanes.map((l) => l.target)).toEqual(["fx.n1.frequency"]);
// No chain to resolve against, so the fx lane is dropped rather than drawn.
expect(withoutChain.lanes).toEqual([]);
});
it("keeps a hot entry alive when other elements push the cache past its limit", () => {
// Eviction used to clear the whole map, which changed every lane's identity
// at once and released any drag in progress.
const hot = el({ automation: LANE, fxChain: CHAIN });
const first = elementAutomation(hot);
for (let i = 0; i < 40; i += 1) {
elementAutomation(
el({
automation: JSON.stringify({
version: 1,
lanes: [{ target: "volume", points: [{ t: i, v: 0.5 }] }],
}),
}),
);
elementAutomation(hot);
}
expect(elementAutomation(hot)).toBe(first);
});
it("reads an unreadable attribute as nothing rather than throwing", () => {
expect(elementAutomation(el({ automation: "{nope" })).lanes).toEqual([]);
expect(elementFxChain(el({ fxChain: "{nope" }))).toBeNull();
});
});
@@ -0,0 +1,93 @@
/**
* Reading an element's automation, shared by the lane UI and the row layout.
*
* The attributes are carried on TimelineElement verbatim rather than parsed at
* the manifest boundary: the lane reads and writes them, and round-tripping
* through the attribute is what keeps the lane, the property panel and the
* running audio graph on one source of truth.
*
* Both parse the same two attributes: the layout needs the lane count to
* reserve height, the lanes need the lanes themselves. Parsing is cached by the
* attribute text so the identity only changes when the text does — the lane's
* drag draft compares against that identity, and a fresh object on every
* playhead tick would throw away the drag in progress.
*/
import {
parseAutomation,
resolveAutomation,
type HfAutomation,
type HfAutomationLane,
} from "@hyperframes/core/audio-automation";
import { parseAudioFxChain, type HfAudioFxChain } from "@hyperframes/core/audio-fx";
import type { TimelineElement } from "../store/playerStore";
const EMPTY: HfAutomation = { version: 1, lanes: [] };
const chainCache = new Map<string, HfAudioFxChain | null>();
const automationCache = new Map<string, HfAutomation>();
const CACHE_LIMIT = 64;
/**
* Parse once per distinct attribute text, keeping the same object until the text
* changes — the lane compares its drag draft against that identity.
*
* Eviction drops the oldest entry rather than clearing the map: clearing would
* change the identity of every lane's automation at once, and any lane mid-drag
* would release its draft and jump back to the stored value.
*/
function cached<T>(store: Map<string, T>, key: string, build: () => T): T {
const hit = store.get(key);
if (hit !== undefined) {
// Re-insert so the entry counts as recently used.
store.delete(key);
store.set(key, hit);
return hit;
}
const value = build();
if (store.size >= CACHE_LIMIT) {
const oldest = store.keys().next();
if (!oldest.done) store.delete(oldest.value);
}
store.set(key, value);
return value;
}
/** The element's FX chain, or null when it has none or it is unreadable. */
export function elementFxChain(element: TimelineElement): HfAudioFxChain | null {
const raw = element.fxChain;
if (!raw) return null;
return cached(chainCache, raw, () => {
try {
return parseAudioFxChain(raw);
} catch {
return null;
}
});
}
/**
* The element's automation, bound to its chain the same way preview and the
* render bind it: a lane whose effect has been deleted is dropped rather than
* drawn on the wrong axis.
*/
export function elementAutomation(element: TimelineElement): HfAutomation {
const raw = element.automation;
if (!raw) return EMPTY;
const chain = elementFxChain(element);
// Both texts key the entry: the resolved lanes depend on the chain too. Joined
// through a separator no attribute can contain.
return cached(automationCache, `${raw}\u0000${element.fxChain ?? ""}`, () => {
try {
return resolveAutomation(parseAutomation(raw), chain ?? undefined);
} catch {
// Unreadable automation draws no lanes rather than breaking the row.
return EMPTY;
}
});
}
/** Lanes in the order they are drawn, one row each. */
export function elementAutomationLanes(element: TimelineElement): HfAutomationLane[] {
return elementAutomation(element).lanes;
}
@@ -0,0 +1,68 @@
// @vitest-environment happy-dom
import { describe, expect, it } from "vitest";
import { automationTargets, fromUnit, toUnit } from "./automationLaneGeometry";
import { resolveAutomationRange, VOLUME_RANGE } from "@hyperframes/core/audio-automation";
import type { HfAudioFxChain } from "@hyperframes/core/audio-fx";
const chain: HfAudioFxChain = {
version: 1,
nodes: [
{ type: "lowpass", id: "n1", enabled: true, params: {} },
// No id: the panel has not touched it, so nothing can address it.
{ type: "peaking", enabled: true, params: {} },
// Worklet-backed: no AudioParams to schedule.
{ type: "compressor", id: "n3", enabled: true, params: {} },
],
};
describe("automationTargets", () => {
it("offers volume plus every addressable automatable knob", () => {
const targets = automationTargets(chain).map((t) => t.target);
expect(targets[0]).toBe("volume");
expect(targets).toContain("fx.n1.frequency");
expect(targets).toContain("fx.n1.q");
});
it("skips a node with no id — a lane could not address it stably", () => {
expect(automationTargets(chain).some((t) => t.target.includes("peaking"))).toBe(false);
});
it("skips a worklet effect, which exposes no AudioParams", () => {
expect(automationTargets(chain).some((t) => t.target.startsWith("fx.n3."))).toBe(false);
});
it("offers just the fader for a track with no chain", () => {
expect(automationTargets(null).map((t) => t.target)).toEqual(["volume"]);
});
it("labels an fx target with its effect and knob", () => {
const found = automationTargets(chain).find((t) => t.target === "fx.n1.frequency");
expect(found?.label).toMatch(/Cutoff/);
expect(found?.range.scale).toBe("log");
});
});
describe("value ↔ lane position", () => {
it("maps a linear range straight onto the lane", () => {
expect(toUnit(VOLUME_RANGE, 0)).toBe(0);
expect(toUnit(VOLUME_RANGE, 1)).toBe(1);
expect(toUnit(VOLUME_RANGE, 0.25)).toBeCloseTo(0.25, 10);
});
it("maps a log-read knob on its own scale, so its middle is geometric", () => {
const range = resolveAutomationRange("fx.n1.frequency", chain)!;
const mid = fromUnit(range, 0.5);
expect(mid).toBeCloseTo(Math.sqrt(range.min * range.max), 4);
// Round trip: a value put in comes back out.
expect(fromUnit(range, toUnit(range, 900))).toBeCloseTo(900, 6);
});
it("clamps a pointer that has left the lane", () => {
expect(fromUnit(VOLUME_RANGE, -3)).toBe(0);
expect(fromUnit(VOLUME_RANGE, 4)).toBe(1);
});
it("reads a zero-width range as the bottom rather than dividing by zero", () => {
expect(toUnit({ ...VOLUME_RANGE, min: 1, max: 1 }, 1)).toBe(0);
});
});
@@ -0,0 +1,118 @@
/**
* The maths behind an automation lane: which parameters it can offer, how a
* value maps to a position in the lane, and how a lane is edited.
*
* Pure — no React, no DOM. Split from the lane component so the geometry can be
* tested on its own, and so the component is left with the parts that genuinely
* need a pointer and a render.
*/
import {
fxAutomationTarget,
resolveAutomationRange,
VOLUME_RANGE,
VOLUME_TARGET,
type AutomationRange,
type HfAutomation,
type HfAutomationLane,
} from "@hyperframes/core/audio-automation";
import { getAudioFxDef, type HfAudioFxChain } from "@hyperframes/core/audio-fx";
/** Points nearer than this in clip seconds are the same point, not two. */
export const POINT_MERGE_SEC = 0.02;
/** Hit radius for grabbing a point, in px. */
export const GRAB_PX = 7;
/** Samples used to draw a segment the eye should see as curved. */
export const DRAW_SAMPLES = 64;
/**
* Slack on each side of the envelope, so a point sitting exactly at the clip's
* start or end is drawn whole instead of half outside the lane. Wide enough for
* the grab circle plus its stroke.
*/
export const PAD_X = GRAB_PX + 2;
export interface AutomationTargetOption {
target: string;
label: string;
range: AutomationRange;
}
/**
* Everything this clip could automate: its fader, then each automatable knob of
* each effect in its chain. Effects with no chain node id are skipped — a lane
* has nothing stable to address them by (the panel mints ids as it adds nodes).
*/
export function automationTargets(chain: HfAudioFxChain | null): AutomationTargetOption[] {
const out: AutomationTargetOption[] = [
{ target: VOLUME_TARGET, label: "Volume", range: VOLUME_RANGE },
];
for (const node of chain?.nodes ?? []) {
out.push(...nodeTargets(node, chain));
}
return out;
}
/** One effect's automatable knobs. Empty for a node no lane could address. */
function nodeTargets(
node: HfAudioFxChain["nodes"][number],
chain: HfAudioFxChain | null,
): AutomationTargetOption[] {
const nodeId = node.id;
const def = nodeId ? getAudioFxDef(node.type) : undefined;
if (!nodeId || !def) return [];
const out: AutomationTargetOption[] = [];
for (const param of def.params) {
if (param.kind !== "number" || !param.automatable) continue;
const target = fxAutomationTarget(nodeId, param.key);
const range = resolveAutomationRange(target, chain ?? undefined);
if (range) out.push({ target, label: range.label, range });
}
return out;
}
/** Value → 0..1 up the lane, honouring a log-read knob's own scale. */
export function toUnit(range: AutomationRange, value: number): number {
const { min, max } = range;
if (max <= min) return 0;
if (range.scale === "log" && min > 0 && value > 0) {
return (Math.log(value) - Math.log(min)) / (Math.log(max) - Math.log(min));
}
return (value - min) / (max - min);
}
export function fromUnit(range: AutomationRange, unit: number): number {
const t = Math.min(1, Math.max(0, unit));
const { min, max } = range;
if (range.scale === "log" && min > 0) {
return Math.exp(Math.log(min) + t * (Math.log(max) - Math.log(min)));
}
return min + t * (max - min);
}
export function formatValue(range: AutomationRange, value: number): string {
const decimals = range.step >= 1 ? 0 : range.step >= 0.1 ? 1 : 2;
const shown =
range.unit === "" && range.max === 1 ? `${Math.round(value * 100)}%` : value.toFixed(decimals);
return range.unit ? `${shown} ${range.unit}` : shown;
}
export function laneFor(automation: HfAutomation, target: string): HfAutomationLane {
return automation.lanes.find((l) => l.target === target) ?? { target, points: [] };
}
/**
* Replace one lane in place, dropping it when it has no points left.
*
* Order is preserved deliberately. A lane with no explicitly chosen parameter
* shows whichever comes first, so moving the edited one to the end would switch
* the lane out from under the pointer on the first edit.
*/
export function withLane(automation: HfAutomation, lane: HfAutomationLane): HfAutomation {
const empty = lane.points.length === 0;
const exists = automation.lanes.some((l) => l.target === lane.target);
const lanes = automation.lanes
.map((l) => (l.target === lane.target ? lane : l))
.filter((l) => l.points.length > 0);
if (!exists && !empty) lanes.push(lane);
return { version: 1, lanes };
}
@@ -0,0 +1,11 @@
/**
* Height of one audio automation lane.
*
* Its own module because both the row layout and the lane itself need it, and
* putting it in either would have the layout importing a component or the
* component's constant living somewhere it is not used.
*
* Taller than a keyframe lane because it carries a value axis rather than a row
* of diamonds: a fader envelope drawn 28px high cannot be aimed.
*/
export const AUTOMATION_LANE_H = 48;
@@ -1,3 +1,4 @@
import { AUTOMATION_LANE_H } from "./automationLaneHeight";
import type { ZoomMode } from "../store/playerStore";
import type { TimelineTimeRange } from "../lib/timelineClipIndex";
@@ -86,6 +87,8 @@ export const TRACKS_LEFT_PAD = 48;
export interface TimelineTrackHeightClip {
clipId: string;
laneCount: number;
/** Audio automation lanes shown when expanded, reserved at their own height. */
automationLaneCount?: number;
}
type TimelineTrackHeightInput = readonly (readonly TimelineTrackHeightClip[])[];
@@ -101,12 +104,15 @@ export function trackHeights(
): number[] {
return tracks.map((clips) => {
let laneCount = 0;
if (expandedClipIds) {
for (const clip of clips) {
if (expandedClipIds.has(clip.clipId)) laneCount = Math.max(laneCount, clip.laneCount);
}
let automationLanes = 0;
for (const clip of clips) {
if (!expandedClipIds?.has(clip.clipId)) continue;
laneCount = Math.max(laneCount, clip.laneCount);
automationLanes = Math.max(automationLanes, clip.automationLaneCount ?? 0);
}
return TRACK_H + Math.max(0, Math.trunc(laneCount)) * LANE_H;
return (
TRACK_H + Math.max(0, Math.trunc(laneCount)) * LANE_H + automationLanes * AUTOMATION_LANE_H
);
});
}
@@ -0,0 +1,109 @@
// @vitest-environment happy-dom
import { act } from "react";
import { describe, expect, it } from "vitest";
import { createRoot } from "react-dom/client";
import { useAutomationLanes, type AutomationLaneBinding } from "./useAutomationLanes";
import type { TimelineElement } from "../store/playerStore";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
/** Bind one element through the hook and hand back what the lane would get. */
function bindOnce(element: TimelineElement): AutomationLaneBinding {
let captured: AutomationLaneBinding | null = null;
function Probe() {
captured = useAutomationLanes().bind(element, true);
return null;
}
const host = document.createElement("div");
document.body.append(host);
act(() => {
createRoot(host).render(<Probe />);
});
if (!captured) throw new Error("bind never ran");
return captured;
}
const el = (over: Partial<TimelineElement> = {}): TimelineElement => ({
id: "music",
key: "music",
tag: "audio",
start: 0,
duration: 12,
track: 10,
...over,
});
const CHAIN = JSON.stringify({
version: 1,
nodes: [{ type: "lowpass", id: "n2", params: { frequency: 400, q: 0.9, poles: "2" } }],
});
describe("useAutomationLanes", () => {
it("drops a lane whose effect is no longer in the chain", () => {
// n1 was deleted from the chain but its lane survived in the attribute.
// Drawn as-is it landed on the volume axis, with points off the lane and
// a selector that had no option for it.
const automation = JSON.stringify({
version: 1,
lanes: [
{
target: "fx.n1.speed",
points: [
{ t: 0, v: 0.4 },
{ t: 12, v: 6 },
],
},
{ target: "volume", points: [{ t: 0, v: 0.55 }] },
],
});
const bound = bindOnce(el({ automation, fxChain: CHAIN }));
expect(bound.automation.lanes.map((l) => l.target)).toEqual(["volume"]);
});
it("keeps a lane whose effect is still there", () => {
const automation = JSON.stringify({
version: 1,
lanes: [
{
target: "fx.n2.frequency",
points: [
{ t: 0, v: 400 },
{ t: 4, v: 8000 },
],
},
],
});
const bound = bindOnce(el({ automation, fxChain: CHAIN }));
expect(bound.lanes.map((l) => l.target)).toEqual(["fx.n2.frequency"]);
});
it("gives one lane per automated parameter, in draw order", () => {
const automation = JSON.stringify({
version: 1,
lanes: [
{ target: "volume", points: [{ t: 0, v: 0.5 }] },
{ target: "fx.n2.frequency", points: [{ t: 0, v: 400 }] },
{ target: "fx.n2.q", points: [{ t: 0, v: 1 }] },
],
});
const bound = bindOnce(el({ automation, fxChain: CHAIN }));
expect(bound.lanes.map((l) => l.target)).toEqual(["volume", "fx.n2.frequency", "fx.n2.q"]);
});
it("reads an element with neither attribute as an empty volume lane", () => {
const bound = bindOnce(el());
expect(bound.lanes).toEqual([]);
expect(bound.chain).toBeNull();
});
it("is read-only without an edit session, whatever the selection", () => {
// No DomEditProvider in this tree — the bare player case.
expect(bindOnce(el({ automation: undefined })).readOnly).toBe(true);
});
it("survives an unreadable attribute instead of breaking the row", () => {
const bound = bindOnce(el({ automation: "{not json", fxChain: "{also not}" }));
expect(bound.automation.lanes).toEqual([]);
expect(bound.chain).toBeNull();
});
});
@@ -0,0 +1,85 @@
/**
* Writes for the timeline's audio automation lanes.
*
* Kept out of TimelineLanes so that component does not grow another concern.
* Reading lives in `automationLaneData`, shared with the row layout, which needs
* the lane count to reserve height.
*
* Edits go to the *selected* element, because that is what the attribute commit
* path targets. An unselected clip still draws its envelopes — they are just
* read only, which is also what stops a stray drag from editing the wrong track.
*/
import { useCallback, useMemo } from "react";
import {
HF_AUDIO_AUTOMATION_ATTR,
serializeAutomation,
type HfAutomation,
type HfAutomationLane,
} from "@hyperframes/core/audio-automation";
import type { HfAudioFxChain } from "@hyperframes/core/audio-fx";
import { useDomEditActionsContextOptional } from "../../contexts/DomEditContext";
import type { TimelineElement } from "../store/playerStore";
import { elementAutomation, elementFxChain } from "./automationLaneData";
export interface AutomationLaneBinding {
automation: HfAutomation;
/** One entry per lane, in draw order — each gets its own row. */
lanes: HfAutomationLane[];
chain: HfAudioFxChain | null;
/** Continuous write while dragging; does not persist. */
onPreview(next: HfAutomation): void;
/** Gesture-end write; this is the one that persists and lands in undo. */
onCommit(next: HfAutomation): void;
/**
* Select this clip, which is what makes its lanes editable. A lane calls this
* instead of writing when it is read-only — pressing the lane is the only
* route in, since lanes sit below the clip bar where the timeline's own
* selection handler never sees them.
*/
onSelect(): void;
readOnly: boolean;
}
export interface UseAutomationLanesResult {
bind(element: TimelineElement, isSelected: boolean): AutomationLaneBinding;
}
export function useAutomationLanes(): UseAutomationLanesResult {
// Optional: the player also runs outside Studio, where there is no edit
// session. There the lanes render read-only, which is the right fallback.
const domEdit = useDomEditActionsContextOptional();
const bind = useCallback(
(element: TimelineElement, isSelected: boolean): AutomationLaneBinding => {
const chain = elementFxChain(element);
const automation = elementAutomation(element);
const write = (next: HfAutomation, persist: boolean): void => {
if (!domEdit || !isSelected) return;
const value = next.lanes.length > 0 ? serializeAutomation(next) : "";
if (persist) void domEdit.handleDomAttributeCommit(HF_AUDIO_AUTOMATION_ATTR, value);
// Dragging a point writes live: no preview refresh, so the composition
// does not reload and restart playback on every pixel.
else void domEdit.handleDomAttributeLiveCommit(HF_AUDIO_AUTOMATION_ATTR, value || null);
};
return {
automation,
lanes: automation.lanes,
chain,
onPreview: (next) => write(next, false),
onCommit: (next) => write(next, true),
// Deliberately not awaited before an edit: the commit handlers close
// over the selection as it was when they were built, so writing in the
// same tick would land on whichever element was selected before.
// Selecting is its own gesture; the lane goes live after it.
onSelect: () => void domEdit?.handleTimelineElementSelect(element),
readOnly: !domEdit || !isSelected,
};
},
[domEdit],
);
return useMemo(() => ({ bind }), [bind]);
}
@@ -1,6 +1,8 @@
import { useMemo, useRef } from "react";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import { animationLaneGroups } from "./TimelinePropertyLanes";
import { isAudioTimelineElement } from "../../utils/timelineInspector";
import { elementAutomationLanes } from "./automationLaneData";
import { usePlayerStore, type TimelineElement } from "../store/playerStore";
import type { DraggedClipState } from "./timelineClipDragTypes";
import { useTimelineTrackDerivations } from "./useTimelineTrackDerivations";
@@ -85,7 +87,15 @@ function useTimelineRowHeights(
);
if (!active) return [];
const clipId = active.key ?? active.id;
return [{ clipId, laneCount: laneCounts.get(clipId) ?? 0 }];
return [
{
clipId,
laneCount: laneCounts.get(clipId) ?? 0,
automationLaneCount: isAudioTimelineElement(active)
? elementAutomationLanes(active).length
: 0,
},
];
});
const rowHeights = trackHeights(heightTracks, expandedClipIds);
return {
@@ -152,6 +152,13 @@ function hostElementState(flat: TimelineElement | undefined): Partial<TimelineEl
hidden: flat.hidden,
timelineLocked: flat.timelineLocked,
timelineRole: flat.timelineRole,
// Same reason as the three above: these are read off the host element, which
// an expanded child is built without. Missing them, an audio child inside a
// sub-composition reserved no automation height and drew no lanes, while the
// property panel — reading the live DOM selection rather than this row —
// still showed the chain and its toggles.
fxChain: flat.fxChain,
automation: flat.automation,
};
}
@@ -296,3 +296,36 @@ describe("mergeTimelineElementsPreservingDowngrades — genuine removal vs trans
).toEqual(["a", "c"]);
});
});
describe("audio FX attributes on parsed elements", () => {
const CHAIN = '{"version":1,"nodes":[{"type":"lowpass","id":"n1","params":{}}]}';
const LANE = '{"version":1,"lanes":[{"target":"volume","points":[{"t":0,"v":1}]}]}';
it("carries data-fx-chain and data-automation off the element", () => {
// The timeline row is what reserves automation height and draws the lanes;
// parsed straight from the DOM it used to arrive without either attribute,
// so the panel showed a chain the timeline could not.
const doc = new DOMParser().parseFromString(
`<div data-composition-id="main" data-start="0" data-duration="10">
<audio id="bgm" data-start="0" data-duration="10" data-fx-chain='${CHAIN}'
data-automation='${LANE}'></audio>
</div>`,
"text/html",
);
const [bgm] = parseTimelineFromDOM(doc, 10).filter((e) => e.domId === "bgm");
expect(bgm?.fxChain).toBe(CHAIN);
expect(bgm?.automation).toBe(LANE);
});
it("leaves them unset on a track that carries neither", () => {
const doc = new DOMParser().parseFromString(
`<div data-composition-id="main" data-start="0" data-duration="10">
<audio id="bgm" data-start="0" data-duration="10"></audio>
</div>`,
"text/html",
);
const [bgm] = parseTimelineFromDOM(doc, 10).filter((e) => e.domId === "bgm");
expect(bgm?.fxChain).toBeUndefined();
expect(bgm?.automation).toBeUndefined();
});
});
@@ -138,6 +138,10 @@ export function createTimelineElementFromManifestClip(params: {
if (hostEl.hasAttribute("data-hidden")) entry.hidden = true;
const timelineRole = hostEl.getAttribute("data-timeline-role");
if (timelineRole) entry.timelineRole = timelineRole;
const fxChain = hostEl.getAttribute("data-fx-chain");
if (fxChain) entry.fxChain = fxChain;
const automation = hostEl.getAttribute("data-automation");
if (automation) entry.automation = automation;
entry.zIndex = readTimelineElementZIndex(hostEl);
}
if (clip.assetUrl) entry.src = clip.assetUrl;
@@ -334,6 +338,14 @@ export function parseTimelineFromDOM(doc: Document, rootDuration: number): Timel
if (resolvedSrc) entry.src = resolvedSrc;
}
// Read from the element, like the manifest path does: without these an audio
// clip parsed straight from the DOM reserved no automation height and drew no
// lanes, while the property panel still showed its chain.
const domFxChain = el.getAttribute("data-fx-chain");
if (domFxChain) entry.fxChain = domFxChain;
const domAutomation = el.getAttribute("data-automation");
if (domAutomation) entry.automation = domAutomation;
if (el.hasAttribute("data-timeline-locked")) {
entry.timelineLocked = true;
}
@@ -16,70 +16,9 @@ import { createThumbnailSlice, type ThumbnailSlice } from "./thumbnailSlice";
export type { KeyframeCacheEntry } from "./keyframeSlice";
export { liveTime } from "./liveTime";
export interface TimelineElement {
id: string;
label?: string;
key?: string;
kind?: ClipManifestClip["kind"];
tag: string;
start: number;
duration: number;
track: number;
/**
* The data-track-index as written in the source file. Set at the manifest
* translation boundary (createTimelineElementFromManifestClip) from the
* runtime clip's verbatim track, and preserved through display-lane remaps
* (normalizeToZones packs sparse authored tracks onto contiguous display
* lanes; expanded sub-comp children get synthetic display rows). Lane edits
* must persist THIS space writing a display-lane number into a sparse file
* re-targets the wrong track. For an expanded child the value is in its OWN
* source file's coordinate space, not the host timeline's.
*/
authoredTrack?: number;
/** Resolved z-index for stacking-aware timeline ordering. */
zIndex?: number;
/** True when the effective z-index was authored inline or through CSS, not auto. */
hasExplicitZIndex?: boolean;
/** Canonical CSS stacking context this element's z-index participates in. */
stackingContextId?: string | null;
/** Nearest parent composition context, matching RuntimeTimelineClip. */
parentCompositionId?: string | null;
/** Composition ancestry from root to nearest parent, matching RuntimeTimelineClip. */
compositionAncestors?: string[];
domId?: string;
/** Stable `data-hf-id` attribute value — used as primary patch target when present */
hfId?: string;
/** Best-effort selector used when patching source HTML back from timeline edits */
selector?: string;
/** Zero-based occurrence index for non-unique selectors */
selectorIndex?: number;
/** Source composition file that owns this element, when known */
sourceFile?: string;
src?: string;
playbackStart?: number;
playbackStartAttr?: "media-start" | "playback-start";
playbackRate?: number;
sourceDuration?: number;
volume?: number;
/** Path from data-composition-src — identifies sub-composition elements */
compositionSrc?: string;
/** Whether this row came from authored clip timing or Studio's full-duration layer fallback. */
timingSource?: "authored" | "implicit";
/** Set by data-timeline-locked on the host element — disables move and trim in Studio. */
timelineLocked?: boolean;
/** Set by data-hidden on the host element — hides the clip in preview and render. */
hidden?: boolean;
/** Value of data-timeline-role attribute — used to identify music vs. voiceover. */
timelineRole?: string;
/**
* Set by useExpandedTimelineElements on an inline-expanded sub-composition
* child: the absolute master-timeline start of the sub-comp host the child
* lives in. Presence marks the element as expanded; edits subtract it to get
* the child's local (sourceFile-relative) time. Works at any nesting depth.
*/
expandedParentStart?: number;
expandedHostKey?: string;
}
import type { TimelineElement } from "./timelineElement";
export type { TimelineElement };
export type ZoomMode = "fit" | "manual";
type TimelineTool = "select" | "razor";
@@ -0,0 +1,78 @@
/**
* One row in the timeline: a clip as Studio needs it, translated from the
* runtime's manifest at createTimelineElementFromManifestClip.
*
* Split out of playerStore, which had reached the 600-line studio ceiling and
* could not carry another field. Re-exported from there, so every existing
* importer is unaffected.
*/
import type { ClipManifestClip } from "../lib/playbackTypes";
export interface TimelineElement {
id: string;
label?: string;
key?: string;
kind?: ClipManifestClip["kind"];
tag: string;
start: number;
duration: number;
track: number;
/**
* The data-track-index as written in the source file. Set at the manifest
* translation boundary (createTimelineElementFromManifestClip) from the
* runtime clip's verbatim track, and preserved through display-lane remaps
* (normalizeToZones packs sparse authored tracks onto contiguous display
* lanes; expanded sub-comp children get synthetic display rows). Lane edits
* must persist THIS space writing a display-lane number into a sparse file
* re-targets the wrong track. For an expanded child the value is in its OWN
* source file's coordinate space, not the host timeline's.
*/
authoredTrack?: number;
/** Resolved z-index for stacking-aware timeline ordering. */
zIndex?: number;
/** True when the effective z-index was authored inline or through CSS, not auto. */
hasExplicitZIndex?: boolean;
/** Canonical CSS stacking context this element's z-index participates in. */
stackingContextId?: string | null;
/** Nearest parent composition context, matching RuntimeTimelineClip. */
parentCompositionId?: string | null;
/** Composition ancestry from root to nearest parent, matching RuntimeTimelineClip. */
compositionAncestors?: string[];
domId?: string;
/** Stable `data-hf-id` attribute value — used as primary patch target when present */
hfId?: string;
/** Best-effort selector used when patching source HTML back from timeline edits */
selector?: string;
/** Zero-based occurrence index for non-unique selectors */
selectorIndex?: number;
/** Source composition file that owns this element, when known */
sourceFile?: string;
src?: string;
playbackStart?: number;
playbackStartAttr?: "media-start" | "playback-start";
playbackRate?: number;
sourceDuration?: number;
volume?: number;
/** Verbatim `data-fx-chain` / `data-automation`; see automationLaneData. */
fxChain?: string;
automation?: string;
/** Path from data-composition-src — identifies sub-composition elements */
compositionSrc?: string;
/** Whether this row came from authored clip timing or Studio's full-duration layer fallback. */
timingSource?: "authored" | "implicit";
/** Set by data-timeline-locked on the host element — disables move and trim in Studio. */
timelineLocked?: boolean;
/** Set by data-hidden on the host element — hides the clip in preview and render. */
hidden?: boolean;
/** Value of data-timeline-role attribute — used to identify music vs. voiceover. */
timelineRole?: string;
/**
* Set by useExpandedTimelineElements on an inline-expanded sub-composition
* child: the absolute master-timeline start of the sub-comp host the child
* lives in. Presence marks the element as expanded; edits subtract it to get
* the child's local (sourceFile-relative) time. Works at any nesting depth.
*/
expandedParentStart?: number;
expandedHostKey?: string;
}