Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(core): align preview transport with grouped audio (#3445)
Vance Ingalls16ff1eb14532
diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.tsindex 0da332ec94..262a08321d 100644--- a/packages/core/src/runtime/init.test.ts+++ b/packages/core/src/runtime/init.test.ts@@ -190,6 +190,99 @@ describe("initSandboxRuntimeModular", () => {window.cancelAnimationFrame = originalCancelAnimationFrame;});+ /**+ * `data-volume` is an authoring GAIN up to `MAX_AUDIO_GAIN` (12 dB ~ 3.98) —+ * `HTMLMediaElement.volume` accepts only 0..1. The bridge clamps its own+ * argument, but the PRODUCT `clipVolume * volume` was assigned unclamped, so a+ * clip authored above unity threw+ * `IndexSizeError: The volume provided (2.42103) is outside the range [0, 1]`+ * (2.42103 is the +7.68 dB fader stop) — and the throw aborted the loop, so+ * every media element after it kept its old volume too.+ */+ it("clamps the native volume of an over-unity clip instead of throwing", () => {+ const root = document.createElement("div");+ root.setAttribute("data-composition-id", "main");+ root.setAttribute("data-root", "true");+ root.setAttribute("data-start", "0");+ root.setAttribute("data-duration", "10");+ root.setAttribute("data-width", "1920");+ root.setAttribute("data-height", "1080");+ document.body.appendChild(root);++ const loud = document.createElement("audio");+ loud.setAttribute("data-start", "0");+ loud.setAttribute("data-duration", "10");+ loud.setAttribute("data-volume", "2.42103");+ loud.load = () => {};+ root.appendChild(loud);+ // Second element proves the throw took the whole sweep down with it, not just+ // the offending clip.+ const quiet = document.createElement("audio");+ quiet.setAttribute("data-start", "0");+ quiet.setAttribute("data-duration", "10");+ quiet.setAttribute("data-volume", "0.5");+ quiet.load = () => {};+ root.appendChild(quiet);++ window.__timelines = { main: createMockTimeline(10) };+ initSandboxRuntimeModular();++ const errors: string[] = [];+ const onError = (e: ErrorEvent) => errors.push(String(e.message ?? e.error));+ window.addEventListener("error", onError);+ window.dispatchEvent(+ new MessageEvent("message", {+ data: { source: "hf-parent", type: "control", action: "set-volume", volume: 1 },+ }),+ );+ window.removeEventListener("error", onError);+ expect(errors).toEqual([]);+ });++ /**+ * The runtime stamps `data-start`/`data-duration` on every id'd child of the+ * composition root so a blank canvas still shows selectable rows. An+ * `<hf-audio-group>` is a mixer BUS, not a clip: stamping it put it in+ * `__clipManifest` as a full-duration element, which the studio drew as an+ * ordinary clip row above the real group header — draggable, trimmable, and+ * deletable, and deleting it takes the bus (so the group's FX rack) with it.+ */+ it("does not stamp timing onto an <hf-audio-group> bus", () => {+ const root = document.createElement("div");+ root.setAttribute("data-composition-id", "main");+ root.setAttribute("data-root", "true");+ root.setAttribute("data-start", "0");+ root.setAttribute("data-duration", "10");+ root.setAttribute("data-width", "1920");+ root.setAttribute("data-height", "1080");+ document.body.appendChild(root);++ const bus = document.createElement("hf-audio-group");+ bus.id = "voiceover";+ bus.setAttribute("data-label", "Voiceover");+ root.appendChild(bus);++ // A plain id'd sibling proves the stamp still happens for everything else.+ const caption = document.createElement("div");+ caption.id = "cap-1";+ root.appendChild(caption);++ window.__timelines = { main: createMockTimeline(10) };+ // The stamp only runs inside the studio preview (`window.parent !== window`),+ // which jsdom is not — so the condition has to be staged for the test.+ const realParent = window.parent;+ Object.defineProperty(window, "parent", { value: {}, configurable: true });+ try {+ initSandboxRuntimeModular();+ } finally {+ Object.defineProperty(window, "parent", { value: realParent, configurable: true });+ }++ expect(bus.hasAttribute("data-start")).toBe(false);+ expect(bus.hasAttribute("data-duration")).toBe(false);+ expect(caption.getAttribute("data-start")).toBe("0");+ });+it("resolves Studio hold as a deterministic step at the segment end", () => {const defaultEase = (progress: number) => progress;const originalParseEase = vi.fn(() => defaultEase);@@ -1350,10 +1443,13 @@ describe("initSandboxRuntimeModular", () => {window.__timelines = { main: createMockTimeline(10) };initSandboxRuntimeModular();- // `scheduleMediaElementPlayback` is the Web Audio scheduling entry point (#3322 routed- // media-element clips straight through the graph; `decodeAudioElement` is only the fallback- // for the rate-shifted case, so it is NOT called on this path).- const scheduleSpy = vi.spyOn(WebAudioTransport.prototype, "scheduleMediaElementPlayback");+ // `scheduleMediaElementPlayback`, not `decodeAudioElement`: the media-element+ // transport is the path the runtime tries FIRST for audio, and the decoded+ // buffer is only its fallback. What is under test either way is which+ // ELEMENTS get scheduled at all.+ const scheduleSpy = vi+ .spyOn(WebAudioTransport.prototype, "scheduleMediaElementPlayback")+ .mockResolvedValue(null);const player = window.__player;player?.play();@@ -1363,6 +1459,50 @@ describe("initSandboxRuntimeModular", () => {expect(scheduleSpy.mock.calls[0]?.[0]).toBe(audibleAudio);});+ it("reschedules only when a data-hidden mutation actually moved something", () => {+ const root = document.createElement("div");+ root.setAttribute("data-composition-id", "main");+ root.setAttribute("data-root", "true");+ root.setAttribute("data-start", "0");+ root.setAttribute("data-duration", "10");+ root.setAttribute("data-width", "1920");+ root.setAttribute("data-height", "1080");+ document.body.appendChild(root);++ const hiddenAudio = document.createElement("audio");+ hiddenAudio.setAttribute("data-start", "0");+ hiddenAudio.setAttribute("data-duration", "10");+ hiddenAudio.setAttribute("data-hidden", "");+ hiddenAudio.load = () => {};+ hiddenAudio.play = vi.fn(() => Promise.resolve());+ root.appendChild(hiddenAudio);++ window.__timelines = { main: createMockTimeline(10) };+ initSandboxRuntimeModular();++ const stopSpy = vi.spyOn(WebAudioTransport.prototype, "stopAll");+ const player = window.__player;+ player?.play();++ // A seek stops the transport itself, so the COUNT is the measure. Without+ // the dirty gate the reschedule fired on every visibility pass, adding a+ // second stop — an audible stop-and-restart across the whole mix — to+ // rebuild an identical active set.+ stopSpy.mockClear();+ player?.seek(1, { keepPlaying: true });+ const seekOnly = stopSpy.mock.calls.length;++ // The dirty flag is set by a data-hidden MUTATION, so the toggle is the+ // gesture; a plain seek never reaches the reschedule at all.+ stopSpy.mockClear();+ hiddenAudio.removeAttribute("data-hidden");+ player?.seek(2, { keepPlaying: true });+ const afterToggle = stopSpy.mock.calls.length;++ expect(seekOnly).toBe(1);+ expect(afterToggle).toBe(seekOnly + 1);+ });+it("batches a mid-playback data-hidden toggle into exactly one Web Audio reschedule", () => {const root = document.createElement("div");root.setAttribute("data-composition-id", "main");@@ -1401,7 +1541,9 @@ describe("initSandboxRuntimeModular", () => {// toggles away from.player?.play();- const scheduleSpy = vi.spyOn(WebAudioTransport.prototype, "scheduleMediaElementPlayback");+ const scheduleSpy = vi+ .spyOn(WebAudioTransport.prototype, "scheduleMediaElementPlayback")+ .mockResolvedValue(null);const generationSpy = vi.spyOn(WebAudioTransport.prototype, "startGeneration");// Both become visible in the SAME sync pass — must still be one reschedule.@@ -1415,6 +1557,52 @@ describe("initSandboxRuntimeModular", () => {expect(scheduleSpy).toHaveBeenCalledTimes(2);});+ // Scheduling does NOT replace the active set: it bumps a generation, which+ // only rejects schedules still in flight. Every source already started keeps+ // playing and there is no per-element dedup, so rescheduling on its own laid+ // a second buffer source over every sounding clip — the whole mix doubled,+ // slightly out of phase, from one mute click until the next pause.+ it("stops the running sources before rescheduling on a data-hidden toggle", () => {+ const root = document.createElement("div");+ root.setAttribute("data-composition-id", "main");+ root.setAttribute("data-root", "true");+ root.setAttribute("data-start", "0");+ root.setAttribute("data-duration", "10");+ root.setAttribute("data-width", "1920");+ root.setAttribute("data-height", "1080");+ document.body.appendChild(root);++ const audio = document.createElement("audio");+ audio.setAttribute("data-start", "0");+ audio.setAttribute("data-duration", "10");+ audio.setAttribute("data-hidden", "");+ audio.load = () => {};+ audio.play = vi.fn(() => Promise.resolve());+ root.appendChild(audio);++ window.__timelines = { main: createMockTimeline(10) };+ initSandboxRuntimeModular();+ const player = window.__player;+ player?.play();++ vi.spyOn(WebAudioTransport.prototype, "decodeAudioElement").mockResolvedValue(null);+ const stopSpy = vi.spyOn(WebAudioTransport.prototype, "stopAll");+ const generationSpy = vi.spyOn(WebAudioTransport.prototype, "startGeneration");++ audio.removeAttribute("data-hidden");+ player?.seek(1, { keepPlaying: true });++ expect(generationSpy).toHaveBeenCalledTimes(1);+ // Two: `seek` clears the graph on its way in, and the toggle's own+ // reschedule clears it again. Only the second one is what this covers —+ // without it the count is 1 and the reschedule stacks on live sources.+ expect(stopSpy.mock.calls.length).toBeGreaterThanOrEqual(2);+ // Order matters, not just presence: stopping AFTER the reschedule would+ // silence the clips it had just started.+ const lastStop = Math.max(...stopSpy.mock.invocationCallOrder);+ expect(lastStop).toBeLessThan(generationSpy.mock.invocationCallOrder[0] ?? 0);+ });+it("does not stamp Studio timing on GSAP targets inside authored timed clips", () => {withStudioIframe(() => {const root = document.createElement("div");diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.tsindex cf8636ab23..9ff991a4e9 100644--- a/packages/core/src/runtime/init.ts+++ b/packages/core/src/runtime/init.ts@@ -39,11 +39,17 @@ import { loadExternalCompositions, loadInlineTemplateCompositions } from "./compimport { applyCaptionOverrides } from "./captionOverrides";import { applyPositionEdits, installPositionEditsSeekReapply } from "./positionEdits";import { applyVariableBindings } from "./applyVariableBindings";-import { ensureAudioGroupInertStyle } from "../audioGroups.js";import { createColorGradingRuntime, type RuntimeColorGradingApi } from "./colorGrading";import { TransportClock } from "./clock";import { WebAudioTransport } from "./webAudioTransport";-import { HF_AUDIO_GROUP_TAG, audioGroupOf, isAudibleUnderSolo } from "../audioGroups";+import {+ audioGroupOf,+ ensureAudioGroupInertStyle,+ HF_AUDIO_GROUP_TAG,+ isAudibleUnderSolo,+ isMemberGroupHidden,+} from "../audioGroups";+import { clampNativeMediaVolume } from "../audioGain";import { quantizeTimeToFrame } from "../inline-scripts/parityContract";import { STUDIO_MANUAL_EDIT_GESTURE_ATTR } from "../editing/draftMarkers";import type {@@ -183,20 +189,20 @@ export function initSandboxRuntimeModular(): void {void webAudio.init().then((ok) => {webAudioReady = ok;});- // Studio's "Hear only this" push channel — session-only, so it rides a- // dedicated `__hf` field (mirrors `colorGrading`'s lazy-init pattern) rather- // than a DOM attribute: solo must never be written to the document (design- // doc §2.2 / the export-safety guarantee), so there is nothing here for- // `syncTimedElementVisibility`'s attribute-diffing to key off. Kept in this- // closure too (not just inside `webAudio`) so `syncRuntimeMedia`'s- // HTMLMedia-fallback path (video/non-transport audio) can apply the same- // predicate per tick, the same split A2 used for `data-hidden`.+ // Keep Studio's session-only "Hear only this" bridge alive until the solo+ // controls are removed later in the stack. It must not be serialized into+ // the composition because solo is preview state, not authored state.let soloedIds: ReadonlySet<string> = new Set();window.__hf = window.__hf || {};window.__hf.setAudioSolo = (ids) => {soloedIds = new Set(ids);webAudio.setSolo(soloedIds);};+ /** Hidden by an ancestor, or by the BUS this clip belongs to. The bus is+ * never an ancestor — membership is on the member's `data-audio-group` — so+ * `closest()` alone could not see a muted group, which the render drops. */+ const isSilencedByHidden = (el: Element): boolean =>+ el.closest("[data-hidden]") !== null || isMemberGroupHidden(el.ownerDocument, el);// `_auto` is a Studio-internal keyframe marker (an auto-tracked endpoint the// parser reads back), NOT an animatable property. Register it as a no-op GSAP// plugin so GSAP doesn't log "Invalid property _auto" on every tween build —@@ -1451,6 +1457,14 @@ export function initSandboxRuntimeModular(): void {// scene container we auto-stamp below (e.g. an opacity-crossfaded scene)// must NOT suppress its own animated children — otherwise those children// never become timeline clips and that scene can't inline-expand.+ // A bus is not a clip. `<hf-audio-group>` carries a group's label, fader,+ // mute and FX chain and has no timing of its own, so stamping it put it in+ // `__clipManifest` as a full-duration element — which the studio drew as an+ // ordinary clip row above the real group header. That row was draggable,+ // trimmable and deletable, and deleting it removed the bus, taking the+ // group's automation lanes and FX rack with it.+ const isAudioGroupBus = (el: Element): boolean =>+ el.tagName.toLowerCase() === HF_AUDIO_GROUP_TAG;const authoredTimed = new Set<Element>(document.querySelectorAll("[data-start]"));const hasAuthoredTimedAncestor = (element: HTMLElement): boolean => {let node = element.parentElement;@@ -1469,6 +1483,7 @@ export function initSandboxRuntimeModular(): void {for (const target of child.targets()) {if (!(target instanceof HTMLElement)) continue;if (target === rootComp) continue;+ if (isAudioGroupBus(target)) continue;if (target.hasAttribute("data-start")) continue;if (hasAuthoredTimedAncestor(target)) continue;if (seen.has(target)) continue;@@ -1496,6 +1511,7 @@ export function initSandboxRuntimeModular(): void {if (hasAuthoredTimedAncestor(el)) continue;if (seen.has(el)) continue;if (el.tagName === "SCRIPT" || el.tagName === "STYLE" || el.tagName === "LINK") continue;+ if (isAudioGroupBus(el)) continue;seen.add(el);el.setAttribute("data-start", "0");el.setAttribute("data-duration", dur);@@ -1939,7 +1955,16 @@ export function initSandboxRuntimeModular(): void {// A data-hidden toggle on (or affecting) an audio element must re-schedule// WebAudio playback so the hidden clip's source is dropped/restored mid-// playback. Batched to one call per syncTimedElementVisibility pass, not- // one per toggled node (schedulePlayback replaces the whole active set).+ // one per toggled node.+ //+ // The reschedule is paired with `stopAll()` below, for the reason+ // `applyWebAudioRate` already spells out: scheduling does+ // NOT replace the active set. It bumps a generation, which only rejects+ // stale schedules still in flight — every source already started keeps+ // playing, and there is no per-element dedup. This comment used to claim the+ // opposite and the call site trusted it, so muting a track mid-playback+ // started a second buffer source for every in-window clip on top of the ones+ // still sounding: the whole mix audibly doubled, slightly out of phase.let hiddenAudioDirty = false;const nodeAffectsAudio = (node: HTMLElement): boolean =>node.matches("audio[data-start]") || node.querySelector("audio[data-start]") !== null;@@ -1950,7 +1975,13 @@ export function initSandboxRuntimeModular(): void {// export time, per B4); this just keeps the live WebAudio group bus in// sync with a `data-hidden` toggle made mid-playback.const groupHiddenLast = new WeakMap<Element, boolean>();+ /** Set when a `data-hidden` mutation could have touched a BUS, so the sweep+ * below is not a whole-document query on every visibility pass. Same+ * dirty-flag shape as `hiddenAudioDirty` right above it. */+ let groupMuteDirty = true;const syncAudioGroupMute = () => {+ if (!groupMuteDirty) return;+ groupMuteDirty = false;for (const groupEl of document.querySelectorAll(HF_AUDIO_GROUP_TAG)) {const hidden = groupEl.hasAttribute("data-hidden");if (groupHiddenLast.get(groupEl) === hidden) continue;@@ -1972,6 +2003,7 @@ export function initSandboxRuntimeModular(): void {dataHiddenDisplayRestores.set(rawNode, rawNode.style.getPropertyValue("display"));dataHiddenDisplayNodes.add(rawNode);if (nodeAffectsAudio(rawNode)) hiddenAudioDirty = true;+ groupMuteDirty = true;}rawNode.style.display = "none";if (rawNode instanceof HTMLVideoElement || rawNode instanceof HTMLImageElement) {@@ -1990,6 +2022,7 @@ export function initSandboxRuntimeModular(): void {dataHiddenDisplayRestores.delete(rawNode);dataHiddenDisplayNodes.delete(rawNode);if (nodeAffectsAudio(rawNode)) hiddenAudioDirty = true;+ groupMuteDirty = true;}let isVisibleNow = isTimedElementVisibleAt(rawNode, currentTime);@@ -2019,7 +2052,12 @@ export function initSandboxRuntimeModular(): void {rawNode.style.display = "none";}}+ // Only when a `data-hidden` mutation actually moved something: the skips+ // this reschedule exists to re-run are what change the active set, so+ // firing it otherwise was an audible stop-and-restart across the whole mix+ // that rebuilt an identical set.if (hiddenAudioDirty && clock.isPlaying()) {+ webAudio.stopAll();scheduleWebAudioForActiveClips();}hiddenAudioDirty = false;@@ -2177,25 +2215,6 @@ export function initSandboxRuntimeModular(): void {scheduleRootStageLayoutDiagnostics();};- /** One meter reading per group with an active member — polled from the- * transport's analyser, not the DOM, so an idle group (never played, no- * matching `<hf-audio-group>`) is simply absent rather than reported as- * zero. Cheap when nothing is grouped: `groupIds()` is empty. */- const postGroupLevels = () => {- const groupIds = webAudio.groupIds();- if (groupIds.length === 0) return;- const levels = groupIds- .map((groupId) => {- const reading = webAudio.groupLevel(groupId);- return reading ? { groupId, ...reading } : null;- })- .filter(- (entry): entry is { groupId: string; level: number; clipped: boolean } => entry !== null,- );- if (levels.length === 0) return;- postRuntimeMessage({ source: "hf-preview", type: "group-levels", levels });- };-const finitePositiveDuration = (value: number | null | undefined): number =>typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;@@ -2953,9 +2972,6 @@ export function initSandboxRuntimeModular(): void {if (transportTickCount % 30 === 0) {bindMediaMetadataListeners();}- if (clock.isPlaying()) {- postGroupLevels();- }// Sync clock duration with the resolved timeline each tick (catches async// rebinds, live data-duration edits). Never shrink while playing — transient@@ -2987,7 +3003,7 @@ export function initSandboxRuntimeModular(): void {let foundActive = false;for (const rawEl of audioEls) {if (!(rawEl instanceof HTMLMediaElement) || !rawEl.isConnected) continue;- if (rawEl.closest("[data-hidden]")) continue;+ if (isSilencedByHidden(rawEl)) continue;const start = Number.parseFloat(rawEl.dataset.start ?? "");const durAttr = parseStrictFiniteTimingNumber(rawEl.dataset.duration);const end = durAttr != null && durAttr > 0 ? start + durAttr : Infinity;@@ -3095,7 +3111,7 @@ export function initSandboxRuntimeModular(): void {const audioEls = document.querySelectorAll("audio[data-start]");for (const rawEl of audioEls) {if (!(rawEl instanceof HTMLMediaElement) || !rawEl.isConnected) continue;- if (rawEl.closest("[data-hidden]")) continue;+ if (isSilencedByHidden(rawEl)) continue;const compStart = Number.parseFloat(rawEl.dataset.start ?? "");if (!Number.isFinite(compStart)) continue;const mediaStart = readElementPlaybackStart(rawEl);@@ -3238,7 +3254,11 @@ export function initSandboxRuntimeModular(): void {// assigning the product raw THROWS IndexSizeError and takes the rest of// the loop with it. The element carries the legal part; the boost above// unity belongs to Web Audio, which already has it from `setVolume`.- el.volume = Math.max(0, Math.min(1, clipVolume * volume));+ //+ // Through `clampNativeMediaVolume` rather than an inline clamp: that+ // helper exists in `audioGain.ts` for exactly this bound and is what+ // `withUnclampedVolume` uses, so the two cannot drift.+ el.volume = clampNativeMediaVolume(clipVolume * volume);}},onSetMediaOutputMuted: (muted) => {diff --git a/packages/core/src/runtime/media.test.ts b/packages/core/src/runtime/media.test.tsindex acf890724b..d6a2d46c3c 100644--- a/packages/core/src/runtime/media.test.ts+++ b/packages/core/src/runtime/media.test.ts@@ -577,14 +577,16 @@ describe("syncRuntimeMedia", () => {});describe("data-hidden silences preview volume", () => {- it("zeroes effective volume for a clip under a data-hidden ancestor", () => {+ const hiddenClip = () => {const clip = createMockClip({ start: 0, end: 10, volume: 0.8 });Object.defineProperty(clip.el, "readyState", { value: 4, writable: true });const hiddenAncestor = document.createElement("div");hiddenAncestor.setAttribute("data-hidden", "");document.body.appendChild(hiddenAncestor);hiddenAncestor.appendChild(clip.el);-+ return clip;+ };+ const volumeSeen = (clip: ReturnType<typeof hiddenClip>) => {let seen = -1;syncRuntimeMedia({clips: [clip],@@ -595,20 +597,32 @@ describe("syncRuntimeMedia", () => {seen = v;},});+ return seen;+ };- expect(seen).toBe(0);+ it("zeroes effective volume for a clip under a data-hidden ancestor", () => {+ expect(volumeSeen(hiddenClip())).toBe(0);});- it("does not touch el.muted when silencing a hidden clip (RULES trap: transport owns el.muted)", () => {+ // A visible clip is the control: the zero above has to come from the+ // ancestor, not from the fixture reading 0 for some other reason.+ it("leaves a visible clip at its authored volume", () => {const clip = createMockClip({ start: 0, end: 10, volume: 0.8 });Object.defineProperty(clip.el, "readyState", { value: 4, writable: true });- const hiddenAncestor = document.createElement("div");- hiddenAncestor.setAttribute("data-hidden", "");- document.body.appendChild(hiddenAncestor);- hiddenAncestor.appendChild(clip.el);+ document.body.appendChild(clip.el);+ expect(volumeSeen(clip)).toBe(0.8);+ });++ it("does not touch el.muted when silencing a hidden clip (RULES trap: transport owns el.muted)", () => {+ const clip = hiddenClip();clip.el.muted = false;- syncRuntimeMedia({ clips: [clip], timeSeconds: 1, playing: true, playbackRate: 1 });+ syncRuntimeMedia({+ clips: [clip],+ timeSeconds: 1,+ playing: true,+ playbackRate: 1,+ });expect(clip.el.muted).toBe(false);});diff --git a/packages/core/src/runtime/media.ts b/packages/core/src/runtime/media.tsindex 0ae934ecbd..08b1298ad5 100644--- a/packages/core/src/runtime/media.ts+++ b/packages/core/src/runtime/media.ts@@ -3,6 +3,7 @@ import { interpolateVolumeGain, type VolumeKeyframe } from "./mediaVolumeEnvelopimport { elementVolumeLaneGain } from "./audioAutomationVolume.js";import { readElementPlaybackRate, readMediaStart } from "./playbackRate.js";import { clampAudioGain } from "../audioGain.js";+import { isMemberGroupHidden } from "../audioGroups.js";import { findInjectedRenderFrame } from "./renderFrameSibling.js";export { readElementPlaybackRate, resolveNaturalMediaTimelineDuration } from "./playbackRate.js";@@ -223,10 +224,8 @@ export function syncRuntimeMedia(params: {/** Native media routed through WebAudio keeps its upstream element volume at* unity; do not mistake that transport write for an authored volume edit. */isWebAudioRouted?: (el: HTMLMediaElement) => boolean;- /** "Hear only this" gate for the HTMLMedia fallback path (video / any audio- * not owned by the Web Audio transport, which applies its own dedicated- * solo gain instead — see `WebAudioTransport.setSolo`). Absent when solo- * isn't wired up at all, which reads as "always audible". */+ /** "Hear only this" gate for the HTMLMedia fallback path. WebAudio-owned+ * sources apply the same predicate on their dedicated solo gain. */isAudibleUnderSolo?: (el: HTMLMediaElement) => boolean;forceSync?: boolean;}): void {@@ -335,13 +334,18 @@ export function syncRuntimeMedia(params: {}// A data-hidden ancestor is silent in the export (audioMixer.ts drops- // it); preview must match. Folded into the per-tick volume, not+ // it), so preview matches. Folded into the per-tick volume, not// el.muted (RULES trap: el.muted is the transport's ownership flag).- // Solo rides the same fold for the same reason — never el.muted, and- // never touching any attribute (it is session-only, unlike hidden).+ // Two independent ways to be silent, and the second is not an ancestor+ // question: membership lives on the MEMBER's `data-audio-group`, so a+ // muted BUS is invisible to `closest()`. The render drops such members+ // (`memberGroupHidden`), so without this the export was silent where the+ // fallback played at full level.+ const silencedByHidden =+ el.closest("[data-hidden]") !== null || isMemberGroupHidden(el.ownerDocument, el);const silencedBySolo = params.isAudibleUnderSolo ? !params.isAudibleUnderSolo(el) : false;const effectiveVolume =- el.closest("[data-hidden]") || silencedBySolo ? 0 : clampVolume(authorVolume * userVol);+ silencedByHidden || silencedBySolo ? 0 : clampVolume(authorVolume * userVol);el.volume = effectiveVolume;lastRuntimeAppliedVolume.set(el, effectiveVolume);params.onElementVolume?.(el, effectiveVolume, authorVolume);diff --git a/packages/core/src/runtime/webAudioTransport.test.ts b/packages/core/src/runtime/webAudioTransport.test.tsindex 031de18852..b8545c2625 100644--- a/packages/core/src/runtime/webAudioTransport.test.ts+++ b/packages/core/src/runtime/webAudioTransport.test.ts@@ -18,10 +18,8 @@ function createMockAudioContext(currentTime = 100) {}),_fireEnded: () => endedListeners.forEach((cb) => cb()),};- // One node per createGain() call, not one shared node for all of them. The- // shared version made every assertion on "the gain" read whichever node the- // scheduler happened to build last — a solo gain's 1 overwriting the volume- // gain's 0.8, for instance.+ // Every createGain call returns a distinct node. Sharing one hides graph+ // errors because the solo stage can overwrite the authored-volume stage.const gainNodes: Array<{gain: { value: number };connect: ReturnType<typeof vi.fn>;@@ -32,7 +30,6 @@ function createMockAudioContext(currentTime = 100) {gainNodes.push(node);return node;};- /** The volume gain: the first node any scheduler asks for. */const gainNode = makeGain();let served = 0;const mediaElementSourceNode = {@@ -124,13 +121,8 @@ describe("WebAudioTransport", () => {expect(mock.ctx.createMediaElementSource).toHaveBeenCalledWith(mockEl);expect(mock.ctx.createBufferSource).not.toHaveBeenCalled();expect(mock.mediaElementSourceNode.connect).toHaveBeenCalled();- // Volume gain → its own solo gain → master, the same tail the buffer path- // uses. Connecting straight to master here left native media exempt from- // "hear only this" and from group routing.const [volumeGain, soloGain] = mock.gainNodes;- expect(volumeGain).toBe(mock.gainNode);expect(volumeGain?.connect).toHaveBeenCalledWith(soloGain);- expect(volumeGain?.connect).not.toHaveBeenCalledWith(mock.masterGain);expect(soloGain?.connect).toHaveBeenCalledWith(mock.masterGain);expect(mockEl.muted).toBe(false);expect(mockEl.volume).toBe(1);@@ -405,36 +397,6 @@ describe("WebAudioTransport", () => {expect(mock.startFn).toHaveBeenCalledWith(0, 3, 7);});- // The bound is in BUFFER seconds, and an authored `data-playback-rate`- // is the only thing that makes buffer seconds differ from composition- // seconds — the global rate scales the transport clock and the source's- // playbackRate together, so it cancels out. Dropping the `* mediaRate`- // therefore looks harmless at the default rate and truncates every- // authored-fast clip, which is why these two cases exist.- it("bounds an authored 2x clip by its buffer length, not its clip length", async () => {- const { transport, mock, gen } = setupTransport(100);- const fast = {- muted: false,- getAttribute: (name: string) => (name === "data-playback-rate" ? "2" : null),- } as unknown as HTMLMediaElement;- // A 10s clip authored at 2x consumes 20 buffer seconds; playing from the- // start must hand `start()` all 20, or the audio stops at the halfway mark.- await transport.schedulePlayback(fast, mockBuffer, 5, 0, 5, 1, gen, 1, 10);- expect(mock.startFn).toHaveBeenCalledWith(0, 0, 20);- });-- it("bounds an authored 0.5x clip by its buffer length, not its clip length", async () => {- const { transport, mock, gen } = setupTransport(100);- const slow = {- muted: false,- getAttribute: (name: string) => (name === "data-playback-rate" ? "0.5" : null),- } as unknown as HTMLMediaElement;- // The mirror case: 10 composition seconds at 0.5x consume 5 buffer- // seconds, so an unscaled bound of 10 would run 5s past the clip's end.- await transport.schedulePlayback(slow, mockBuffer, 5, 0, 5, 1, gen, 1, 10);- expect(mock.startFn).toHaveBeenCalledWith(0, 0, 5);- });-it("plays unbounded when clipDuration is omitted (legacy behavior)", async () => {const { transport, mock, gen } = setupTransport(100);await transport.schedulePlayback(mockEl, mockBuffer, 5, 0, 8, 1, gen);@@ -691,6 +653,7 @@ describe("WebAudioTransport", () => {getFloatTimeDomainData: ReturnType<typeof vi.fn>;}[] = [];const masterGain = { gain: { value: 1 }, connect: vi.fn(), disconnect: vi.fn() };+ const mediaElementSource = { connect: vi.fn(), disconnect: vi.fn() };const ctx = {currentTime,state: "running",@@ -705,7 +668,24 @@ describe("WebAudioTransport", () => {addEventListener: vi.fn(),})),createGain: vi.fn(() => {- const node = { gain: { value: 1 }, connect: vi.fn(), disconnect: vi.fn() };+ // The AudioParam scheduling surface is part of the contract the group+ // bus uses (`clearParamLane` cancels before re-seeding a reused bus).+ // A bare `{ value }` made any such call throw, and `schedulePlayback`+ // swallows throws into `return null` — so the mock's own gap read as+ // "the member did not play" rather than as a missing stub.+ const node = {+ gain: {+ value: 1,+ cancelScheduledValues: vi.fn(),+ cancelAndHoldAtTime: vi.fn(),+ setValueAtTime: vi.fn(),+ linearRampToValueAtTime: vi.fn(),+ exponentialRampToValueAtTime: vi.fn(),+ setValueCurveAtTime: vi.fn(),+ },+ connect: vi.fn(),+ disconnect: vi.fn(),+ };gainNodes.push(node);return node;}),@@ -719,10 +699,14 @@ describe("WebAudioTransport", () => {analysers.push(node);return node;}),+ // The media-element route needs this as much as the decoded one: without+ // it `scheduleMediaElementPlayback` throws and its catch returns null,+ // which reads as "the member did not play" rather than a missing stub.+ createMediaElementSource: vi.fn(() => mediaElementSource),destination: {},close: vi.fn(),};- return { ctx, gainNodes, analysers, masterGain };+ return { ctx, gainNodes, analysers, masterGain, mediaElementSource };}function setupGroupTransport(currentTime = 100) {@@ -756,59 +740,118 @@ describe("WebAudioTransport", () => {}/** The group's own input gain is built lazily on the first member — index- * 2 in creation order (that member's own gain is 0, its solo gain 1). */+ * 1 in creation order (that member's own gain is 0). */const firstGroupInput = (mock: ReturnType<typeof createGroupMockAudioContext>) =>- mock.gainNodes[2]!;+ mock.gainNodes[1]!;beforeEach(() => {document.body.innerHTML = "";});- it("routes an ungrouped member straight to master, through its own solo gain", async () => {+ it("routes an ungrouped clip to master through its own solo stage", async () => {const { transport, mock, gen } = setupGroupTransport();- await scheduleGrouped(transport, gen, "solo");+ await scheduleGrouped(transport, gen, "lone");- // Member gain, then its dedicated solo gain (B5) — never straight to master.expect(mock.gainNodes).toHaveLength(2);- const [memberGain, soloGain] = mock.gainNodes;- expect(memberGain!.connect).toHaveBeenCalledWith(soloGain);- expect(memberGain!.connect).not.toHaveBeenCalledWith(mock.masterGain);+ const [clipGain, soloGain] = mock.gainNodes;+ expect(clipGain!.connect).toHaveBeenCalledWith(soloGain);expect(soloGain!.connect).toHaveBeenCalledWith(mock.masterGain);});+ // The media-element transport is the PRIMARY path for audio — the runtime+ // tries it first and only falls back to a decoded buffer. It has to reach+ // the same bus, or grouping silently applies to nothing that actually plays.+ // The render clamps a track volume with `clampAudioGain` (ceiling ~3.98),+ // so an over-unity bus previewed at 1.0 exported up to 12 dB louder than+ // it auditioned.+ it("previews an over-unity bus fader at the render's ceiling, not unity", async () => {+ const { transport, mock, gen } = setupGroupTransport();+ document.body.innerHTML = `<hf-audio-group id="vo" data-volume="10"></hf-audio-group>`;+ await scheduleGrouped(transport, gen, "a", "vo");++ // Creation order: a-gain(0), groupInput(1), groupOutput(2), muteGain(3), fader(4).+ expect(mock.gainNodes[4]!.gain.value).toBeCloseTo(3.9811, 3);+ });++ it("still floors a negative bus fader at zero", async () => {+ const { transport, mock, gen } = setupGroupTransport();+ document.body.innerHTML = `<hf-audio-group id="vo" data-volume="-1"></hf-audio-group>`;+ await scheduleGrouped(transport, gen, "a", "vo");++ expect(mock.gainNodes[4]!.gain.value).toBe(0);+ });++ // A bare getElementById read a member's own fader and chain as the bus's.+ it("ignores a non-<hf-audio-group> element sharing the group id", async () => {+ const { transport, mock, gen } = setupGroupTransport();+ document.body.innerHTML = `<div id="vo" data-volume="0.25" data-hidden></div>`;+ await scheduleGrouped(transport, gen, "a", "vo");++ // Flat bus: unity fader, unmuted — the documented "group with no element"+ // degradation, not the stranger's settings.+ expect(mock.gainNodes[4]!.gain.value).toBe(1);+ expect(mock.gainNodes[3]!.gain.value).toBe(1);+ });++ it("routes a grouped clip's MEDIA-ELEMENT playback to the group bus, not master", async () => {+ const { transport, mock, gen } = setupGroupTransport();+ const el = groupedAudioEl("vo-1", "vo");++ await transport.scheduleMediaElementPlayback(el, 0, 0, 0, 1, gen, 1);++ const clipGain = mock.gainNodes[0]!;+ const soloGain = mock.gainNodes[5]!;+ expect(clipGain.connect).toHaveBeenCalledWith(soloGain);+ expect(soloGain.connect).toHaveBeenCalledWith(firstGroupInput(mock));+ expect(clipGain.connect).not.toHaveBeenCalledWith(mock.masterGain);+ });++ it("routes an UNGROUPED clip's media-element playback straight to master", async () => {+ const { transport, mock, gen } = setupGroupTransport();+ const el = groupedAudioEl("lone");++ await transport.scheduleMediaElementPlayback(el, 0, 0, 0, 1, gen, 1);++ expect(mock.gainNodes).toHaveLength(2);+ expect(mock.gainNodes[0]!.connect).toHaveBeenCalledWith(mock.gainNodes[1]);+ expect(mock.gainNodes[1]!.connect).toHaveBeenCalledWith(mock.masterGain);+ });+it("two members of the same group land on ONE shared group gain, not master directly", async () => {const { transport, mock, gen } = setupGroupTransport();await scheduleGrouped(transport, gen, "a", "vo");await scheduleGrouped(transport, gen, "b", "vo");- // Creation order for a: a-gain(0), a-solo(1), groupInput(2), groupOutput(3),- // muteGain(4) — the group bus is built lazily inside a's schedule call.- // Then b: b-gain(5), b-solo(6).- expect(mock.gainNodes.length).toBeGreaterThanOrEqual(7);+ // Creation order for a: gain(0), group bus(1–4), solo(5). Then b uses+ // gain(6), solo(7); both solo stages feed the one shared group input.+ expect(mock.gainNodes.length).toBeGreaterThanOrEqual(8);const aGain = mock.gainNodes[0]!;- const aSolo = mock.gainNodes[1]!;+ const aSolo = mock.gainNodes[5]!;const groupInput = firstGroupInput(mock);- const groupOutput = mock.gainNodes[3]!;- const muteGain = mock.gainNodes[4]!;- const bGain = mock.gainNodes[5]!;- const bSolo = mock.gainNodes[6]!;+ const groupOutput = mock.gainNodes[2]!;+ const muteGain = mock.gainNodes[3]!;+ const fader = mock.gainNodes[4]!;+ const bGain = mock.gainNodes[6]!;+ const bSolo = mock.gainNodes[7]!;- // Each member feeds its own solo gain, and both solo gains feed the- // shared bus — neither connects straight to master.+ // Both members feed their own solo stage, then the shared bus.expect(aGain.connect).toHaveBeenCalledWith(aSolo);expect(bGain.connect).toHaveBeenCalledWith(bSolo);expect(aSolo.connect).toHaveBeenCalledWith(groupInput);expect(bSolo.connect).toHaveBeenCalledWith(groupInput);- expect(aSolo.connect).not.toHaveBeenCalledWith(mock.masterGain);- expect(bSolo.connect).not.toHaveBeenCalledWith(mock.masterGain);-- // The bus's input never reaches master directly — it lands on the mute- // gain (B5) first (the dry passthrough, since neither member's group has- // a chain-bearing `<hf-audio-group>`), then the output gain, then master.+ expect(aGain.connect).not.toHaveBeenCalledWith(mock.masterGain);+ expect(bGain.connect).not.toHaveBeenCalledWith(mock.masterGain);++ // The bus's input never reaches master directly. It runs through the+ // chain (dry here — neither member's group has a chain-bearing+ // `<hf-audio-group>`) onto the FADER, then the mute gain (B5), then the+ // output gain, then master. The fader sits POST-FX because that is where+ // the render bakes group volume in.expect(groupInput.connect).not.toHaveBeenCalledWith(mock.masterGain);- expect(groupInput.connect).toHaveBeenCalledWith(muteGain);+ expect(groupInput.connect).toHaveBeenCalledWith(fader);+ expect(fader.connect).toHaveBeenCalledWith(muteGain);expect(muteGain.connect).toHaveBeenCalledWith(groupOutput);expect(groupOutput.connect).toHaveBeenCalledWith(mock.masterGain);});@@ -817,10 +860,10 @@ describe("WebAudioTransport", () => {const { transport, mock, gen } = setupGroupTransport();await scheduleGrouped(transport, gen, "a", "vo");- const gainCountAfterFirst = mock.gainNodes.length; // a-gain + a-solo + group-input/output/mute+ const gainCountAfterFirst = mock.gainNodes.length;await scheduleGrouped(transport, gen, "b", "vo");- // Only b's own gain and its solo gain are new — no second group bus minted.+ // Only b's volume and solo gains are new — no second group bus minted.expect(mock.gainNodes.length).toBe(gainCountAfterFirst + 2);});@@ -829,20 +872,38 @@ describe("WebAudioTransport", () => {await scheduleGrouped(transport, gen, "a", "orphan-group"); // no matching element- const muteGain = mock.gainNodes[4]!;- const groupOutput = mock.gainNodes[3]!;- expect(firstGroupInput(mock).connect).toHaveBeenCalledWith(muteGain);+ const muteGain = mock.gainNodes[3]!;+ const groupOutput = mock.gainNodes[2]!;+ const fader = mock.gainNodes[4]!;+ expect(firstGroupInput(mock).connect).toHaveBeenCalledWith(fader);+ expect(fader.connect).toHaveBeenCalledWith(muteGain);expect(muteGain.connect).toHaveBeenCalledWith(groupOutput);expect(groupOutput.connect).toHaveBeenCalledWith(mock.masterGain);+ // No element to read, so the fader sits at unity.+ expect(fader.gain.value).toBe(1);});- it("group volume rides the group's own data-volume via its automation lane, not the member's", async () => {+ // The old assertion here was `resolves.not.toBeNull()` — it was named for+ // group volume and checked only that scheduling did not throw, so the bus+ // sitting at unity while the render applied data-volume went unseen. The+ // export was ~8 dB quieter than what had been auditioned.+ it("puts the group's own data-volume on the bus fader", async () => {+ document.body.innerHTML = `<hf-audio-group id="vo" data-label="Voiceover" data-volume="0.4"></hf-audio-group>`;+ const { transport, mock, gen } = setupGroupTransport();++ await expect(scheduleGrouped(transport, gen, "a", "vo")).resolves.not.toBeNull();++ expect(mock.gainNodes[4]!.gain.value).toBeCloseTo(0.4, 6);+ });++ it("leaves the fader at unity when the group carries no data-volume", async () => {document.body.innerHTML = `<hf-audio-group id="vo" data-label="Voiceover"></hf-audio-group>`;- const { transport, gen } = setupGroupTransport();+ const { transport, mock, gen } = setupGroupTransport();// No throw wiring the group's automation reader against a real// <hf-audio-group> element that carries no fx/automation attrs.await expect(scheduleGrouped(transport, gen, "a", "vo")).resolves.not.toBeNull();+ expect(mock.gainNodes[4]!.gain.value).toBe(1);});it("destroy() disposes every group bus", async () => {@@ -869,74 +930,90 @@ describe("WebAudioTransport", () => {expect(mock.gainNodes.filter((n) => n === groupInput)).toHaveLength(1);});- describe('solo — "Hear only this" (B5)', () => {- it("silences a non-soloed member via its own solo gain, without touching the group bus", async () => {+ describe('solo — "Hear only this" compatibility bridge', () => {+ it("silences non-soloed members without attenuating their shared group bus", async () => {const { transport, mock, gen } = setupGroupTransport();await scheduleGrouped(transport, gen, "a", "vo");await scheduleGrouped(transport, gen, "b", "vo");- const aSolo = mock.gainNodes[1]!;- const bSolo = mock.gainNodes[6]!;- const groupInput = firstGroupInput(mock);-- transport.setSolo(new Set(["other-clip"]));-- expect(aSolo.gain.value).toBe(0);- expect(bSolo.gain.value).toBe(0);- // The group's own bus is never attenuated by solo — only the member- // gain stage is (design doc §2.2: "never ancestors").- expect(groupInput.gain.value).toBe(1);- });-- it("soloing a member of a group leaves the group's gain untouched, and only that member is audible", async () => {- const { transport, mock, gen } = setupGroupTransport();- await scheduleGrouped(transport, gen, "a", "vo");- await scheduleGrouped(transport, gen, "b", "vo");- const aSolo = mock.gainNodes[1]!;- const bSolo = mock.gainNodes[6]!;- const groupInput = firstGroupInput(mock);transport.setSolo(new Set(["a"]));- expect(aSolo.gain.value).toBe(1);- expect(bSolo.gain.value).toBe(0); // sibling stays silent- expect(groupInput.gain.value).toBe(1); // group bus itself untouched+ expect(mock.gainNodes[5]!.gain.value).toBe(1);+ expect(mock.gainNodes[7]!.gain.value).toBe(0);+ expect(firstGroupInput(mock).gain.value).toBe(1);});- it("soloing the GROUP id makes every member audible (group solo = members solo)", async () => {+ it("soloing a group keeps every member of that group audible", async () => {const { transport, mock, gen } = setupGroupTransport();await scheduleGrouped(transport, gen, "a", "vo");await scheduleGrouped(transport, gen, "b", "vo");- const aSolo = mock.gainNodes[1]!;- const bSolo = mock.gainNodes[6]!;transport.setSolo(new Set(["vo"]));- expect(aSolo.gain.value).toBe(1);- expect(bSolo.gain.value).toBe(1);+ expect(mock.gainNodes[5]!.gain.value).toBe(1);+ expect(mock.gainNodes[7]!.gain.value).toBe(1);});- it("clearing solo (empty set) restores every member to audible", async () => {+ it("applies an existing solo to newly scheduled clips and restores them when cleared", async () => {const { transport, mock, gen } = setupGroupTransport();- await scheduleGrouped(transport, gen, "a", "vo");- const aSolo = mock.gainNodes[1]!;+ transport.setSolo(new Set(["a"]));+ await scheduleGrouped(transport, gen, "a");+ await scheduleGrouped(transport, gen, "b");- transport.setSolo(new Set(["other"]));- expect(aSolo.gain.value).toBe(0);+ expect(mock.gainNodes[1]!.gain.value).toBe(1);+ expect(mock.gainNodes[3]!.gain.value).toBe(0);transport.setSolo(new Set());- expect(aSolo.gain.value).toBe(1);+ expect(mock.gainNodes[1]!.gain.value).toBe(1);+ expect(mock.gainNodes[3]!.gain.value).toBe(1);});+ });- it("a newly scheduled member picks up an already-active solo immediately", async () => {- const { transport, mock, gen } = setupGroupTransport();- transport.setSolo(new Set(["a"]));+ // Surviving stopAll() is the point of the bus — and the trap. Its envelopes+ // were booked against the FIRST pass's absolute context times, so a replay+ // or a seek left the fader holding that pass's last value: 0 after a+ // fade-out, i.e. silent for the rest of the session.+ it("re-anchors the reused bus once per play generation, and only once", async () => {+ document.body.innerHTML = `<hf-audio-group id="vo" data-volume="0.5"></hf-audio-group>`;+ const { transport, mock, gen } = setupGroupTransport();+ await scheduleGrouped(transport, gen, "a", "vo");+ const fader = mock.gainNodes[4]!;- await scheduleGrouped(transport, gen, "a");- await scheduleGrouped(transport, gen, "b");+ // Something moved the fader mid-pass (a ramp reaching its last point).+ fader.gain.value = 0;+ transport.stopAll();- expect(mock.gainNodes[1]!.gain.value).toBe(1); // a's own solo gain- expect(mock.gainNodes[3]!.gain.value).toBe(0); // b's own solo gain+ const gen2 = transport.startGeneration();+ await scheduleGrouped(transport, gen2, "a", "vo");+ expect(fader.gain.value).toBeCloseTo(0.5, 6);++ // A second member in the SAME pass must not re-book on top of the first.+ fader.gain.value = 0;+ await scheduleGrouped(transport, gen2, "b", "vo");+ expect(fader.gain.value).toBe(0);+ });++ // reanchor runs inside schedulePlayback, whose catch turns any throw into+ // `return null` — so a bus that fails to re-anchor would silently take the+ // MEMBER out of the pass, and a generation stamped before the attempt would+ // stop every later member retrying.+ it("keeps the member playing when re-anchoring the bus throws", async () => {+ document.body.innerHTML = `<hf-audio-group id="vo" data-volume="0.5"></hf-audio-group>`;+ const { transport, mock, gen } = setupGroupTransport();+ await scheduleGrouped(transport, gen, "a", "vo");+ const fader = mock.gainNodes[4]!;+ fader.gain.cancelScheduledValues = vi.fn(() => {+ throw new Error("param is not schedulable");});++ transport.stopAll();+ const gen2 = transport.startGeneration();++ await expect(scheduleGrouped(transport, gen2, "a", "vo")).resolves.not.toBeNull();+ // Generation not consumed by the failed attempt, so a sibling still tries.+ fader.gain.cancelScheduledValues = vi.fn();+ await scheduleGrouped(transport, gen2, "b", "vo");+ expect(fader.gain.value).toBeCloseTo(0.5, 6);});describe("group mute (B5)", () => {@@ -946,14 +1023,14 @@ describe("WebAudioTransport", () => {await scheduleGrouped(transport, gen, "a", "vo");- const muteGain = mock.gainNodes[4]!;+ const muteGain = mock.gainNodes[3]!;expect(muteGain.gain.value).toBe(0);});it("setGroupMuted toggles the mute gain on an active group bus", async () => {const { transport, mock, gen } = setupGroupTransport();await scheduleGrouped(transport, gen, "a", "vo");- const muteGain = mock.gainNodes[4]!;+ const muteGain = mock.gainNodes[3]!;expect(muteGain.gain.value).toBe(1);transport.setGroupMuted("vo", true);@@ -968,66 +1045,6 @@ describe("WebAudioTransport", () => {expect(() => transport.setGroupMuted("never-played", true)).not.toThrow();});});-- describe("groupLevel meter (B7)", () => {- it("groupLevel returns null for an unknown/idle group id", () => {- const { transport } = setupGroupTransport();- expect(transport.groupLevel("never-played")).toBeNull();- });-- it("creates exactly one analyser per group, lazily, on first member", async () => {- const { transport, mock, gen } = setupGroupTransport();- expect(mock.analysers).toHaveLength(0);-- await scheduleGrouped(transport, gen, "a", "vo");- expect(mock.analysers).toHaveLength(1);- expect(mock.analysers[0]!.fftSize).toBe(256); // level, not spectrum-- await scheduleGrouped(transport, gen, "b", "vo");- expect(mock.analysers).toHaveLength(1); // second member reuses the bus-- expect(transport.groupIds()).toEqual(["vo"]);- });-- it("groupLevel reads RMS off the group's own analyser once a member is scheduled", async () => {- const { transport, mock, gen } = setupGroupTransport();- await scheduleGrouped(transport, gen, "a", "vo");-- const analyser = mock.analysers[0]!;- analyser.getFloatTimeDomainData.mockImplementation((buf: Float32Array) => {- buf.fill(0.5);- });-- const reading = transport.groupLevel("vo");- expect(reading).not.toBeNull();- expect(reading!.level).toBeCloseTo(0.5, 5);- expect(reading!.clipped).toBe(false);- });-- it("flags clipped when any sample hits the ceiling", async () => {- const { transport, mock, gen } = setupGroupTransport();- await scheduleGrouped(transport, gen, "a", "vo");-- const analyser = mock.analysers[0]!;- analyser.getFloatTimeDomainData.mockImplementation((buf: Float32Array) => {- buf.fill(0.1);- buf[0] = 0.995;- });-- expect(transport.groupLevel("vo")!.clipped).toBe(true);- });-- it("disposes the analyser along with the rest of the group bus", async () => {- const { transport, mock, gen } = setupGroupTransport();- await scheduleGrouped(transport, gen, "a", "vo");- const analyser = mock.analysers[0]!;-- transport.destroy();-- expect(analyser.disconnect).toHaveBeenCalled();- expect(transport.groupLevel("vo")).toBeNull();- });- });});describe("decodeAudioElement retry policy (late-asset self-heal)", () => {diff --git a/packages/core/src/runtime/webAudioTransport.ts b/packages/core/src/runtime/webAudioTransport.tsindex 6fe1318eed..0a3f8aa42e 100644--- a/packages/core/src/runtime/webAudioTransport.ts+++ b/packages/core/src/runtime/webAudioTransport.ts@@ -1,11 +1,17 @@import { attachElementFxChain, readElementAutomation, type ElementFxHandle } from "./audioFx.js";import {+ clearParamLane,scheduleParamLane,volumeLane,type AutomationTiming,} from "../audio/audioFxAutomation.js";import { VOLUME_RANGE } from "../audioAutomation.js";-import { audioGroupOf, isAudibleUnderSolo } from "../audioGroups.js";+import {+ audioGroupOf,+ isAudibleUnderSolo,+ readAudioGroupVolume,+ resolveGroupElement,+} from "../audioGroups.js";import { swallow } from "./diagnostics";import { clampAudioGain } from "../audioGain.js";import { getDebugSurface } from "./globals.js";@@ -16,6 +22,23 @@ function normalizeRate(rate: number): number {return rate;}+/**+ * The render puts every track volume through `clampVolume`, which is+ * `clampAudioGain` — ceiling MAX_AUDIO_GAIN (+12 dB, ~3.98), not unity. Preview+ * has to agree or the two diverge on exactly the attribute this bus exists to+ * honour: an authored `<hf-audio-group data-volume="2">` previewed at 1.0 and+ * exported at 2.0, up to 6 dB quieter in the audition than in the file, and+ * 12 dB at the ceiling. Preview was also self-inconsistent — the same+ * parameter's automation lane is bounded by `VOLUME_RANGE.max`, which IS+ * MAX_AUDIO_GAIN, so an envelope could reach 3.98 where the static fader could+ * not pass 1.0. `clampAudioGain` still floors at 0, so a negative value cannot+ * invert polarity in preview while rendering silent. Compositions are+ * hand-authorable, so out-of-range values do not need a slider to be reachable.+ */+function clampGroupVolume(volume: number): number {+ return clampAudioGain(volume);+}+/*** Breadcrumb for the per-element-mute handoff: the transport just claimed a track* that was audibly playing through the HTMLMedia fallback. Quiet unless@@ -88,10 +111,7 @@ function scheduleVolumeLane(type ScheduledSourceBase = {el: HTMLMediaElement;gainNode: GainNode;- /** Solo ("Hear only this") attenuation — dedicated node, parallel to the- * volume gain, so a solo toggle never fights `scheduleVolumeLane`'s ramps- * on the same param (same hazard B5's group-mute gain was split out to- * avoid). 0 while silenced by an active solo elsewhere, 1 otherwise. */+ /** Dedicated solo stage so toggles never overwrite authored volume ramps. */soloGain: GainNode;/** FX chain spliced between source and gain, when the element carries one. */fx?: ElementFxHandle | null;@@ -136,12 +156,15 @@ export class WebAudioTransport {string,{input: GainNode;+ /** Post-FX fader: `data-volume` plus the volume lane. */+ fader: GainNode;muteGain: GainNode;- analyser: AnalyserNode;- // `Float32Array<ArrayBuffer>`, not bare `Float32Array`: the runtime- // typecheck resolves the latter to `Float32Array<ArrayBufferLike>`, which- // `getFloatTimeDomainData` rejects (it wants a non-shared buffer).- levelBuf: Float32Array<ArrayBuffer>;+ /** Kept so `setRate` can re-aim this bus's FX automation, the way it does+ * every source's — its docblock claims it already did. */+ fx: ElementFxHandle | null;+ /** Play generation the current envelopes were booked against. */+ generation: number;+ reanchor(timing: AutomationTiming): void;dispose(): void;}>();@@ -153,9 +176,7 @@ export class WebAudioTransport {private _rate = 1;private _paused = true;private _playGeneration = 0;- // Session-only "Hear only this" set (clip ids and group ids). Never read- // from or written to any attribute — studio pushes it in directly via- // `setSolo`; see `isAudibleUnderSolo` for the exact predicate.+ // Session-only preview state pushed by Studio. Never serialized.private _soloed: ReadonlySet<string> = new Set();async init(): Promise<boolean> {@@ -230,15 +251,9 @@ export class WebAudioTransport {return this._playGeneration;}- /**- * Gain → solo → destination: the graph tail every scheduled source shares.- *- * Both schedulers need the dedicated solo node (parallel to the volume gain,- * so a solo toggle never fights `scheduleVolumeLane`'s ramps on the same- * param) and both need the group bus when the element belongs to one. Kept in- * one place because a path that skipped either was silently exempt from- * "hear only this" and from group routing.- */+ /** Connect one source through its own solo stage and then into its group bus+ * (or master for an ungrouped clip). Resolving the group first preserves one+ * shared bus while solo remains strictly per member. */private connectThroughSolo(ctx: AudioContext,masterGain: GainNode,@@ -246,13 +261,13 @@ export class WebAudioTransport {gainNode: GainNode,timing: { scheduledAt: number; compositionTime: number; rate: number },): GainNode {+ const destination =+ this.resolveDestination(el, timing.scheduledAt, timing.compositionTime, timing.rate) ??+ masterGain;const soloGain = ctx.createGain();soloGain.gain.value = isAudibleUnderSolo(this._soloed, el.id, audioGroupOf(el)) ? 1 : 0;gainNode.connect(soloGain);- soloGain.connect(- this.resolveDestination(el, timing.scheduledAt, timing.compositionTime, timing.rate) ??- masterGain,- );+ soloGain.connect(destination);return soloGain;}@@ -291,10 +306,11 @@ export class WebAudioTransport {const elapsed = compositionTime - compositionStart;const timing: AutomationTiming = { scheduledAt, elapsed, rate: safeRate };const fx = attachElementFxChain(this._ctx, el, sourceNode, gainNode, timing);- // A native-media clip used to connect straight to master, which left it- // immune to "hear only this" and outside its group's bus — preview- // disagreeing with the render for exactly the elements this transport- // exists to keep in step.+ // The group bus, not master, for a member — same as the decoded-buffer+ // path. This transport is the PRIMARY one for audio (the decode path is+ // its fallback), so routing it at master would have left every grouped+ // track bypassing the bus whose whole premise is that a group is one+ // signal.const soloGain = this.connectThroughSolo(this._ctx, this._masterGain, el, gainNode, {scheduledAt,compositionTime,@@ -346,48 +362,94 @@ export class WebAudioTransport {*/private groupInput(groupId: string, doc: Document, timing: AutomationTiming): GainNode | null {const existing = this._groups.get(groupId);- if (existing) return existing.input;+ if (existing) {+ // The bus outlives `stopAll()` on purpose, so a replay or a seek reuses+ // this graph — but its envelopes were committed to the FIRST pass's+ // absolute context times. Left alone they hold their last value forever,+ // which for a fade-out is silence for the rest of the session. Re-anchor+ // once per play generation, not once per member scheduled.+ if (existing.generation !== this._playGeneration) {+ // Stamped only on success, and isolated: this runs inside+ // `schedulePlayback`, whose catch turns any throw into `return null` —+ // i.e. a bus problem would silently drop the MEMBER from the pass. And+ // stamping first would consume the generation, so no later member of+ // the same group would retry and the bus would keep the previous pass's+ // envelopes: finding 11 unfixed on exactly the pass that failed.+ try {+ existing.reanchor(timing);+ existing.generation = this._playGeneration;+ } catch (err) {+ swallow("webAudioTransport.groupReanchor", err);+ }+ }+ return existing.input;+ }if (!this._ctx || !this._masterGain) return null;const input = this._ctx.createGain();// Stable point the FX chain (or, when there's none, the dry passthrough —// see `attachElementFxChain`'s `detach()`) always lands on before master,- // regardless of whether a chain is attached/detached/rebuilt later. B7's- // meter taps here. The mute gain splices in BEFORE `output` (between the- // FX chain and here), never after — the meter is defined to read the- // group's true, honestly-muted level (design doc §5), and this node is- // that contract's anchor.+ // regardless of whether a chain is attached/detached/rebuilt later. The+ // mute gain splices in BEFORE `output`, between the FX chain and here.const output = this._ctx.createGain();output.connect(this._masterGain);- const analyser = this._ctx.createAnalyser();- analyser.fftSize = 256; // level, not spectrum- output.connect(analyser);- const groupEl = doc.getElementById(groupId);+ // Tag-checked, and re-resolved on every reanchor below rather than frozen:+ // a bus whose element does not exist yet (studio group creation, or a+ // sub-composition that loads later) kept the `getAttribute: () => null`+ // stub for the whole session, so its fader, chain and mute never reached+ // preview while the export honoured all three.+ const resolveEl = (): Element | null => resolveGroupElement(doc, groupId);+ const groupEl = resolveEl();const muteGain = this._ctx.createGain();muteGain.gain.value = groupEl?.hasAttribute("data-hidden") ? 0 : 1;muteGain.connect(output);+ // The group's fader, POST-FX: `data-volume` is the static position and the+ // volume lane rides it, which is where a DAW puts it and the order the+ // render bakes it in (`scheduleVolumeLane`'s own contract). Scheduling it+ // on `input` instead put the fader ahead of the effects, so any nonlinear+ // group effect — a compressor, the Giant preset — previewed differently+ // than it rendered.+ const fader = this._ctx.createGain();+ fader.gain.value = clampGroupVolume(readAudioGroupVolume(groupEl));+ fader.connect(muteGain);const fx = attachElementFxChain(this._ctx,groupEl ?? { getAttribute: () => null },input,- muteGain,+ fader,timing,);- if (groupEl) scheduleVolumeLane(groupEl, input, timing);+ if (groupEl) scheduleVolumeLane(groupEl, fader, timing);this._groups.set(groupId, {input,+ fader,muteGain,- analyser,- levelBuf: new Float32Array(analyser.fftSize),+ fx,+ generation: this._playGeneration,+ reanchor: (at: AutomationTiming) => {+ // Cleared BEFORE the value write, and unconditionally. `scheduleVolumeLane`+ // clears as part of scheduling, but returns early when the group no+ // longer has a lane — and a scheduled envelope outranks a `.value`+ // write, so deleting a group's automation mid-session otherwise left+ // the previous pass's ramps still owning the param (for a fade-out,+ // silence) for the rest of the session.+ clearParamLane([{ param: fader.gain }]);+ // Re-resolved, not the element captured at build time — see `resolveEl`.+ const live = resolveEl();+ fader.gain.value = clampGroupVolume(readAudioGroupVolume(live));+ muteGain.gain.value = live?.hasAttribute("data-hidden") ? 0 : 1;+ fx?.reanchor(at);+ if (live) scheduleVolumeLane(live, fader, at);+ },dispose: () => {try {fx?.dispose();input.disconnect();+ fader.disconnect();muteGain.disconnect();output.disconnect();- analyser.disconnect();} catch {// Already torn down.}@@ -398,7 +460,7 @@ export class WebAudioTransport {/*** Group mute, preview side — a separate gain from `input`'s volume fader- * (B7) so a mute toggle never fights `scheduleVolumeLane`'s ramps on the+ * so a mute toggle never fights `scheduleVolumeLane`'s ramps on the* same param (the same hazard the design doc flags for §2.1). A no-op* until the group has an active member: at that point `groupInput` reads* the element's own `data-hidden` for its initial value, so there is@@ -414,30 +476,6 @@ export class WebAudioTransport {}}- /** Every group id currently routing audio (built lazily by `groupInput` —- * a group with no active member yet has no entry here). */- groupIds(): string[] {- return [...this._groups.keys()];- }-- /**- * RMS-ish level 0..1 and whether the last block clipped, for the group's- * meter — or null when the group has no active member (idle/unknown).- * Reuses a per-group buffer; no per-frame allocation.- */- groupLevel(groupId: string): { level: number; clipped: boolean } | null {- const g = this._groups.get(groupId);- if (!g) return null;- g.analyser.getFloatTimeDomainData(g.levelBuf);- let sumSquares = 0;- let clipped = false;- for (const sample of g.levelBuf) {- sumSquares += sample * sample;- if (Math.abs(sample) >= 0.99) clipped = true;- }- return { level: Math.sqrt(sumSquares / g.levelBuf.length), clipped };- }-/** Master, unless `el` belongs to a group — then that group's bus (built on* first use, per `groupInput`). */private resolveDestination(@@ -625,6 +663,16 @@ export class WebAudioTransport {swallow("webAudioTransport.setRate", err);}}+ // Group buses are not in `_activeSources` — they outlive it — so their FX+ // automation needs re-aiming here too, or a rate change leaves a group's+ // envelopes running the old plan over audio at the new speed.+ for (const group of this._groups.values()) {+ try {+ group.fx?.setRate(safeRate);+ } catch (err) {+ swallow("webAudioTransport.setRate.group", err);+ }+ }return true;}@@ -687,18 +735,8 @@ export class WebAudioTransport {this.applyMasterGain();}- private applyMasterGain(): void {- if (this._masterGain) this._masterGain.gain.value = this._masterMuted ? 0 : this._masterVolume;- }-- /**- * Push the current "Hear only this" set and re-evaluate every active- * source's solo gain against it — a gain-stage update, never a graph- * rebuild (rule 3 of B5's step doc). Group buses are never touched here:- * per `isAudibleUnderSolo`, a group is never attenuated by solo, so a- * soloed member's path through its (unattenuated) group stays open by- * construction.- */+ /** Update every active source without rebuilding the graph. Group ids solo+ * all members through the shared audibility predicate. */setSolo(soloed: ReadonlySet<string>): void {this._soloed = soloed;for (const source of this._activeSources) {@@ -716,6 +754,10 @@ export class WebAudioTransport {}}+ private applyMasterGain(): void {+ if (this._masterGain) this._masterGain.gain.value = this._masterMuted ? 0 : this._masterVolume;+ }+isActive(): boolean {return this._activeSources.length > 0 && !this._paused;}