Skip to content

Commit ea03441

Browse files
vanceingallsclaude
andauthored
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>
1 parent 95751d6 commit ea03441

11 files changed

Lines changed: 632 additions & 145 deletions

File tree

packages/cli/src/commands/render.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,17 @@ vi.mock("../browser/preflight.js", () => ({
193193
runEnvironmentChecks: vi.fn(async () => preflightState.result),
194194
}));
195195

196+
// The "render command explicit composition" test below drives the real
197+
// `render.js` command handler, which takes the plan-based `execute.ts` path
198+
// (not the `renderLocal` unit under test above) — that path calls
199+
// `ensureBrowser` directly instead of going through the mocked preflight.
200+
// Unmocked, it performs a real network download of chrome-headless-shell into
201+
// the shared `~/.cache/hyperframes/chrome`, racing other packages' browser
202+
// tests in CI.
203+
vi.mock("../browser/manager.js", () => ({
204+
ensureBrowser: vi.fn(async () => ({ executablePath: "/mock/chrome", source: "cache" })),
205+
}));
206+
196207
vi.mock("../utils/orphanCleanup.js", () => ({
197208
killOrphanedProcesses: vi.fn(() => {
198209
orphanCleanupState.calls += 1;

packages/core/src/runtime/audioFx.test.ts

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,124 @@ describe("attachElementFxChain", () => {
315315
});
316316
});
317317

318+
/**
319+
* Lanes are committed to absolute context times, so the schedule is only
320+
* right for the rate it was booked at. Bumping `playbackRate` alone left a
321+
* lowpass sweeping over its original 10 wall-clock seconds while the audio
322+
* underneath ran through 20 clip-seconds of material — and the runtime's
323+
* stopAll()+reschedule recovery never fired for an unbounded source.
324+
*/
325+
describe("a rate change mid-playback", () => {
326+
/** Records what was booked and when, without the browser's overlap rules. */
327+
class TimedParam {
328+
curves: { time: number; duration: number }[] = [];
329+
ramps: number[] = [];
330+
value = 0;
331+
setValueAtTime(v: number): void {
332+
this.value = v;
333+
}
334+
linearRampToValueAtTime(v: number, t: number): void {
335+
this.ramps.push(t);
336+
this.value = v;
337+
}
338+
setValueCurveAtTime(_v: Float32Array, time: number, duration: number): void {
339+
this.curves.push({ time, duration });
340+
}
341+
cancelScheduledValues(): void {}
342+
cancelAndHoldAtTime(): void {}
343+
/** The last span booked, however the scheduler chose to express it. */
344+
last(): { time: number; duration: number } | undefined {
345+
return this.curves.at(-1);
346+
}
347+
}
348+
349+
const sweep = {
350+
version: 1,
351+
nodes: [{ type: "lowpass", id: "n1", params: { frequency: 300, q: 0.707 } }],
352+
};
353+
const lane = JSON.stringify({
354+
version: 1,
355+
lanes: [
356+
{
357+
target: "fx.n1.frequency",
358+
points: [
359+
{ t: 0, v: 300 },
360+
{ t: 8, v: 3000 },
361+
],
362+
},
363+
],
364+
});
365+
366+
const build = () => {
367+
const clock = { currentTime: 0 };
368+
const made: { frequency: TimedParam }[] = [];
369+
class TimedNode extends Node {
370+
override frequency = new TimedParam() as unknown as { value: number };
371+
}
372+
class TimedCtx extends Ctx {
373+
get currentTime(): number {
374+
return clock.currentTime;
375+
}
376+
override createBiquadFilter(): Node {
377+
const n = new TimedNode();
378+
made.push(n as unknown as { frequency: TimedParam });
379+
return n;
380+
}
381+
}
382+
const node = document.createElement("audio");
383+
node.setAttribute("data-fx-chain", JSON.stringify(sweep));
384+
node.setAttribute("data-automation", lane);
385+
document.body.append(node);
386+
const handle = attachElementFxChain(
387+
new TimedCtx() as unknown as BaseAudioContext,
388+
node,
389+
new Node() as never,
390+
new Node() as never,
391+
{ scheduledAt: 0, elapsed: 0, rate: 1 },
392+
);
393+
return { clock, node, handle, param: () => made[0]?.frequency as unknown as TimedParam };
394+
};
395+
396+
it("re-aims the envelope so the sweep still ends with the material", () => {
397+
const { clock, handle, param } = build();
398+
// Booked at 1x: the whole 8 s lane spans 8 s of context time.
399+
expect(param().last()).toEqual({ time: 0, duration: 8 });
400+
401+
clock.currentTime = 2;
402+
handle?.setRate(2);
403+
404+
// 6 clip-seconds are left, and at 2x they take 3 wall-clock seconds.
405+
// Without this the sweep kept its original plan to t=8 while the audio
406+
// ran out at t=5.
407+
expect(param().last()).toEqual({ time: 2, duration: 3 });
408+
});
409+
410+
it("measures later edits from the new rate, not the one it started at", async () => {
411+
// `elapsed` advances at whatever rate the reference frame holds, so a
412+
// frame left at 1x re-aims every subsequent edit at the wrong clip
413+
// position for as long as the track plays.
414+
const { clock, node, handle, param } = build();
415+
clock.currentTime = 2;
416+
handle?.setRate(2);
417+
418+
clock.currentTime = 4;
419+
// 2 wall-clock seconds at 2x is 4 clip-seconds, so the playhead is at 6
420+
// and 2 clip-seconds remain: 1 second of wall clock.
421+
node.setAttribute("data-automation", lane);
422+
await new Promise((r) => setTimeout(r, 0));
423+
expect(param().last()).toEqual({ time: 4, duration: 1 });
424+
});
425+
426+
it("ignores a rate that is not a rate", () => {
427+
const { clock, handle, param } = build();
428+
clock.currentTime = 2;
429+
handle?.setRate(0);
430+
handle?.setRate(Number.NaN);
431+
handle?.setRate(1);
432+
expect(param().last()).toEqual({ time: 0, duration: 8 });
433+
});
434+
});
435+
318436
it("tears the chain down on dispose", () => {
319437
const src = new Node();
320438
const dst = new Node();

packages/core/src/runtime/audioFx.ts

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -93,15 +93,29 @@ export function readElementAutomation(el: {
9393
* first effect is then heard without rescheduling the source.
9494
*
9595
* With `timing`, the element's automation lanes are scheduled onto the built
96-
* effects as AudioParam ramps, and rescheduled when the attribute is edited.
96+
* effects as AudioParam ramps, and rescheduled when the attribute is edited or
97+
* `setRate` reports the transport changed speed.
9798
*/
99+
export interface ElementFxHandle {
100+
dispose(): void;
101+
/**
102+
* Re-aim every booked envelope at a new playback rate.
103+
*
104+
* Lanes are committed to absolute context times, so a param scheduled at 1×
105+
* keeps its original wall-clock plan while the audio underneath runs at the
106+
* new speed: a lowpass sweeping over 10 clip-seconds, switched to 2×, eats
107+
* 20 s of material in 10 s of wall clock with the sweep unchanged.
108+
*/
109+
setRate(rate: number): void;
110+
}
111+
98112
export function attachElementFxChain(
99113
ctx: BaseAudioContext,
100114
el: { getAttribute?(name: string): string | null },
101115
source: AudioNode,
102116
destination: AudioNode,
103117
timing?: AutomationTiming,
104-
): { dispose(): void } | null {
118+
): ElementFxHandle | null {
105119
const { chain } = readChain(el);
106120

107121
// Null means the source runs straight into its gain: an empty chain, or one
@@ -178,20 +192,26 @@ export function attachElementFxChain(
178192
at && handle ? scheduleChainAutomation(readAutomation(el, next), next, handle.nodes, at) : [];
179193
};
180194

195+
// The reference frame every later reschedule measures from. Mutable because a
196+
// rate change rebases it: `elapsed` has to stop advancing at the old rate the
197+
// instant the new one takes effect, or every subsequent edit re-aims the
198+
// envelope at the wrong clip position.
199+
let frame: AutomationTiming | null = timing ? { ...timing } : null;
200+
181201
attach(chain);
182-
scheduleFor(chain, timing ?? null);
202+
scheduleFor(chain, frame);
183203

184204
/**
185205
* Re-aim the envelope at the live playhead. An edit lands mid-playback, so
186206
* the clip has advanced past the offset the source was scheduled with.
187207
*/
188208
const timingNow = (): AutomationTiming | null => {
189-
if (!timing) return null;
190-
const now = typeof ctx.currentTime === "number" ? ctx.currentTime : timing.scheduledAt;
209+
if (!frame) return null;
210+
const now = typeof ctx.currentTime === "number" ? ctx.currentTime : frame.scheduledAt;
191211
return {
192212
scheduledAt: now,
193-
elapsed: timing.elapsed + (now - timing.scheduledAt) * timing.rate,
194-
rate: timing.rate,
213+
elapsed: frame.elapsed + (now - frame.scheduledAt) * frame.rate,
214+
rate: frame.rate,
195215
};
196216
};
197217

@@ -251,6 +271,15 @@ export function attachElementFxChain(
251271
}
252272

253273
return {
274+
setRate: (rate: number) => {
275+
const at = timingNow();
276+
if (disposed || !at || !Number.isFinite(rate) || rate <= 0 || rate === at.rate) return;
277+
// Rebased at the playhead the OLD rate carried us to, then replayed from
278+
// there at the new one.
279+
frame = { ...at, rate };
280+
cancelParamLane(automated, at.scheduledAt);
281+
scheduleFor(readChain(el).chain, frame);
282+
},
254283
dispose: () => {
255284
disposed = true;
256285
observer?.disconnect();

packages/core/src/runtime/webAudioTransport.test.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,23 @@ describe("WebAudioTransport", () => {
289289
expect(mock.sourceNode.playbackRate.value).toBe(2);
290290
});
291291

292+
it("setRate re-aims each source's FX automation, not just its playback rate", async () => {
293+
// The lanes are committed to absolute context times when the source is
294+
// scheduled, so bumping playbackRate alone left every automated parameter
295+
// running its original plan over audio moving at a different speed.
296+
const { transport, mock, gen } = setupTransport(100);
297+
await transport.schedulePlayback(mockEl, mockBuffer, 5, 0, 8, 1, gen, 1);
298+
const active = (transport as unknown as { _activeSources: { fx?: unknown }[] })
299+
._activeSources;
300+
const setRate = vi.fn();
301+
active[0]!.fx = { dispose: vi.fn(), setRate };
302+
303+
transport.setRate(2);
304+
305+
expect(setRate).toHaveBeenCalledWith(2);
306+
expect(mock.sourceNode.playbackRate.value).toBe(2);
307+
});
308+
292309
it("setRate before any sources are scheduled does not throw", () => {
293310
const transport = new WebAudioTransport();
294311
expect(() => transport.setRate(2)).not.toThrow();

packages/core/src/runtime/webAudioTransport.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { attachElementFxChain, readElementAutomation } from "./audioFx.js";
1+
import { attachElementFxChain, readElementAutomation, type ElementFxHandle } from "./audioFx.js";
22
import {
33
scheduleParamLane,
44
volumeLane,
@@ -82,7 +82,7 @@ export type ScheduledSource = {
8282
sourceNode: AudioBufferSourceNode;
8383
gainNode: GainNode;
8484
/** FX chain spliced between source and gain, when the element carries one. */
85-
fx?: { dispose(): void } | null;
85+
fx?: ElementFxHandle | null;
8686
compositionStart: number;
8787
mediaStart: number;
8888
scheduledAt: number;
@@ -295,6 +295,14 @@ export class WebAudioTransport {
295295
* `getTime()` stays continuous across the change. Sources scheduled to
296296
* start in the future keep their original wallclock start time — callers
297297
* that need rate-correct future starts should `stopAll()` and reschedule.
298+
*
299+
* Each source's FX automation is re-aimed too. Lanes are committed to
300+
* absolute context times when the source is scheduled, so bumping only
301+
* `playbackRate` left every automated parameter running its original plan
302+
* over audio moving at a different speed. The `stopAll()`+reschedule recovery
303+
* in the runtime is no help here: it only fires for bounded sources, and a
304+
* project-level music bed with no `data-duration` is unbounded, so it never
305+
* recovered at all.
298306
*/
299307
setRate(rate: number): boolean {
300308
const safeRate = normalizeRate(rate);
@@ -307,6 +315,7 @@ export class WebAudioTransport {
307315
for (const source of this._activeSources) {
308316
try {
309317
source.sourceNode.playbackRate.value = safeRate;
318+
source.fx?.setRate(safeRate);
310319
} catch (err) {
311320
swallow("webAudioTransport.setRate", err);
312321
}

0 commit comments

Comments
 (0)