Skip to content

Commit b839dbd

Browse files
vanceingallsclaude
andauthored
fix(core): give the chorus and phaser LFOs a phase, and unwire them on dispose (#3183)
* 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. --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 2f97fc2 commit b839dbd

15 files changed

Lines changed: 522 additions & 172 deletions

‎packages/core/package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -596,9 +596,9 @@
596596
"typecheck": "tsc --noEmit && bun run typecheck:runtime",
597597
"typecheck:runtime": "tsc --noEmit -p tsconfig.runtime.json",
598598
"lint:runtime-preview-guards": "bun scripts/lint-runtime-preview-guards.ts",
599-
"build:audio-fx-runtime": "tsx scripts/build-inline-artifact.ts audio-fx",
599+
"build:audio-fx-runtime": "tsx scripts/build-audio-fx-runtime.ts",
600600
"build:hyperframes-runtime": "tsx scripts/build-hyperframes-runtime-artifact.ts",
601-
"build:position-edits-render": "tsx scripts/build-inline-artifact.ts position-edits",
601+
"build:position-edits-render": "tsx scripts/build-position-edits-render.ts",
602602
"check:position-edits-render": "bun run build:position-edits-render && git diff --exit-code -- src/generated/position-edits-render-inline.ts",
603603
"build:hyperframes-runtime:modular": "SANDBOX_RUNTIME_VARIANT=modular tsx scripts/build-hyperframes-runtime-artifact.ts",
604604
"build:hyperframe-runtime": "tsx scripts/build-hyperframes-runtime-artifact.ts",
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/** Build the injectable audio-FX runtime artifact from the canonical runtime. */
2+
3+
import { buildInjectedArtifact } from "./buildInjectedArtifact.js";
4+
5+
buildInjectedArtifact({
6+
scriptUrl: import.meta.url,
7+
entry: "stubs/audio-fx-runtime-entry.ts",
8+
out: "audio-fx-runtime-inline.ts",
9+
constName: "AUDIO_FX_RUNTIME_IIFE",
10+
fnName: "getAudioFxRuntimeScript",
11+
what: "audio-FX runtime IIFE",
12+
event: "audio_fx_runtime_generated",
13+
});

‎packages/core/scripts/build-inline-artifact.ts‎

Lines changed: 0 additions & 97 deletions
This file was deleted.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/** Build the injectable position-edits render artifact from the canonical runtime. */
2+
3+
import { buildInjectedArtifact } from "./buildInjectedArtifact.js";
4+
5+
buildInjectedArtifact({
6+
scriptUrl: import.meta.url,
7+
entry: "stubs/position-edits-render-entry.ts",
8+
out: "position-edits-render-inline.ts",
9+
constName: "POSITION_EDITS_RENDER_IIFE",
10+
fnName: "getPositionEditsRenderScript",
11+
what: "position-edits render IIFE",
12+
event: "position_edits_render_generated",
13+
});
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/**
2+
* Bundle a stub entry into an injectable IIFE, wrapped as a TypeScript constant.
3+
*
4+
* Two artifacts are built this way — the audio-FX runtime and the position-edits
5+
* render — and the engine injects both into the headless browser as a script tag.
6+
* They were two copies of this file differing in five names, which is a poor
7+
* place for a divergence to hide: whichever copy stopped being edited would go on
8+
* producing a subtly different artifact with nothing to say so.
9+
*/
10+
11+
import { execFileSync } from "node:child_process";
12+
import { mkdirSync, writeFileSync } from "node:fs";
13+
import { dirname, resolve } from "node:path";
14+
import { fileURLToPath } from "node:url";
15+
import { buildSync } from "esbuild";
16+
17+
export interface InjectedArtifact {
18+
/** The build script's own `import.meta.url`, so paths resolve beside it. */
19+
scriptUrl: string;
20+
/** Entry stub, relative to the package root. */
21+
entry: string;
22+
/** Output file name inside `src/generated`. */
23+
out: string;
24+
/** SCREAMING_CASE name for the string constant holding the IIFE. */
25+
constName: string;
26+
/** The accessor the rest of the codebase imports. */
27+
fnName: string;
28+
/** What that accessor returns, for its doc comment: "the pre-built X". */
29+
what: string;
30+
/** Structured log event name. */
31+
event: string;
32+
}
33+
34+
export function buildInjectedArtifact(spec: InjectedArtifact): void {
35+
const scriptDir = dirname(fileURLToPath(spec.scriptUrl));
36+
const scriptName = spec.scriptUrl.split("/").pop() ?? "";
37+
const repoRoot = resolve(scriptDir, "..");
38+
const entry = resolve(repoRoot, spec.entry);
39+
const generatedDir = resolve(repoRoot, "src/generated");
40+
const outPath = resolve(generatedDir, spec.out);
41+
42+
const result = buildSync({
43+
entryPoints: [entry],
44+
bundle: true,
45+
write: false,
46+
platform: "browser",
47+
format: "iife",
48+
target: ["es2020"],
49+
minify: true,
50+
legalComments: "none",
51+
});
52+
const iife = result.outputFiles[0]?.text ?? "";
53+
if (!iife) throw new Error(`esbuild produced no output for ${spec.entry.split("/").pop()}`);
54+
55+
mkdirSync(generatedDir, { recursive: true });
56+
writeFileSync(
57+
outPath,
58+
[
59+
`// AUTO-GENERATED by scripts/${scriptName} - do not edit`,
60+
`const ${spec.constName}: string = ${JSON.stringify(iife)};`,
61+
"",
62+
`/** Returns the pre-built ${spec.what} as a string constant. */`,
63+
`export function ${spec.fnName}(): string {`,
64+
` return ${spec.constName};`,
65+
"}",
66+
"",
67+
].join("\n"),
68+
"utf8",
69+
);
70+
71+
try {
72+
execFileSync("bun", ["x", "oxfmt", outPath], { stdio: "ignore" });
73+
} catch {
74+
// Formatting is best effort when the generator runs in a minimal environment.
75+
}
76+
77+
console.log(JSON.stringify({ event: spec.event, outPath, bytes: iife.length }));
78+
}

‎packages/core/src/audio/audioFxGraph.test.ts‎

Lines changed: 107 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,17 @@ class FakeNode {
2525
Q = new FakeParam();
2626
gain = new FakeParam();
2727
delayTime = new FakeParam();
28+
playbackRate = new FakeParam();
29+
loop = false;
2830
type = "";
2931
curve: Float32Array | null = null;
3032
oversample = "none";
31-
buffer: unknown = null;
33+
buffer: FakeBuffer | null = null;
3234
normalize = true;
3335
port = { postMessage: (m: unknown) => this.messages.push(m) };
3436
messages: unknown[] = [];
37+
/** `start(when, offset)` — the offset is the LFO's phase, so it is asserted. */
38+
startArgs: (number | undefined)[] | null = null;
3539
constructor(public kind: string) {}
3640
connect(next: FakeNode): FakeNode {
3741
this.connections.push(next);
@@ -40,10 +44,23 @@ class FakeNode {
4044
disconnect(): void {
4145
this.disconnected = true;
4246
}
43-
start(): void {}
47+
start(...args: (number | undefined)[]): void {
48+
this.startArgs = args;
49+
}
4450
stop(): void {}
4551
}
4652

53+
/** One channel, kept across `getChannelData` calls so what is written can be read. */
54+
class FakeBuffer {
55+
private data: Float32Array;
56+
constructor(public length: number) {
57+
this.data = new Float32Array(length);
58+
}
59+
getChannelData(): Float32Array {
60+
return this.data;
61+
}
62+
}
63+
4764
class FakeCtx {
4865
sampleRate = 48000;
4966
created: FakeNode[] = [];
@@ -67,14 +84,17 @@ class FakeCtx {
6784
createOscillator() {
6885
return this.make("osc");
6986
}
87+
createBufferSource() {
88+
return this.make("bufferSource");
89+
}
7090
createWaveShaper() {
7191
return this.make("waveshaper");
7292
}
7393
createConvolver() {
7494
return this.make("convolver");
7595
}
7696
createBuffer(_c: number, length: number) {
77-
return { length, getChannelData: () => new Float32Array(length) };
97+
return new FakeBuffer(length);
7898
}
7999
}
80100

@@ -350,19 +370,91 @@ describe("levels and per-channel state", () => {
350370
});
351371

352372
it("sets the phaser LFO waveform it declares", () => {
353-
const ctx = new FakeCtx();
354-
buildFxNode(ctx as unknown as BaseAudioContext, "phaser", {
355-
...defaultAudioFxParams("phaser"),
356-
type: "0",
357-
});
358-
const osc = ctx.created.find((n) => n.kind === "osc");
359-
expect(osc?.type).toBe("triangle");
360-
const ctx2 = new FakeCtx();
361-
buildFxNode(ctx2 as unknown as BaseAudioContext, "phaser", {
362-
...defaultAudioFxParams("phaser"),
363-
type: "1",
373+
// A quarter of the way through the cycle both waveforms peak at 1, so the
374+
// eighth is where they part: a sine is at sin(π/4), a triangle halfway up.
375+
const eighth = (c: FakeCtx): number => {
376+
const buffer = c.created.find((n) => n.kind === "bufferSource")?.buffer;
377+
if (!buffer) throw new Error("no LFO buffer");
378+
return buffer.getChannelData()[Math.round(buffer.length / 8)] ?? 0;
379+
};
380+
const build = (type: string): FakeCtx => {
381+
const c = new FakeCtx();
382+
buildFxNode(c as unknown as BaseAudioContext, "phaser", {
383+
...defaultAudioFxParams("phaser"),
384+
type,
385+
});
386+
return c;
387+
};
388+
expect(eighth(build("0"))).toBeCloseTo(0.5, 3);
389+
expect(eighth(build("1"))).toBeCloseTo(Math.SQRT1_2, 3);
390+
});
391+
392+
/**
393+
* The waveform is baked into a buffer at construction, so pushing a type change
394+
* into the running graph would be a no-op — preview would keep sweeping on a
395+
* triangle while the render used the sine the attribute now says.
396+
*/
397+
it("rebuilds a phaser when its LFO waveform changes", () => {
398+
const phaser = (params: Record<string, number | string>): HfAudioFxChain => ({
399+
version: 1,
400+
nodes: [
401+
{
402+
type: "phaser",
403+
enabled: true,
404+
params: { ...defaultAudioFxParams("phaser"), type: "0", ...params },
405+
},
406+
],
364407
});
365-
expect(ctx2.created.find((n) => n.kind === "osc")?.type).toBe("sine");
408+
const built = buildFxChain(asCtx(ctx()), phaser({}));
409+
expect(built.update(phaser({ type: "1" }))).toBe(false);
410+
// Everything else about a phaser still updates in place.
411+
const other = buildFxChain(asCtx(ctx()), phaser({}));
412+
expect(other.update(phaser({ speed: 2 }))).toBe(true);
413+
});
414+
415+
/**
416+
* An LFO's phase is the whole reason it is a looping buffer rather than an
417+
* OscillatorNode, whose phase is zero at `start()` and cannot be set.
418+
*
419+
* Preview rebuilds the graph mid-play — a seek, a scrub, any structural edit —
420+
* and an oscillator restarted there put the chorus at the top of its sweep
421+
* wherever the playhead happened to be, so preview disagreed with the render
422+
* and with itself across an edit.
423+
*/
424+
it("starts a modulated effect's LFO at the phase the clip has reached", () => {
425+
// 3.5 s at 2 Hz is seven whole cycles: back at phase zero.
426+
const whole = ctx();
427+
buildFxNode(asCtx(whole), "chorus", { ...defaultAudioFxParams("chorus"), speed: 2 }, 3.5);
428+
expect(whole.created.find((n) => n.kind === "bufferSource")?.startArgs?.[1]).toBeCloseTo(0, 6);
429+
// 3.6 s at 2 Hz is seven cycles and a fifth.
430+
const part = ctx();
431+
buildFxNode(asCtx(part), "chorus", { ...defaultAudioFxParams("chorus"), speed: 2 }, 3.6);
432+
const src = part.created.find((n) => n.kind === "bufferSource");
433+
expect(src?.startArgs?.[1]).toBeCloseTo(0.2, 6);
434+
expect(src?.loop).toBe(true);
435+
// One second of waveform: the rate reads in Hz, so a speed lane needs no map.
436+
expect(src?.playbackRate.value).toBeCloseTo(2, 6);
437+
});
438+
439+
/**
440+
* A source node is not retired by disconnecting what it feeds. The chorus and
441+
* phaser stopped their LFO and left it out of the nodes they disconnect, so
442+
* every rebuild that dropped one left a modulator still wired to the delay or
443+
* the allpass bank it had been driving.
444+
*/
445+
it("unwires a modulated effect's LFO when the effect is disposed", () => {
446+
for (const type of ["chorus", "phaser"]) {
447+
const c = ctx();
448+
buildFxNode(asCtx(c), type, defaultAudioFxParams(type)).dispose();
449+
const lfo = c.created.find((node) => node.kind === "bufferSource");
450+
expect(lfo?.disconnected, `${type} left its LFO connected`).toBe(true);
451+
}
452+
});
453+
454+
it("starts the LFO at zero for a render, which always begins at the clip's start", () => {
455+
const c = ctx();
456+
buildFxNode(asCtx(c), "phaser", defaultAudioFxParams("phaser"));
457+
expect(c.created.find((n) => n.kind === "bufferSource")?.startArgs?.[1]).toBe(0);
366458
});
367459

368460
it("rebuilds a one-pole filter when its cutoff moves", () => {

0 commit comments

Comments
 (0)