diff --git a/packages/core/src/runtime/clipTree.ts b/packages/core/src/runtime/clipTree.ts index 47ad3575b9..bdb64234c5 100644 --- a/packages/core/src/runtime/clipTree.ts +++ b/packages/core/src/runtime/clipTree.ts @@ -10,6 +10,7 @@ * absolute start) when a caller needs them. */ +import { sourceLengthOf } from "./sourceLength"; import type { RuntimeTimelineLike } from "./types"; import { parseStrictFiniteTimingNumber, @@ -74,8 +75,8 @@ function durationFromTimeline( function durationFromMedia(el: Element): number | null { if (isMediaElement(el)) { - return Number.isFinite(el.duration) - ? resolveNaturalMediaTimelineDuration(el, el.duration) + return Number.isFinite(sourceLengthOf(el)) + ? resolveNaturalMediaTimelineDuration(el, sourceLengthOf(el)) : null; } return resolveTimedImageDurationSeconds(el); diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts index 935ee72999..f170ff4c86 100644 --- a/packages/core/src/runtime/init.ts +++ b/packages/core/src/runtime/init.ts @@ -1,4 +1,5 @@ // fallow-ignore-file code-duplication complexity +import { rememberSourceLength, sourceLengthOf } from "./sourceLength"; import { wallClearTimeout, wallSetTimeout } from "./wallClock"; import { setPreviewRasterScale } from "./previewRasterHints"; import { createFarSceneSkip } from "./farScenes"; @@ -1557,6 +1558,7 @@ export function initSandboxRuntimeModular(): void { const invalidateOnMediaTimingEvent = (event: Event) => { const target = event.target; + if (isMediaElement(target)) rememberSourceLength(target); if (isMediaElement(target) && lengthIsAuthored(target)) return; invalidateCompositionTimingCaches(); }; @@ -3655,8 +3657,8 @@ export function initSandboxRuntimeModular(): void { context.inheritedDuration > 0 ? Math.max(0, context.inheritedStart + context.inheritedDuration - start) : null; - const sourceDuration = Number.isFinite(element.duration) - ? resolveNaturalMediaTimelineDuration(element, element.duration) + const sourceDuration = Number.isFinite(sourceLengthOf(element)) + ? resolveNaturalMediaTimelineDuration(element, sourceLengthOf(element)) : null; // The element's own data-duration is an explicit clip-length trim // (the studio writes it when you drag the clip edge). It must bound diff --git a/packages/core/src/runtime/media.ts b/packages/core/src/runtime/media.ts index 5bc7a7e27f..dad72d5205 100644 --- a/packages/core/src/runtime/media.ts +++ b/packages/core/src/runtime/media.ts @@ -1,3 +1,4 @@ +import { sourceLengthOf } from "./sourceLength"; import { wallClearTimeout, wallSetTimeout } from "./wallClock"; import { swallow } from "./diagnostics"; import { isClipVisibleAt, isInClipWindow } from "./clipWindow"; @@ -149,7 +150,8 @@ export function refreshRuntimeMediaCache(params?: { const playbackRate = readElementPlaybackRate(el); const rate = readElementRateSpec(el); const loop = el.loop; - const sourceDuration = Number.isFinite(el.duration) && el.duration > 0 ? el.duration : null; + const length = sourceLengthOf(el); + const sourceDuration = Number.isFinite(length) && length > 0 ? length : null; let duration = params?.resolveDurationSeconds?.(el) ?? Number.parseFloat(el.dataset.duration ?? ""); if ((!Number.isFinite(duration) || duration < 0) && sourceDuration != null) { diff --git a/packages/core/src/runtime/playbackRate.ts b/packages/core/src/runtime/playbackRate.ts index d31bb1f956..6e28e1c7f3 100644 --- a/packages/core/src/runtime/playbackRate.ts +++ b/packages/core/src/runtime/playbackRate.ts @@ -1,3 +1,4 @@ +import { sourceLengthOf } from "./sourceLength"; import { clampPlaybackRate, readAuthoredDurationSeconds, @@ -62,12 +63,12 @@ export function resolveMediaElementDurationSeconds( const resolved = resolveMediaDuration({ tag: "video", // video and audio resolve identically authoredDurationSeconds: readDataDurationSeconds((name) => el.getAttribute(name)), - sourceDurationSeconds: Number.isFinite(el.duration) ? el.duration : null, + sourceDurationSeconds: Number.isFinite(sourceLengthOf(el)) ? sourceLengthOf(el) : null, mediaStartSeconds: readMediaStart(el), playbackRate: readElementPlaybackRate(el), }); return resolved.source === "media" - ? resolveNaturalMediaTimelineDuration(el, el.duration) + ? resolveNaturalMediaTimelineDuration(el, sourceLengthOf(el)) : resolved.seconds; } diff --git a/packages/core/src/runtime/sourceLength.ts b/packages/core/src/runtime/sourceLength.ts new file mode 100644 index 0000000000..174a7a3067 --- /dev/null +++ b/packages/core/src/runtime/sourceLength.ts @@ -0,0 +1,13 @@ +const measured = new WeakMap(); + +export function rememberSourceLength(media: HTMLMediaElement): void { + if (Number.isFinite(media.duration) && media.duration > 0) + measured.set(media, { src: media.src, seconds: media.duration }); +} + +/** The source length: the element's own, else the one measured for the same `src` before a reload emptied it; NaN. */ +export function sourceLengthOf(media: { duration: number; src?: string }): number { + if (Number.isFinite(media.duration)) return media.duration; + const kept = measured.get(media); + return kept !== undefined && kept.src === media.src ? kept.seconds : Number.NaN; +} diff --git a/packages/core/src/runtime/startResolver.ts b/packages/core/src/runtime/startResolver.ts index c1ef59a2c7..ed7699081a 100644 --- a/packages/core/src/runtime/startResolver.ts +++ b/packages/core/src/runtime/startResolver.ts @@ -1,3 +1,4 @@ +import { sourceLengthOf } from "./sourceLength"; import type { RuntimeTimelineLike } from "./types"; import { readTimelineDurationSeconds } from "./timelineDuration"; import { resolveAuthoredTimingWindow } from "./authoredTiming"; @@ -100,7 +101,7 @@ export function createRuntimeStartTimeResolver(params: { resolveAuthoredDuration(element) ?? positive( isMediaElement(element) - ? resolveNaturalMediaTimelineDuration(element, element.duration) + ? resolveNaturalMediaTimelineDuration(element, sourceLengthOf(element)) : null, ) ?? positive(resolveTimedImageDurationSeconds(element)) ?? diff --git a/packages/core/src/runtime/timeline.test.ts b/packages/core/src/runtime/timeline.test.ts index 7f4c0bf80e..d1f3227e46 100644 --- a/packages/core/src/runtime/timeline.test.ts +++ b/packages/core/src/runtime/timeline.test.ts @@ -6,6 +6,7 @@ import { runtimeElementWindow, } from "./timeline"; import { createRuntimeStartTimeResolver } from "./startResolver"; +import { rememberSourceLength } from "./sourceLength"; type TimelineTestWindow = Window & { __timelines?: Record number }>; @@ -309,6 +310,26 @@ describe("collectRuntimeTimelinePayload", () => { ); }); + // fails without the fix: a far clip the runtime let go of dropped out of the clip list. + it("keeps an untrimmed clip the runtime let go of, at its measured length", () => { + const root = document.createElement("div"); + root.setAttribute("data-composition-id", "main"); + document.body.appendChild(root); + const video = document.createElement("video"); + video.id = "far"; + video.src = "far.mp4"; + video.setAttribute("data-start", "300"); + root.appendChild(video); + Object.defineProperty(video, "duration", { value: 600, writable: true, configurable: true }); + rememberSourceLength(video); + video.duration = Number.NaN; + + const far = collectRuntimeTimelinePayload(defaultParams).clips.find( + (clip) => clip.id === "far", + ); + expect(far?.duration).toBe(600); + }); + it("identifies video clips by tag", () => { const root = document.createElement("div"); root.setAttribute("data-composition-id", "main"); diff --git a/packages/core/src/runtime/timeline.ts b/packages/core/src/runtime/timeline.ts index 94757fc876..bc901f671e 100644 --- a/packages/core/src/runtime/timeline.ts +++ b/packages/core/src/runtime/timeline.ts @@ -1,3 +1,4 @@ +import { sourceLengthOf } from "./sourceLength"; import type { RuntimeTimelineClip, RuntimeTimelineMessage, @@ -447,8 +448,8 @@ export function collectRuntimeTimelinePayload(params: { duration = resolveTimelineDurationSeconds(nodeCompositionId); } if (duration == null && isMediaElement(node)) { - if (Number.isFinite(node.duration)) { - duration = resolveNaturalMediaTimelineDuration(node, node.duration); + if (Number.isFinite(sourceLengthOf(node))) { + duration = resolveNaturalMediaTimelineDuration(node, sourceLengthOf(node)); } } if (duration == null) duration = resolveTimedImageDurationSeconds(node, start); diff --git a/packages/studio/src/utils/runtimeClipLength.browser.test.ts b/packages/studio/src/utils/runtimeClipLength.browser.test.ts new file mode 100644 index 0000000000..6417171182 --- /dev/null +++ b/packages/studio/src/utils/runtimeClipLength.browser.test.ts @@ -0,0 +1,76 @@ +// Real Chrome: a capture page's film length while the runtime lets go of a far clip it has already measured. +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import type { Browser } from "puppeteer-core"; +import { afterAll, beforeAll, expect, it } from "vitest"; +import { + STUDIO_PREVIEW_CAPTURE_MODE, + STUDIO_PREVIEW_MARK_META, +} from "@hyperframes/core/studio-preview-mark"; +import { closeTestChrome, launchTestChrome } from "../../tests/chromeTestUtils"; + +const require = createRequire(import.meta.url); +const ORIGIN = "https://fixture.hyperframes.test"; +const CLIP = readFileSync(new URL("../../tests/fixtures/clip-600s.webm", import.meta.url)); + +/** The clip trimmed to 37.43 s at 0, and untrimmed (600 s) at 300 s: the film is 900 s long. */ +function filmHtml(): string { + const gsap = readFileSync(require.resolve("gsap/dist/gsap.min.js"), "utf8"); + const runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8"); + return ` + + +
+ + +
+ + `; +} + +let browser: Browser; +beforeAll(async () => { + browser = await launchTestChrome(); +}); +afterAll(() => closeTestChrome(browser)); + +// fails without the fix: each time the runtime let go of the far clip, the film fell back to 37.43 s. +it("keeps a far clip's measured length while the runtime lets go of it", async () => { + const page = await browser.newPage(); + await page.setRequestInterception(true); + page.on("request", (request) => { + const url = request.url(); + if (url === `${ORIGIN}/index.html`) + return void request.respond({ status: 200, contentType: "text/html", body: filmHtml() }); + if (url === `${ORIGIN}/clip-600s.webm`) + return void request.respond({ status: 200, contentType: "video/webm", body: CLIP }); + void request.abort(); + }); + await page.goto(`${ORIGIN}/index.html`); + await page.waitForFunction( + () => (window as unknown as { __playerReady?: boolean }).__playerReady === true, + ); + // Asks the far clip to load as a length read does, and notes the film's length every 16 ms for 2 s. + const lengths = await page.evaluate( + () => + new Promise((resolve) => { + const far = document.getElementById("far") as HTMLVideoElement; + const player = (window as unknown as { __player: { getDuration(): number } }).__player; + const seen: number[] = []; + const started = performance.now(); + (function poll() { + if (far.readyState < 1 && far.networkState !== 2) { + far.preload = "metadata"; + far.load(); + } + seen.push(player.getDuration()); + if (performance.now() - started > 2000) return resolve(seen); + setTimeout(poll, 16); + })(); + }), + ); + await page.close(); + const measured = lengths.indexOf(900); + expect(measured).toBeGreaterThanOrEqual(0); + expect(lengths.slice(measured).filter((seconds) => seconds !== 900)).toEqual([]); +}, 30_000); diff --git a/packages/studio/tests/fixtures/clip-600s.webm b/packages/studio/tests/fixtures/clip-600s.webm new file mode 100644 index 0000000000..9b424a8d61 Binary files /dev/null and b/packages/studio/tests/fixtures/clip-600s.webm differ