Skip to content

Write HTML. Render video. Built for agents.

feat(audio): automation envelope model (#3015)

Vance Ingallsfd97926cf67e
diff --git a/packages/core/package-subpaths.json b/packages/core/package-subpaths.json
index b8905eb8e2..a11d35c426 100644
--- a/packages/core/package-subpaths.json
+++ b/packages/core/package-subpaths.json
@@ -110,6 +110,12 @@
"types": "./dist/audioCarve.d.ts",
"environments": ["browser", "bun", "node"]
},
+ "./audio-automation": {
+ "source": "./src/audioAutomation.ts",
+ "runtime": "./dist/audioAutomation.js",
+ "types": "./dist/audioAutomation.d.ts",
+ "environments": ["browser", "bun", "node"]
+ },
"./color-grading": {
"source": "./src/colorGrading.ts",
"runtime": "./dist/colorGrading.js",
diff --git a/packages/core/package.json b/packages/core/package.json
index 95f8d81cb8..33e41b7264 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -124,6 +124,12 @@
"import": "./src/audioCarve.ts",
"types": "./src/audioCarve.ts"
},
+ "./audio-automation": {
+ "bun": "./src/audioAutomation.ts",
+ "node": "./dist/audioAutomation.js",
+ "import": "./src/audioAutomation.ts",
+ "types": "./src/audioAutomation.ts"
+ },
"./color-grading": {
"bun": "./src/colorGrading.ts",
"node": "./dist/colorGrading.js",
@@ -398,6 +404,10 @@
"import": "./dist/audioCarve.js",
"types": "./dist/audioCarve.d.ts"
},
+ "./audio-automation": {
+ "import": "./dist/audioAutomation.js",
+ "types": "./dist/audioAutomation.d.ts"
+ },
"./color-grading": {
"import": "./dist/colorGrading.js",
"types": "./dist/colorGrading.d.ts"
diff --git a/packages/core/src/audio/audioFxGraph.test.ts b/packages/core/src/audio/audioFxGraph.test.ts
index 61cf137315..6339ba5f23 100644
--- a/packages/core/src/audio/audioFxGraph.test.ts
+++ b/packages/core/src/audio/audioFxGraph.test.ts
@@ -341,3 +341,67 @@ describe("levels and per-channel state", () => {
expect(buildFxChain(ctx, twoPole(300)).update(twoPole(2000))).toBe(true);
});
});
+
+describe("automatable parameters", () => {
+ /**
+ * The registry's `automatable` flag is what the panel and the scheduler both
+ * trust, and it is written by hand. Build every effect and check that each
+ * flagged knob really does reach an AudioParam — a flag that lies would
+ * offer an automation lane that silently does nothing.
+ */
+ it("exposes an AudioParam for every knob the registry marks automatable", () => {
+ for (const def of HF_AUDIO_FX) {
+ const ctx = new FakeCtx() as unknown as BaseAudioContext;
+ const handle = buildFxNode(ctx, def.id, defaultAudioFxParams(def.id));
+ const flagged = def.params
+ .filter((p) => p.kind === "number" && p.automatable)
+ .map((p) => p.key);
+ for (const key of flagged) {
+ const targets = handle.automation?.[key];
+ expect(
+ targets,
+ `${def.id}.${key} is flagged automatable but exposes no AudioParam`,
+ ).toBeTruthy();
+ expect(targets?.length, `${def.id}.${key} exposes an empty target list`).toBeGreaterThan(0);
+ }
+ }
+ });
+
+ it("exposes nothing the registry has not flagged", () => {
+ for (const def of HF_AUDIO_FX) {
+ const ctx = new FakeCtx() as unknown as BaseAudioContext;
+ const handle = buildFxNode(ctx, def.id, defaultAudioFxParams(def.id));
+ const flagged = new Set(
+ def.params.filter((p) => p.kind === "number" && p.automatable).map((p) => p.key),
+ );
+ for (const key of Object.keys(handle.automation ?? {})) {
+ expect(flagged.has(key), `${def.id}.${key} is exposed but not flagged automatable`).toBe(
+ true,
+ );
+ }
+ }
+ });
+
+ it("maps a knob's own unit onto the AudioParam it drives", () => {
+ const ctx = new FakeCtx() as unknown as BaseAudioContext;
+ const delay = buildFxNode(ctx, "delay", { ...defaultAudioFxParams("delay"), time: 250 });
+ // The knob reads milliseconds; delayTime is in seconds.
+ expect(delay.automation?.time?.[0]?.map?.(250)).toBeCloseTo(0.25, 10);
+ // A wet/dry mix is two gains moving in opposition, not one.
+ const mix = delay.automation?.mix ?? [];
+ expect(mix.length).toBe(2);
+ expect(mix[0]?.map?.(0.3) ?? 0.3).toBeCloseTo(0.3, 10);
+ expect(mix[1]?.map?.(0.3)).toBeCloseTo(0.7, 10);
+ });
+
+ it("leaves a one-pole filter unexposed, since its coefficients are fixed", () => {
+ const ctx = new FakeCtx() as unknown as BaseAudioContext;
+ const twoPole = buildFxNode(ctx, "highpass", defaultAudioFxParams("highpass"));
+ expect(twoPole.automation?.frequency?.length).toBe(1);
+ const onePole = buildFxNode(ctx, "highpass", {
+ ...defaultAudioFxParams("highpass"),
+ poles: "1",
+ });
+ expect(onePole.automation?.frequency).toBeUndefined();
+ });
+});
diff --git a/packages/core/src/audio/audioFxGraph.ts b/packages/core/src/audio/audioFxGraph.ts
index 1a026e280d..dc3f5a7111 100644
--- a/packages/core/src/audio/audioFxGraph.ts
+++ b/packages/core/src/audio/audioFxGraph.ts
@@ -58,10 +58,27 @@ export function synthesizeReverbImpulse(
return out;
}
+/**
+ * Where an automation lane writes when it drives one knob.
+ *
+ * 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 its own mapping out of the knob's declared unit.
+ */
+export interface FxParamTarget {
+ param: AudioParam;
+ map?: (value: number) => number;
+}
+
export interface FxNodeHandle {
input: AudioNode;
output: AudioNode;
update(params: HfAudioFxParamValues): void;
+ /**
+ * AudioParams behind the knobs the registry marks `automatable`, keyed by
+ * parameter key. Absent for a node whose values cannot be scheduled.
+ */
+ automation?: Record<string, FxParamTarget[]>;
dispose(): void;
}
@@ -69,6 +86,14 @@ type Builder = (ctx: BaseAudioContext, p: HfAudioFxParamValues) => FxNodeHandle;
const n = (v: number | string | undefined): number => (typeof v === "number" ? v : Number(v ?? 0));
+/** Milliseconds on the knob, seconds on the AudioParam. */
+const msToSec = (v: number): number => v / 1000;
+
+/** A wet/dry pair: the dry side is whatever the wet side is not. */
+function mixTargets(wet: AudioParam, dry: AudioParam): FxParamTarget[] {
+ return [{ param: wet }, { param: dry, map: (v) => 1 - v }];
+}
+
/** Linear crossfade: dry falls as wet rises, in lockstep. */
function setWetDryMix(wet: GainNode, dry: GainNode, mix: number): void {
wet.gain.value = mix;
@@ -76,10 +101,22 @@ function setWetDryMix(wet: GainNode, dry: GainNode, mix: number): void {
}
/** A node that is its own input and output and has nothing to tear down. */
-function simple(node: AudioNode, update: (p: HfAudioFxParamValues) => void): FxNodeHandle {
- return { input: node, output: node, update, dispose: () => node.disconnect() };
+function simple(
+ node: AudioNode,
+ update: (p: HfAudioFxParamValues) => void,
+ automation?: Record<string, FxParamTarget[]>,
+): FxNodeHandle {
+ return { input: node, output: node, update, automation, dispose: () => node.disconnect() };
}
+/**
+ * Filter types whose Q a BiquadFilterNode actually reads. The spec leaves it
+ * unused for shelving filters, so the registry offers no shelf Q and the graph
+ * must expose none either — the exposure invariant would otherwise advertise an
+ * AudioParam for a knob nobody can set.
+ */
+const USES_Q: ReadonlySet<BiquadFilterType> = new Set(["peaking", "highpass", "lowpass"]);
+
function biquad(type: BiquadFilterType, useGain: boolean): Builder {
return (ctx, p) => {
const f = ctx.createBiquadFilter();
@@ -90,7 +127,11 @@ function biquad(type: BiquadFilterType, useGain: boolean): Builder {
if (useGain) f.gain.value = n(v.gain);
};
apply(p);
- return simple(f, apply);
+ return simple(f, apply, {
+ frequency: [{ param: f.frequency }],
+ ...(USES_Q.has(type) ? { q: [{ param: f.Q }] } : {}),
+ ...(useGain ? { gain: [{ param: f.gain }] } : {}),
+ });
};
}
@@ -108,6 +149,8 @@ function onePoleBuilder(kind: "highpass" | "lowpass"): Builder {
? ctx.createIIRFilter([1 / (1 + k), -1 / (1 + k)], [1, (k - 1) / (k + 1)])
: ctx.createIIRFilter([k / (1 + k), k / (1 + k)], [1, (k - 1) / (k + 1)]);
// IIRFilterNode coefficients are immutable; the caller rebuilds on change.
+ // Nothing here is schedulable either, so a frequency lane on a one-pole
+ // filter has nowhere to write — the scheduler skips what is not exposed.
return simple(node, () => {});
};
}
@@ -160,6 +203,9 @@ const waveshaper: Builder = (ctx, p) => {
input: preGain,
output: postGain,
update: apply,
+ // The curve itself is rebuilt wholesale, but the make-up gain after it is
+ // an ordinary AudioParam.
+ automation: { output: [{ param: postGain.gain, map: (v) => Math.pow(10, v / 20) }] },
dispose: () => {
preGain.disconnect();
ws.disconnect();
@@ -190,6 +236,11 @@ const delayFeedback: Builder = (ctx, p) => {
input,
output: out,
update: apply,
+ automation: {
+ time: [{ param: dl.delayTime, map: (v) => Math.min(5, msToSec(v)) }],
+ feedback: [{ param: fb.gain }],
+ mix: mixTargets(wet.gain, dry.gain),
+ },
dispose: () => [input, out, dl, fb, wet, dry].forEach((x) => x.disconnect()),
};
};
@@ -217,6 +268,12 @@ const chorusLfo: Builder = (ctx, p) => {
input,
output: out,
update: apply,
+ automation: {
+ delay: [{ param: dl.delayTime, map: msToSec }],
+ depth: [{ param: depth.gain, map: msToSec }],
+ speed: [{ param: lfo.frequency }],
+ mix: mixTargets(wet.gain, dry.gain),
+ },
dispose: () => {
try {
lfo.stop();
@@ -283,6 +340,13 @@ const allpassPhaser: Builder = (ctx, p) => {
input,
output: out,
update: apply,
+ // `delay` and `decay` set the sweep centre, which feeds every stage's
+ // frequency at once — not one knob, one param — so they stay unautomated.
+ automation: {
+ speed: [{ param: lfo.frequency }],
+ in_gain: [{ param: dry.gain }],
+ out_gain: [{ param: wet.gain }],
+ },
dispose: () => {
try {
lfo.stop();
@@ -322,6 +386,9 @@ const convolver: Builder = (ctx, p) => {
input,
output: out,
update: apply,
+ // Size and damping regenerate the impulse response, so only the wet/dry
+ // balance is schedulable.
+ automation: { wet: [{ param: wet.gain }], dry: [{ param: dry.gain }] },
dispose: () => [input, out, conv, wet, dry].forEach((x) => x.disconnect()),
};
};
diff --git a/packages/core/src/audioAutomation.test.ts b/packages/core/src/audioAutomation.test.ts
new file mode 100644
index 0000000000..4a59caae8a
--- /dev/null
+++ b/packages/core/src/audioAutomation.test.ts
@@ -0,0 +1,290 @@
+import { describe, expect, it } from "vitest";
+import {
+ applyCurve,
+ fxAutomationTarget,
+ isConstantLane,
+ parseAutomation,
+ parseAutomationTarget,
+ resolveAutomation,
+ resolveAutomationRange,
+ sampleAutomationCurve,
+ sampleAutomationLane,
+ serializeAutomation,
+ VOLUME_RANGE,
+ type HfAutomationLane,
+} from "./audioAutomation.js";
+import { mintAudioFxNodeId, parseAudioFxChain, type HfAudioFxChain } from "./audioFx.js";
+
+const chain: HfAudioFxChain = {
+ version: 1,
+ nodes: [
+ { type: "peaking", id: "n1", enabled: true, params: { frequency: 1000, gain: 0, Q: 1 } },
+ { type: "highpass", id: "n2", enabled: true, params: {} },
+ ],
+};
+
+const lane = (points: HfAutomationLane["points"], target = "volume"): HfAutomationLane => ({
+ target,
+ points,
+});
+
+describe("targets", () => {
+ it("reads volume and fx targets, and rejects anything else", () => {
+ expect(parseAutomationTarget("volume")).toEqual({ kind: "volume" });
+ expect(parseAutomationTarget("fx.n1.frequency")).toEqual({
+ kind: "fx",
+ nodeId: "n1",
+ param: "frequency",
+ });
+ expect(parseAutomationTarget("fx.n1")).toBeNull();
+ expect(parseAutomationTarget("gain")).toBeNull();
+ expect(parseAutomationTarget("")).toBeNull();
+ });
+
+ it("resolves a range from the registry, not from the lane", () => {
+ const r = resolveAutomationRange(fxAutomationTarget("n1", "frequency"), chain);
+ expect(r).not.toBeNull();
+ expect(r?.scale).toBe("log");
+ expect(r?.unit).toBe("Hz");
+ expect(r?.min).toBeGreaterThan(0);
+ expect(resolveAutomationRange("volume", chain)).toEqual(VOLUME_RANGE);
+ });
+
+ it("has no range for a missing node, a missing param, or an enum param", () => {
+ expect(resolveAutomationRange("fx.nope.frequency", chain)).toBeNull();
+ expect(resolveAutomationRange("fx.n1.nonsense", chain)).toBeNull();
+ // `poles` is an enum: there is no envelope between one and two poles.
+ expect(resolveAutomationRange("fx.n2.poles", chain)).toBeNull();
+ });
+});
+
+describe("normalisation", () => {
+ it("sorts points and collapses duplicate times, keeping the later value", () => {
+ const parsed = parseAutomation(
+ JSON.stringify({
+ version: 1,
+ lanes: [
+ {
+ target: "volume",
+ points: [
+ { t: 2, v: 0.2 },
+ { t: 0, v: 1 },
+ { t: 2, v: 0.9 },
+ ],
+ },
+ ],
+ }),
+ );
+ expect(parsed.lanes[0]!.points).toEqual([
+ { t: 0, v: 1 },
+ { t: 2, v: 0.9 },
+ ]);
+ });
+
+ it("drops non-finite points rather than letting NaN reach an AudioParam", () => {
+ const parsed = parseAutomation(
+ JSON.stringify({
+ version: 1,
+ lanes: [
+ {
+ target: "volume",
+ points: [
+ { t: 0, v: 0.5 },
+ { t: 1, v: null },
+ { t: "x", v: 1 },
+ { t: 2, v: 0.25 },
+ ],
+ },
+ ],
+ }),
+ );
+ expect(parsed.lanes[0]!.points).toEqual([
+ { t: 0, v: 0.5 },
+ { t: 2, v: 0.25 },
+ ]);
+ });
+
+ it("clamps volume into 0..1 at parse time", () => {
+ const parsed = parseAutomation(
+ JSON.stringify({
+ version: 1,
+ lanes: [
+ {
+ target: "volume",
+ points: [
+ { t: 0, v: 4 },
+ { t: 1, v: -2 },
+ ],
+ },
+ ],
+ }),
+ );
+ expect(parsed.lanes[0]!.points.map((p) => p.v)).toEqual([1, 0]);
+ });
+
+ it("refuses malformed input instead of silently losing an envelope", () => {
+ expect(() => parseAutomation("{")).toThrow(/not valid JSON/);
+ expect(() => parseAutomation(JSON.stringify({ version: 9, lanes: [] }))).toThrow(
+ /Unsupported automation version/,
+ );
+ expect(() => parseAutomation(JSON.stringify({ version: 1 }))).toThrow(/lanes/);
+ expect(() =>
+ parseAutomation(JSON.stringify({ version: 1, lanes: [{ target: "nope", points: [] }] })),
+ ).toThrow(/unreadable target/);
+ });
+
+ it("round-trips through the attribute", () => {
+ const source = {
+ version: 1,
+ lanes: [
+ lane([
+ { t: 0, v: 0.8 },
+ { t: 3, v: 0.2, curve: 0.5 },
+ ]),
+ lane(
+ [
+ { t: 0, v: 200 },
+ { t: 4, v: 8000 },
+ ],
+ "fx.n1.frequency",
+ ),
+ ],
+ };
+ expect(parseAutomation(serializeAutomation(source))).toEqual(source);
+ });
+});
+
+describe("resolveAutomation", () => {
+ it("drops lanes whose effect was deleted and clamps the rest to the registry", () => {
+ const resolved = resolveAutomation(
+ {
+ version: 1,
+ lanes: [
+ lane([{ t: 0, v: 1_000_000 }], "fx.n1.frequency"),
+ lane([{ t: 0, v: 0.5 }], "fx.gone.frequency"),
+ lane([{ t: 0, v: 0.5 }]),
+ ],
+ },
+ chain,
+ );
+ expect(resolved.lanes.map((l) => l.target)).toEqual(["fx.n1.frequency", "volume"]);
+ const range = resolveAutomationRange("fx.n1.frequency", chain);
+ expect(resolved.lanes[0]!.points[0]!.v).toBe(range?.max);
+ });
+
+ it("drops every fx lane when the track has no chain at all", () => {
+ const resolved = resolveAutomation(
+ { version: 1, lanes: [lane([{ t: 0, v: 1 }], "fx.n1.frequency"), lane([{ t: 0, v: 1 }])] },
+ undefined,
+ );
+ expect(resolved.lanes.map((l) => l.target)).toEqual(["volume"]);
+ });
+});
+
+describe("sampling", () => {
+ const ramp = lane([
+ { t: 1, v: 0 },
+ { t: 3, v: 1 },
+ ]);
+
+ it("holds the end values outside the points", () => {
+ expect(sampleAutomationLane(ramp, 0)).toBe(0);
+ expect(sampleAutomationLane(ramp, 1)).toBe(0);
+ expect(sampleAutomationLane(ramp, 3)).toBe(1);
+ expect(sampleAutomationLane(ramp, 99)).toBe(1);
+ });
+
+ it("interpolates linearly between them", () => {
+ expect(sampleAutomationLane(ramp, 2)).toBeCloseTo(0.5, 10);
+ expect(sampleAutomationLane(ramp, 1.5)).toBeCloseTo(0.25, 10);
+ });
+
+ it("interpolates a log-scaled parameter in log space", () => {
+ const sweep = lane(
+ [
+ { t: 0, v: 200 },
+ { t: 4, v: 8000 },
+ ],
+ "fx.n1.frequency",
+ );
+ // Halfway through the sweep is the geometric mean, not the arithmetic one:
+ // an even-sounding sweep, which is what a log knob already promises.
+ expect(sampleAutomationLane(sweep, 2, "log")).toBeCloseTo(Math.sqrt(200 * 8000), 6);
+ expect(sampleAutomationLane(sweep, 2, "linear")).toBeCloseTo(4100, 6);
+ });
+
+ it("bends a segment with curve, staying pinned at both ends", () => {
+ const bent = lane([
+ { t: 0, v: 0, curve: 1 },
+ { t: 1, v: 1 },
+ ]);
+ expect(sampleAutomationLane(bent, 0)).toBe(0);
+ expect(sampleAutomationLane(bent, 1)).toBe(1);
+ // Positive curve holds low and rises late.
+ expect(sampleAutomationLane(bent, 0.5)).toBeLessThan(0.5);
+ const eased = lane([
+ { t: 0, v: 0, curve: -1 },
+ { t: 1, v: 1 },
+ ]);
+ expect(sampleAutomationLane(eased, 0.5)).toBeGreaterThan(0.5);
+ expect(applyCurve(0.5, 0)).toBe(0.5);
+ });
+
+ it("walks a dense lane by bisection, not by scanning", () => {
+ const points = Array.from({ length: 200 }, (_, i) => ({ t: i, v: i % 2 }));
+ const dense = lane(points);
+ expect(sampleAutomationLane(dense, 100)).toBe(0);
+ expect(sampleAutomationLane(dense, 101)).toBe(1);
+ expect(sampleAutomationLane(dense, 100.5)).toBeCloseTo(0.5, 10);
+ });
+
+ it("caps a pathological lane so the scheduler cannot be hung", () => {
+ const parsed = parseAutomation(
+ JSON.stringify({
+ version: 1,
+ lanes: [
+ { target: "volume", points: Array.from({ length: 5000 }, (_, i) => ({ t: i, v: 0.5 })) },
+ ],
+ }),
+ );
+ expect(parsed.lanes[0]!.points.length).toBe(512);
+ });
+
+ it("samples a curve at both endpoints", () => {
+ const curve = sampleAutomationCurve(ramp, 1, 3, 5);
+ expect(curve.length).toBe(5);
+ expect(curve[0]).toBe(0);
+ expect(curve[4]).toBe(1);
+ expect(curve[2]).toBeCloseTo(0.5, 6);
+ });
+
+ it("spots a lane not worth scheduling", () => {
+ expect(isConstantLane(lane([{ t: 0, v: 0.5 }]))).toBe(true);
+ expect(
+ isConstantLane(
+ lane([
+ { t: 0, v: 0.5 },
+ { t: 2, v: 0.5 },
+ ]),
+ ),
+ ).toBe(true);
+ expect(isConstantLane(ramp)).toBe(false);
+ });
+});
+
+describe("chain node ids", () => {
+ it("mints the first free id and survives a round trip", () => {
+ expect(mintAudioFxNodeId({ version: 1, nodes: [] })).toBe("n1");
+ expect(mintAudioFxNodeId(chain)).toBe("n3");
+ const gap: HfAudioFxChain = { version: 1, nodes: [{ type: "peaking", id: "n2" }] };
+ expect(mintAudioFxNodeId(gap)).toBe("n1");
+ });
+
+ it("keeps ids through parse so lanes stay pointed at the same effect", () => {
+ const json = JSON.stringify({
+ version: 1,
+ nodes: [{ type: "peaking", id: "n7", params: {} }],
+ });
+ expect(parseAudioFxChain(json).nodes[0]!.id).toBe("n7");
+ });
+});
diff --git a/packages/core/src/audioAutomation.ts b/packages/core/src/audioAutomation.ts
new file mode 100644
index 0000000000..f6363f5426
--- /dev/null
+++ b/packages/core/src/audioAutomation.ts
@@ -0,0 +1,368 @@
+/**
+ * Automation envelopes for audio tracks.
+ *
+ * A lane is a list of breakpoints over one parameter — track volume, or one
+ * knob of one effect in the track's FX chain. Ableton's clip-envelope model:
+ * times are clip-local, so an envelope travels with the clip when it moves.
+ *
+ * Nothing here touches Web Audio. This module owns the format and the
+ * interpolation, and the same `sampleAutomationLane` is used to draw the lane
+ * in the timeline, to schedule it in preview, and to bake it at render — one
+ * curve, three consumers, or the picture and the sound disagree.
+ */
+
+import { getAudioFxDef, type HfAudioFxChain, type HfAudioFxNumberParam } from "./audioFx.js";
+
+export const HF_AUDIO_AUTOMATION_ATTR = "data-automation";
+
+/** Automation files are versioned; a reader must refuse a version it doesn't know. */
+export const HF_AUDIO_AUTOMATION_VERSION = 1;
+
+/**
+ * A pathological document should not be able to hang the scheduler, which
+ * expands every segment into scheduled ramps. Well past any hand-drawn
+ * envelope; a lane is dense at 100 points.
+ */
+export const MAX_AUTOMATION_POINTS = 512;
+
+export interface HfAutomationPoint {
+ /** Seconds from the start of the clip, not the composition. */
+ t: number;
+ /** Value in the parameter's own unit — dB for a threshold, Hz for a cutoff. */
+ v: number;
+ /**
+ * Curvature of the segment *leaving* this point, -1..1. Absent or 0 is a
+ * straight line; positive holds low then rises late, negative rises early.
+ */
+ curve?: number;
+}
+
+export interface HfAutomationLane {
+ /** `volume`, or `fx.<nodeId>.<paramKey>`. */
+ target: string;
+ points: HfAutomationPoint[];
+}
+
+export interface HfAutomation {
+ version: number;
+ lanes: HfAutomationLane[];
+}
+
+export class AudioAutomationError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "AudioAutomationError";
+ }
+}
+
+export const VOLUME_TARGET = "volume";
+
+export type HfAutomationTarget = { kind: "volume" } | { kind: "fx"; nodeId: string; param: string };
+
+/** Split a target string. Returns null for anything unrecognised. */
+export function parseAutomationTarget(target: string): HfAutomationTarget | null {
+ if (target === VOLUME_TARGET) return { kind: "volume" };
+ const parts = target.split(".");
+ if (parts.length !== 3 || parts[0] !== "fx") return null;
+ const [, nodeId, param] = parts;
+ if (!nodeId || !param) return null;
+ return { kind: "fx", nodeId, param };
+}
+
+export function fxAutomationTarget(nodeId: string, param: string): string {
+ return `fx.${nodeId}.${param}`;
+}
+
+/**
+ * The value range a lane is drawn and clamped against.
+ *
+ * Volume is linear 0..1, matching `data-volume` and the existing volume
+ * envelope machinery — no dB conversion enters the volume path. Everything
+ * else is read from the effect registry, so a lane can never offer a value the
+ * renderer would reject, and the log-scaled knobs sweep the way a DAW's do.
+ */
+export interface AutomationRange {
+ min: number;
+ max: number;
+ step: number;
+ unit: string;
+ label: string;
+ scale: "linear" | "log";
+ /** Where an empty lane draws its flat line, and what a new point starts at. */
+ default: number;
+}
+
+export const VOLUME_RANGE: AutomationRange = {
+ min: 0,
+ max: 1,
+ step: 0.01,
+ unit: "",
+ label: "Volume",
+ scale: "linear",
+ default: 1,
+};
+
+/**
+ * Resolve a lane's target against a chain. Returns null when the target names
+ * a node or parameter that is not there — the effect was deleted, or the
+ * parameter is an enum, which has no envelope between its values.
+ */
+export function resolveAutomationRange(
+ target: string,
+ chain: HfAudioFxChain | undefined,
+): AutomationRange | null {
+ const parsed = parseAutomationTarget(target);
+ if (!parsed) return null;
+ if (parsed.kind === "volume") return VOLUME_RANGE;
+ const node = chain?.nodes.find((n) => n.id === parsed.nodeId);
+ if (!node) return null;
+ const def = getAudioFxDef(node.type);
+ const param = def?.params.find((p) => p.key === parsed.param);
+ if (!param || param.kind !== "number") return null;
+ const p = param as HfAudioFxNumberParam;
+ return {
+ min: p.min,
+ max: p.max,
+ step: p.step,
+ unit: p.unit,
+ label: `${def?.label ?? node.type} · ${p.label}`,
+ scale: p.scale === "log" && p.min > 0 ? "log" : "linear",
+ default: p.default,
+ };
+}
+
+/**
+ * Coerce a JSON field to a number, treating anything that is not already one —
+ * or a string that plainly reads as one — as absent.
+ *
+ * Not `Number(raw)`: that turns `null`, `""` and `[]` into 0, which for an
+ * envelope means a silent drop to zero rather than a point the reader rejects.
+ */
+function numberOrNull(raw: unknown): number | null {
+ if (typeof raw === "number") return Number.isFinite(raw) ? raw : null;
+ if (typeof raw === "string" && raw.trim() !== "") {
+ const n = Number(raw);
+ return Number.isFinite(n) ? n : null;
+ }
+ return null;
+}
+
+function clampCurve(v: unknown): number {
+ const n = numberOrNull(v);
+ if (n === null || n === 0) return 0;
+ return Math.min(1, Math.max(-1, n));
+}
+
+/**
+ * Clean one point, or reject it.
+ *
+ * A missing or non-finite value reaching an AudioParam silences the node for
+ * the rest of the render, so such a point is dropped rather than coerced.
+ */
+function cleanPoint(
+ p: HfAutomationPoint | undefined,
+ range: AutomationRange | null,
+): HfAutomationPoint | null {
+ const t = numberOrNull(p?.t);
+ const v = numberOrNull(p?.v);
+ if (t === null || v === null) return null;
+ const clamped = range ? Math.min(range.max, Math.max(range.min, v)) : v;
+ const curve = clampCurve(p?.curve);
+ return { t: Math.max(0, t), v: clamped, ...(curve ? { curve } : {}) };
+}
+
+/**
+ * Order points, drop unusable ones, and collapse duplicate times.
+ *
+ * Later wins on a tie so that dragging a point onto another replaces it rather
+ * than leaving an invisible one underneath.
+ */
+function normalizePoints(
+ points: readonly HfAutomationPoint[],
+ range: AutomationRange | null,
+): HfAutomationPoint[] {
+ const clean = points
+ .map((p) => cleanPoint(p, range))
+ .filter((p): p is HfAutomationPoint => p !== null)
+ .sort((a, b) => a.t - b.t);
+ const out: HfAutomationPoint[] = [];
+ for (const p of clean) {
+ if (out.length > 0 && out[out.length - 1]!.t === p.t) out[out.length - 1] = p;
+ else out.push(p);
+ }
+ return out.slice(0, MAX_AUTOMATION_POINTS);
+}
+
+/**
+ * Structural normalisation, with no knowledge of the chain: sort and clean the
+ * points of every lane and drop lanes that carry none. Range clamping and
+ * orphan removal need the chain and happen in `resolveAutomation`.
+ */
+export function normalizeAutomation(automation: HfAutomation): HfAutomation {
+ const lanes: HfAutomationLane[] = [];
+ for (const lane of automation.lanes) {
+ if (!parseAutomationTarget(lane.target)) continue;
+ const range = lane.target === VOLUME_TARGET ? VOLUME_RANGE : null;
+ const points = normalizePoints(lane.points ?? [], range);
+ if (points.length > 0) lanes.push({ target: lane.target, points });
+ }
+ return { version: HF_AUDIO_AUTOMATION_VERSION, lanes };
+}
+
+/**
+ * Bind automation to a chain: clamp each lane into its parameter's declared
+ * range and drop lanes whose target no longer exists.
+ *
+ * Dropping is deliberate. An envelope on a deleted effect has nothing to
+ * drive, and keeping it would silently reattach if an unrelated effect later
+ * took the same node id.
+ */
+export function resolveAutomation(
+ automation: HfAutomation,
+ chain: HfAudioFxChain | undefined,
+): HfAutomation {
+ const lanes: HfAutomationLane[] = [];
+ for (const lane of automation.lanes) {
+ const range = resolveAutomationRange(lane.target, chain);
+ if (!range) continue;
+ const points = normalizePoints(lane.points, range);
+ if (points.length > 0) lanes.push({ target: lane.target, points });
+ }
+ return { version: HF_AUDIO_AUTOMATION_VERSION, lanes };
+}
+
+/**
+ * Parse an automation attribute.
+ *
+ * Malformed input throws rather than being skipped, matching the chain reader:
+ * a track that quietly loses its envelope renders differently from the project
+ * the author saved, which is worse than refusing.
+ */
+export function parseAutomation(json: string): HfAutomation {
+ let raw: unknown;
+ try {
+ raw = JSON.parse(json);
+ } catch (err) {
+ throw new AudioAutomationError(`Automation is not valid JSON: ${(err as Error).message}`);
+ }
+ if (typeof raw !== "object" || raw === null) {
+ throw new AudioAutomationError("Automation must be a JSON object.");
+ }
+ const obj = raw as { version?: unknown; lanes?: unknown };
+ if (obj.version !== HF_AUDIO_AUTOMATION_VERSION) {
+ throw new AudioAutomationError(`Unsupported automation version: ${String(obj.version)}`);
+ }
+ if (!Array.isArray(obj.lanes)) {
+ throw new AudioAutomationError("Automation is missing a `lanes` array.");
+ }
+ const lanes: HfAutomationLane[] = obj.lanes.map((l, i) => {
+ if (typeof l !== "object" || l === null) {
+ throw new AudioAutomationError(`Lane ${i} is not an object.`);
+ }
+ const lane = l as { target?: unknown; points?: unknown };
+ if (typeof lane.target !== "string" || !parseAutomationTarget(lane.target)) {
+ throw new AudioAutomationError(`Lane ${i} has an unreadable target: ${String(lane.target)}`);
+ }
+ if (!Array.isArray(lane.points)) {
+ throw new AudioAutomationError(`Lane ${i} is missing a \`points\` array.`);
+ }
+ return { target: lane.target, points: lane.points as HfAutomationPoint[] };
+ });
+ return normalizeAutomation({ version: HF_AUDIO_AUTOMATION_VERSION, lanes });
+}
+
+/** Serialise for the `data-automation` attribute. */
+export function serializeAutomation(automation: HfAutomation): string {
+ return JSON.stringify({
+ version: HF_AUDIO_AUTOMATION_VERSION,
+ lanes: automation.lanes.map((lane) => ({
+ target: lane.target,
+ points: lane.points.map((p) => ({
+ t: p.t,
+ v: p.v,
+ ...(p.curve ? { curve: p.curve } : {}),
+ })),
+ })),
+ });
+}
+
+/**
+ * Shape the 0..1 progress across a segment.
+ *
+ * `curve` is an exponent in disguise: 0 is linear, and the ends reach a
+ * quarter-power and a fourth-power bend, which is about the range a DAW's
+ * envelope handle covers before the segment stops reading as a curve.
+ */
+export function applyCurve(x: number, curve: number | undefined): number {
+ if (!curve) return x;
+ return Math.pow(x, Math.pow(2, 2 * curve));
+}
+
+function lerpValue(a: number, b: number, x: number, scale: "linear" | "log"): number {
+ // A frequency sweep interpolated linearly spends almost all its time in the
+ // top octave. Log-scaled parameters interpolate in log space so a 200 Hz to
+ // 8 kHz move sounds like an even sweep, which is what the knob's own scale
+ // already promises.
+ if (scale === "log" && a > 0 && b > 0) {
+ return Math.exp(Math.log(a) + (Math.log(b) - Math.log(a)) * x);
+ }
+ return a + (b - a) * x;
+}
+
+/**
+ * Value of a lane at a clip-local time.
+ *
+ * Outside the points, the envelope holds — the first value before it starts
+ * and the last value after it ends, so a lane never snaps to zero at the edges.
+ */
+export function sampleAutomationLane(
+ lane: HfAutomationLane,
+ t: number,
+ scale: "linear" | "log" = "linear",
+): number {
+ const pts = lane.points;
+ if (pts.length === 0) return 0;
+ const first = pts[0]!;
+ if (t <= first.t) return first.v;
+ const last = pts[pts.length - 1]!;
+ if (t >= last.t) return last.v;
+
+ let lo = 0;
+ let hi = pts.length - 1;
+ while (hi - lo > 1) {
+ const mid = (lo + hi) >> 1;
+ if (pts[mid]!.t <= t) lo = mid;
+ else hi = mid;
+ }
+ const a = pts[lo]!;
+ const b = pts[hi]!;
+ const span = b.t - a.t;
+ if (span <= 0) return b.v;
+ return lerpValue(a.v, b.v, applyCurve((t - a.t) / span, a.curve), scale);
+}
+
+/** True when the lane is a single value, i.e. worth setting once and not scheduling. */
+export function isConstantLane(lane: HfAutomationLane): boolean {
+ return lane.points.length <= 1 || lane.points.every((p) => p.v === lane.points[0]!.v);
+}
+
+/**
+ * Sample a lane onto evenly spaced times, for consumers that want a plain
+ * curve rather than a breakpoint list: `setValueCurveAtTime`, the render-side
+ * volume envelope, and the lane's own drawing code.
+ */
+export function sampleAutomationCurve(
+ lane: HfAutomationLane,
+ from: number,
+ to: number,
+ count: number,
+ scale: "linear" | "log" = "linear",
+): Float32Array {
+ const n = Math.max(2, Math.floor(count));
+ const out = new Float32Array(n);
+ const span = to - from;
+ for (let i = 0; i < n; i += 1) {
+ out[i] = sampleAutomationLane(lane, from + (span * i) / (n - 1), scale);
+ }
+ return out;
+}
diff --git a/packages/core/src/audioFx.ts b/packages/core/src/audioFx.ts
index a9bada7242..2eb2db83d4 100644
--- a/packages/core/src/audioFx.ts
+++ b/packages/core/src/audioFx.ts
@@ -33,6 +33,15 @@ export interface HfAudioFxNumberParam {
default: number;
/** Frequency-style controls need a log knob to be usable. */
scale?: "linear" | "log";
+ /**
+ * The knob is backed by an AudioParam, so an automation lane can drive it.
+ *
+ * Not every knob can be: a WaveShaper curve, a convolution impulse and a
+ * worklet's `processorOptions` are all set wholesale rather than scheduled.
+ * A graph builder must expose an AudioParam for every parameter flagged here
+ * — `audioFxGraph.test.ts` builds each effect and checks it.
+ */
+ automatable?: boolean;
/** One line explaining what turning this does, shown on the control. */
hint?: string;
}
@@ -81,6 +90,7 @@ const freq = (
step: 1,
default: def,
scale: "log",
+ automatable: true,
});
const qParam = (def = 0.707, hint = "Bandwidth — higher is narrower."): HfAudioFxNumberParam => ({
@@ -93,6 +103,7 @@ const qParam = (def = 0.707, hint = "Bandwidth — higher is narrower."): HfAudi
step: 0.01,
default: def,
scale: "log",
+ automatable: true,
hint,
});
@@ -105,6 +116,7 @@ const gainDb = (min = -40, max = 40, def = 0): HfAudioFxNumberParam => ({
max,
step: 0.1,
default: def,
+ automatable: true,
});
const poles: HfAudioFxEnumParam = {
@@ -411,6 +423,7 @@ export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [
{
kind: "number",
key: "output",
+ automatable: true,
label: "Output",
unit: "dB",
min: -24,
@@ -482,6 +495,7 @@ export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [
{
kind: "number",
key: "time",
+ automatable: true,
label: "Time",
unit: "ms",
min: 1,
@@ -495,6 +509,7 @@ export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [
{
kind: "number",
key: "feedback",
+ automatable: true,
label: "Feedback",
unit: "",
min: 0.01,
@@ -505,6 +520,7 @@ export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [
{
kind: "number",
key: "mix",
+ automatable: true,
label: "Mix",
unit: "",
min: 0,
@@ -524,6 +540,7 @@ export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [
{
kind: "number",
key: "delay",
+ automatable: true,
label: "Delay",
unit: "ms",
min: 1,
@@ -534,6 +551,7 @@ export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [
{
kind: "number",
key: "depth",
+ automatable: true,
label: "Depth",
unit: "ms",
min: 0,
@@ -544,6 +562,7 @@ export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [
{
kind: "number",
key: "speed",
+ automatable: true,
label: "Rate",
unit: "Hz",
min: 0.01,
@@ -554,6 +573,7 @@ export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [
{
kind: "number",
key: "mix",
+ automatable: true,
label: "Mix",
unit: "",
min: 0,
@@ -573,6 +593,7 @@ export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [
{
kind: "number",
key: "in_gain",
+ automatable: true,
label: "Input",
unit: "",
min: 0,
@@ -583,6 +604,7 @@ export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [
{
kind: "number",
key: "out_gain",
+ automatable: true,
label: "Output",
unit: "",
min: 0,
@@ -615,6 +637,7 @@ export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [
{
kind: "number",
key: "speed",
+ automatable: true,
label: "Rate",
unit: "Hz",
min: 0.1,
@@ -666,6 +689,7 @@ export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [
{
kind: "number",
key: "wet",
+ automatable: true,
label: "Wet",
unit: "",
min: 0,
@@ -676,6 +700,7 @@ export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [
{
kind: "number",
key: "dry",
+ automatable: true,
label: "Dry",
unit: "",
min: 0,
@@ -735,6 +760,14 @@ export function normalizeAudioFxParams(
export interface HfAudioFxNode {
/** Effect id from HF_AUDIO_FX. */
type: string;
+ /**
+ * Stable handle for this node within its chain, minted when the node is
+ * added. Automation lanes address nodes by id (`fx.<id>.<param>`) so that
+ * reordering the chain never re-points a lane at a different effect. Older
+ * chains have no ids; they load fine and simply cannot be automated until
+ * the panel touches them.
+ */
+ id?: string;
/** Set on nodes the carve analysis generated, so re-running replaces them
* instead of stacking another set on top of hand-added effects. */
fromCarve?: boolean;
@@ -781,12 +814,19 @@ export function parseAudioFxChain(json: string): HfAudioFxChain {
if (typeof n !== "object" || n === null) {
throw new AudioFxChainError(`Node ${i} is not an object.`);
}
- const node = n as { type?: unknown; enabled?: unknown; params?: unknown; fromCarve?: unknown };
+ const node = n as {
+ type?: unknown;
+ id?: unknown;
+ enabled?: unknown;
+ params?: unknown;
+ fromCarve?: unknown;
+ };
if (typeof node.type !== "string" || !BY_ID.has(node.type)) {
throw new AudioFxChainError(`Node ${i} has unknown effect type: ${String(node.type)}`);
}
return {
type: node.type,
+ ...(typeof node.id === "string" && node.id ? { id: node.id } : {}),
...(node.fromCarve === true ? { fromCarve: true as const } : {}),
enabled: node.enabled !== false,
params: normalizeAudioFxParams(
@@ -809,9 +849,23 @@ export function serializeAudioFxChain(chain: HfAudioFxChain): string {
version: HF_AUDIO_FX_CHAIN_VERSION,
nodes: chain.nodes.map((node) => ({
type: node.type,
+ ...(node.id ? { id: node.id } : {}),
...(node.fromCarve === true ? { fromCarve: true } : {}),
...(node.enabled === false ? { enabled: false } : {}),
params: normalizeAudioFxParams(node.type, node.params),
})),
});
}
+
+/**
+ * Next free node id for a chain, as `n1`, `n2`, … — counted rather than random
+ * so that adding an effect produces the same document on every machine, which
+ * compositions require.
+ */
+export function mintAudioFxNodeId(chain: HfAudioFxChain): string {
+ const taken = new Set(chain.nodes.map((n) => n.id).filter(Boolean));
+ for (let i = 1; ; i += 1) {
+ const id = `n${i}`;
+ if (!taken.has(id)) return id;
+ }
+}
diff --git a/packages/lint/src/rules/media.test.ts b/packages/lint/src/rules/media.test.ts
index b9ae81d3a7..f2574aa178 100644
--- a/packages/lint/src/rules/media.test.ts
+++ b/packages/lint/src/rules/media.test.ts
@@ -428,3 +428,42 @@ describe("media_variable_src_no_fallback", () => {
expect(result.findings.some((f) => f.code === "media_missing_src")).toBe(true);
});
});
+
+describe("audio_volume_double_automation", () => {
+ const withScript = (audioAttrs: string, script: string) => `<!DOCTYPE html><html><body>
+ <div id="root" data-composition-id="main" data-start="0" data-width="1920" data-height="1080" data-duration="10">
+ <audio id="bgm" src="a.wav" data-start="0" data-duration="10" ${audioAttrs}></audio>
+ </div>
+ <script>${script}</script>
+ </body></html>`;
+
+ const LANE = `data-automation='{"version":1,"lanes":[{"target":"volume","points":[{"t":0,"v":1}]}]}'`;
+
+ it("warns when a lane and a GSAP volume tween both shape the same track", async () => {
+ const res = await lintHyperframeHtml(
+ withScript(LANE, `tl.to("#bgm", { volume: 0, duration: 1 });`),
+ );
+ const finding = res.findings.find((f) => f.code === "audio_volume_double_automation");
+ expect(finding?.severity).toBe("warning");
+ expect(finding?.elementId).toBe("bgm");
+ });
+
+ it("stays quiet for a lane alone, a tween alone, or a tween on another track", async () => {
+ const laneOnly = await lintHyperframeHtml(withScript(LANE, `tl.to("#bgm", { x: 10 });`));
+ const tweenOnly = await lintHyperframeHtml(withScript("", `tl.to("#bgm", { volume: 0 });`));
+ const otherTrack = await lintHyperframeHtml(withScript(LANE, `tl.to("#vo", { volume: 0 });`));
+ for (const res of [laneOnly, tweenOnly, otherTrack]) {
+ expect(res.findings.some((f) => f.code === "audio_volume_double_automation")).toBe(false);
+ }
+ });
+
+ it("ignores a lane that automates something other than volume", async () => {
+ const res = await lintHyperframeHtml(
+ withScript(
+ `data-automation='{"version":1,"lanes":[{"target":"fx.n1.frequency","points":[{"t":0,"v":200}]}]}'`,
+ `tl.to("#bgm", { volume: 0 });`,
+ ),
+ );
+ expect(res.findings.some((f) => f.code === "audio_volume_double_automation")).toBe(false);
+ });
+});
diff --git a/packages/lint/src/rules/media.ts b/packages/lint/src/rules/media.ts
index 08abde636a..9efca4f6fe 100644
--- a/packages/lint/src/rules/media.ts
+++ b/packages/lint/src/rules/media.ts
@@ -1,5 +1,5 @@
import type { LintContext, HyperframeLintFinding } from "../context";
-import { readAttr, readDecodedAttr, truncateSnippet, isMediaTag } from "../utils";
+import { readAttr, readDecodedAttr, stripJsComments, truncateSnippet, isMediaTag } from "../utils";
import { validateColorGradingContract } from "@hyperframes/parsers/color-grading-contract";
function escapeRegExp(value: string): string {
@@ -597,4 +597,45 @@ export const mediaRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> =
// imperative_media_control
findImperativeMediaControlFindings,
+
+ // audio_volume_double_automation
+ findVolumeDoubleAutomationFindings,
];
+
+/**
+ * A track can have its volume shaped by an automation lane or by a GSAP tween,
+ * and only the lane is heard: the runtime reads `data-automation` first and
+ * never falls through to the probed tween. Both present means one of them is
+ * silently doing nothing, which is invisible in the file and in preview.
+ */
+function findVolumeDoubleAutomationFindings(ctx: LintContext): HyperframeLintFinding[] {
+ const automated = ctx.tags
+ .filter((tag) => isMediaTag(tag.name))
+ .map((tag) => ({ tag, automation: readDecodedAttr(tag.raw, "data-automation") }))
+ .filter((entry) => entry.automation && /"target"\s*:\s*"volume"/.test(entry.automation))
+ .map((entry) => ({ ...entry, id: readAttr(entry.tag.raw, "id") }))
+ .filter((entry): entry is typeof entry & { id: string } => Boolean(entry.id));
+ if (automated.length === 0) return [];
+
+ const script = ctx.scripts.map((block) => stripJsComments(block.content)).join("\n");
+ const findings: HyperframeLintFinding[] = [];
+ for (const { tag, id } of automated) {
+ // ponytail: a tween is recognised by a `volume` key appearing shortly after
+ // the element's own selector, rather than by parsing the timeline. It reads
+ // the same call the runtime's own probe would pick up, and the rule only
+ // warns, so a miss costs nothing.
+ const escaped = escapeRegExp(id);
+ const tweened = new RegExp(`#${escaped}(?![\\w-])[^;]{0,200}?\\bvolume\\s*:`, "s").test(script);
+ if (!tweened) continue;
+ findings.push({
+ code: "audio_volume_double_automation",
+ severity: "warning",
+ message: `#${id} has both a volume automation lane and a GSAP tween on \`volume\`. The lane wins — the tween is ignored in preview and in the render.`,
+ elementId: id,
+ fixHint:
+ "Keep one of them: delete the volume lane to go back to tweening, or drop the tween and shape the level in the automation lane.",
+ snippet: truncateSnippet(tag.raw),
+ });
+ }
+ return findings;
+}