Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(audio): hear the FX chain while previewing (#3014)
Vance Ingalls9b0c5e85596e
diff --git a/packages/core/src/audio/audioFxGraph.ts b/packages/core/src/audio/audioFxGraph.tsindex ab8dc34101..1a026e280d 100644--- a/packages/core/src/audio/audioFxGraph.ts+++ b/packages/core/src/audio/audioFxGraph.ts@@ -14,7 +14,7 @@ import {type HfAudioFxChain,type HfAudioFxParamValues,} from "../audioFx.js";-import { ensureAudioFxWorklets } from "./audioFxWorklets.js";+import { audioFxWorkletsReady, ensureAudioFxWorklets } from "./audioFxWorklets.js";/*** Deterministic reverb impulse, shared by both engines so the browser and the@@ -69,6 +69,12 @@ type Builder = (ctx: BaseAudioContext, p: HfAudioFxParamValues) => FxNodeHandle;const n = (v: number | string | undefined): number => (typeof v === "number" ? v : Number(v ?? 0));+/** Linear crossfade: dry falls as wet rises, in lockstep. */+function setWetDryMix(wet: GainNode, dry: GainNode, mix: number): void {+ wet.gain.value = mix;+ dry.gain.value = 1 - mix;+}+/** 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() };@@ -177,8 +183,7 @@ const delayFeedback: Builder = (ctx, p) => {const apply = (v: HfAudioFxParamValues): void => {dl.delayTime.value = Math.min(5, n(v.time) / 1000);fb.gain.value = n(v.feedback);- wet.gain.value = n(v.mix);- dry.gain.value = 1 - n(v.mix);+ setWetDryMix(wet, dry, n(v.mix));};apply(p);return {@@ -205,8 +210,7 @@ const chorusLfo: Builder = (ctx, p) => {dl.delayTime.value = n(v.delay) / 1000;depth.gain.value = n(v.depth) / 1000;lfo.frequency.value = n(v.speed);- wet.gain.value = n(v.mix);- dry.gain.value = 1 - n(v.mix);+ setWetDryMix(wet, dry, n(v.mix));};apply(p);return {@@ -432,4 +436,4 @@ export function buildFxChain(ctx: BaseAudioContext, chain: HfAudioFxChain): FxCh};}-export { ensureAudioFxWorklets };+export { audioFxWorkletsReady, ensureAudioFxWorklets };diff --git a/packages/core/src/audio/audioFxWorklets.ts b/packages/core/src/audio/audioFxWorklets.tsindex 4a36a938ba..e421d34099 100644--- a/packages/core/src/audio/audioFxWorklets.ts+++ b/packages/core/src/audio/audioFxWorklets.ts@@ -9,7 +9,7 @@* Kept as a source string so it can be registered from a Blob URL without a* separate bundled asset, which keeps the studio's build unchanged.*/-export const AUDIO_FX_WORKLET_SOURCE = `+const AUDIO_FX_WORKLET_SOURCE = `const dbToLin = (db) => Math.pow(10, db / 20);/**@@ -47,6 +47,13 @@ function kneeGain(envDb, thresholdDb, ratio, kneeDb) {return over > 0 ? -(over * (1 - 1 / ratio)) : 0;}+// log10/exp per sample is the single most expensive thing a dynamics processor+// can do on the audio thread, and every sample below the knee needs neither:+// its gain is exactly unity. Comparing envelopes in the linear domain lets the+// quiet majority of samples skip the transcendentals entirely.+const LN10_OVER_20 = Math.LN10 / 20;+const dbToLinFast = (db) => Math.exp(db * LN10_OVER_20);+class HfCompressor extends AudioWorkletProcessor {constructor(o) {super();@@ -65,14 +72,26 @@ class HfCompressor extends AudioWorkletProcessor {const mix = p.mix ?? 1;// Knee is expressed as a ratio in FFmpeg; convert to dB width.const kneeDb = 20 * Math.log10(Math.max(1.0001, p.knee ?? 2.83));+ const thresholdDb = p.threshold ?? -24;+ const ratio = p.ratio ?? 4;+ // Below this the gain computer returns unity, so the sample needs no+ // logarithm at all.+ const kneeStartLin = dbToLin(thresholdDb - kneeDb);+ const dry = 1 - mix;for (let ch = 0; ch < i.length; ch++) {const inp = i[ch], out = o[ch];for (let n = 0; n < inp.length; n++) {const x = inp[n];+ // Per-channel follower, and the sub-knee shortcut: below the knee the+ // gain is exactly unity, so the sample needs no logarithm at all.const env = this.env.push(ch, x);- const envDb = env > 1e-9 ? 20 * Math.log10(env) : -200;- const g = dbToLin(kneeGain(envDb, p.threshold ?? -24, p.ratio ?? 4, kneeDb));- out[n] = x * g * makeup * mix + x * (1 - mix);+ if (env <= kneeStartLin) {+ out[n] = x * makeup * mix + x * dry;+ continue;+ }+ const envDb = 20 * Math.log10(env);+ const g = dbToLinFast(kneeGain(envDb, thresholdDb, ratio, kneeDb));+ out[n] = x * g * makeup * mix + x * dry;}}return true;@@ -139,6 +158,7 @@ class HfGate extends AudioWorkletProcessor {const x = inp[n];const env = this.env.push(ch, x);let target = 1;+ // Above the threshold the gate is fully open; skip the pow entirely.if (env < threshold) {const under = env > 1e-9 ? threshold / env : 1e9;target = Math.max(floor, 1 / Math.pow(under, ratio - 1));@@ -191,31 +211,40 @@ class HfBitcrush extends AudioWorkletProcessor {registerProcessor("hf-bitcrush", HfBitcrush);`;-let modulePromise: Promise<void> | undefined;+// Registration is per context, not per module: a processor registered on one+// AudioContext does not exist on another, so caching a single promise made+// every context after the first believe it was ready when it was not.+const registered = new WeakMap<BaseAudioContext, Promise<void>>();++/** True once the processors are usable on this context. */+export function audioFxWorkletsReady(ctx: BaseAudioContext): boolean {+ return readyContexts.has(ctx);+}+const readyContexts = new WeakSet<BaseAudioContext>();/**- * Register the processors on a context. Idempotent per module instance, since+ * Register the processors on a context. Idempotent per context, since* addModule throws if the same processor name is registered twice.*/export function ensureAudioFxWorklets(ctx: BaseAudioContext): Promise<void> {- modulePromise ??= (async () => {- if (!ctx.audioWorklet) {- throw new Error(- "AudioWorklet is unavailable — the page needs a secure context (https, localhost or file://)",- );- }- // A data: URL rather than a blob:, because a blob inherits the page origin- // and is treated as opaque on a file:// page, where the module then fails- // to load with an unhelpful AbortError.- const url = `data:text/javascript;base64,${btoa(- String.fromCharCode(...new TextEncoder().encode(AUDIO_FX_WORKLET_SOURCE)),- )}`;- await ctx.audioWorklet.addModule(url);- })();+ let modulePromise = registered.get(ctx);+ if (!modulePromise) {+ modulePromise = (async () => {+ if (!ctx.audioWorklet) {+ throw new Error(+ "AudioWorklet is unavailable — the page needs a secure context (https, localhost or file://)",+ );+ }+ // A data: URL rather than a blob:, because a blob inherits the page origin+ // and is treated as opaque on a file:// page, where the module then fails+ // to load with an unhelpful AbortError.+ const url = `data:text/javascript;base64,${btoa(+ String.fromCharCode(...new TextEncoder().encode(AUDIO_FX_WORKLET_SOURCE)),+ )}`;+ await ctx.audioWorklet.addModule(url);+ readyContexts.add(ctx);+ })();+ registered.set(ctx, modulePromise);+ }return modulePromise;}--/** Test seam: forget the cached registration so a fresh context can register. */-export function __resetAudioFxWorkletsForTests(): void {- modulePromise = undefined;-}diff --git a/packages/core/src/audioFx.ts b/packages/core/src/audioFx.tsindex 28fc739636..a9bada7242 100644--- a/packages/core/src/audioFx.ts+++ b/packages/core/src/audioFx.ts@@ -735,6 +735,9 @@ export function normalizeAudioFxParams(export interface HfAudioFxNode {/** Effect id from HF_AUDIO_FX. */type: 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;/** Absent means enabled — chain files written before the field existed still load. */enabled?: boolean;params?: HfAudioFxParamValues;@@ -778,12 +781,13 @@ 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 };+ const node = n as { type?: 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,+ ...(node.fromCarve === true ? { fromCarve: true as const } : {}),enabled: node.enabled !== false,params: normalizeAudioFxParams(node.type,@@ -805,6 +809,7 @@ export function serializeAudioFxChain(chain: HfAudioFxChain): string {version: HF_AUDIO_FX_CHAIN_VERSION,nodes: chain.nodes.map((node) => ({type: node.type,+ ...(node.fromCarve === true ? { fromCarve: true } : {}),...(node.enabled === false ? { enabled: false } : {}),params: normalizeAudioFxParams(node.type, node.params),})),diff --git a/packages/core/src/runtime/audioFx.test.ts b/packages/core/src/runtime/audioFx.test.tsnew file mode 100644index 0000000000..64110c5de8--- /dev/null+++ b/packages/core/src/runtime/audioFx.test.ts@@ -0,0 +1,129 @@+// @vitest-environment happy-dom+import { describe, expect, it } from "vitest";+import { attachElementFxChain } from "./audioFx.js";++/**+ * The DSP is proven in a real browser by the engine's render tests. What needs+ * covering here is the splice: whether the chain gets inserted between the+ * transport's source and its gain, and whether it stays out of the way when+ * there is nothing to apply.+ */+class Node {+ connections: Node[] = [];+ disconnected = false;+ frequency = { value: 0 };+ Q = { value: 0 };+ gain = { value: 0 };+ delayTime = { value: 0 };+ type = "";+ curve: Float32Array | null = null;+ oversample = "none";+ buffer: unknown = null;+ normalize = true;+ connect(n: Node): Node {+ this.connections.push(n);+ return n;+ }+ disconnect(): void {+ this.disconnected = true;+ }+ start(): void {}+ stop(): void {}+}+class Ctx {+ sampleRate = 48000;+ createGain() {+ return new Node();+ }+ createBiquadFilter() {+ return new Node();+ }+ createIIRFilter() {+ return new Node();+ }+ createDelay() {+ return new Node();+ }+ createOscillator() {+ return new Node();+ }+ createWaveShaper() {+ return new Node();+ }+ createConvolver() {+ return new Node();+ }+ createBuffer(_c: number, length: number) {+ return { length, getChannelData: () => new Float32Array(length) };+ }+}+const ctx = () => new Ctx() as unknown as BaseAudioContext;+const el = (chain?: unknown) => ({+ getAttribute: (n: string) => (n === "data-fx-chain" && chain ? JSON.stringify(chain) : null),+});+const CHAIN = {+ version: 1,+ nodes: [{ type: "peaking", params: { frequency: 1000, gain: -6, q: 1 } }],+};++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();+ expect(src.connections).toContain(dst);+ });++ it("routes through the chain instead of directly when one is present", () => {+ const src = new Node();+ const dst = new Node();+ const handle = attachElementFxChain(ctx(), el(CHAIN), src as never, dst as never);+ expect(handle).not.toBeNull();+ // The whole point: the dry path must no longer exist.+ expect(src.connections).not.toContain(dst);+ expect(src.connections).toHaveLength(1);+ });++ it("tolerates an element that cannot carry attributes", () => {+ // The transport's element is any media-like object in some call paths.+ const src = new Node();+ const dst = new Node();+ expect(() => attachElementFxChain(ctx(), {}, src as never, dst as never)).not.toThrow();+ expect(src.connections).toContain(dst);+ });++ it("plays dry rather than silent when the chain is unreadable", () => {+ const src = new Node();+ const dst = new Node();+ const handle = attachElementFxChain(+ ctx(),+ { getAttribute: () => "{not json" },+ src as never,+ dst as never,+ );+ expect(handle).toBeNull();+ expect(src.connections).toContain(dst);+ });++ it("plays dry rather than silent when the chain names an unknown effect", () => {+ const src = new Node();+ const dst = new Node();+ const handle = attachElementFxChain(+ ctx(),+ el({ version: 1, nodes: [{ type: "not-an-effect" }] }),+ src as never,+ dst as never,+ );+ expect(handle).toBeNull();+ expect(src.connections).toContain(dst);+ });++ it("tears the chain down on dispose", () => {+ const src = new Node();+ const dst = new Node();+ const handle = attachElementFxChain(ctx(), el(CHAIN), src as never, dst as never);+ handle!.dispose();+ expect((src.connections[0] as Node).disconnected).toBe(true);+ });+});diff --git a/packages/core/src/runtime/audioFx.ts b/packages/core/src/runtime/audioFx.tsnew file mode 100644index 0000000000..0c6290a5e3--- /dev/null+++ b/packages/core/src/runtime/audioFx.ts@@ -0,0 +1,130 @@+/**+ * Live audio FX in preview.+ *+ * The transport plays each track from a decoded AudioBuffer and mutes the+ * `<audio>` element to avoid doubling, so effects are spliced into that graph+ * rather than captured off the element — capturing it would process a stream+ * nothing is listening to.+ *+ * Preview and the offline render call the same graph builders, so what is heard+ * while scrubbing is what gets written.+ */++import { HF_AUDIO_FX_ATTR, parseAudioFxChain, type HfAudioFxChain } from "../audioFx.js";+import {+ audioFxWorkletsReady,+ buildFxChain,+ chainNeedsWorklets,+ ensureAudioFxWorklets,+} from "../audio/audioFxGraph.js";+import type { FxChainHandle } from "../audio/audioFxGraph.js";++const EMPTY: HfAudioFxChain = { version: 1, nodes: [] };++function readChain(el: { getAttribute?(name: string): string | null }): {+ chain: HfAudioFxChain;+ raw: string;+} {+ // Callers include the transport, whose element may be any media-like object;+ // anything without getAttribute simply has no chain.+ const raw =+ (typeof el.getAttribute === "function" ? el.getAttribute(HF_AUDIO_FX_ATTR) : null) ?? "";+ if (!raw) return { chain: EMPTY, raw: "" };+ try {+ return { chain: parseAudioFxChain(raw), raw };+ } catch {+ // An unreadable chain plays dry rather than silencing the track.+ return { chain: EMPTY, raw: "" };+ }+}++/**+ * Splice an element's FX chain between a decoded source and its gain stage.+ *+ * The transport plays audio from a decoded AudioBuffer rather than from the+ * `<audio>` element (the element is muted to avoid doubling), so this is the+ * 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.+ */+export function attachElementFxChain(+ ctx: BaseAudioContext,+ el: { getAttribute?(name: string): string | null },+ source: AudioNode,+ destination: AudioNode,+): { 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+ // needs worklets and the module has not landed yet, play dry and swap the+ // graph in once registration resolves.+ if (chainNeedsWorklets(chain) && !audioFxWorkletsReady(ctx)) {+ source.connect(destination);+ let cancelled = false;+ let pending: FxChainHandle | null = null;+ void ensureAudioFxWorklets(ctx)+ .then(() => {+ if (cancelled) return;+ try {+ const late = buildFxChain(ctx, chain);+ source.disconnect(destination);+ source.connect(late.input);+ late.output.connect(destination);+ pending = late;+ } catch {+ // Still unbuildable; the dry connection already stands.+ }+ })+ .catch(() => undefined);+ return {+ dispose: () => {+ cancelled = true;+ pending?.dispose();+ },+ };+ }++ 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;+ }++ source.connect(handle.input);+ handle.output.connect(destination);++ // 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.+ let observer: MutationObserver | null = null;+ const target = el as unknown as Node;+ if (+ typeof MutationObserver !== "undefined" &&+ typeof (target as Element)?.nodeType === "number"+ ) {+ observer = new MutationObserver(() => {+ const next = readChain(el);+ if (next.chain.nodes.length > 0) handle.update(next.chain);+ });+ observer.observe(target, { attributes: true, attributeFilter: [HF_AUDIO_FX_ATTR] });+ }++ return {+ dispose: () => {+ observer?.disconnect();+ handle.dispose();+ },+ };+}diff --git a/packages/core/src/runtime/webAudioTransport.ts b/packages/core/src/runtime/webAudioTransport.tsindex d4497ac389..33d9c93f75 100644--- a/packages/core/src/runtime/webAudioTransport.ts+++ b/packages/core/src/runtime/webAudioTransport.ts@@ -1,3 +1,4 @@+import { attachElementFxChain } from "./audioFx.js";import { swallow } from "./diagnostics";import { getDebugSurface } from "./globals.js";@@ -60,6 +61,8 @@ export type ScheduledSource = {el: HTMLMediaElement;sourceNode: AudioBufferSourceNode;gainNode: GainNode;+ /** FX chain spliced between source and gain, when the element carries one. */+ fx?: { dispose(): void } | null;compositionStart: number;mediaStart: number;scheduledAt: number;@@ -184,7 +187,12 @@ export class WebAudioTransport {const gainNode = this._ctx.createGain();gainNode.gain.value = volume;- sourceNode.connect(gainNode);++ // Splice the element's FX chain between the decoded source and its gain,+ // so effects see the raw signal and volume automation rides on their+ // output — the same order the offline render uses. Preview and render run+ // the identical graph builders, so what is heard here is what is written.+ const fx = attachElementFxChain(this._ctx, el, sourceNode, gainNode);gainNode.connect(this._masterGain);const elapsed = compositionTime - compositionStart;@@ -204,6 +212,7 @@ export class WebAudioTransport {) {// Playhead already past the clip end — discard the nodes we built.sourceNode.disconnect();+ fx?.dispose();gainNode.disconnect();return null;}@@ -213,6 +222,7 @@ export class WebAudioTransport {logFallbackHandoff(el, priorMuted);const scheduled: ScheduledSource = {+ fx,el,sourceNode,gainNode,@@ -277,6 +287,7 @@ export class WebAudioTransport {try {source.sourceNode.stop();source.sourceNode.disconnect();+ source.fx?.dispose();source.gainNode.disconnect();} catch {// already stoppeddiff --git a/packages/studio/src/components/editor/PropertyPanelFlat.tsx b/packages/studio/src/components/editor/PropertyPanelFlat.tsxindex 3d267ed5f6..5006f8e0a6 100644--- a/packages/studio/src/components/editor/PropertyPanelFlat.tsx+++ b/packages/studio/src/components/editor/PropertyPanelFlat.tsx@@ -13,22 +13,10 @@ import { FlatTextSection } from "./propertyPanelFlatTextSection";import { FlatStyleSection } from "./propertyPanelFlatStyleSections";import { FlatLayoutSection } from "./propertyPanelFlatLayoutSection";import { FlatMotionSection } from "./propertyPanelFlatMotionSection";-import {- HF_AUDIO_FX_ATTR,- parseAudioFxChain,- serializeAudioFxChain,- type HfAudioFxChain,-} from "@hyperframes/core/audio-fx";-import {- HF_AUDIO_CARVE_ATTR,- normalizeCarveSettings,- type HfCarveSettings,-} from "@hyperframes/core/audio-carve";import { isCanaryEnabled } from "../../telemetry/canary";import { audioFxSummary } from "./audioFxSummary";+import { AudioFxGroup } from "./propertyPanelAudioFxGroup";import { FlatMediaSection } from "./propertyPanelFlatMediaSection";-import type { DomEditSelection } from "./domEditing";-import { FxSection, type AudioTrackOption } from "./propertyPanelFxSection";import { deriveElementTiming } from "./propertyPanelFlatTimingDerivation";import { createGsapLivePreview } from "./gsapLivePreview";import { formatTextFieldPreview } from "./propertyPanelSections";@@ -443,7 +431,13 @@ export function PropertyPanelFlat({id: "audio-fx",title: "Audio FX",summary: audioFxSummary(element),- content: <AudioFxGroup element={element} onSetAttribute={onSetAttribute} />,+ content: (+ <AudioFxGroup+ element={element}+ onSetAttribute={onSetAttribute}+ onSetAttributeLive={onSetAttributeLive}+ />+ ),});}if (sections.media) {@@ -540,60 +534,3 @@ export function PropertyPanelFlat({</DesignPanelInputProvider>);}--/**- * Bridges the FX panel to the element/attribute world. Chain and carve are- * serialised onto the element the way colour grading carries its config, so- * persistence is an ordinary attribute write with no new server route.- */-function AudioFxGroup({- element,- onSetAttribute,-}: {- element: DomEditSelection;- onSetAttribute: (attr: string, value: string) => void | Promise<void>;-}) {- const chain = ((): HfAudioFxChain => {- const raw = element.dataAttributes?.["fx-chain"];- if (!raw) return { version: 1, nodes: [] };- try {- return parseAudioFxChain(raw);- } catch {- // Show an unreadable chain as empty rather than breaking the panel; the- // attribute is left untouched until the user changes something.- return { version: 1, nodes: [] };- }- })();-- const carve = ((): HfCarveSettings | null => {- const raw = element.dataAttributes?.["fx-carve"];- if (!raw) return null;- try {- return normalizeCarveSettings(JSON.parse(raw));- } catch {- return null;- }- })();-- const sourceOptions: AudioTrackOption[] = (() => {- const doc = element.element?.ownerDocument;- if (!doc) return [];- return Array.from(doc.querySelectorAll<HTMLAudioElement>("audio[id]"))- .filter((a) => a.id !== element.id)- .map((a) => ({ id: a.id, label: a.id }));- })();-- return (- <FxSection- chain={chain}- onChainChange={(next) =>- onSetAttribute(HF_AUDIO_FX_ATTR, next.nodes.length ? serializeAudioFxChain(next) : "")- }- carve={carve}- onCarveChange={(next) =>- onSetAttribute(HF_AUDIO_CARVE_ATTR, next ? JSON.stringify(next) : "")- }- sourceOptions={sourceOptions}- />- );-}diff --git a/packages/studio/src/components/editor/propertyPanelAudioFxGroup.tsx b/packages/studio/src/components/editor/propertyPanelAudioFxGroup.tsxnew file mode 100644index 0000000000..d0b3c516c3--- /dev/null+++ b/packages/studio/src/components/editor/propertyPanelAudioFxGroup.tsx@@ -0,0 +1,133 @@+/**+ * The audio FX panel's bridge to the element/attribute world.+ *+ * Chain and carve are serialised onto the element the way colour grading carries+ * its config, so persistence is an ordinary attribute write with no new server+ * route. Split out of PropertyPanelFlat, which is at its size budget.+ */++import { useState } from "react";+import {+ HF_AUDIO_FX_ATTR,+ parseAudioFxChain,+ serializeAudioFxChain,+ type HfAudioFxChain,+} from "@hyperframes/core/audio-fx";+import {+ analyseCarveBands,+ carveBandsToChain,+ HF_AUDIO_CARVE_ATTR,+ normalizeCarveSettings,+ type HfCarveSettings,+} from "@hyperframes/core/audio-carve";+import type { DomEditSelection } from "./domEditing";+import { FxSection, type AudioTrackOption } from "./propertyPanelFxSection";++/**+ * Bridges the FX panel to the element/attribute world. Chain and carve are+ * serialised onto the element the way colour grading carries its config, so+ * persistence is an ordinary attribute write with no new server route.+ */+export function AudioFxGroup({+ element,+ onSetAttribute,+ onSetAttributeLive,+}: {+ element: DomEditSelection;+ onSetAttribute: (attr: string, value: string) => void | Promise<void>;+ onSetAttributeLive: (attr: string, value: string | null) => void | Promise<void>;+}) {+ const chain = ((): HfAudioFxChain => {+ const raw = element.dataAttributes?.["fx-chain"];+ if (!raw) return { version: 1, nodes: [] };+ try {+ return parseAudioFxChain(raw);+ } catch {+ // Show an unreadable chain as empty rather than breaking the panel; the+ // attribute is left untouched until the user changes something.+ return { version: 1, nodes: [] };+ }+ })();++ const carve = ((): HfCarveSettings | null => {+ const raw = element.dataAttributes?.["fx-carve"];+ if (!raw) return null;+ try {+ return normalizeCarveSettings(JSON.parse(raw));+ } catch {+ return null;+ }+ })();++ const sourceOptions: AudioTrackOption[] = (() => {+ const doc = element.element?.ownerDocument;+ if (!doc) return [];+ return Array.from(doc.querySelectorAll<HTMLAudioElement>("audio[id]"))+ .filter((a) => a.id !== element.id)+ .map((a) => ({ id: a.id, label: a.id }));+ })();++ const [analysing, setAnalysing] = useState(false);++ /**+ * Decodes the chosen voice track and turns its spectrum into peaking filters+ * on this one. The bands replace any previous carve output but leave+ * hand-added effects alone, so re-analysing does not discard other work.+ */+ const analyse = async (): Promise<void> => {+ if (!carve?.source) return;+ const doc = element.element?.ownerDocument;+ const voice = doc?.getElementById(carve.source) as HTMLAudioElement | null;+ const src = voice?.getAttribute("src");+ if (!src) return;+ setAnalysing(true);+ try {+ const res = await fetch(new URL(src, doc!.baseURI).href);+ const bytes = await res.arrayBuffer();+ const Ctor =+ window.AudioContext ??+ (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;+ if (!Ctor) return;+ const ctx = new Ctor();+ try {+ const buffer = await ctx.decodeAudioData(bytes);+ const bands = analyseCarveBands(buffer.getChannelData(0), buffer.sampleRate, carve);+ const carved = carveBandsToChain(bands);+ // Carve output is tagged so a re-run replaces it instead of stacking.+ const kept = chain.nodes.filter((n) => !n.fromCarve);+ const next = {+ version: 1,+ nodes: [...carved.nodes.map((n) => ({ ...n, fromCarve: true })), ...kept],+ };+ onSetAttribute(HF_AUDIO_FX_ATTR, serializeAudioFxChain(next));+ } finally {+ void ctx.close().catch(() => undefined);+ }+ } catch {+ // Leave the chain as it was; the button simply re-enables.+ } finally {+ setAnalysing(false);+ }+ };++ return (+ <FxSection+ chain={chain}+ onChainChange={(next) =>+ onSetAttribute(HF_AUDIO_FX_ATTR, next.nodes.length ? serializeAudioFxChain(next) : "")+ }+ onChainPreview={(next) =>+ // Live writes skip the preview refresh, so dragging a knob no longer+ // reloads the composition and restarts playback on every pixel.+ onSetAttributeLive(HF_AUDIO_FX_ATTR, next.nodes.length ? serializeAudioFxChain(next) : null)+ }+ carve={carve}+ onCarveChange={(next) =>+ onSetAttribute(HF_AUDIO_CARVE_ATTR, next ? JSON.stringify(next) : "")+ }+ sourceOptions={sourceOptions}+ onAnalyseCarve={() => void analyse()}+ analysing={analysing}+ />+ );+}diff --git a/packages/studio/src/components/editor/propertyPanelFxControls.tsx b/packages/studio/src/components/editor/propertyPanelFxControls.tsxindex 2181e2451f..e435157427 100644--- a/packages/studio/src/components/editor/propertyPanelFxControls.tsx+++ b/packages/studio/src/components/editor/propertyPanelFxControls.tsx@@ -7,7 +7,7 @@* panel cannot offer a value the renderer would reject.*/-import { useCallback } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import type {HfAudioFxDef,HfAudioFxNumberParam,@@ -41,19 +41,40 @@ function display(p: HfAudioFxNumberParam, value: number): string {interface ParamRowProps {param: HfAudioFxParam;value: number | string;+ /** Fires continuously while dragging — cheap, not persisted. */onChange(key: string, value: number | string): void;+ /** Fires once when the gesture ends — this is the write that persists. */+ onCommit?(key: string, value: number | string): void;disabled?: boolean;}-export function FxParamRow({ param, value, onChange, disabled }: ParamRowProps) {+export function FxParamRow({ param, value, onChange, onCommit, disabled }: ParamRowProps) {+ // While dragging, the slider is driven locally. Waiting for the value to come+ // back through the element attribute makes the control feel laggy and fights+ // the pointer.+ const [dragging, setDragging] = useState(false);+ const [local, setLocal] = useState(value);+ const latest = useRef(value);+ useEffect(() => {+ if (!dragging) setLocal(value);+ }, [value, dragging]);+const handleNumber = useCallback((raw: number) => {const p = param as HfAudioFxNumberParam;- onChange(param.key, Math.min(p.max, Math.max(p.min, raw)));+ const next = Math.min(p.max, Math.max(p.min, raw));+ latest.current = next;+ setLocal(next);+ onChange(param.key, next);},[param, onChange],);+ const commit = useCallback(() => {+ setDragging(false);+ onCommit?.(param.key, latest.current);+ }, [onCommit, param.key]);+if (param.kind === "enum") {return (<label className="hf-fx-row flex min-h-6 items-center gap-2" title={param.hint}>@@ -64,7 +85,11 @@ export function FxParamRow({ param, value, onChange, disabled }: ParamRowProps)className="hf-fx-select min-w-0 flex-1 rounded-[3px] bg-panel-surface px-1 py-0.5 font-mono text-[10px] text-panel-text-0"value={String(value)}disabled={disabled}- onChange={(e) => onChange(param.key, e.target.value)}+ onChange={(e) => {+ // A select has no drag; the change is already the commit.+ onChange(param.key, e.target.value);+ onCommit?.(param.key, e.target.value);+ }}>{param.options.map((o) => (<option key={o.value} value={o.value}>@@ -76,7 +101,8 @@ export function FxParamRow({ param, value, onChange, disabled }: ParamRowProps));}- const numeric = typeof value === "number" ? value : Number(value);+ const shown = dragging ? local : value;+ const numeric = typeof shown === "number" ? shown : Number(shown);const current = Number.isFinite(numeric) ? numeric : param.default;return (@@ -93,7 +119,11 @@ export function FxParamRow({ param, value, onChange, disabled }: ParamRowProps)value={toSlider(param, current)}disabled={disabled}aria-label={param.label}+ onPointerDown={() => setDragging(true)}onChange={(e) => handleNumber(fromSlider(param, Number(e.target.value)))}+ onPointerUp={commit}+ onKeyUp={commit}+ onBlur={commit}/><inputclassName="hf-fx-number w-[54px] flex-shrink-0 rounded-[3px] bg-panel-surface px-1 py-0.5 text-right font-mono text-[10px] text-panel-text-0"@@ -107,6 +137,10 @@ export function FxParamRow({ param, value, onChange, disabled }: ParamRowProps)const next = Number(e.target.value);if (Number.isFinite(next)) handleNumber(next);}}+ onBlur={commit}+ onKeyDown={(e) => {+ if (e.key === "Enter") commit();+ }}/>{param.unit ? (<span className="hf-fx-unit w-[22px] flex-shrink-0 font-mono text-[9px] text-panel-text-4">@@ -121,15 +155,20 @@ interface FxParamsProps {def: HfAudioFxDef;params: HfAudioFxParamValues;onChange(params: HfAudioFxParamValues): void;+ onCommit?(params: HfAudioFxParamValues): void;disabled?: boolean;}/** Every knob the effect declares, in registry order. */-export function FxParams({ def, params, onChange, disabled }: FxParamsProps) {+export function FxParams({ def, params, onChange, onCommit, disabled }: FxParamsProps) {const set = useCallback((key: string, value: number | string) => onChange({ ...params, [key]: value }),[params, onChange],);+ const commit = useCallback(+ (key: string, value: number | string) => onCommit?.({ ...params, [key]: value }),+ [params, onCommit],+ );return (<div className="hf-fx-params space-y-0.5 border-t border-panel-border-input px-1.5 py-1.5">{def.params.map((p) => (@@ -138,6 +177,7 @@ export function FxParams({ def, params, onChange, disabled }: FxParamsProps) {param={p}value={params[p.key] ?? p.default}onChange={set}+ onCommit={commit}disabled={disabled}/>))}diff --git a/packages/studio/src/components/editor/propertyPanelFxSection.test.tsx b/packages/studio/src/components/editor/propertyPanelFxSection.test.tsxindex e702b5b84e..7beeafa0cb 100644--- a/packages/studio/src/components/editor/propertyPanelFxSection.test.tsx+++ b/packages/studio/src/components/editor/propertyPanelFxSection.test.tsx@@ -32,11 +32,13 @@ const noop = () => {};function mount(overrides: Partial<Parameters<typeof FxSection>[0]> = {}) {const onChainChange = vi.fn();+ const onChainPreview = vi.fn();const onCarveChange = vi.fn();const { host } = renderInto(<FxSectionchain={overrides.chain ?? { version: 1, nodes: [] }}onChainChange={overrides.onChainChange ?? onChainChange}+ onChainPreview={overrides.onChainPreview ?? onChainPreview}carve={overrides.carve ?? null}onCarveChange={overrides.onCarveChange ?? onCarveChange}sourceOptions={overrides.sourceOptions ?? [{ id: "vo", label: "Voiceover" }]}@@ -45,7 +47,7 @@ function mount(overrides: Partial<Parameters<typeof FxSection>[0]> = {}) {disabled={overrides.disabled}/>,);- return { host, onChainChange, onCarveChange };+ return { host, onChainChange, onChainPreview, onCarveChange };}const click = (el: Element | null | undefined) => {@@ -153,9 +155,43 @@ describe("FxSection chain", () => {expect(next.nodes.map((n) => n.type)).toEqual(["reverb"]);});+ it("previews while dragging and only persists on release", () => {+ // Persisting on every input event refreshes the preview, which reloads the+ // composition and restarts audio — that is what made playback stutter.+ const { host, onChainChange, onChainPreview } = mount({ chain: chainOf("peaking") });+ const slider = host.querySelector<HTMLInputElement>(".hf-fx-slider")!;+ act(() => slider.dispatchEvent(new Event("pointerdown", { bubbles: true })));+ for (const v of ["5000", "10000", "15000"]) {+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;+ act(() => {+ setter?.call(slider, v);+ slider.dispatchEvent(new Event("input", { bubbles: true }));+ });+ }+ expect(onChainPreview.mock.calls.length).toBeGreaterThanOrEqual(3);+ expect(onChainChange).not.toHaveBeenCalled();++ act(() => slider.dispatchEvent(new Event("pointerup", { bubbles: true })));+ expect(onChainChange).toHaveBeenCalledTimes(1);+ });++ it("commits an enum immediately, since a select has no drag", () => {+ const { host, onChainChange } = mount({ chain: chainOf("saturate") });+ const select = host.querySelector<HTMLSelectElement>(".hf-fx-select")!;+ const setter = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, "value")?.set;+ act(() => {+ setter?.call(select, "atan");+ select.dispatchEvent(new Event("change", { bubbles: true }));+ });+ expect(onChainChange).toHaveBeenCalledTimes(1);+ });+it("clamps a typed value into the renderable range", () => {const { host, onChainChange } = mount({ chain: chainOf("peaking") });- typeInto(host.querySelector<HTMLInputElement>(".hf-fx-number")!, "999999");+ const input = host.querySelector<HTMLInputElement>(".hf-fx-number")!;+ typeInto(input, "999999");+ // React delegates onBlur through focusout, which is the event that bubbles.+ act(() => input.dispatchEvent(new FocusEvent("focusout", { bubbles: true })));const next = onChainChange.mock.calls.at(-1)![0] as HfAudioFxChain;expect(next.nodes[0]!.params!.frequency).toBe(20000);});diff --git a/packages/studio/src/components/editor/propertyPanelFxSection.tsx b/packages/studio/src/components/editor/propertyPanelFxSection.tsxindex efdc1a2288..16e60ea5af 100644--- a/packages/studio/src/components/editor/propertyPanelFxSection.tsx+++ b/packages/studio/src/components/editor/propertyPanelFxSection.tsx@@ -34,25 +34,52 @@ export interface AudioTrackOption {label: string;}-export interface FxSectionProps {- chain: HfAudioFxChain;- onChainChange(chain: HfAudioFxChain): void;- carve: HfCarveSettings | null;- onCarveChange(carve: HfCarveSettings | null): void;- /** Other audio elements that could act as the carve source. */- sourceOptions: AudioTrackOption[];- /** Re-run analysis against the current source audio. */- onAnalyseCarve?(): void;- analysing?: boolean;+interface FxNodeRowProps {+ node: HfAudioFxNode;+ index: number;+ open: boolean;+ /** Last in the chain, so it cannot move further down. */+ last: boolean;disabled?: boolean;+ onToggleOpen(): void;+ onUpdate(index: number, patch: Partial<HfAudioFxNode>): void;+ onMove(index: number, delta: number): void;+ onRemove(index: number): void;+ onPreview(index: number, params: HfAudioFxParamValues): void;}-function FxNodeControls({+/** Reorder arrow. Disabled at the end of the chain it would move past. */+function FxMoveButton({+ label,+ glyph,+ disabled,+ onClick,+}: {+ label: string;+ glyph: string;+ disabled: boolean;+ onClick(): void;+}) {+ return (+ <button+ type="button"+ className="hf-fx-move px-1 font-mono text-[10px] text-panel-text-4 hover:text-panel-text-0 disabled:opacity-25"+ title={label}+ disabled={disabled}+ onClick={onClick}+ >+ {glyph}+ </button>+ );+}++/** Name, bypass, reorder and remove for one effect. */+function FxNodeHeader({label,- index,- total,open,bypassed,+ first,+ last,disabled,onToggleOpen,onToggleBypass,@@ -60,10 +87,10 @@ function FxNodeControls({onRemove,}: {label: string;- index: number;- total: number;open: boolean;bypassed: boolean;+ first: boolean;+ last: boolean;disabled?: boolean;onToggleOpen(): void;onToggleBypass(): void;@@ -90,24 +117,18 @@ function FxNodeControls({>{bypassed ? "Off" : "On"}</button>- <button- type="button"- className="hf-fx-move px-1 font-mono text-[10px] text-panel-text-4 hover:text-panel-text-0 disabled:opacity-25"- title="Move up"- disabled={disabled || index === 0}+ <FxMoveButton+ label="Move up"+ glyph="↑"+ disabled={Boolean(disabled) || first}onClick={() => onMove(-1)}- >- ↑- </button>- <button- type="button"- className="hf-fx-move px-1 font-mono text-[10px] text-panel-text-4 hover:text-panel-text-0 disabled:opacity-25"- title="Move down"- disabled={disabled || index === total - 1}+ />+ <FxMoveButton+ label="Move down"+ glyph="↓"+ disabled={Boolean(disabled) || last}onClick={() => onMove(1)}- >- ↓- </button>+ /><buttontype="button"className="hf-fx-remove px-1 font-mono text-[11px] text-panel-text-4 hover:text-red-400 disabled:opacity-40"@@ -121,27 +142,19 @@ function FxNodeControls({);}+/** One effect in the chain: its header controls, and its knobs when open. */function FxNodeRow({node,index,- total,open,+ last,disabled,onToggleOpen,onUpdate,onMove,onRemove,-}: {- node: HfAudioFxNode;- index: number;- total: number;- open: boolean;- disabled?: boolean;- onToggleOpen(): void;- onUpdate(index: number, patch: Partial<HfAudioFxNode>): void;- onMove(index: number, delta: number): void;- onRemove(index: number): void;-}) {+ onPreview,+}: FxNodeRowProps) {const def = getAudioFxDef(node.type);if (!def) return null;const bypassed = node.enabled === false;@@ -150,12 +163,12 @@ function FxNodeRow({className={`hf-fx-node rounded-[4px] border border-panel-border-input${bypassed ? " opacity-50" : ""}`}data-fx-node={node.type}>- <FxNodeControls+ <FxNodeHeaderlabel={def.label}- index={index}- total={total}open={open}bypassed={bypassed}+ first={index === 0}+ last={last}disabled={disabled}onToggleOpen={onToggleOpen}onToggleBypass={() => onUpdate(index, { enabled: bypassed })}@@ -167,16 +180,34 @@ function FxNodeRow({def={def}params={node.params ?? defaultAudioFxParams(node.type)}disabled={disabled || bypassed}- onChange={(params: HfAudioFxParamValues) => onUpdate(index, { params })}+ onChange={(params: HfAudioFxParamValues) => onPreview(index, params)}+ onCommit={(params: HfAudioFxParamValues) => onUpdate(index, { params })}/>) : null}</div>);}+export interface FxSectionProps {+ chain: HfAudioFxChain;+ /** Structural edits and gesture-end writes; this is the one that persists. */+ onChainChange(chain: HfAudioFxChain): void;+ /** Continuous updates while a control is being dragged. */+ onChainPreview?(chain: HfAudioFxChain): void;+ carve: HfCarveSettings | null;+ onCarveChange(carve: HfCarveSettings | null): void;+ /** Other audio elements that could act as the carve source. */+ sourceOptions: AudioTrackOption[];+ /** Re-run analysis against the current source audio. */+ onAnalyseCarve?(): void;+ analysing?: boolean;+ disabled?: boolean;+}+export function FxSection({chain,onChainChange,+ onChainPreview,carve,onCarveChange,sourceOptions,@@ -197,6 +228,16 @@ export function FxSection({[chain, onChainChange],);+ // Dragging a knob previews without persisting; releasing it commits once.+ const previewNode = useCallback(+ (index: number, params: HfAudioFxParamValues) =>+ onChainPreview?.({+ ...chain,+ nodes: chain.nodes.map((n, i) => (i === index ? { ...n, params } : n)),+ }),+ [chain, onChainPreview],+ );+const addEffect = useCallback((type: string) => {mutate([...chain.nodes, { type, enabled: true, params: defaultAudioFxParams(type) }]);@@ -246,13 +287,14 @@ export function FxSection({key={`${node.type}-${i}`}node={node}index={i}- total={chain.nodes.length}open={openNode === i}+ last={i === chain.nodes.length - 1}disabled={disabled}onToggleOpen={() => setOpenNode(openNode === i ? null : i)}onUpdate={updateNode}onMove={moveNode}onRemove={removeNode}+ onPreview={previewNode}/>)))}