Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(core): a sound effect starts on its time instead of a frame late (#4696)
Miguel Ángele0b940aa302e
diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.tsindex 37b7429c7d..b333cbb4a5 100644--- a/packages/core/src/runtime/init.test.ts+++ b/packages/core/src/runtime/init.test.ts@@ -3177,6 +3177,102 @@ describe("initSandboxRuntimeModular", () => {expect(childTimeline.time()).toBeCloseTo(1, 1);});+ const mountLateSfx = () => {+ const raf = createManualRaf();+ vi.spyOn(performance, "now").mockImplementation(() => raf.now());+ window.requestAnimationFrame = raf.requestAnimationFrame as typeof window.requestAnimationFrame;+ window.cancelAnimationFrame = raf.cancelAnimationFrame as typeof window.cancelAnimationFrame;+ 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", "4");+ root.setAttribute("data-width", "1920");+ root.setAttribute("data-height", "1080");+ document.body.appendChild(root);+ const sfx = document.createElement("audio");+ sfx.setAttribute("data-start", "1");+ sfx.setAttribute("data-duration", "1");+ sfx.setAttribute("src", "/assets/click.mp3");+ Object.defineProperty(sfx, "paused", { value: true, writable: true, configurable: true });+ Object.defineProperty(sfx, "currentTime", { value: 0, writable: true, configurable: true });+ Object.defineProperty(sfx, "readyState", { value: 4, configurable: true });+ const startedAt: number[] = [];+ sfx.play = vi.fn(() => {+ startedAt.push(window.__player!.getTime());+ Object.assign(sfx, { paused: false });+ return Promise.resolve();+ });+ sfx.pause = vi.fn(() => Object.assign(sfx, { paused: true }));+ root.appendChild(sfx);+ window.__timelines = { main: createMockTimeline(4) };+ initSandboxRuntimeModular();+ return { raf, sfx, startedAt };+ };++ it("starts an audio clip on the tick before its time, not the tick after", () => {+ const { raf, startedAt } = mountLateSfx();+ window.__player?.play();+ for (let frame = 0; frame < 75; frame++) raf.step(16);++ expect(startedAt.length).toBeGreaterThan(0);+ expect(startedAt[0]).toBeLessThan(1);+ expect(startedAt[0]).toBeGreaterThanOrEqual(1 - 0.02);+ });++ const setRate = (playbackRate: number) =>+ window.dispatchEvent(+ new MessageEvent("message", {+ source: window.parent,+ data: { source: "hf-parent", type: "control", action: "set-playback-rate", playbackRate },+ }),+ );++ it.each([1, 4])(+ "stops a clip it started early when a seek jumps back before it, at %sx",+ (rate) => {+ const { raf, sfx, startedAt } = mountLateSfx();+ setRate(rate);+ window.__player?.play();+ for (let frame = 0; frame < 120 && startedAt.length === 0; frame++) raf.step(13);+ expect(startedAt[0]).toBeLessThan(1);++ window.__player?.seek(0, { keepPlaying: true });+ raf.step(16);++ expect(sfx.pause).toHaveBeenCalled();+ },+ );++ it("does not start a clip early on the tick a seek lands just before it", () => {+ const { raf, startedAt } = mountLateSfx();+ window.__player?.play();+ raf.step(16);+ window.__player?.seek(0.99, { keepPlaying: true }); // lands on the frame at 0.967++ expect(startedAt).toEqual([]);+ for (let frame = 0; frame < 10 && startedAt.length === 0; frame++) raf.step(16);+ expect(startedAt[0]).toBeGreaterThanOrEqual(1 - 0.02);+ });++ it("starts a clip at most 40 ms of real time early at a slow speed", () => {+ const { raf, startedAt } = mountLateSfx();+ setRate(0.25);+ window.__player?.play();+ for (let frame = 0; frame < 60 && startedAt.length === 0; frame++) raf.step(76);++ expect(startedAt[0]).toBeGreaterThanOrEqual(1 - 0.04 * 0.25);+ });++ it("starts a clip at most 40 ms of film time early at a fast speed", () => {+ const { raf, startedAt } = mountLateSfx();+ setRate(4);+ window.__player?.play();+ for (let frame = 0; frame < 30 && startedAt.length === 0; frame++) raf.step(18);++ expect(startedAt[0]).toBeGreaterThanOrEqual(1 - 0.04);+ });+it.each([24, 30, 60, 30_000 / 1_001])("preserves public playback state across keepPlaying seeks at %s fps",(fps) => {diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.tsindex eae5c00c76..408d4064d3 100644--- a/packages/core/src/runtime/init.ts+++ b/packages/core/src/runtime/init.ts@@ -30,6 +30,7 @@ import {import { sourceTimeAt } from "../speedRamp";import { createWaapiAdapter } from "./adapters/waapi";import {+ MEDIA_SYNC_TOLERANCE_SECONDS,isUnplayable,readElementPlaybackRate,readElementPlaybackStart,@@ -2843,8 +2844,8 @@ export function initSandboxRuntimeModular(): void {* The media elements this pass must visit, and the argument that the rest can* be skipped.*- * `isActive` requires `isInClipWindow`, so a clip whose window excludes the- * new time is inactive there no matter what its element state is. A clip that+ * `isActive` requires `isInClipWindow` (or, for audio, a start within the early-start+ * margin), so a clip outside that is inactive there whatever its element state. A clip that* is in neither the previous in-window set nor the set of windows whose* endpoint the transport just crossed was therefore out of window BEFORE and* is out of window NOW — the pass would only have evicted sync state that is@@ -2858,6 +2859,7 @@ export function initSandboxRuntimeModular(): void {const collectMediaElementsToVisit = (index: MediaClipIndex,toSeconds: number,+ cueAheadSeconds: number,): Array<HTMLVideoElement | HTMLAudioElement> => {const fromSeconds = lastSyncedMediaTimeSeconds;if (fromSeconds === null) return index.clips.map((clip) => clip.el);@@ -2867,7 +2869,12 @@ export function initSandboxRuntimeModular(): void {const hi = Math.max(fromSeconds, toSeconds) + sameInstantMargin;const visiting = new Set<HTMLVideoElement | HTMLAudioElement>();for (const clip of mediaClipsInWindow) visiting.add(clip.el);- for (const clip of clipsWithEndpointBetween(index.byStart, (c) => c.start, lo, hi)) {+ for (const clip of clipsWithEndpointBetween(+ index.byStart,+ (c) => c.start,+ lo,+ hi + cueAheadSeconds,+ )) {visiting.add(clip.el);}for (const clip of clipsWithEndpointBetween(index.byEnd, (c) => c.end, lo, hi)) {@@ -2971,6 +2978,13 @@ export function initSandboxRuntimeModular(): void {// stale one cannot be recovered, so it visits all of them exactly as before.// Same reasoning, and the same latch, as the duration floors above.const indexed = !renderCaptureSeekStarted;+ const cueAheadSeconds =+ state.isPlaying && !state.mediaForceSyncNextTick && lastSyncedMediaTimeSeconds !== null+ ? Math.min(+ Math.max(0, state.currentTime - lastSyncedMediaTimeSeconds),+ MEDIA_SYNC_TOLERANCE_SECONDS * Math.min(1, state.playbackRate),+ )+ : 0;const mediaClips = withTimingResolver(() => {if (!indexed) return buildRuntimeMediaCache().mediaClips;const index = resolveMediaClipIndex();@@ -2978,8 +2992,9 @@ export function initSandboxRuntimeModular(): void {// is re-read here: `el.duration` is reset by any `el.load()` the retry path// made last pass, and a cached copy of it would be exactly the stale// duration the two-scope rule exists to prevent.- return buildRuntimeMediaCache(collectMediaElementsToVisit(index, state.currentTime))- .mediaClips;+ return buildRuntimeMediaCache(+ collectMediaElementsToVisit(index, state.currentTime, cueAheadSeconds),+ ).mediaClips;});// Attach probed volume keyframes to clips so syncRuntimeMedia can use the// same envelope the renderer uses instead of tracking GSAP-change diffs.@@ -3008,6 +3023,7 @@ export function initSandboxRuntimeModular(): void {userMuted: state.bridgeMuted,userVolume: state.bridgeVolume,forceSync,+ cueAheadSeconds,getCompositionDuration: () =>getSafeTimelineDurationSeconds(state.capturedTimeline, 0, timingRevision),onElementVolume: (el, _effectiveVolume, authorVolume) =>@@ -3025,7 +3041,7 @@ export function initSandboxRuntimeModular(): void {// Every clip not visited was out of window at both ends of this seek, so// the visited ones are the only possible members.mediaClipsInWindow = mediaClips.filter((clip) =>- isInClipWindow(state.currentTime, clip.start, clip.end),+ isInClipWindow(state.currentTime, clip.start - MEDIA_SYNC_TOLERANCE_SECONDS, clip.end),);} else {lastSyncedMediaTimeSeconds = null;diff --git a/packages/core/src/runtime/media.test.ts b/packages/core/src/runtime/media.test.tsindex 7f703a5bc0..458c7a5237 100644--- a/packages/core/src/runtime/media.test.ts+++ b/packages/core/src/runtime/media.test.ts@@ -874,6 +874,100 @@ describe("syncRuntimeMedia", () => {expect(clip.el.play).not.toHaveBeenCalled();});+ it("starts an audio clip due within the next tick, from its first sample", () => {+ const clip = createMockClip({ start: 5, end: 6, mediaStart: 2 }, "audio");+ syncRuntimeMedia({+ clips: [clip],+ timeSeconds: 4.99,+ playing: true,+ playbackRate: 1,+ cueAheadSeconds: 0.017,+ });+ expect(clip.el.play).toHaveBeenCalledTimes(1);+ expect(clip.el.currentTime).toBe(2);+ });++ it("does not start an audio clip further away than the next tick", () => {+ const clip = createMockClip({ start: 5, end: 6 }, "audio");+ syncRuntimeMedia({+ clips: [clip],+ timeSeconds: 4.95,+ playing: true,+ playbackRate: 1,+ cueAheadSeconds: 0.017,+ });+ expect(clip.el.play).not.toHaveBeenCalled();+ });++ it("does not start a sped-up clip so early that its window opens it past strict sync", () => {+ const clip = createMockClip({ start: 5, end: 6, rate: 3 }, "audio");+ syncRuntimeMedia({+ clips: [clip],+ timeSeconds: 4.98,+ playing: true,+ playbackRate: 1,+ cueAheadSeconds: 0.034,+ });+ expect(clip.el.play).not.toHaveBeenCalled();+ });++ it("keeps a clip it started early playing when the next tick is shorter", () => {+ const clip = createMockClip({ start: 5, end: 6 }, "audio");+ syncRuntimeMedia({+ clips: [clip],+ timeSeconds: 4.97,+ playing: true,+ playbackRate: 1,+ cueAheadSeconds: 0.034,+ });+ Object.defineProperty(clip.el, "paused", {+ value: false,+ writable: true,+ configurable: true,+ });+ syncRuntimeMedia({+ clips: [clip],+ timeSeconds: 4.98,+ playing: true,+ playbackRate: 1,+ cueAheadSeconds: 0.01,+ });+ expect(clip.el.pause).not.toHaveBeenCalled();+ });++ it("does not start a clip again once the playhead is past it", () => {+ const clip = createMockClip({ start: 5, end: 6 }, "audio");+ syncRuntimeMedia({+ clips: [clip],+ timeSeconds: 6.01,+ playing: true,+ playbackRate: 1,+ cueAheadSeconds: 0.017,+ });+ expect(clip.el.play).not.toHaveBeenCalled();+ });++ it("starts nothing early while paused, and never a video", () => {+ const audio = createMockClip({ start: 5, end: 6 }, "audio");+ syncRuntimeMedia({+ clips: [audio],+ timeSeconds: 4.99,+ playing: false,+ playbackRate: 1,+ cueAheadSeconds: 0.017,+ });+ const video = createMockClip({ start: 5, end: 6 }, "video");+ syncRuntimeMedia({+ clips: [video],+ timeSeconds: 4.99,+ playing: true,+ playbackRate: 1,+ cueAheadSeconds: 0.017,+ });+ expect(audio.el.play).not.toHaveBeenCalled();+ expect(video.el.play).not.toHaveBeenCalled();+ });+it("does not play() an element whose networkState is NO_SOURCE", () => {const clip = createMockClip({ start: 0, end: 10 });Object.defineProperty(clip.el, "networkState", { value: 3, configurable: true });diff --git a/packages/core/src/runtime/media.ts b/packages/core/src/runtime/media.tsindex f790727b05..7c7c548e51 100644--- a/packages/core/src/runtime/media.ts+++ b/packages/core/src/runtime/media.ts@@ -195,6 +195,7 @@ const seekLoadRetried = new WeakSet<HTMLMediaElement>();// AbortError / NotAllowedError that should surface. Cleared on the `playing`// event (actual playback started) or on `pause`/`error` (state ended).const playRequested = new WeakSet<HTMLMediaElement>();+const startedEarly = new WeakSet<HTMLMediaElement>();function markPlayRequested(el: HTMLMediaElement): void {if (playRequested.has(el)) return;playRequested.add(el);@@ -253,7 +254,7 @@ export function hasMediaSyncStateForTest(el: HTMLMediaElement): boolean {export const MEDIA_HARD_SYNC_SECONDS = 0.5;/** Drift a playing audio element may carry before sync pulls it back onto the playhead. */-const MEDIA_SYNC_TOLERANCE_SECONDS = 0.04;+export const MEDIA_SYNC_TOLERANCE_SECONDS = 0.04;// A playing video is steered back by rate, not seeked (a seek resets its decoder).// Its rate is written only when steering starts or stops: every write costs a frame.@@ -311,6 +312,8 @@ export function syncRuntimeMedia(params: {* unity; do not mistake that transport write for an authored volume edit. */isWebAudioRouted?: (el: HTMLMediaElement) => boolean;forceSync?: boolean;+ /** How far the next tick will move the playhead: an audio clip due within it starts now. */+ cueAheadSeconds?: number;/** Lets a video clip that runs to the composition end hold its last frame at the terminal time.* A thunk, because deriving the duration is only worth it for a clip past its own end. */getCompositionDuration: () => number;@@ -322,6 +325,18 @@ export function syncRuntimeMedia(params: {const clipRate = clip.rate ?? clip.playbackRate;const isNonLoopVideo = el.tagName === "VIDEO" && !clip.loop;const inWindow = isInClipWindow(params.timeSeconds, clip.start, clip.end);+ const dueIn = clip.start - params.timeSeconds;+ const startsEarly =+ el.tagName === "AUDIO" &&+ !inWindow &&+ dueIn > 0 &&+ dueIn * Math.max(1, rateAt(clipRate, 0)) <=+ Math.max(+ params.cueAheadSeconds ?? 0,+ startedEarly.has(el) ? MEDIA_SYNC_TOLERANCE_SECONDS : 0,+ );+ if (startsEarly) startedEarly.add(el);+ else startedEarly.delete(el);// A video that runs to the composition end stays the visible frame at and past it, so it// is held on the frame it shows at its own end rather than left on a stale one.const isTerminalVideo =@@ -355,7 +370,7 @@ export function syncRuntimeMedia(params: {// video additionally remains an active visual through// its authored window, with tail seeks clamped to the final frame.const isActive =- (inWindow || isTerminalVideo) &&+ (inWindow || isTerminalVideo || startsEarly) &&relTime >= 0 &&(!el.ended || clip.loop || isHeldVideoTail || canSeekEndedMediaBackward);if (isActive) {