fix(engine): duck before quantising, chunk the PCM, reschedule on rate change (#3174)

* 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.

* fix(studio): pull TimelineLanes under the 600-line cap

TimelineLanes.tsx hit 620 lines. Extracted the three per-clip pointer
gestures (resize-start, pointer-down move-arm, click/razor-split) into
createClipGestureHandlers — one factory call per rendered clip instead of
~120 lines of inline handler bodies in the render loop. 529 lines now.

* fix(studio): split the extracted pointerdown handler under the CRAP threshold

Moving the ~120-line gesture logic into timelineClipGestureHandlers.ts
concentrated it into two functions fallow flagged (onPointerDown at CRAP
63.6, onResizeStart at 31.6). Split the decision logic (which gesture a
pointerdown implies) into a pure resolvePointerDownAction, then split
its own intent-blocking check into isIntentBlocked. onResizeStart's guard
moved into canStartResize. Every function now scores under 30.

* fix(studio): drop the unused DomEditSelection import in PropertyPanelFlat

CI caught it on PR #3026 (wa-12-panel-params); a later refactor in the
stack removed the last use of the type here without removing the import.

* fix(studio): close the typecheck and fallow gaps wa-18b-reschedule opened

useAutomationLanes.ts's write() assumed gesture-scoped coalescing and a
preview-only commit that useDomEditAttributeCommits.ts never grew — backported
that option support from its own later commit so the two sides of the API
agree. The paste path and its tests were missing the box selection's v0/v1
bounds a sibling commit added to AutomationSelection. The FX panel's carve
controls still edited the six mechanism numbers (maxCutDb, bands,
intelligibilityBias) after carveProfile() collapsed authoring to one Strength
knob, so those fields no longer existed on HfCarveSettings; UI now edits
strength, and analyseCarveBands is called with carveProfile(strength).

Also closes fallow's complexity, dead-code and duplication findings on this
PR's diff: extracted automationLaneDragMath.ts (pure group/point-move math)
and useAutomationRangeDrag.ts (the marquee-select gesture) out of
useAutomationLaneGestures.ts, pulled a couple of render-loop ternaries and a
resolver into named functions, dropped an export nothing outside its file
used, and shared a step-simplifier between audioCarve's two envelope
builders.

The edge-stretch vs. box-select priority test in TimelineAutomationLane.test
was still pinning the pre-box-select rule (edge wins over a point sitting on
it) that a sibling commit deliberately reversed — a point inside the box is
now selected content, so grabbing it drags the group instead. Updated the
test to the shipped rule instead of the old one.

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

* fix(core): cap the via conic's weight so an edge-clamped via point can't NaN

A via point pulled out past the segment (viaX: 5, viaY: -3) clamps to
(0.999, 0.001) — exactly on the steady region's edge, where edge - viaX is 0.
viaConic divided by that zero to get an infinite weight, and shapeVia turned
Infinity into NaN a few steps later (Infinity - Infinity in the quadratic
coefficient). NaN reaching setValueCurveAtTime silences the automated
parameter for the rest of the render.

Capped the weight at 1e6 instead of leaving it unbounded — past that point
the arc already reads as touching the via point, so nothing visible is lost.
Also hardened shapeVia's existing denominator guard (`<= 0`) to `!(> 0)`,
since NaN fails the original comparison and fell through it.

Review by Miga (PR #3208).

* fix(studio-server): fingerprint the proactive waveform cache key too

The route already keys the waveform cache on the asset's size and mtime as
well as its path, so a rebuilt-in-place file gets fresh peaks instead of
stale ones. generateWaveformCache — the proactive path that runs on upload —
still called buildWaveformCacheKey with the path alone, so it wrote to a
different key than the route reads from (making the pre-generated cache
never found) and kept the exact collision bug this fingerprint exists to fix
on its own path.

Review by Miga (PR #3211).

* style(docs): run oxfmt on the /hyperframes-audio skill docs

Table column widths had drifted out of alignment with oxfmt's own rules,
failing format:check and blocking the Preflight gate every downstream
branch inherits. Whitespace only, no content change.

* fix(core): stop \b from missing underscore-separated names, guard clipsOverlap's negative duration

\b treats `_` as a word character, so \bbed\b never matched bed_01,
music_bed_loop, or theme_song, and \bvo\b/\bvox\b/\btts\b had the same gap —
an underscore-separated bed classified as "unknown" and could end up offered
as its own carve source. Replaced the short hints with a boundary that
actually excludes letters and digits on both sides.

clipsOverlap computed end = start + duration without guarding sign, so a
negative duration put end before start — an interval that does not describe
anything, and one specific case showed it silently dropping a real overlap
(a shorter, earlier broken end rejected a clip that genuinely contained the
point). Duration clamps to zero instead: a clip cannot un-play time, and a
zero-length clip at its start is the sane reading of "duration nobody wrote
down as positive."

Review by Miga (PR #3212).

* fix(studio): widen PropertyPanel's resetModules render timeout again

The 20s margin (already once widened for the same reason) is timing out in
CI's full-monorepo Test run — the resetModules()+fresh-import render this
test needs is uncached and competes with every other package's test suite
for the same worker pool, and the same test passes in well under 2s
standalone. Went to 45s rather than re-tuning to whatever number happens to
clear the current CI load, since that number moves every time CI gains a
package.

* fix(studio): stop the single-candidate auto-apply carve firing twice

Two auto-apply effects both fire when sourceOptions.length === 1: the
multi-candidate effect only guards length === 0, so a single candidate
passes it too, and the single-candidate effect passes its own guard right
after — both compute the same sources list and both call setCarve, so the
common case (one narrator, one bed) triggered two decodes, two FFT runs, and
two concurrent attribute writes for one decision.

The multi-candidate effect now defers to its sibling for exactly one
candidate, which already has its own detailed handling for that case.

Review by Miga (PR #3213).

* feat(core): carve against every voice over a bed, always (#3212)

* feat(core): carve against every voice over a bed, always dynamically

A bed usually runs under a whole sequence — a narrator, an interview answer, a
second presenter — and carving against one of them left the others fighting it.
`source` becomes `sources`, and `mixCarveSources` sums every voice onto the BED's
clock before anything is measured. That is what keeps one analysis sufficient: the
chain is fixed, so there is no per-voice filter to switch between, and bands drawn
from all the speech there is with envelopes that rise wherever any of it happens
answer the actual question — where and when is speech masking this bed.

Summed rather than averaged: two people talking at once mask more than either
alone. Audio before the bed starts is dropped rather than folded in at zero, since
it plays over nothing and shifting it would put a cut where there is no voice.

`dynamic` is gone. A fixed depth thins the bed through every pause, and once both
have been heard there is no reason to want it, so every carve follows the speech.

Two helpers the panel and the headless script now share instead of each carrying a
copy — two definitions of "what does this name suggest" drift, and then the two
disagree about which track is the voice:

- `classifyAudioName` reads a track's kind from its id and filename together.
  `unknown` is deliberately common: treating an unrecognised name as "not a voice"
  would hide the one track somebody needs to pick.
- `clipsOverlap` keeps out a voice that never plays while the bed does. An unwritten
  duration counts as unbounded, not zero — refusing a clip whose length the
  composition leaves to the media would drop the commonest case there is.

Files written before this still load: a single `source` reads as a one-voice list,
a stored `dynamic` is ignored, and an absent attribute means the defaults whole.

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

* fix(core): stop \b from missing underscore-separated names, guard clipsOverlap's negative duration

\b treats `_` as a word character, so \bbed\b never matched bed_01,
music_bed_loop, or theme_song, and \bvo\b/\bvox\b/\btts\b had the same gap —
an underscore-separated bed classified as "unknown" and could end up offered
as its own carve source. Replaced the short hints with a boundary that
actually excludes letters and digits on both sides.

clipsOverlap computed end = start + duration without guarding sign, so a
negative duration put end before start — an interval that does not describe
anything, and one specific case showed it silently dropping a real overlap
(a shorter, earlier broken end rejected a clip that genuinely contained the
point). Duration clamps to zero instead: a clip cannot un-play time, and a
zero-length clip at its start is the sane reading of "duration nobody wrote
down as positive."

Review by Miga (PR #3212).

---------

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

* fix(studio): port the carve UI off the removed source/dynamic fields

#3212 (accidentally squash-merged into this branch instead of main) changed
HfCarveSettings from a single `source` + `dynamic` toggle to a `sources`
list with dynamic mode removed outright — the multi-voice UI consumer that
goes with that shape lands in the very next PR, so this branch was left with
a type that no longer matched its own code.

Minimal port, not the multi-voice redesign that PR does properly: the
"Listen to" picker and analyse() treat sources[0] as the one voice this UI
still understands, and every dynamic-mode branch (the automated envelope
lanes, the toggle, the checkbox) is gone along with the field — a carve is
now always the static value the analysis computes, matching what the type
change made permanent. Test suite trimmed the same way: the automation-lane
and toggle tests covered behavior that no longer exists.

* fix(cli): stop render.test.ts from downloading a real browser

The "render command explicit composition" test drives the full render.js
command handler, which takes the plan-based execute.ts path instead of the
renderLocal path the other tests in this file exercise. That path calls
ensureBrowser directly, bypassing the mocked preflight.js, and performs a
real network install of chrome-headless-shell into the shared
~/.cache/hyperframes/chrome cache as a side effect of running the test suite.
In CI this raced with the engine's audioFxRender browser tests running in a
parallel worker against the same HOME, producing an intermittent EACCES on
the partially-installed binary.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Vance Ingalls
2026-08-13 05:23:40 -07:00
committed by GitHub
co-authored by Claude Sonnet 5
parent 95751d6b10
commit ea0344122c
11 changed files with 632 additions and 145 deletions
+118
View File
@@ -315,6 +315,124 @@ describe("attachElementFxChain", () => {
});
});
/**
* Lanes are committed to absolute context times, so the schedule is only
* right for the rate it was booked at. Bumping `playbackRate` alone left a
* lowpass sweeping over its original 10 wall-clock seconds while the audio
* underneath ran through 20 clip-seconds of material — and the runtime's
* stopAll()+reschedule recovery never fired for an unbounded source.
*/
describe("a rate change mid-playback", () => {
/** Records what was booked and when, without the browser's overlap rules. */
class TimedParam {
curves: { time: number; duration: number }[] = [];
ramps: number[] = [];
value = 0;
setValueAtTime(v: number): void {
this.value = v;
}
linearRampToValueAtTime(v: number, t: number): void {
this.ramps.push(t);
this.value = v;
}
setValueCurveAtTime(_v: Float32Array, time: number, duration: number): void {
this.curves.push({ time, duration });
}
cancelScheduledValues(): void {}
cancelAndHoldAtTime(): void {}
/** The last span booked, however the scheduler chose to express it. */
last(): { time: number; duration: number } | undefined {
return this.curves.at(-1);
}
}
const sweep = {
version: 1,
nodes: [{ type: "lowpass", id: "n1", params: { frequency: 300, q: 0.707 } }],
};
const lane = JSON.stringify({
version: 1,
lanes: [
{
target: "fx.n1.frequency",
points: [
{ t: 0, v: 300 },
{ t: 8, v: 3000 },
],
},
],
});
const build = () => {
const clock = { currentTime: 0 };
const made: { frequency: TimedParam }[] = [];
class TimedNode extends Node {
override frequency = new TimedParam() as unknown as { value: number };
}
class TimedCtx extends Ctx {
get currentTime(): number {
return clock.currentTime;
}
override createBiquadFilter(): Node {
const n = new TimedNode();
made.push(n as unknown as { frequency: TimedParam });
return n;
}
}
const node = document.createElement("audio");
node.setAttribute("data-fx-chain", JSON.stringify(sweep));
node.setAttribute("data-automation", lane);
document.body.append(node);
const handle = attachElementFxChain(
new TimedCtx() as unknown as BaseAudioContext,
node,
new Node() as never,
new Node() as never,
{ scheduledAt: 0, elapsed: 0, rate: 1 },
);
return { clock, node, handle, param: () => made[0]?.frequency as unknown as TimedParam };
};
it("re-aims the envelope so the sweep still ends with the material", () => {
const { clock, handle, param } = build();
// Booked at 1x: the whole 8 s lane spans 8 s of context time.
expect(param().last()).toEqual({ time: 0, duration: 8 });
clock.currentTime = 2;
handle?.setRate(2);
// 6 clip-seconds are left, and at 2x they take 3 wall-clock seconds.
// Without this the sweep kept its original plan to t=8 while the audio
// ran out at t=5.
expect(param().last()).toEqual({ time: 2, duration: 3 });
});
it("measures later edits from the new rate, not the one it started at", async () => {
// `elapsed` advances at whatever rate the reference frame holds, so a
// frame left at 1x re-aims every subsequent edit at the wrong clip
// position for as long as the track plays.
const { clock, node, handle, param } = build();
clock.currentTime = 2;
handle?.setRate(2);
clock.currentTime = 4;
// 2 wall-clock seconds at 2x is 4 clip-seconds, so the playhead is at 6
// and 2 clip-seconds remain: 1 second of wall clock.
node.setAttribute("data-automation", lane);
await new Promise((r) => setTimeout(r, 0));
expect(param().last()).toEqual({ time: 4, duration: 1 });
});
it("ignores a rate that is not a rate", () => {
const { clock, handle, param } = build();
clock.currentTime = 2;
handle?.setRate(0);
handle?.setRate(Number.NaN);
handle?.setRate(1);
expect(param().last()).toEqual({ time: 0, duration: 8 });
});
});
it("tears the chain down on dispose", () => {
const src = new Node();
const dst = new Node();
+36 -7
View File
@@ -93,15 +93,29 @@ export function readElementAutomation(el: {
* first effect is then heard without rescheduling the source.
*
* With `timing`, the element's automation lanes are scheduled onto the built
* effects as AudioParam ramps, and rescheduled when the attribute is edited.
* effects as AudioParam ramps, and rescheduled when the attribute is edited or
* `setRate` reports the transport changed speed.
*/
export interface ElementFxHandle {
dispose(): void;
/**
* Re-aim every booked envelope at a new playback rate.
*
* Lanes are committed to absolute context times, so a param scheduled at 1×
* keeps its original wall-clock plan while the audio underneath runs at the
* new speed: a lowpass sweeping over 10 clip-seconds, switched to 2×, eats
* 20 s of material in 10 s of wall clock with the sweep unchanged.
*/
setRate(rate: number): void;
}
export function attachElementFxChain(
ctx: BaseAudioContext,
el: { getAttribute?(name: string): string | null },
source: AudioNode,
destination: AudioNode,
timing?: AutomationTiming,
): { dispose(): void } | null {
): ElementFxHandle | null {
const { chain } = readChain(el);
// Null means the source runs straight into its gain: an empty chain, or one
@@ -178,20 +192,26 @@ export function attachElementFxChain(
at && handle ? scheduleChainAutomation(readAutomation(el, next), next, handle.nodes, at) : [];
};
// The reference frame every later reschedule measures from. Mutable because a
// rate change rebases it: `elapsed` has to stop advancing at the old rate the
// instant the new one takes effect, or every subsequent edit re-aims the
// envelope at the wrong clip position.
let frame: AutomationTiming | null = timing ? { ...timing } : null;
attach(chain);
scheduleFor(chain, timing ?? null);
scheduleFor(chain, frame);
/**
* Re-aim the envelope at the live playhead. An edit lands mid-playback, so
* the clip has advanced past the offset the source was scheduled with.
*/
const timingNow = (): AutomationTiming | null => {
if (!timing) return null;
const now = typeof ctx.currentTime === "number" ? ctx.currentTime : timing.scheduledAt;
if (!frame) return null;
const now = typeof ctx.currentTime === "number" ? ctx.currentTime : frame.scheduledAt;
return {
scheduledAt: now,
elapsed: timing.elapsed + (now - timing.scheduledAt) * timing.rate,
rate: timing.rate,
elapsed: frame.elapsed + (now - frame.scheduledAt) * frame.rate,
rate: frame.rate,
};
};
@@ -251,6 +271,15 @@ export function attachElementFxChain(
}
return {
setRate: (rate: number) => {
const at = timingNow();
if (disposed || !at || !Number.isFinite(rate) || rate <= 0 || rate === at.rate) return;
// Rebased at the playhead the OLD rate carried us to, then replayed from
// there at the new one.
frame = { ...at, rate };
cancelParamLane(automated, at.scheduledAt);
scheduleFor(readChain(el).chain, frame);
},
dispose: () => {
disposed = true;
observer?.disconnect();
@@ -289,6 +289,23 @@ describe("WebAudioTransport", () => {
expect(mock.sourceNode.playbackRate.value).toBe(2);
});
it("setRate re-aims each source's FX automation, not just its playback rate", async () => {
// The lanes are committed to absolute context times when the source is
// scheduled, so bumping playbackRate alone left every automated parameter
// running its original plan over audio moving at a different speed.
const { transport, mock, gen } = setupTransport(100);
await transport.schedulePlayback(mockEl, mockBuffer, 5, 0, 8, 1, gen, 1);
const active = (transport as unknown as { _activeSources: { fx?: unknown }[] })
._activeSources;
const setRate = vi.fn();
active[0]!.fx = { dispose: vi.fn(), setRate };
transport.setRate(2);
expect(setRate).toHaveBeenCalledWith(2);
expect(mock.sourceNode.playbackRate.value).toBe(2);
});
it("setRate before any sources are scheduled does not throw", () => {
const transport = new WebAudioTransport();
expect(() => transport.setRate(2)).not.toThrow();
+11 -2
View File
@@ -1,4 +1,4 @@
import { attachElementFxChain, readElementAutomation } from "./audioFx.js";
import { attachElementFxChain, readElementAutomation, type ElementFxHandle } from "./audioFx.js";
import {
scheduleParamLane,
volumeLane,
@@ -82,7 +82,7 @@ export type ScheduledSource = {
sourceNode: AudioBufferSourceNode;
gainNode: GainNode;
/** FX chain spliced between source and gain, when the element carries one. */
fx?: { dispose(): void } | null;
fx?: ElementFxHandle | null;
compositionStart: number;
mediaStart: number;
scheduledAt: number;
@@ -295,6 +295,14 @@ export class WebAudioTransport {
* `getTime()` stays continuous across the change. Sources scheduled to
* start in the future keep their original wallclock start time callers
* that need rate-correct future starts should `stopAll()` and reschedule.
*
* Each source's FX automation is re-aimed too. Lanes are committed to
* absolute context times when the source is scheduled, so bumping only
* `playbackRate` left every automated parameter running its original plan
* over audio moving at a different speed. The `stopAll()`+reschedule recovery
* in the runtime is no help here: it only fires for bounded sources, and a
* project-level music bed with no `data-duration` is unbounded, so it never
* recovered at all.
*/
setRate(rate: number): boolean {
const safeRate = normalizeRate(rate);
@@ -307,6 +315,7 @@ export class WebAudioTransport {
for (const source of this._activeSources) {
try {
source.sourceNode.playbackRate.value = safeRate;
source.fx?.setRate(safeRate);
} catch (err) {
swallow("webAudioTransport.setRate", err);
}