Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(core): harden audio FX and group identity (#3444)
Vance Ingalls6faf4d608494
diff --git a/packages/core/src/audio/audioFxWorklets.test.ts b/packages/core/src/audio/audioFxWorklets.test.tsindex e7089d7ce0..2f342f6669 100644--- a/packages/core/src/audio/audioFxWorklets.test.ts+++ b/packages/core/src/audio/audioFxWorklets.test.ts@@ -136,25 +136,127 @@ describe("the worklet processors themselves", () => {return crossings / ((s.length - start) / SR);}- it("at semitones: 0, mix: 1 reproduces the input, delayed by exactly one grain/2", async () => {+ // This assertion used to be that the output equalled the input DELAYED by+ // grain/2 — the measurement was right and was written down as the contract.+ // But the grain delay is there to shift pitch, and at semitones: 0 nothing+ // is being shifted: the node degenerated into a pure 50 ms delay of the+ // signal, plus a head of silence while the ring filled, under a label that+ // reads "Unchanged pitch".+ it("at semitones: 0, mix: 1 passes the input through untouched", async () => {const HfPitchshift = (await loadProcessors()).get("hf-pitchshift");if (!HfPitchshift) throw new Error("hf-pitchshift not registered");const p = new HfPitchshift({ processorOptions: { semitones: 0, mix: 1 } });const input = sine(440, 0.5);const output = run(p, input);- const grain = Math.round(SR * 0.1);- // readTap reads from `write - 1`, i.e. one sample behind the one just- // written in this same iteration — so the effective delay is one sample- // more than the nominal grain/2.- const delay = grain / 2 + 1;- // Skip the first grain while the ring buffer is still filling.let maxErr = 0;- for (let i = grain * 2; i < input.length; i++) {- maxErr = Math.max(maxErr, Math.abs((output[i] ?? 0) - (input[i - delay] ?? 0)));+ for (let i = 0; i < input.length; i++) {+ maxErr = Math.max(maxErr, Math.abs((output[i] ?? 0) - (input[i] ?? 0)));}expect(maxErr).toBeLessThan(1e-6);});+ it("mix: 0 passes the input through untouched too", async () => {+ const HfPitchshift = (await loadProcessors()).get("hf-pitchshift");+ if (!HfPitchshift) throw new Error("hf-pitchshift not registered");+ const p = new HfPitchshift({ processorOptions: { semitones: 7, mix: 0 } });+ const input = sine(440, 0.25);+ const output = run(p, input);+ let maxErr = 0;+ for (let i = 0; i < input.length; i++) {+ maxErr = Math.max(maxErr, Math.abs((output[i] ?? 0) - (input[i] ?? 0)));+ }+ expect(maxErr).toBeLessThan(1e-6);+ });++ /** Largest sample-to-sample step — a splice between the dry and the+ * ~50 ms-delayed wet path shows up here as a discontinuity. */+ function maxStep(s: Float32Array, from: number, to: number): number {+ let worst = 0;+ for (let i = from + 1; i < to; i++) {+ worst = Math.max(worst, Math.abs((s[i] ?? 0) - (s[i - 1] ?? 0)));+ }+ return worst;+ }++ // Dragging the semitones slider off zero mid-playback swaps the output from+ // x[t] to x[t-50ms]. Switched hard that is an audible click; the wet amount+ // is ramped instead. A 440 Hz sine steps ~0.057 per sample at its steepest,+ // so anything near the signal's own peak is a splice, not the waveform.+ it("does not click when the shift moves off zero mid-signal", async () => {+ const HfPitchshift = (await loadProcessors()).get("hf-pitchshift");+ if (!HfPitchshift) throw new Error("hf-pitchshift not registered");+ const p = new HfPitchshift({ processorOptions: { semitones: 0, mix: 1 } });+ run(p, sine(440, 0.3)); // settled dry, ring warm+ p.p = { ...p.p, semitones: 7 };+ const output = run(p, sine(440, 0.3));+ expect(maxStep(output, 0, output.length)).toBeLessThan(0.2);+ });++ it("does not click on the way back to zero either", async () => {+ const HfPitchshift = (await loadProcessors()).get("hf-pitchshift");+ if (!HfPitchshift) throw new Error("hf-pitchshift not registered");+ const p = new HfPitchshift({ processorOptions: { semitones: 7, mix: 1 } });+ run(p, sine(440, 0.3));+ p.p = { ...p.p, semitones: 0 };+ const output = run(p, sine(440, 0.3));+ expect(maxStep(output, 0, output.length)).toBeLessThan(0.2);+ });++ // ...and having ramped back down it must reach TRUE bypass, not sit on a+ // permanently latched wet path. The render builds a fresh node from the+ // saved attribute and bypasses at semitones 0; a preview that stayed wet+ // would carry a 50 ms delay the export does not have.+ it("returns to true bypass after being shifted and set back to zero", async () => {+ const HfPitchshift = (await loadProcessors()).get("hf-pitchshift");+ if (!HfPitchshift) throw new Error("hf-pitchshift not registered");+ const p = new HfPitchshift({ processorOptions: { semitones: 7, mix: 1 } });+ run(p, sine(440, 0.3));+ p.p = { ...p.p, semitones: 0 };+ run(p, sine(440, 0.3)); // ramp down settles here++ const input = sine(440, 0.3);+ const output = run(p, input);+ let maxErr = 0;+ for (let i = 0; i < input.length; i++) {+ maxErr = Math.max(maxErr, Math.abs((output[i] ?? 0) - (input[i] ?? 0)));+ }+ expect(maxErr).toBeLessThan(1e-6);+ });++ // A node parked at mix 0 has shifted nothing, so it must not have spent+ // anything that stops the zero-shift bypass engaging later.+ it("is transparent at zero after sitting mixed fully out", async () => {+ const HfPitchshift = (await loadProcessors()).get("hf-pitchshift");+ if (!HfPitchshift) throw new Error("hf-pitchshift not registered");+ const p = new HfPitchshift({ processorOptions: { semitones: 7, mix: 0 } });+ run(p, sine(440, 0.3));++ p.p = { ...p.p, semitones: 0, mix: 1 };+ const input = sine(440, 0.3);+ const output = run(p, input);+ let maxErr = 0;+ for (let i = 0; i < input.length; i++) {+ maxErr = Math.max(maxErr, Math.abs((output[i] ?? 0) - (input[i] ?? 0)));+ }+ expect(maxErr).toBeLessThan(1e-6);+ });++ // The ring starts empty, so the taps read zeros for the first grain. That+ // used to come out of the head of every clip as silence; it ramps the wet+ // path in instead, which is unshifted audio rather than no audio.+ it("does not open with silence while the grain buffer fills", async () => {+ const HfPitchshift = (await loadProcessors()).get("hf-pitchshift");+ if (!HfPitchshift) throw new Error("hf-pitchshift not registered");+ const p = new HfPitchshift({ processorOptions: { semitones: 7, mix: 1 } });+ const input = sine(440, 0.5);+ const output = run(p, input);+ // Peak over the first 20 ms — well inside the old dead zone.+ let peak = 0;+ for (let i = 0; i < Math.round(SR * 0.02); i++)+ peak = Math.max(peak, Math.abs(output[i] ?? 0));+ expect(peak).toBeGreaterThan(0.5);+ });+it("at semitones: 12, doubles the fundamental (one octave up)", async () => {const HfPitchshift = (await loadProcessors()).get("hf-pitchshift");if (!HfPitchshift) throw new Error("hf-pitchshift not registered");diff --git a/packages/core/src/audio/audioFxWorklets.ts b/packages/core/src/audio/audioFxWorklets.tsindex d0dd8dded5..5aa3d9fc16 100644--- a/packages/core/src/audio/audioFxWorklets.ts+++ b/packages/core/src/audio/audioFxWorklets.ts@@ -253,6 +253,21 @@ class HfPitchshift extends AudioWorkletProcessor {this.buf = [];this.write = 0;this.phase = 0;+ // Samples written so far, capped at one grain. The taps read up to a grain+ // behind the write head, so until this fills they would read the ring's+ // zeros — the head of every clip came out attenuated or silent.+ this.filled = 0;+ // How much of the wet (pitch-shifted) path is currently in the output, and+ // where it is heading. Crossing between dry and wet is a ~50 ms jump in the+ // signal, so it is RAMPED rather than switched: a hard swap either way is a+ // click. Ramping in both directions is also what lets a node return to true+ // bypass at semitones 0 — a one-way latch left preview stuck with the delay+ // that the render, building a fresh node from the attribute, does not have.+ this.wet = 0;+ this.wetTarget = 0;+ // ~15 ms one-pole, short enough to feel immediate on a slider drag and long+ // enough that the splice is inaudible.+ this.wetCoef = Math.exp(-1 / (sampleRate * 0.015));this.port.onmessage = (e) => {if (e.data && e.data.__hfDispose) { this.dead = true; return; }this.p = { ...this.p, ...e.data };@@ -265,20 +280,51 @@ class HfPitchshift extends AudioWorkletProcessor {const p = this.p;const semitones = Math.max(-12, Math.min(12, p.semitones ?? 0));const mix = Math.max(0, Math.min(1, p.mix ?? 1));- const ratio = Math.pow(2, semitones / 12);const grain = this.grain;const ringLen = grain * 2;- const inc = (1 - ratio) / grain;const n = i[0] ? i[0].length : 0;for (let ch = 0; ch < i.length; ch++) {if (!this.buf[ch]) this.buf[ch] = new Float32Array(ringLen);}- let write = this.write, phase = this.phase;++ // Nothing to shift, or mixed fully out. The grain delay is ~grain/2+ // whatever the ratio, so at semitones=0 this degenerated into a pure 50 ms+ // delay of the signal — while the copy for that exact setting reads+ // "Unchanged pitch".+ this.wetTarget = semitones === 0 ? 0 : mix;++ // Fully dry AND settled: take the cheap transparent path. The ring keeps+ // filling, so a later shift does not start cold.+ if (this.wetTarget === 0 && this.wet < 1e-4) {+ this.wet = 0;+ let w = this.write;+ for (let s = 0; s < n; s++) {+ for (let ch = 0; ch < i.length; ch++) {+ const x = i[ch][s];+ this.buf[ch][w] = x;+ o[ch][s] = x;+ }+ w = (w + 1) % ringLen;+ }+ this.write = w;+ this.filled = Math.min(grain, this.filled + n);+ return true;+ }++ const ratio = Math.pow(2, semitones / 12);+ const inc = (1 - ratio) / grain;+ let write = this.write, phase = this.phase, filled = this.filled, wetNow = this.wet;+ const target = this.wetTarget, coef = this.wetCoef;for (let s = 0; s < n; s++) {phase += inc;phase -= Math.floor(phase);const phaseB = (phase + 0.5) % 1;const gA = xfade(phase), gB = xfade(phaseB);+ // Ramp the wet path in as the ring fills rather than reading zeros:+ // 100 ms of unshifted audio at the head of a clip beats 50 ms of silence.+ const warm = filled >= grain ? 1 : filled / grain;+ wetNow = target + coef * (wetNow - target);+ const wetMix = wetNow * warm;for (let ch = 0; ch < i.length; ch++) {const ring = this.buf[ch];const inp = i[ch], out = o[ch];@@ -286,12 +332,15 @@ class HfPitchshift extends AudioWorkletProcessor {ring[write] = x;const wet =readTap(ring, write, phase * grain) * gA + readTap(ring, write, phaseB * grain) * gB;- out[s] = x * (1 - mix) + wet * mix;+ out[s] = x * (1 - wetMix) + wet * wetMix;}write = (write + 1) % ringLen;+ if (filled < grain) filled++;}this.write = write;this.phase = phase;+ this.filled = filled;+ this.wet = wetNow;return true;}}diff --git a/packages/core/src/audioCarve.test.ts b/packages/core/src/audioCarve.test.tsindex be4dcfb14d..60fdbec2b4 100644--- a/packages/core/src/audioCarve.test.ts+++ b/packages/core/src/audioCarve.test.ts@@ -10,6 +10,8 @@ import {clipsOverlap,mixCarveSources,couldBeCarveSource,+ couldBeCarveBed,+ isNamedCarveBed,DEFAULT_CARVE,normalizeCarveSettings,} from "./audioCarve.js";@@ -538,6 +540,30 @@ describe("classifyAudioName", () => {expect(couldBeCarveSource("sfx-explosion")).toBe(false);});+ // The near-end rule, which nothing used to ask. `couldBeCarveSource` shipped+ // with its own doc comment ("music and sfx are out") and no caller; the bed+ // side had no predicate at all, so a narration clip was offered the carve and+ // — finding one candidate — had one applied for it, against the group it was+ // a member of.+ it("never offers a voice track as the bed, but keeps an unnamed one eligible", () => {+ expect(couldBeCarveBed("music-bed")).toBe(true);+ expect(couldBeCarveBed("sfx-riser")).toBe(true);+ expect(couldBeCarveBed("a1")).toBe(true);+ expect(couldBeCarveBed("vo-2")).toBe(false);+ expect(couldBeCarveBed("voiceover")).toBe(false);+ expect(couldBeCarveBed("narration-3")).toBe(false);+ });++ // Showing the control is a suggestion; writing the attribute is a decision.+ // A decision taken off a name that said nothing is how a carve appears that+ // nobody remembers configuring — so `a1` may be offered but never chosen.+ it("only self-applies to a name that positively reads as a bed", () => {+ expect(isNamedCarveBed("music-bed")).toBe(true);+ expect(isNamedCarveBed("sfx-riser")).toBe(true);+ expect(isNamedCarveBed("a1")).toBe(false);+ expect(isNamedCarveBed("vo-2")).toBe(false);+ });+it("treats underscores as separators, not word characters, for short hints", () => {// `\b` treats `_` as a word character, so `\bbed\b` used to miss `bed_01` —// an underscore-separated bed classified as "unknown" and could end updiff --git a/packages/core/src/audioCarve.ts b/packages/core/src/audioCarve.tsindex 265b48352d..c43500c5db 100644--- a/packages/core/src/audioCarve.ts+++ b/packages/core/src/audioCarve.ts@@ -188,6 +188,40 @@ export function couldBeCarveSource(...parts: readonly (string | null | undefinedreturn kind === "voice" || kind === "unknown";}+/**+ * Could this track be the BED a carve is written onto?+ *+ * The other half of `couldBeCarveSource`, and the half nothing used to ask. A+ * carve makes room in a bed for a voice; a voice track has no room to make for+ * itself, and offering it the control is offering a track to duck against its+ * own kind. Observed: a narration clip in a Voiceover group carved against that+ * group — a member ducking the bus it feeds.+ *+ * Loose in the same direction as its sibling: a name that says nothing stays+ * eligible, because a name is a hint and an author may know better. Only a name+ * that positively reads as speech is refused.+ */+export function couldBeCarveBed(...parts: readonly (string | null | undefined)[]): boolean {+ return classifyAudioName(...parts) !== "voice";+}++/**+ * Does this track's name positively say "bed"?+ *+ * Stricter than `couldBeCarveBed`, for the one act the author did not ask for:+ * applying a carve on their behalf. Offering the control on a track named `a1`+ * is a suggestion they can ignore; writing `data-fx-carve` onto it is a decision,+ * and a decision taken off a name that said nothing is how a carve appears that+ * nobody remembers configuring.+ *+ * The same split the source side already makes between what the picker may show+ * and what `autoSourceIds` may choose unprompted.+ */+export function isNamedCarveBed(...parts: readonly (string | null | undefined)[]): boolean {+ const kind = classifyAudioName(...parts);+ return kind === "music" || kind === "sfx";+}+export const DEFAULT_CARVE: HfCarveSettings = {enabled: true,sources: [],diff --git a/packages/core/src/audioFx.ts b/packages/core/src/audioFx.tsindex fd31285b89..181ddb67c6 100644--- a/packages/core/src/audioFx.ts+++ b/packages/core/src/audioFx.ts@@ -509,7 +509,12 @@ export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [id: "pitchshift",label: "Pitch shift",group: "time",- description: "Shifts pitch up or down without changing playback speed.",+ // The granular algorithm reads from a 100 ms grain, so its output runs a+ // constant ~50 ms behind its input and nothing in the graph subtracts that+ // — there is no latency/pre-roll concept here yet. It is inaudible on its+ // own and audible against picture or against an unshifted track, so it is+ // stated rather than hidden. `semitones: 0` bypasses the node entirely.+ description: "Shifts pitch up or down without changing playback speed. Adds ~50 ms of latency.",params: [{kind: "number",@@ -917,50 +922,7 @@ export function parseAudioFxChain(json: string): HfAudioFxChain {if (!Array.isArray(obj.nodes)) {throw new AudioFxChainError("Chain file is missing a `nodes` array.");}- const nodes: HfAudioFxNode[] = obj.nodes.map((n, i) => {- if (typeof n !== "object" || n === null) {- throw new AudioFxChainError(`Node ${i} is not an object.`);- }- const node = n as {- type?: unknown;- id?: unknown;- enabled?: unknown;- params?: unknown;- fromCarve?: unknown;- fromPreset?: unknown;- label?: unknown;- fromEq?: unknown;- fromLeveller?: unknown;- presetAmount?: 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 } : {}),- // Both survive the round trip or a preset stops being able to find its- // own nodes after a reload: re-applying would stack a second copy and- // the rack would lose the grouping it braces them with.- ...(typeof node.fromPreset === "string" && node.fromPreset- ? { fromPreset: node.fromPreset }- : {}),- ...(typeof node.label === "string" && node.label ? { label: node.label } : {}),- ...(typeof node.fromEq === "string" && node.fromEq ? { fromEq: node.fromEq } : {}),- ...(node.fromLeveller === true ? { fromLeveller: true as const } : {}),- // Clamped on the way in: the blend is two gains in opposition, and a value- // outside 0..1 makes the dry leg negative rather than simply loud.- ...(typeof node.presetAmount === "number" && Number.isFinite(node.presetAmount)- ? { presetAmount: Math.min(1, Math.max(0, node.presetAmount)) }- : {}),- enabled: node.enabled !== false,- params: normalizeAudioFxParams(- node.type,- (node.params ?? undefined) as HfAudioFxParamValues | undefined,- ),- };- });+ const nodes = obj.nodes.map(parseAudioFxNode);return { version: HF_AUDIO_FX_CHAIN_VERSION, nodes };}@@ -973,22 +935,7 @@ export function enabledAudioFxNodes(chain: HfAudioFxChain): HfAudioFxNode[] {export function serializeAudioFxChain(chain: HfAudioFxChain): string {return JSON.stringify({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.fromPreset ? { fromPreset: node.fromPreset } : {}),- ...(node.label ? { label: node.label } : {}),- ...(node.fromEq ? { fromEq: node.fromEq } : {}),- ...(node.fromLeveller === true ? { fromLeveller: true } : {}),- // Omitted when fully applied, so an untouched preset does not grow a field- // in every chain that carries one.- ...(typeof node.presetAmount === "number" && node.presetAmount !== 1- ? { presetAmount: node.presetAmount }- : {}),- ...(node.enabled === false ? { enabled: false } : {}),- params: normalizeAudioFxParams(node.type, node.params),- })),+ nodes: chain.nodes.map(serializeAudioFxNode),});}@@ -1004,3 +951,102 @@ export function mintAudioFxNodeId(chain: HfAudioFxChain): string {if (!taken.has(id)) return id;}}++/** The shape a node is READ as: everything unknown until checked. */+interface RawAudioFxNode {+ type?: unknown;+ id?: unknown;+ enabled?: unknown;+ params?: unknown;+ fromCarve?: unknown;+ fromPreset?: unknown;+ label?: unknown;+ fromEq?: unknown;+ fromLeveller?: unknown;+ presetAmount?: unknown;+}++/**+ * One node out of a chain file, validated. Throws rather than dropping: a chain+ * that silently loses a node would render differently from the project the+ * author saved.+ */+function parseAudioFxNode(n: unknown, i: number): HfAudioFxNode {+ if (typeof n !== "object" || n === null) {+ throw new AudioFxChainError(`Node ${i} is not an object.`);+ }+ const node = n as RawAudioFxNode;+ if (typeof node.type !== "string" || !BY_ID.has(node.type)) {+ throw new AudioFxChainError(`Node ${i} has unknown effect type: ${String(node.type)}`);+ }+ return withoutUndefined({+ type: node.type,+ id: nonEmptyString(node.id),+ fromCarve: onlyTrue(node.fromCarve),+ // fromPreset and label both survive the round trip or a preset stops being+ // able to find its own nodes after a reload: re-applying would stack a+ // second copy and the rack would lose the grouping it braces them with.+ fromPreset: nonEmptyString(node.fromPreset),+ label: nonEmptyString(node.label),+ fromEq: nonEmptyString(node.fromEq),+ fromLeveller: onlyTrue(node.fromLeveller),+ presetAmount: clampedPresetAmount(node.presetAmount),+ enabled: node.enabled !== false,+ params: normalizeAudioFxParams(+ node.type,+ (node.params ?? undefined) as HfAudioFxParamValues | undefined,+ ),+ });+}++/** One node as the `data-fx-chain` attribute carries it. Every optional field is+ * omitted when it holds its default, so a plain chain stays plain. */+function serializeAudioFxNode(node: HfAudioFxNode) {+ return withoutUndefined({+ type: node.type,+ id: nonEmptyString(node.id),+ fromCarve: onlyTrue(node.fromCarve),+ fromPreset: nonEmptyString(node.fromPreset),+ label: nonEmptyString(node.label),+ fromEq: nonEmptyString(node.fromEq),+ fromLeveller: onlyTrue(node.fromLeveller),+ // Omitted when fully applied, so an untouched preset does not grow a field+ // in every chain that carries one.+ presetAmount: node.presetAmount === 1 ? undefined : clampedPresetAmount(node.presetAmount),+ // Only the non-default is written: a chain of enabled nodes stays plain.+ enabled: node.enabled === false ? (false as const) : undefined,+ params: normalizeAudioFxParams(node.type, node.params),+ });+}++/**+ * The field readers the two node codecs share.+ *+ * Written as readers rather than as conditional spreads inline: nine+ * `...(cond ? { x } : {})` clauses in one object literal is nine branches in a+ * function whose actual job is "copy the fields that are set", and it read as+ * complex because it was measured as complex.+ */+function nonEmptyString(value: unknown): string | undefined {+ return typeof value === "string" && value ? value : undefined;+}++function onlyTrue(value: unknown): true | undefined {+ return value === true ? true : undefined;+}++/** Clamped on the way in: the blend is two gains in opposition, and a value+ * outside 0..1 makes the dry leg negative rather than simply loud. */+function clampedPresetAmount(value: unknown): number | undefined {+ if (typeof value !== "number" || !Number.isFinite(value)) return undefined;+ return Math.min(1, Math.max(0, value));+}++/** Drop the keys whose reader returned undefined, so an absent field stays+ * absent rather than becoming an explicit `undefined` in the document. */+function withoutUndefined<T extends object>(obj: T): T {+ for (const key of Object.keys(obj) as Array<keyof T>) {+ if (obj[key] === undefined) delete obj[key];+ }+ return obj;+}diff --git a/packages/core/src/audioGroups.test.ts b/packages/core/src/audioGroups.test.tsindex edc16d16a7..606112d2de 100644--- a/packages/core/src/audioGroups.test.ts+++ b/packages/core/src/audioGroups.test.ts@@ -3,15 +3,15 @@ import {audioGroupOf,ensureAudioGroupInertStyle,HF_AUDIO_GROUP_ATTR,+ isMemberGroupHidden,resolveAudioGroups,resolveCarveSourceIds,+ resolveGroupElement,} from "./audioGroups.js";+import { AUDIO_GROUP_RENDER_ID_ATTR, MEDIA_RENDER_ID_ATTR } from "./compiler/mediaRenderIds.js";beforeEach(() => {document.body.innerHTML = "";- // The inert stylesheet is injected once per document, so a leftover from an- // earlier test would carry the assertion for the one after it.- document.getElementById("__hf-audio-group-inert")?.remove();});describe("resolveAudioGroups", () => {@@ -115,18 +115,14 @@ describe("audioGroupOf", () => {expect(audioGroupOf(document.getElementById("vo-1") as Element)).toBeNull();});- // The mirror of resolveAudioGroups' own video case. These two readers used to- // disagree here: the resolver saw no group, this one answered "voiceover", so- // preview routed a track through a bus the export would never build (the- // render enforces audio-only in audioMixer).- it("returns null for a video, matching resolveAudioGroups", () => {+ it("ignores video membership so preview matches the audio-only render", () => {document.body.innerHTML = `<video id="v-1" data-audio-group="voiceover"></video>`;const el = document.getElementById("v-1") as Element;expect(audioGroupOf(el)).toBeNull();expect(resolveAudioGroups(document)).toEqual([]);});- it("returns null for an empty attribute, not an empty string", () => {+ it("normalizes an empty membership attribute to null", () => {document.body.innerHTML = `<audio id="vo-1" data-audio-group=""></audio>`;expect(audioGroupOf(document.getElementById("vo-1") as Element)).toBeNull();expect(resolveAudioGroups(document)).toEqual([]);@@ -139,40 +135,6 @@ describe("audioGroupOf", () => {});});-describe("ensureAudioGroupInertStyle", () => {- it("takes the group element out of layout", () => {- document.body.innerHTML = `<hf-audio-group id="voiceover"></hf-audio-group>`;- const el = document.getElementById("voiceover") as HTMLElement;- ensureAudioGroupInertStyle(document);- expect(getComputedStyle(el).display).toBe("none");- });-- // An unknown custom element is an ordinary inline box, so in a flex or grid- // root it takes a slot: a gap, a justify-content share, and every- // :nth-child after it shifts. An author rule must not be able to put it- // back — and an id selector outranks this rule's type selector no matter- // which stylesheet came last, so `!important` is the only thing holding the- // contract. Dropping it makes this case fail.- it("beats an author rule that outranks it on specificity", () => {- document.head.insertAdjacentHTML(- "beforeend",- `<style id="author">#voiceover{display:flex}</style>`,- );- document.body.innerHTML = `<hf-audio-group id="voiceover"></hf-audio-group>`;- ensureAudioGroupInertStyle(document);- expect(getComputedStyle(document.getElementById("voiceover") as HTMLElement).display).toBe(- "none",- );- document.getElementById("author")?.remove();- });-- it("injects once, however many times it is called", () => {- ensureAudioGroupInertStyle(document);- ensureAudioGroupInertStyle(document);- expect(document.querySelectorAll("#__hf-audio-group-inert")).toHaveLength(1);- });-});-describe("resolveCarveSourceIds", () => {it("expands a group id to its current members", () => {document.body.innerHTML = `@@ -219,3 +181,123 @@ describe(HF_AUDIO_GROUP_ATTR, () => {expect(HF_AUDIO_GROUP_ATTR).toBe("data-audio-group");});});++describe("resolveGroupElement", () => {+ const doc = (html: string): Document => {+ const d = document.implementation.createHTMLDocument("t");+ d.body.innerHTML = html;+ return d;+ };++ it("returns the bus for a real <hf-audio-group>", () => {+ const d = doc(`<hf-audio-group id="vo" data-volume="0.5"></hf-audio-group>`);+ expect(resolveGroupElement(d, "vo")?.tagName.toLowerCase()).toBe("hf-audio-group");+ });++ // The trap: a bare getElementById read a member's OWN fader and chain as the+ // bus's, applying both a second time on the sub-mix.+ it("refuses an <audio> sharing the group id", () => {+ const d = doc(`<audio id="vo" data-audio-group="vo" data-volume="0.5"></audio>`);+ expect(resolveGroupElement(d, "vo")).toBeNull();+ });++ it("refuses an unrelated element sharing the group id", () => {+ const d = doc(`<div id="bg" data-hidden></div>`);+ expect(resolveGroupElement(d, "bg")).toBeNull();+ });++ it("matches a stamped id containing selector syntax without throwing", () => {+ const d = doc("");+ const bus = d.createElement("hf-audio-group");+ bus.setAttribute(MEDIA_RENDER_ID_ATTR, 'vo"\\instance');+ d.body.append(bus);++ expect(resolveGroupElement(d, 'vo"\\instance')).toBe(bus);+ });+});++describe("isMemberGroupHidden", () => {+ const doc = (html: string): Document => {+ const d = document.implementation.createHTMLDocument("t");+ d.body.innerHTML = html;+ return d;+ };++ // Membership is on the MEMBER, so the bus is never an ancestor and+ // `closest("[data-hidden]")` cannot see it.+ it("sees a muted bus that does not nest its member", () => {+ const d = doc(+ `<hf-audio-group id="vo" data-hidden></hf-audio-group>+ <div><audio id="vo-1" data-audio-group="vo"></audio></div>`,+ );+ const member = d.getElementById("vo-1");+ expect(member?.closest("[data-hidden]")).toBeNull();+ expect(isMemberGroupHidden(d, member)).toBe(true);+ });++ it("is false for an unmuted bus and for a member with no group", () => {+ const d = doc(+ `<hf-audio-group id="vo"></hf-audio-group>+ <audio id="vo-1" data-audio-group="vo"></audio>+ <audio id="lone"></audio>`,+ );+ expect(isMemberGroupHidden(d, d.getElementById("vo-1"))).toBe(false);+ expect(isMemberGroupHidden(d, d.getElementById("lone"))).toBe(false);+ });++ it("uses the stamped bus instance when repeated compositions disagree on mute", () => {+ const d = doc(`+ <hf-audio-group id="bed" ${MEDIA_RENDER_ID_ATTR}="bed"></hf-audio-group>+ <audio id="m1" data-audio-group="bed" ${AUDIO_GROUP_RENDER_ID_ATTR}="bed"></audio>+ <hf-audio-group id="bed" ${MEDIA_RENDER_ID_ATTR}="bed__hf2" data-hidden></hf-audio-group>+ <audio id="m2" data-audio-group="bed" ${AUDIO_GROUP_RENDER_ID_ATTR}="bed__hf2"></audio>+ `);++ expect(isMemberGroupHidden(d, d.getElementById("m1"))).toBe(false);+ expect(isMemberGroupHidden(d, d.getElementById("m2"))).toBe(true);+ });+});++describe("resolveCarveSourceIds — empty group", () => {+ it("drops an empty group's own bus id instead of returning it as a clip", () => {+ const d = document.implementation.createHTMLDocument("t");+ d.body.innerHTML = `<hf-audio-group id="voiceover"></hf-audio-group>`;+ // No members, so the group resolves to nothing; its element must not pass+ // the existence check as if it were a clip the analysis could read.+ expect(resolveCarveSourceIds(d, ["voiceover"])).toEqual([]);+ });+});++describe("ensureAudioGroupInertStyle", () => {+ it("takes the group element out of layout", () => {+ document.body.innerHTML = `<hf-audio-group id="voiceover"></hf-audio-group>`;+ const el = document.getElementById("voiceover") as HTMLElement;+ ensureAudioGroupInertStyle(document);+ expect(getComputedStyle(el).display).toBe("none");+ });++ // An unknown custom element is an ordinary inline box, so in a flex or grid+ // root it takes a slot: a gap, a justify-content share, and every+ // :nth-child after it shifts. An author rule must not be able to put it+ // back — and an id selector outranks this rule's type selector no matter+ // which stylesheet came last, so `!important` is the only thing holding the+ // contract. Dropping it makes this case fail.+ it("beats an author rule that outranks it on specificity", () => {+ document.head.insertAdjacentHTML(+ "beforeend",+ `<style id="author">#voiceover{display:flex}</style>`,+ );+ document.body.innerHTML = `<hf-audio-group id="voiceover"></hf-audio-group>`;+ ensureAudioGroupInertStyle(document);+ expect(getComputedStyle(document.getElementById("voiceover") as HTMLElement).display).toBe(+ "none",+ );+ document.getElementById("author")?.remove();+ });++ it("injects once, however many times it is called", () => {+ ensureAudioGroupInertStyle(document);+ ensureAudioGroupInertStyle(document);+ expect(document.querySelectorAll("#__hf-audio-group-inert")).toHaveLength(1);+ });+});diff --git a/packages/core/src/audioGroups.ts b/packages/core/src/audioGroups.tsindex 4732d72b71..94e47fe622 100644--- a/packages/core/src/audioGroups.ts+++ b/packages/core/src/audioGroups.ts@@ -10,25 +10,12 @@*/import { HF_AUDIO_FX_ATTR } from "./audioFx.js";+import { AUDIO_GROUP_RENDER_ID_ATTR, MEDIA_RENDER_ID_ATTR } from "./compiler/mediaRenderIds.js";import { HF_AUDIO_AUTOMATION_ATTR } from "./audioAutomation.js";export const HF_AUDIO_GROUP_TAG = "hf-audio-group";export const HF_AUDIO_GROUP_ATTR = "data-audio-group";-/**- * v1 membership, in one place: an `<audio>` carrying a NON-EMPTY- * `data-audio-group`.- *- * Both readers below derive from this string, because they disagreed when they- * did not. `resolveAudioGroups` scanned `audio[...]` while `audioGroupOf`- * returned the attribute off any element, so the same DOM answered "no group"- * for a `<video data-audio-group="voiceover">` in one and `"voiceover"` in the- * other. The render already enforces audio-only (see audioMixer's- * `type === "audio"` guard), so the disagreement was preview routing a track- * the export would never group.- */-const MEMBER_SELECTOR = `audio[${HF_AUDIO_GROUP_ATTR}]`;-export interface HfAudioGroup {id: string;/** `data-label`, falling back to the id when absent. */@@ -49,7 +36,13 @@ export interface HfAudioGroup {hidden: boolean;}-function parseGroupVolume(el: Element | undefined): number {+/**+ * A group element's `data-volume`, defaulting to 1 for a missing, unparseable+ * or absent element. Shared so the preview bus and `resolveAudioGroups` (which+ * the render reads) cannot drift: the export was ~8 dB quieter than what was+ * auditioned for exactly as long as the preview ignored this.+ */+export function readAudioGroupVolume(el: Element | null | undefined): number {const raw = el?.getAttribute("data-volume");const parsed = raw ? parseFloat(raw) : 1;return Number.isFinite(parsed) ? parsed : 1;@@ -64,7 +57,7 @@ function buildGroup(id: string, memberIds: string[], el: Element | undefined): HmemberIds,...(fxChain ? { fxChain } : {}),...(automation ? { automation } : {}),- volume: parseGroupVolume(el),+ volume: readAudioGroupVolume(el),hidden: el?.hasAttribute("data-hidden") ?? false,};}@@ -76,10 +69,76 @@ function buildGroup(id: string, memberIds: string[], el: Element | undefined): H* (label = id) so a hand-authored composition degrades gracefully. Audio* only in v1 — a `data-audio-group` on a `<video>` is ignored.*/+/**+ * The `<hf-audio-group>` element for a group id, or null.+ *+ * Tag-checked, which a bare `getElementById` is not. Every group attribute —+ * the fader, the mute, the FX chain, the automation lane — is read off whatever+ * this returns, so an unrelated element sharing the id used to be read as a bus:+ * an `<audio id="vo" data-audio-group="vo" data-volume="0.5" data-fx-chain=…>`+ * had its own fader and chain applied a SECOND time on the bus, and a+ * `<div id="bg" data-hidden>` silenced group "bg" in preview only. The render+ * never had this problem — `resolveAudioGroups` only ever accepted the tag —+ * so the two disagreed on exactly the attributes the bus exists to carry.+ *+ * Returning null is the documented "group with no element" case, which+ * degrades to a flat sum rather than borrowing a stranger's settings.+ */+export function resolveGroupElement(+ doc:+ | (Pick<Document, "getElementById"> & Partial<Pick<Document, "querySelectorAll">>)+ | null+ | undefined,+ groupId: string,+): Element | null {+ // A render-stamped key names an INSTANCE, and `getElementById` cannot find it+ // — the author id is what is on the element's `id`. Tried first so a compiled+ // document resolves the right one of two identically-named buses.+ // Compare the raw attribute value instead of interpolating an author-provided+ // id into a selector. Quotes and backslashes are valid attribute values, and+ // turning one into selector syntax made this otherwise tolerant reader throw.+ const stamped = Array.from(+ doc?.querySelectorAll?.(`${HF_AUDIO_GROUP_TAG}[${MEDIA_RENDER_ID_ATTR}]`) ?? [],+ ).find((candidate) => candidate.getAttribute(MEDIA_RENDER_ID_ATTR) === groupId);+ if (stamped) return stamped;+ const el = doc?.getElementById(groupId) ?? null;+ if (!el) return null;+ return el.tagName?.toLowerCase() === HF_AUDIO_GROUP_TAG ? el : null;+}++/**+ * Whether the bus a member belongs to is muted.+ *+ * Membership is held by the MEMBER's `data-audio-group`; a group never nests+ * its members. So `el.closest("[data-hidden]")` cannot see a muted bus, which+ * is how the render came to drop a hidden group's members while the preview+ * fallback played them at full level.+ */+export function isMemberGroupHidden(+ doc: Pick<Document, "getElementById"> | null | undefined,+ el: Element | null | undefined,+): boolean {+ // A compiler stamp identifies the bus INSTANCE. The author id is only unique+ // within one composition file, so resolving by it in an inlined document made+ // every repeated sub-composition consult the first instance's mute state.+ const groupId =+ el?.getAttribute?.(AUDIO_GROUP_RENDER_ID_ATTR) ?? el?.getAttribute?.(HF_AUDIO_GROUP_ATTR);+ if (!groupId) return false;+ return resolveGroupElement(doc, groupId)?.hasAttribute("data-hidden") ?? false;+}+export function resolveAudioGroups(root: ParentNode): HfAudioGroup[] {const membersByGroup = new Map<string, string[]>();- for (const member of root.querySelectorAll(MEMBER_SELECTOR)) {- const groupId = member.getAttribute(HF_AUDIO_GROUP_ATTR);+ for (const member of root.querySelectorAll(`audio[${HF_AUDIO_GROUP_ATTR}]`)) {+ // The render-stamped instance key when the compiler has been through+ // (`assignMediaRenderIds`), else the author id. An author id is unique only+ // per composition FILE, so a sub-composition declaring a bus AND its members+ // and used twice put both instances' members under one key — one sub-mix for+ // two independent buses, instance B's fader and chain over instance A's+ // audio, and with only B muted BOTH instances dropped from the export. The+ // live preview has no stamps, so it reads exactly as before.+ const groupId =+ member.getAttribute(AUDIO_GROUP_RENDER_ID_ATTR) ?? member.getAttribute(HF_AUDIO_GROUP_ATTR);if (!groupId || !member.id) continue;const members = membersByGroup.get(groupId);if (members) members.push(member.id);@@ -88,7 +147,10 @@ export function resolveAudioGroups(root: ParentNode): HfAudioGroup[] {const groupElements = new Map<string, Element>();for (const el of root.querySelectorAll(HF_AUDIO_GROUP_TAG)) {- if (el.id) groupElements.set(el.id, el);+ // Keyed the same way, so a stamped document pairs instance for instance and+ // an unstamped one keeps id-for-id.+ const key = el.getAttribute(MEDIA_RENDER_ID_ATTR) ?? el.id;+ if (key) groupElements.set(key, el);}const groups: HfAudioGroup[] = [];@@ -122,27 +184,25 @@ export function resolveCarveSourceIds(doc: Document, ids: readonly string[]): stconst group = groupsById.get(id);if (group) {group.memberIds.forEach(add);- } else if (doc.getElementById(id)) {+ } else if (doc.getElementById(id) && !resolveGroupElement(doc, id)) {+ // A group with no members resolves to no entry above, and its own bus+ // element would then pass this existence check and be returned as if it+ // were a clip — a source the analysis can only fail to find, which the+ // docblock above promises is dropped.add(id);}}return out;}-/**- * The group a member belongs to, or null — the same predicate- * `resolveAudioGroups` scans with, so the two can never disagree about a given- * element.- *- * Non-`<audio>` returns null: video is out of scope in v1, and so is- * `data-audio-group` on an `<hf-audio-group>` itself (groups do not nest).- * `data-audio-group=""` returns null rather than `""` — the resolver skips a- * falsy id, and the "or null" in this contract has to mean it.+/** The group an audio member belongs to, or null. Membership is audio-only in+ * v1, matching `resolveAudioGroups` and the render mixer; video and group-bus+ * attributes are inert.*- * Tolerant of objects that only partially implement `Element` (test doubles for- * `HTMLMediaElement` commonly do): anything missing `tagName` or `getAttribute`- * simply has no group, mirroring `readChain`'s style in `runtime/audioFx.ts`.- */+ * Tolerant of objects that only partially implement `Element` (test doubles+ * for `HTMLMediaElement` commonly do) — anything missing `tagName` or+ * `getAttribute` simply has no group, mirroring `readChain`'s style in+ * `runtime/audioFx.ts`. */export function audioGroupOf(el: Element): string | null {if (typeof el.tagName !== "string" || el.tagName.toLowerCase() !== "audio") return null;if (typeof el.getAttribute !== "function") return null;@@ -165,25 +225,15 @@ export function audioGroupOf(el: Element): string | null {* runtime rather than the compiler so preview and render share one source.*/export function ensureAudioGroupInertStyle(doc: Document): void {- const STYLE_ID = "__hf-audio-group-inert";- if (!doc?.head || doc.getElementById(STYLE_ID)) return;+ const styleId = "__hf-audio-group-inert";+ if (!doc?.head || doc.getElementById(styleId)) return;const style = doc.createElement("style");- style.id = STYLE_ID;+ style.id = styleId;style.textContent = `${HF_AUDIO_GROUP_TAG}{display:none!important}`;doc.head.appendChild(style);}-/**- * Solo ("Hear only this") predicate — shared by the studio store (which owns- * the `soloed` set and the UI's lit/half-lit state) and the preview transport- * (which turns it into gain). An element is audible while any solo is active- * only if IT is soloed, or its OWN group is soloed (group solo = members- * solo). There is no "ancestor" to reach up to in this data model — a group- * bus is never itself attenuated by solo, so a soloed member's path through- * its group stays open by construction; this predicate only ever gates the- * member's own gain. No solo active at all is the one path that returns true- * unconditionally.- */+/** Compatibility bridge until the Studio solo controls are removed later in the stack. */export function isAudibleUnderSolo(soloed: ReadonlySet<string>,id: string,@@ -194,8 +244,7 @@ export function isAudibleUnderSolo(return Boolean(groupId && soloed.has(groupId));}-/** Half-lit: this group itself isn't soloed, but at least one of its members- * is — the display-only signal that "some of what's under here still plays". */+/** Compatibility bridge until the Studio solo controls are removed later in the stack. */export function isGroupHalfLitUnderSolo(soloed: ReadonlySet<string>,groupId: string,diff --git a/packages/core/src/compiler/index.ts b/packages/core/src/compiler/index.tsindex 6b2ba12efd..91d01e36b8 100644--- a/packages/core/src/compiler/index.ts+++ b/packages/core/src/compiler/index.ts@@ -90,4 +90,8 @@ export {// Asset-path primitives (shared across core, producer, CLI)export { CSS_URL_RE, PATH_ATTRS, isNonRelativeUrl, isPathInside } from "./assetPaths";-export { MEDIA_RENDER_ID_ATTR, assignMediaRenderIds } from "./mediaRenderIds";+export {+ AUDIO_GROUP_RENDER_ID_ATTR,+ MEDIA_RENDER_ID_ATTR,+ assignMediaRenderIds,+} from "./mediaRenderIds";diff --git a/packages/core/src/compiler/mediaRenderIds.test.ts b/packages/core/src/compiler/mediaRenderIds.test.tsindex 465c816048..3671c4de54 100644--- a/packages/core/src/compiler/mediaRenderIds.test.ts+++ b/packages/core/src/compiler/mediaRenderIds.test.ts@@ -1,6 +1,10 @@import { describe, it, expect } from "vitest";import { parseHTML } from "linkedom";-import { MEDIA_RENDER_ID_ATTR, assignMediaRenderIds } from "./mediaRenderIds";+import {+ AUDIO_GROUP_RENDER_ID_ATTR,+ MEDIA_RENDER_ID_ATTR,+ assignMediaRenderIds,+} from "./mediaRenderIds";function stamp(html: string): string[] {const { document } = parseHTML(html);@@ -77,3 +81,72 @@ describe("assignMediaRenderIds", () => {expect(document.querySelector("video")?.hasAttribute(MEDIA_RENDER_ID_ATTR)).toBe(false);});});++describe("audio group render ids", () => {+ /**+ * A sub-composition declaring a bus AND its members, used twice. The author id+ * `bed` is unique per FILE and duplicated once inlined, and the two instances+ * are indistinguishable by `data-composition-id` — both carry the file's own —+ * so the subtree element is the only thing that separates them.+ */+ const doc = (html: string) => parseHTML(`<html><body>${html}</body></html>`).document;+ const TWICE = `+ <div data-composition-id="bedcomp">+ <hf-audio-group id="bed" data-volume="0.5"></hf-audio-group>+ <audio id="m1" src="a.wav" data-audio-group="bed"></audio>+ </div>+ <div data-composition-id="bedcomp">+ <hf-audio-group id="bed" data-volume="0.5"></hf-audio-group>+ <audio id="m1" src="a.wav" data-audio-group="bed"></audio>+ </div>`;++ it("gives each bus instance its own key and pairs each member to its own subtree", () => {+ const d = doc(TWICE);+ assignMediaRenderIds(d);++ const buses = [...d.querySelectorAll("hf-audio-group")];+ const members = [...d.querySelectorAll("audio")];+ expect(buses.map((b) => b.getAttribute(MEDIA_RENDER_ID_ATTR))).toEqual(["bed", "bed__hf2"]);+ // Member N belongs to bus N — the whole point. Cross-paired, one instance's+ // fader and chain would land on the other instance's audio.+ expect(members.map((m) => m.getAttribute(AUDIO_GROUP_RENDER_ID_ATTR))).toEqual([+ "bed",+ "bed__hf2",+ ]);+ });++ it("leaves a single-instance bus keyed by its own id", () => {+ const d = doc(`<hf-audio-group id="vo"></hf-audio-group>+ <audio id="a" src="a.wav" data-audio-group="vo"></audio>`);+ assignMediaRenderIds(d);+ expect(d.querySelector("hf-audio-group")?.getAttribute(MEDIA_RENDER_ID_ATTR)).toBe("vo");+ expect(d.querySelector("audio")?.getAttribute(AUDIO_GROUP_RENDER_ID_ATTR)).toBe("vo");+ });++ it("leaves a member alone when no bus element declares its group", () => {+ const d = doc(`<audio id="a" src="a.wav" data-audio-group="ghost"></audio>`);+ assignMediaRenderIds(d);+ // The element-less group is a supported shape; it just has no instance to+ // name, so resolution falls back to the author id as it always did.+ expect(d.querySelector("audio")?.hasAttribute(AUDIO_GROUP_RENDER_ID_ATTR)).toBe(false);+ });++ it("does not bind a root member to a same-named bus in a nested composition", () => {+ const d = doc(`<div data-composition-id="root">+ <div data-composition-id="child">+ <hf-audio-group id="bed"></hf-audio-group>+ <audio id="child-member" src="child.wav" data-audio-group="bed"></audio>+ </div>+ <audio id="root-member" src="root.wav" data-audio-group="bed"></audio>+ <hf-audio-group id="bed"></hf-audio-group>+ </div>`);+ assignMediaRenderIds(d);++ const buses = [...d.querySelectorAll("hf-audio-group")];+ expect(buses.map((bus) => bus.getAttribute(MEDIA_RENDER_ID_ATTR))).toEqual(["bed", "bed__hf2"]);+ expect(d.getElementById("child-member")?.getAttribute(AUDIO_GROUP_RENDER_ID_ATTR)).toBe("bed");+ expect(d.getElementById("root-member")?.getAttribute(AUDIO_GROUP_RENDER_ID_ATTR)).toBe(+ "bed__hf2",+ );+ });+});diff --git a/packages/core/src/compiler/mediaRenderIds.ts b/packages/core/src/compiler/mediaRenderIds.tsindex c7e3639a4e..8f0a517b4d 100644--- a/packages/core/src/compiler/mediaRenderIds.ts+++ b/packages/core/src/compiler/mediaRenderIds.ts@@ -27,14 +27,35 @@export const MEDIA_RENDER_ID_ATTR = "data-hf-render-id";+/**+ * The bus a member belongs to, as a DOCUMENT-unique key.+ *+ * `data-audio-group` names a bus by author id, unique only per composition FILE+ * — so a sub-composition that declares a bus AND its members, used twice, put+ * both instances' members under one key and let the second bus element+ * overwrite the first. The mixer then sub-mixed two independent buses as one,+ * applied instance B's fader, chain and label to instance A's audio, and — with+ * only B muted — dropped BOTH instances from the export. This attribute is that+ * collision resolved at the same boundary the media ids are.+ */+export const AUDIO_GROUP_RENDER_ID_ATTR = "data-hf-group-render-id";+/** Elements the render pipeline addresses by id. */const MEDIA_SELECTOR = "video[src], audio[src], img[src]";+/** Buses, which are addressed by id in exactly the same way and collide the+ * same way. Only an id'd bus can be joined at all. */+const AUDIO_GROUP_SELECTOR = "hf-audio-group[id]";interface MediaElementLike {getAttribute(name: string): string | null;setAttribute(name: string, value: string): void;}+/** A bus or member, which additionally needs subtree scoping to be paired up. */+interface ScopedElementLike extends MediaElementLike {+ closest?(selector: string): ScopedElementLike | null;+}+interface DocumentLike {querySelectorAll(selector: string): Iterable<MediaElementLike>;}@@ -84,4 +105,86 @@ export function assignMediaRenderIds(document: DocumentLike): void {taken.add(renderId);el.setAttribute(MEDIA_RENDER_ID_ATTR, renderId);}++ assignAudioGroupRenderIds(document, taken);+}++/**+ * Give every `<hf-audio-group>` a document-unique render id, and tell each+ * member which INSTANCE of its bus it belongs to.+ *+ * Shares the `taken` set with the media pass, so a bus id and a clip id can+ * never resolve to the same key either.+ *+ * A member is paired to the bus inside its OWN composition subtree. Two+ * instances of the same sub-composition are indistinguishable by+ * `data-composition-id` — both carry the file's own id — so the subtree+ * ELEMENT is the only thing that separates them, which is exactly what+ * `closest()` returns. A member whose bus is not in its subtree (a+ * hand-authored bus in the root composition, members in a scene) falls back to+ * the first bus with that id, which is the pre-existing behaviour and the only+ * sensible reading when there is one bus and several scenes referencing it.+ */+function assignAudioGroupRenderIds(document: DocumentLike, taken: Set<string>): void {+ const busesById = stampAudioGroupBuses(document, taken);+ if (busesById.size === 0) return;++ for (const member of document.querySelectorAll(+ "audio[data-audio-group]",+ ) as Iterable<ScopedElementLike>) {+ const groupId = member.getAttribute("data-audio-group");+ const buses = groupId ? busesById.get(groupId) : undefined;+ if (!groupId || !buses?.length) continue;+ const renderId = busForMember(member, groupId, buses)?.getAttribute(MEDIA_RENDER_ID_ATTR);+ if (renderId) member.setAttribute(AUDIO_GROUP_RENDER_ID_ATTR, renderId);+ }+}++/** Every id'd bus, stamped and indexed by author id — several per id when a+ * sub-composition that declares one is used more than once. */+function stampAudioGroupBuses(+ document: DocumentLike,+ taken: Set<string>,+): Map<string, ScopedElementLike[]> {+ const busesById = new Map<string, ScopedElementLike[]>();+ for (const bus of document.querySelectorAll(+ AUDIO_GROUP_SELECTOR,+ ) as Iterable<ScopedElementLike>) {+ const id = bus.getAttribute("id");+ if (!id) continue;+ const renderId = bus.getAttribute(MEDIA_RENDER_ID_ATTR) ?? uniqueRenderId(id, taken);+ taken.add(renderId);+ bus.setAttribute(MEDIA_RENDER_ID_ATTR, renderId);+ const existing = busesById.get(id);+ if (existing) existing.push(bus);+ else busesById.set(id, [bus]);+ }+ return busesById;+}++/**+ * Which instance of a bus a member belongs to: the one in its own composition+ * subtree. Falls back to the first when the bus is not in the member's subtree+ * at all — a hand-authored bus in the root composition with members in scenes —+ * which is the pre-existing reading and the only sensible one there.+ */+function busForMember(+ member: ScopedElementLike,+ groupId: string,+ buses: ScopedElementLike[],+): MediaElementLike | undefined {+ if (buses.length === 1) return buses[0];+ const scope = member.closest?.("[data-composition-id]");+ if (!scope) return buses[0];+ // `scope.querySelectorAll()` also sees buses owned by nested compositions.+ // Compare each bus's own nearest composition instead, so a root member does+ // not bind to a same-named bus inside a child merely because the child comes+ // first in document order.+ return (+ buses.find(+ (candidate) =>+ candidate.getAttribute("id") === groupId &&+ candidate.closest?.("[data-composition-id]") === scope,+ ) ?? buses[0]+ );}diff --git a/packages/core/src/editing/affordances.test.ts b/packages/core/src/editing/affordances.test.tsindex 409d3780be..81574e3deb 100644--- a/packages/core/src/editing/affordances.test.ts+++ b/packages/core/src/editing/affordances.test.ts@@ -4,6 +4,7 @@ import {resolveEditingSections,type EditableElementFacts,} from "./affordances";+import { HF_AUDIO_GROUP_TAG } from "../audioGroups";function baseFacts(over: Partial<EditableElementFacts> = {}): EditableElementFacts {return {@@ -209,3 +210,41 @@ describe("audioFx section", () => {expect(resolveEditingSections(baseFacts({ tag: "div" })).audioFx).toBe(false);});});++describe("audio has timing but no animation; a bus has neither", () => {+ // Nothing on an `<audio>` element or an `<hf-audio-group>` bus has a+ // transform, an opacity or a box, so a tween on one moves nothing. The panel+ // showed its GSAP editor for both anyway, because it gated that on the+ // handlers being wired rather than on the element being animatable.+ it("withholds animation from an audio clip that HAS tweens", () => {+ const s = resolveEditingSections(baseFacts({ tag: "audio", animationCount: 3 }));+ expect(s.animation).toBe(false);+ });++ it("withholds it from a bus too", () => {+ const s = resolveEditingSections(baseFacts({ tag: HF_AUDIO_GROUP_TAG, animationCount: 3 }));+ expect(s.animation).toBe(false);+ });++ it("still grants it to a div with tweens, so the gate is the tag", () => {+ expect(resolveEditingSections(baseFacts({ tag: "div", animationCount: 1 })).animation).toBe(+ true,+ );+ });++ // An audio clip is placed on the timeline like any other, so Start/Duration+ // stay editable — that is the half of the old Motion section worth keeping.+ it("keeps timing on an audio clip with an authored start", () => {+ const s = resolveEditingSections(baseFacts({ tag: "audio", hasTimingStart: true }));+ expect(s.timing).toBe(true);+ });++ // A bus has no `data-start` and no duration; its automation clock is+ // composition time. Start/Duration/End would be editing nothing.+ it("withholds timing from a bus even if something claims a start", () => {+ const s = resolveEditingSections(+ baseFacts({ tag: HF_AUDIO_GROUP_TAG, hasTimingStart: true, animationCount: 2 }),+ );+ expect(s.timing).toBe(false);+ });+});diff --git a/packages/core/src/editing/affordances.ts b/packages/core/src/editing/affordances.tsindex f0e3be6ae9..682494094f 100644--- a/packages/core/src/editing/affordances.ts+++ b/packages/core/src/editing/affordances.ts@@ -1,3 +1,4 @@+import { HF_AUDIO_GROUP_TAG } from "../audioGroups.js";/*** Pure, DOM-free editing-affordance resolution. Single source of truth for what* the studio's edit panel (and any SDK consumer) surfaces per selected element:@@ -203,17 +204,33 @@ function resolveCapabilities(facts: EditableElementFacts): DomEditCapabilities {* without re-running the capability geometry parse.*/export function resolveEditingSections(facts: EditableElementFacts): EditingSectionApplicability {+ // An `<hf-audio-group>` is a mixer bus: it has no visual frame AND no media+ // of its own, but it does carry a `data-fx-chain`, which is the whole point+ // of selecting one. Without this the timeline's "Open rack" on a group led to+ // a panel offering Fill, Gradient, Stroke and Shadow for something that paints+ // nothing — and no Audio FX section at all, so a bus effect could only ever be+ // applied from the preset popover and never edited.+ const isAudioBus = facts.tag === HF_AUDIO_GROUP_TAG;// `<audio>` never paints a visual frame — position/size/rotation/stacking// and fill/radius/stroke/shadow/etc. are all inert on it. Every other tag// (div, img, video, svg, canvas, composition hosts) renders a real box.- const hasVisualBox = facts.tag !== "audio";+ const hasVisualBox = facts.tag !== "audio" && !isAudioBus;return {text: facts.hasEditableText && !facts.isCompositionHost && !facts.isInsideLockedComposition,media: facts.tag === "video" || facts.tag === "audio" || facts.tag === "img",- audioFx: facts.tag === "audio",+ audioFx: facts.tag === "audio" || isAudioBus,colorGrading: facts.tag === "video" || facts.tag === "img",- timing: facts.hasTimingStart || facts.animationCount > 0,- animation: facts.animationCount > 0,+ // A bus has no clip range at all — no `data-start`, no duration, and its+ // automation clock is composition time — so Start/Duration/End would be+ // editing nothing. Audio keeps its timing: an `<audio>` clip is placed on+ // the timeline like any other, it just cannot be tweened (see `animation`).+ timing: !isAudioBus && (facts.hasTimingStart || facts.animationCount > 0),+ // Has tweens AND could meaningfully have them. Neither an `<audio>` clip nor+ // a bus has a transform, opacity or box, so a tween on one moves nothing —+ // the flat panel gates its editor on the same two tags, and does it by tag+ // rather than by this flag because a div with no tweens yet must still+ // offer "+ Add".+ animation: facts.animationCount > 0 && facts.tag !== "audio" && !isAudioBus,layout: hasVisualBox,style: hasVisualBox,};diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 2ce24c12bb..7081a348d6 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -151,7 +151,11 @@ export {MEDIA_DURATION_CLAMP_EPSILON_SECONDS,} from "./compiler/timingCompiler";-export { MEDIA_RENDER_ID_ATTR, assignMediaRenderIds } from "./compiler/mediaRenderIds";+export {+ AUDIO_GROUP_RENDER_ID_ATTR,+ MEDIA_RENDER_ID_ATTR,+ assignMediaRenderIds,+} from "./compiler/mediaRenderIds";export {RENDER_FRAME_ID_PREFIX,diff --git a/packages/core/src/runtime/audioFx.ts b/packages/core/src/runtime/audioFx.tsindex 0068a129ee..bd459af013 100644--- a/packages/core/src/runtime/audioFx.ts+++ b/packages/core/src/runtime/audioFx.ts@@ -98,6 +98,16 @@ export function readElementAutomation(el: {*/export interface ElementFxHandle {dispose(): void;+ /**+ * Re-book every envelope against a fresh reference frame.+ *+ * For a graph that OUTLIVES the source feeding it — a group bus, which is+ * built once and kept for the session — a replay or a seek starts a new pass+ * over the same chain. Without re-anchoring, the envelopes stay committed to+ * the first pass's absolute context times: past their last point that is a+ * stuck value, which for a fade-out is silence for the rest of the session.+ */+ reanchor(timing: AutomationTiming): void;/*** Re-aim every booked envelope at a new playback rate.*@@ -277,6 +287,13 @@ export function attachElementFxChain(}return {+ reanchor: (next: AutomationTiming) => {+ if (disposed) return;+ const at = timingNow();+ if (at) cancelParamLane(automated, at.scheduledAt);+ frame = { ...next };+ scheduleFor(readChain(el).chain, frame);+ },setRate: (rate: number) => {const at = timingNow();if (disposed || !at || !Number.isFinite(rate) || rate <= 0 || rate === at.rate) return;