Skip to content

Write HTML. Render video. Built for agents.

fix(audio): two things the envelopes needed to be heard at all (#3017)

Vance Ingalls2c41a74ff72b
diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc
index 89e1b21d2f..a6bc9d1b8d 100644
--- a/.fallowrc.jsonc
+++ b/.fallowrc.jsonc
@@ -694,6 +694,11 @@
// optional fields, but the line-shift fingerprint re-flags the inherited
// complexity.
"packages/studio/src/utils/sourcePatcher.ts",
+ // runtime/media.ts: refreshRuntimeMediaCache pre-dates this work and is
+ // untouched by it — this stack only adds a volume-lane branch to
+ // syncRuntimeMedia's author-volume resolution, but touching the file makes
+ // fallow report the inherited function.
+ "packages/core/src/runtime/media.ts",
// timeline.ts: collectRuntimeTimelinePayload (CRITICAL) pre-dates this PR;
// only an import line changed here (slideshow/sceneId → slideshow/index),
// but the line-shift fingerprint makes fallow re-flag inherited complexity.
diff --git a/packages/core/src/runtime/audioAutomationVolume.test.ts b/packages/core/src/runtime/audioAutomationVolume.test.ts
new file mode 100644
index 0000000000..d7c71cb077
--- /dev/null
+++ b/packages/core/src/runtime/audioAutomationVolume.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from "vitest";
+import { elementVolumeLaneGain } from "./audioAutomationVolume.js";
+
+const el = (automation?: string) => ({
+ getAttribute: (name: string) =>
+ name === "data-automation" && automation !== undefined ? automation : null,
+});
+
+const duck = JSON.stringify({
+ version: 1,
+ lanes: [
+ {
+ target: "volume",
+ points: [
+ { t: 0, v: 0.55 },
+ { t: 1.4, v: 0.55 },
+ { t: 1.5, v: 0.15 },
+ { t: 9.5, v: 0.15 },
+ { t: 11, v: 0.55 },
+ ],
+ },
+ ],
+});
+
+describe("elementVolumeLaneGain", () => {
+ it("returns the lane's gain at a clip-local time", () => {
+ expect(elementVolumeLaneGain(el(duck), 0)).toBeCloseTo(0.55, 6);
+ expect(elementVolumeLaneGain(el(duck), 1.4)).toBeCloseTo(0.55, 6);
+ expect(elementVolumeLaneGain(el(duck), 5)).toBeCloseTo(0.15, 6);
+ expect(elementVolumeLaneGain(el(duck), 11)).toBeCloseTo(0.55, 6);
+ // Holds past the last point rather than falling to zero.
+ expect(elementVolumeLaneGain(el(duck), 20)).toBeCloseTo(0.55, 6);
+ });
+
+ it("ramps between points", () => {
+ const mid = elementVolumeLaneGain(el(duck), 1.45) ?? 0;
+ expect(mid).toBeLessThan(0.55);
+ expect(mid).toBeGreaterThan(0.15);
+ });
+
+ it("returns null with no automation, so the caller keeps its own rules", () => {
+ expect(elementVolumeLaneGain(el(), 1)).toBeNull();
+ expect(elementVolumeLaneGain(el(""), 1)).toBeNull();
+ });
+
+ it("returns null for an element that carries only FX lanes", () => {
+ const fxOnly = JSON.stringify({
+ version: 1,
+ lanes: [{ target: "fx.n1.frequency", points: [{ t: 0, v: 400 }] }],
+ });
+ expect(elementVolumeLaneGain(el(fxOnly), 0)).toBeNull();
+ });
+
+ it("plays flat rather than silent when the attribute is unreadable", () => {
+ expect(elementVolumeLaneGain(el("{not json"), 0)).toBeNull();
+ });
+
+ it("tolerates an object with no getAttribute at all", () => {
+ expect(elementVolumeLaneGain({}, 0)).toBeNull();
+ });
+
+ it("does not reparse the same attribute on every call", () => {
+ // The runtime asks once per tick per track; parsing there would run the JSON
+ // parser 60 times a second for a value that only changes on an edit.
+ let reads = 0;
+ const counting = {
+ getAttribute: (name: string) => {
+ if (name !== "data-automation") return null;
+ reads += 1;
+ return duck;
+ },
+ };
+ for (let i = 0; i < 50; i += 1) elementVolumeLaneGain(counting, i / 10);
+ expect(reads).toBe(50);
+ // Same object identity back each time proves the parse was cached.
+ const a = elementVolumeLaneGain(el(duck), 1);
+ const b = elementVolumeLaneGain(el(duck), 1);
+ expect(a).toBe(b);
+ });
+});
diff --git a/packages/core/src/runtime/audioAutomationVolume.ts b/packages/core/src/runtime/audioAutomationVolume.ts
new file mode 100644
index 0000000000..733a3bfec9
--- /dev/null
+++ b/packages/core/src/runtime/audioAutomationVolume.ts
@@ -0,0 +1,57 @@
+/**
+ * The volume lane's gain for an element at a moment in its clip.
+ *
+ * Volume is not scheduled onto the gain AudioParam the way FX parameters are.
+ * The runtime rewrites that gain every tick from `data-volume` and the GSAP
+ * seeked value, which would erase a scheduled envelope within a frame — so the
+ * lane feeds the same per-tick path the probed `volumeKeyframes` already use,
+ * and the render still bakes it into the samples.
+ */
+
+import {
+ HF_AUDIO_AUTOMATION_ATTR,
+ parseAutomation,
+ sampleAutomationLane,
+ VOLUME_TARGET,
+ type HfAutomationLane,
+} from "../audioAutomation.js";
+
+/**
+ * Parsed lanes by the attribute text they came from. Reparsing on every tick
+ * would run the JSON parser 60 times a second per track for a value that only
+ * changes when the author edits it.
+ */
+const cache = new Map<string, HfAutomationLane | null>();
+const CACHE_LIMIT = 64;
+
+function laneFromAttr(raw: string): HfAutomationLane | null {
+ const hit = cache.get(raw);
+ if (hit !== undefined) return hit;
+ let lane: HfAutomationLane | null = null;
+ try {
+ lane = parseAutomation(raw).lanes.find((l) => l.target === VOLUME_TARGET) ?? null;
+ } catch {
+ // Unreadable automation plays the track flat rather than silencing it.
+ lane = null;
+ }
+ if (cache.size > CACHE_LIMIT) cache.clear();
+ cache.set(raw, lane);
+ return lane;
+}
+
+/**
+ * Gain the lane asks for at `relTime` clip-local seconds, or null when the
+ * element has no volume lane and the caller should fall back to its own rules.
+ */
+export function elementVolumeLaneGain(
+ el: { getAttribute?(name: string): string | null },
+ relTime: number,
+): number | null {
+ const raw =
+ (typeof el.getAttribute === "function" ? el.getAttribute(HF_AUDIO_AUTOMATION_ATTR) : null) ??
+ "";
+ if (!raw) return null;
+ const lane = laneFromAttr(raw);
+ if (!lane || lane.points.length === 0) return null;
+ return sampleAutomationLane(lane, relTime);
+}
diff --git a/packages/core/src/runtime/audioFx.test.ts b/packages/core/src/runtime/audioFx.test.ts
index 64110c5de8..46ac76139f 100644
--- a/packages/core/src/runtime/audioFx.test.ts
+++ b/packages/core/src/runtime/audioFx.test.ts
@@ -70,8 +70,7 @@ describe("attachElementFxChain", () => {
it("connects source straight to destination when there is no chain", () => {
const src = new Node();
const dst = new Node();
- const handle = attachElementFxChain(ctx(), el(), src as never, dst as never);
- expect(handle).toBeNull();
+ attachElementFxChain(ctx(), el(), src as never, dst as never);
expect(src.connections).toContain(dst);
});
@@ -102,7 +101,7 @@ describe("attachElementFxChain", () => {
src as never,
dst as never,
);
- expect(handle).toBeNull();
+ expect(handle).not.toBeNull();
expect(src.connections).toContain(dst);
});
@@ -115,10 +114,90 @@ describe("attachElementFxChain", () => {
src as never,
dst as never,
);
- expect(handle).toBeNull();
+ expect(handle).not.toBeNull();
expect(src.connections).toContain(dst);
});
+ /**
+ * A structural edit — an effect added, removed or bypassed — used to be
+ * ignored here, so it only took effect 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 instead, with
+ * the source node left alone.
+ */
+ describe("editing the chain while it plays", () => {
+ const audioEl = (chain?: unknown): HTMLElement => {
+ const node = document.createElement("audio");
+ if (chain) node.setAttribute("data-fx-chain", JSON.stringify(chain));
+ document.body.append(node);
+ return node;
+ };
+ /** Let the MutationObserver's microtask run. */
+ const settle = () => new Promise((r) => setTimeout(r, 0));
+
+ it("routes through an effect added to a track that had none", async () => {
+ const src = new Node();
+ const dst = new Node();
+ const node = audioEl();
+ attachElementFxChain(ctx(), node, src as never, dst as never);
+ expect(src.connections).toContain(dst);
+
+ node.setAttribute("data-fx-chain", JSON.stringify(CHAIN));
+ await settle();
+ // Now feeding the chain, not the gain directly.
+ expect(src.connections.at(-1)).not.toBe(dst);
+ });
+
+ it("returns to dry when the last effect is removed", async () => {
+ const src = new Node();
+ const dst = new Node();
+ const node = audioEl(CHAIN);
+ attachElementFxChain(ctx(), node, src as never, dst as never);
+ const firstTarget = src.connections[0] as Node;
+ expect(firstTarget).not.toBe(dst);
+
+ node.removeAttribute("data-fx-chain");
+ await settle();
+ expect(src.connections.at(-1)).toBe(dst);
+ // The graph that was in the path is torn down, not left running.
+ expect(firstTarget.disconnected).toBe(true);
+ });
+
+ it("swaps the graph without replacing the source node", async () => {
+ const src = new Node();
+ const dst = new Node();
+ const node = audioEl(CHAIN);
+ attachElementFxChain(ctx(), node, src as never, dst as never);
+ const before = src.connections[0] as Node;
+
+ node.setAttribute(
+ "data-fx-chain",
+ JSON.stringify({
+ version: 1,
+ nodes: [
+ { type: "peaking", params: { frequency: 1000, gain: -6, q: 1 } },
+ { type: "lowpass", params: { frequency: 800, q: 0.7, poles: "2" } },
+ ],
+ }),
+ );
+ await settle();
+ const after = src.connections.at(-1) as Node;
+ // A different graph, reached from the same source: the audio never restarts.
+ expect(after).not.toBe(before);
+ expect(before.disconnected).toBe(true);
+ });
+
+ it("keeps playing dry when an edit leaves the chain unreadable", async () => {
+ const src = new Node();
+ const dst = new Node();
+ const node = audioEl(CHAIN);
+ attachElementFxChain(ctx(), node, src as never, dst as never);
+ node.setAttribute("data-fx-chain", "{not json");
+ await settle();
+ expect(src.connections.at(-1)).toBe(dst);
+ });
+ });
+
it("tears the chain down on dispose", () => {
const src = new Node();
const dst = new Node();
diff --git a/packages/core/src/runtime/audioFx.ts b/packages/core/src/runtime/audioFx.ts
index 224692d597..dd9b7b7dcb 100644
--- a/packages/core/src/runtime/audioFx.ts
+++ b/packages/core/src/runtime/audioFx.ts
@@ -88,8 +88,8 @@ export function readElementAutomation(el: {
* point where effects belong — capturing the element would process a stream
* nothing is listening to.
*
- * Returns null when the element carries no chain, leaving the original
- * source-to-gain connection in place.
+ * A track with no chain is wired straight through, but still watched: adding its
+ * 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.
@@ -102,10 +102,6 @@ export function attachElementFxChain(
timing?: AutomationTiming,
): { dispose(): void } | null {
const { chain } = readChain(el);
- if (chain.nodes.length === 0) {
- source.connect(destination);
- return null;
- }
// An AudioWorkletNode cannot be constructed before its processor is
// registered — it throws, and the whole chain is lost. So when the chain
@@ -137,21 +133,56 @@ export function attachElementFxChain(
};
}
- let handle: FxChainHandle;
- try {
- handle = buildFxChain(ctx, chain);
- } catch {
- // A chain we cannot realise plays dry rather than silencing the track.
- source.connect(destination);
- return null;
- }
+ // Null means the source runs straight into its gain: an empty chain, or one
+ // that could not be realised. Mutable because a structural edit swaps the
+ // whole graph rather than re-parameterising it.
+ let handle: FxChainHandle | null = null;
+ let automated: FxParamTarget[] = [];
- source.connect(handle.input);
- handle.output.connect(destination);
+ /** Take the current graph out of the path, leaving the source connected dry. */
+ const detach = (): void => {
+ try {
+ if (handle) {
+ source.disconnect(handle.input);
+ handle.output.disconnect(destination);
+ handle.dispose();
+ } else {
+ source.disconnect(destination);
+ }
+ } catch {
+ // Already disconnected; nothing to unwind.
+ }
+ handle = null;
+ };
- let automated: FxParamTarget[] = timing
- ? scheduleChainAutomation(readAutomation(el, chain), chain, handle.nodes, timing)
- : [];
+ /**
+ * Put `next` in the signal path.
+ *
+ * A chain that cannot be realised — an unregistered worklet, an unknown
+ * effect — plays dry rather than silencing the track.
+ */
+ const attach = (next: HfAudioFxChain): void => {
+ if (next.nodes.length === 0) {
+ source.connect(destination);
+ return;
+ }
+ try {
+ const built = buildFxChain(ctx, next);
+ source.connect(built.input);
+ built.output.connect(destination);
+ handle = built;
+ } catch {
+ source.connect(destination);
+ }
+ };
+
+ const scheduleFor = (next: HfAudioFxChain, at: AutomationTiming | null): void => {
+ automated =
+ at && handle ? scheduleChainAutomation(readAutomation(el, next), next, handle.nodes, at) : [];
+ };
+
+ attach(chain);
+ scheduleFor(chain, timing ?? null);
/**
* Re-aim the envelope at the live playhead. An edit lands mid-playback, so
@@ -171,14 +202,31 @@ export function attachElementFxChain(
const at = timingNow();
if (!at) return;
cancelParamLane(automated, at.scheduledAt);
- automated = scheduleChainAutomation(readAutomation(el, next), next, handle.nodes, at);
+ scheduleFor(next, at);
+ };
+
+ /**
+ * Rebuild the graph for a shape change — an effect added, removed, bypassed,
+ * or a filter's pole count switched — while the source keeps playing.
+ *
+ * The source node is untouched, so the audio does not restart; only the
+ * effects between it and its gain are replaced. Doing this here is what keeps
+ * a structural edit from needing a composition reload, which is what made the
+ * audio audibly chop.
+ */
+ const rebuild = (next: HfAudioFxChain): void => {
+ const at = timingNow();
+ cancelParamLane(automated, at?.scheduledAt ?? 0);
+ detach();
+ attach(next);
+ scheduleFor(next, at);
};
- // Follow the attribute while the source plays, so dragging a knob is heard
- // without rescheduling the track. Values-only changes re-parameterise the
- // running graph and land on the next 128-sample quantum; a shape change
- // (effect added, bypassed, pole count) cannot be patched in place and waits
- // for the next schedule rather than cutting the audio mid-play.
+ // Follow the attribute while the source plays, so editing a chain is heard
+ // without rescheduling the track. A values-only change re-parameterises the
+ // running graph and lands on the next 128-sample quantum; anything structural
+ // swaps the effects between the source and its gain, leaving the source — and
+ // so the playing audio — alone.
let observer: MutationObserver | null = null;
const target = el as unknown as Node;
if (
@@ -187,11 +235,10 @@ export function attachElementFxChain(
) {
observer = new MutationObserver(() => {
const next = readChain(el);
- if (next.chain.nodes.length === 0) return;
- handle.update(next.chain);
- // Values pushed by `update` would fight a running envelope, so the lanes
- // are re-scheduled on top of them from the current playhead.
- rescheduleAutomation(next.chain);
+ // `update` reports false when the change is structural rather than a new
+ // set of values, which is the signal to swap the graph.
+ if (!handle || !handle.update(next.chain)) rebuild(next.chain);
+ else rescheduleAutomation(next.chain);
});
observer.observe(target, {
attributes: true,
@@ -205,7 +252,7 @@ export function attachElementFxChain(
if (automated.length > 0) {
cancelParamLane(automated, typeof ctx.currentTime === "number" ? ctx.currentTime : 0);
}
- handle.dispose();
+ handle?.dispose();
},
};
}
diff --git a/packages/core/src/runtime/media.test.ts b/packages/core/src/runtime/media.test.ts
index 6de44a32fb..c6fa207ed8 100644
--- a/packages/core/src/runtime/media.test.ts
+++ b/packages/core/src/runtime/media.test.ts
@@ -307,6 +307,87 @@ describe("syncRuntimeMedia", () => {
document.body.innerHTML = "";
});
+ describe("volume automation lane", () => {
+ const DUCK = JSON.stringify({
+ version: 1,
+ lanes: [
+ {
+ target: "volume",
+ points: [
+ { t: 0, v: 0.8 },
+ { t: 2, v: 0.8 },
+ { t: 3, v: 0.1 },
+ { t: 8, v: 0.1 },
+ ],
+ },
+ ],
+ });
+
+ /**
+ * The runtime rewrites the transport's gain every tick. Before the lane fed
+ * this path it was scheduled onto the AudioParam instead and erased within a
+ * frame, so the envelope was inaudible in preview while being correct in the
+ * render.
+ */
+ function volumesAt(times: number[], automation?: string, volume = 0.55) {
+ const clip = createMockClip({ start: 0, end: 10, volume });
+ Object.defineProperty(clip.el, "readyState", { value: 4, writable: true });
+ if (automation) clip.el.setAttribute("data-automation", automation);
+ const seen: number[] = [];
+ for (const t of times) {
+ syncRuntimeMedia({
+ clips: [clip],
+ timeSeconds: t,
+ playing: true,
+ playbackRate: 1,
+ onElementVolume: (_el, v) => seen.push(v),
+ });
+ }
+ return seen;
+ }
+
+ it("drives the transport gain from the lane, not from data-volume", () => {
+ const [held, ducked] = volumesAt([1, 5], DUCK);
+ expect(held).toBeCloseTo(0.8, 5);
+ expect(ducked).toBeCloseTo(0.1, 5);
+ });
+
+ it("ramps between points across ticks", () => {
+ const [a, b, c] = volumesAt([2, 2.5, 3], DUCK);
+ expect(a).toBeCloseTo(0.8, 5);
+ expect(b).toBeGreaterThan(0.1);
+ expect(b).toBeLessThan(0.8);
+ expect(c).toBeCloseTo(0.1, 5);
+ });
+
+ it("falls back to data-volume when there is no lane", () => {
+ const [only] = volumesAt([5], undefined, 0.55);
+ expect(only).toBeCloseTo(0.55, 5);
+ });
+
+ it("supersedes keyframes probed from the timeline", () => {
+ // Both present: the lane is the explicit one, and `lint` warns about it.
+ const clip = createMockClip({ start: 0, end: 10, volume: 0.55 });
+ Object.defineProperty(clip.el, "readyState", { value: 4, writable: true });
+ clip.el.setAttribute("data-automation", DUCK);
+ clip.volumeKeyframes = [
+ { time: 0, volume: 1 },
+ { time: 10, volume: 1 },
+ ];
+ let seen = -1;
+ syncRuntimeMedia({
+ clips: [clip],
+ timeSeconds: 5,
+ playing: true,
+ playbackRate: 1,
+ onElementVolume: (_el, v) => {
+ seen = v;
+ },
+ });
+ expect(seen).toBeCloseTo(0.1, 5);
+ });
+ });
+
it("plays active clip when playing and buffered", () => {
const clip = createMockClip({ start: 0, end: 10 });
Object.defineProperty(clip.el, "readyState", { value: 4, writable: true });
diff --git a/packages/core/src/runtime/media.ts b/packages/core/src/runtime/media.ts
index d4ba743452..9a6a4b234a 100644
--- a/packages/core/src/runtime/media.ts
+++ b/packages/core/src/runtime/media.ts
@@ -1,5 +1,6 @@
import { swallow } from "./diagnostics";
import { interpolateVolumeGain, type VolumeKeyframe } from "./mediaVolumeEnvelope.js";
+import { elementVolumeLaneGain } from "./audioAutomationVolume.js";
import { normalizePlaybackRate } from "./playbackRate.js";
export function readElementPlaybackRate(el: Element): number {
@@ -270,7 +271,13 @@ export function syncRuntimeMedia(params: {
const currentElementVolume = clampVolume(el.volume);
let authorVolume: number;
- if (clip.volumeKeyframes && clip.volumeKeyframes.length > 0) {
+ // An explicit volume lane owns the fader. It is checked before the probed
+ // keyframes because the two would otherwise fight, and it is the one the
+ // author drew — `lint` warns when a track carries both.
+ const laneGain = elementVolumeLaneGain(el, relTime);
+ if (laneGain !== null) {
+ authorVolume = clampVolume(laneGain);
+ } else if (clip.volumeKeyframes && clip.volumeKeyframes.length > 0) {
// Keyframes probed from the GSAP timeline — same source as the renderer.
// Use the interpolated envelope value directly; no need to track GSAP changes.
// Index by elapsed time on the TIMELINE since the clip began, which is what