mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 16:37:32 +00:00
fix(player): a sealed film is heard when its frame may not start sound (#8495)
* fix(player): a sealed film is heard when its frame may not start sound When a browser refuses the film's own play (an iPhone, or Chrome's tap-first rule for a sealed frame), the player plays copies of the film's media in its page. A sealed player could not read the frame, so it made no copies and muted the frame anyway: silence. The runtime now sends the clips to copy with the refusal, and again whenever they change. The player copies only files under the composition's own folder, anonymously, and mutes the frame only while a copy plays instead. * fix(player): a sealed film's copy plays its file from the composition's own origin The copy's address is now the composition's origin followed by the checked path, never the string the frame sent. The player's size budget rises by exactly what the sealed copies add (npm pack, main vs this branch). * fix(player): a sealed film's copy address is rebuilt from encoded path parts * fix(player): a sealed film's copy refuses an encoded way out of its folder * fix(player): a sealed film is muted only once its copy plays, and only from web addresses Copies come only from http(s) addresses, so two opaque origins never match. A clip with an invalid file address gets no copy, and the rest are still listed. The frame is muted once a copy is playing, and gets its sound back when the last one fails or is dropped. * fix(player): a sealed film gets its sound back when its last playing copy fails * fix(player): a sealed film's mute follows its copies' own state, whatever order events arrive in
This commit is contained in:
@@ -143,6 +143,13 @@ jobs:
|
||||
PUPPETEER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
|
||||
run: bun run test:browser-box
|
||||
|
||||
- name: Verify a sealed player's sound plays where its frame may not start it (load shard only)
|
||||
if: matrix.shard == 'load'
|
||||
working-directory: packages/player
|
||||
env:
|
||||
PUPPETEER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
|
||||
run: bun run test:browser-sealed-audio
|
||||
|
||||
- name: Run player perf — ${{ matrix.shard }} (measure mode)
|
||||
working-directory: packages/player
|
||||
env:
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
AUDIBLE_MEDIA_SELECTOR,
|
||||
audibleVideoNeedsWebAudio,
|
||||
isAudibleVideoElement,
|
||||
parentCopyOf,
|
||||
} from "./audibleVideo";
|
||||
|
||||
const el = (tagName: string, attrs: Record<string, string>) => ({
|
||||
@@ -66,3 +67,56 @@ describe("audibleVideoNeedsWebAudio", () => {
|
||||
expect(audibleVideoNeedsWebAudio(fields)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parentCopyOf", () => {
|
||||
const media = (html: string) => {
|
||||
document.body.innerHTML = html;
|
||||
return document.body.firstElementChild as HTMLMediaElement;
|
||||
};
|
||||
|
||||
it("names a timed clip's file at the document's address, its window and where in the file it begins", () => {
|
||||
expect(
|
||||
parentCopyOf(
|
||||
media(
|
||||
'<audio src="music/a.m4a" data-start="2" data-duration="5" data-media-start="1.5"></audio>',
|
||||
),
|
||||
),
|
||||
).toEqual({
|
||||
kind: "audio",
|
||||
src: new URL("music/a.m4a", document.baseURI).href,
|
||||
start: 2,
|
||||
duration: 5,
|
||||
mediaStart: 1.5,
|
||||
});
|
||||
});
|
||||
|
||||
it("reads a <source> child and gives an open-ended clip no end", () => {
|
||||
expect(parentCopyOf(media('<video data-start="0"><source src="b.mp4"></video>'))).toMatchObject(
|
||||
{ kind: "video", src: new URL("b.mp4", document.baseURI).href, duration: Infinity },
|
||||
);
|
||||
});
|
||||
|
||||
it("copies nothing a render would not hear, or a clip the preloader has put off", () => {
|
||||
expect(parentCopyOf(media('<video src="v.mp4" data-start="0" muted></video>'))).toBeNull();
|
||||
expect(
|
||||
parentCopyOf(media('<video src="v.mp4" data-start="0" data-has-audio="false"></video>')),
|
||||
).toBeNull();
|
||||
expect(
|
||||
parentCopyOf(media('<audio src="a.m4a" data-start="0" preload="metadata"></audio>')),
|
||||
).toBeNull();
|
||||
expect(
|
||||
parentCopyOf(media('<audio src="a.m4a" data-start="0" preload="none"></audio>')),
|
||||
).toBeNull();
|
||||
expect(parentCopyOf(media('<audio data-start="0"></audio>'))).toBeNull();
|
||||
});
|
||||
|
||||
it("gives a clip whose file address is invalid no copy, and leaves the others alone", () => {
|
||||
document.body.innerHTML =
|
||||
'<audio src="https://[" data-start="0"></audio><audio src="b.m4a" data-start="0"></audio>';
|
||||
const copies = [...document.querySelectorAll("audio")].map((el) => parentCopyOf(el));
|
||||
expect(copies.map((c) => c?.src ?? null)).toEqual([
|
||||
null,
|
||||
new URL("b.m4a", document.baseURI).href,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { readClipTiming } from "./compositionContract.js";
|
||||
import { readLinkTiming } from "./mediaLink.js";
|
||||
|
||||
export const AUDIBLE_VIDEO_QUALIFIER =
|
||||
':not([muted]):is(:not([data-has-audio]),[data-has-audio="true"])';
|
||||
|
||||
@@ -25,3 +28,37 @@ export function audibleVideoNeedsWebAudio(fields: {
|
||||
Boolean(fields.fxChain || fields.automation || fields.audioGroup || fields.masterChain)
|
||||
);
|
||||
}
|
||||
|
||||
export interface ParentCopy {
|
||||
kind: "audio" | "video";
|
||||
src: string;
|
||||
start: number;
|
||||
duration: number;
|
||||
mediaStart: number;
|
||||
}
|
||||
|
||||
export function mediaFileOf(el: HTMLMediaElement): string | null {
|
||||
const raw = el.getAttribute("src") || el.querySelector("source")?.getAttribute("src");
|
||||
if (!raw) return null;
|
||||
try {
|
||||
return new URL(raw, el.ownerDocument.baseURI).href;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function parentCopyOf(el: HTMLMediaElement): ParentCopy | null {
|
||||
if (el.preload === "metadata" || el.preload === "none") return null;
|
||||
const tag = el.tagName.toLowerCase();
|
||||
if (tag !== "audio" && !isAudibleVideoElement(el)) return null;
|
||||
const src = mediaFileOf(el);
|
||||
if (!src) return null;
|
||||
const timing = readClipTiming(el);
|
||||
return {
|
||||
kind: tag === "audio" ? "audio" : "video",
|
||||
src,
|
||||
start: timing.start ?? 0,
|
||||
duration: timing.duration ?? Number.POSITIVE_INFINITY,
|
||||
mediaStart: readLinkTiming(el).mediaStart,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -266,7 +266,7 @@ import {
|
||||
isVideoElement,
|
||||
type StylableElement,
|
||||
} from "./domRealm";
|
||||
import { audibleVideoNeedsWebAudio, isAudibleVideoElement } from "../audibleVideo";
|
||||
import { audibleVideoNeedsWebAudio, isAudibleVideoElement, parentCopyOf } from "../audibleVideo";
|
||||
|
||||
/**
|
||||
* A `window.__timelines` entry is authored content and may be a PARTIAL
|
||||
@@ -536,6 +536,11 @@ const joinsWebAudio = (el: Element): el is HTMLMediaElement =>
|
||||
}));
|
||||
const WEB_AUDIO_MEDIA = "audio[data-start], video[data-start]";
|
||||
|
||||
const parentCopies = () =>
|
||||
Array.from(document.querySelectorAll(WEB_AUDIO_MEDIA)).flatMap((el) =>
|
||||
isMediaElement(el) ? (parentCopyOf(el) ?? []) : [],
|
||||
);
|
||||
|
||||
/** WebKit restarts a media element's audio 150 to 400 ms late; a decoded buffer on the context clock starts on time. */
|
||||
function decodesFirst(el: HTMLMediaElement, webAudio: WebAudioTransport): boolean {
|
||||
return (
|
||||
@@ -3293,6 +3298,43 @@ export function initSandboxRuntimeModular(): void {
|
||||
let bufferingFor: HTMLMediaElement[] = [];
|
||||
const playingOrHeldForData = () => clock.isPlaying() || bufferingFor.length > 0;
|
||||
let keepLateMedia = false;
|
||||
// A sealed player copies only the clips this list names. ponytail: once blocked, every watched
|
||||
// change re-reads all media; scope the observer to media records if that shows in a profile.
|
||||
const postParentCopiesWhileTheyChange = () => {
|
||||
let posted = "";
|
||||
const post = () => {
|
||||
const media = parentCopies();
|
||||
const next = JSON.stringify(media);
|
||||
if (next === posted || state.tornDown) return;
|
||||
posted = next;
|
||||
postRuntimeMessage({ source: "hf-preview", type: "media-autoplay-blocked", media });
|
||||
};
|
||||
post();
|
||||
if (typeof MutationObserver === "undefined") return;
|
||||
let queued = false;
|
||||
const observer = new MutationObserver(() => {
|
||||
if (queued) return;
|
||||
queued = true;
|
||||
queueMicrotask(() => {
|
||||
queued = false;
|
||||
post();
|
||||
});
|
||||
});
|
||||
observer.observe(document.documentElement, {
|
||||
subtree: true,
|
||||
childList: true,
|
||||
attributes: true,
|
||||
attributeFilter: [
|
||||
...DURATION_FLOOR_INPUT_ATTRIBUTES,
|
||||
"src",
|
||||
"preload",
|
||||
"muted",
|
||||
"data-has-audio",
|
||||
"data-playback-start",
|
||||
],
|
||||
});
|
||||
runtimeCleanupCallbacks.push(() => observer.disconnect());
|
||||
};
|
||||
const preloadNearPlayhead = (
|
||||
el: HTMLMediaElement,
|
||||
visible: boolean,
|
||||
@@ -3993,7 +4035,7 @@ export function initSandboxRuntimeModular(): void {
|
||||
onAutoplayBlocked: () => {
|
||||
if (state.mediaAutoplayBlockedPosted) return;
|
||||
state.mediaAutoplayBlockedPosted = true;
|
||||
postRuntimeMessage({ source: "hf-preview", type: "media-autoplay-blocked" });
|
||||
postParentCopiesWhileTheyChange();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -32,11 +32,7 @@ export type RuntimeState = {
|
||||
* audible presenter playback and remote sync.
|
||||
*/
|
||||
webAudioMediaDisabled: boolean;
|
||||
/**
|
||||
* Latch so the `media-autoplay-blocked` outbound message is posted at most
|
||||
* once per runtime session. The parent only needs the first signal — it
|
||||
* takes over playback and further rejections are the same problem.
|
||||
*/
|
||||
/** Latch: the first refusal starts `media-autoplay-blocked`, which then follows the media list. */
|
||||
mediaAutoplayBlockedPosted: boolean;
|
||||
/**
|
||||
* One-shot flag: force a hard media sync on the next tick. Set on
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { PreviewTarget } from "../studioPreviewMark";
|
||||
import type { RuntimeAnalyticsEvent } from "./analytics";
|
||||
import type { TextLayerRead } from "./editingElement";
|
||||
import type { AudioFades } from "../audioFade";
|
||||
import type { ParentCopy } from "../audibleVideo";
|
||||
import type { RateSpec } from "../speedRamp";
|
||||
import type { VolumeKeyframe } from "./mediaVolumeEnvelope";
|
||||
|
||||
@@ -193,6 +194,7 @@ export type RuntimeStageSizeMessage = {
|
||||
export type RuntimeMediaAutoplayBlockedMessage = {
|
||||
source: "hf-preview";
|
||||
type: "media-autoplay-blocked";
|
||||
media: ParentCopy[];
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -137,6 +137,8 @@ The player handles this automatically for same-origin iframes (the default — `
|
||||
|
||||
No changes are required by consumers — this works out of the box.
|
||||
|
||||
A sealed player (`sandbox-origin`) cannot read the frame. When the frame's own play is refused, the runtime sends the player the list of clips to copy, and sends it again when it changes. The player copies only files under the composition's own folder, on its origin, with `crossorigin="anonymous"`. Any other file is refused and named in a `playbackerror` event (`detail.refused`). A composition loaded from `srcdoc` has no folder of its own, so it gets no copies. The frame is muted only while a copy plays instead.
|
||||
|
||||
The optional `audio-src` attribute can be used to start preloading a primary audio track before the iframe loads (useful on slow connections), but is not required for mobile playback.
|
||||
|
||||
## JavaScript API
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
"test:browser-security": "bun run tests/browser/sandbox-origin.ts",
|
||||
"test:browser-raster": "bun run tests/browser/preview-raster-size.ts",
|
||||
"test:browser-box": "bun run tests/browser/player-box.ts",
|
||||
"test:browser-sealed-audio": "bun run tests/browser/sealed-audio.ts",
|
||||
"perf": "bun run tests/perf/index.ts",
|
||||
"playbench": "bun run tests/playbench/run.ts"
|
||||
},
|
||||
|
||||
@@ -1104,22 +1104,15 @@ describe("HyperframesPlayer seek() sync path", () => {
|
||||
stubIframeContentDocument(player.iframe, doc);
|
||||
stubContentWindow({ postMessage: post });
|
||||
|
||||
player.setAttribute("audio-src", "https://cdn.example.com/background.mp3");
|
||||
const globalProxyPause = vi.spyOn(player._parentMedia[0]!.el, "pause");
|
||||
const slideProxyPause = vi.fn();
|
||||
const globalProxyPause = vi.fn();
|
||||
player._parentMedia.push(
|
||||
{
|
||||
el: { pause: slideProxyPause, src: "https://cdn.example.com/slide.mp4" },
|
||||
start: 0,
|
||||
duration: 5,
|
||||
source: iframeVideo,
|
||||
},
|
||||
{
|
||||
el: { pause: globalProxyPause, src: "https://cdn.example.com/background.mp3" },
|
||||
start: 0,
|
||||
duration: Infinity,
|
||||
source: null,
|
||||
},
|
||||
);
|
||||
player._parentMedia.push({
|
||||
el: { pause: slideProxyPause, src: "https://cdn.example.com/slide.mp4" },
|
||||
start: 0,
|
||||
duration: 5,
|
||||
source: iframeVideo,
|
||||
});
|
||||
|
||||
player.stopMedia();
|
||||
|
||||
|
||||
@@ -196,6 +196,7 @@ class HyperframesPlayer extends HTMLElement {
|
||||
getPlaybackRate: () => this.playbackRate,
|
||||
getCurrentTime: () => this._currentTime,
|
||||
isPaused: () => this._paused,
|
||||
setFrameMuted: (muted) => this._sendControl("set-media-output-muted", { muted }),
|
||||
});
|
||||
|
||||
this._directTimelineClock = new DirectTimelineClock({
|
||||
@@ -1289,6 +1290,8 @@ class HyperframesPlayer extends HTMLElement {
|
||||
setCompositionSize: (w, h) => this._setCompositionSize(w, h),
|
||||
sendControl: (action, extra) => this._sendControl(action, extra),
|
||||
getIframeDoc: () => this.iframe.contentDocument,
|
||||
getCompositionUrl: () =>
|
||||
this.iframe.hasAttribute("srcdoc") ? null : this.iframe.src || null,
|
||||
onRuntimeReady: () => {
|
||||
this._runtimeBridgeReady = true;
|
||||
this._replayBridgeState();
|
||||
@@ -1721,14 +1724,7 @@ class HyperframesPlayer extends HTMLElement {
|
||||
this._media.mirrorTime(t, opts);
|
||||
}
|
||||
_promoteToParentProxy() {
|
||||
let d: Document | null = null;
|
||||
try {
|
||||
d = this.iframe.contentDocument;
|
||||
} catch {
|
||||
/* x-origin */
|
||||
}
|
||||
this._media.promoteToParentProxy(d, (t, o) => this._mirrorParentMediaTime(t, o));
|
||||
this._sendControl("set-media-output-muted", { muted: true });
|
||||
this._media.promoteToParentProxy((t, o) => this._mirrorParentMediaTime(t, o));
|
||||
}
|
||||
_observeDynamicMedia(doc: Document) {
|
||||
this._media.setupFromIframe(doc);
|
||||
|
||||
@@ -29,6 +29,7 @@ function makeManager(overrides: Partial<{ isPaused: boolean; owner: "runtime" |
|
||||
getPlaybackRate: () => 1,
|
||||
getCurrentTime: () => 0,
|
||||
isPaused: () => overrides.isPaused ?? true,
|
||||
setFrameMuted: () => {},
|
||||
});
|
||||
return mgr;
|
||||
}
|
||||
@@ -282,7 +283,7 @@ describe("ParentMediaManager following its clips", () => {
|
||||
clip.setAttribute("src", copy);
|
||||
await flushObserver();
|
||||
|
||||
mgr.promoteToParentProxy(document);
|
||||
mgr.promoteToParentProxy();
|
||||
|
||||
expect(mgr.entries.map((m) => m.el.src)).toEqual([copy]);
|
||||
});
|
||||
@@ -290,7 +291,7 @@ describe("ParentMediaManager following its clips", () => {
|
||||
it("follows a re-pointed clip at once while the parent owns playback", async () => {
|
||||
const mgr = makeManager();
|
||||
const clip = adoptedClip(mgr, "https://example.test/clip.mov");
|
||||
mgr.promoteToParentProxy(document);
|
||||
mgr.promoteToParentProxy();
|
||||
clip.setAttribute("src", copy);
|
||||
await flushObserver();
|
||||
|
||||
@@ -301,7 +302,7 @@ describe("ParentMediaManager following its clips", () => {
|
||||
const mgr = makeManager();
|
||||
adoptedClip(mgr, "https://example.test/a.mov");
|
||||
const b = adoptedClip(mgr, "https://example.test/b.mov");
|
||||
mgr.promoteToParentProxy(document);
|
||||
mgr.promoteToParentProxy();
|
||||
b.setAttribute("src", "https://example.test/a.mov");
|
||||
await flushObserver();
|
||||
|
||||
@@ -317,7 +318,7 @@ describe("ParentMediaManager following its clips", () => {
|
||||
const mgr = makeManager();
|
||||
const a = adoptedClip(mgr, "https://example.test/a.mov");
|
||||
const b = adoptedClip(mgr, "https://example.test/b.mov");
|
||||
mgr.promoteToParentProxy(document);
|
||||
mgr.promoteToParentProxy();
|
||||
a.setAttribute("src", "https://example.test/b.mov");
|
||||
b.setAttribute("src", "https://example.test/a.mov");
|
||||
await flushObserver();
|
||||
@@ -333,7 +334,7 @@ describe("ParentMediaManager following its clips", () => {
|
||||
b.setAttribute("src", "https://example.test/c.mov");
|
||||
await flushObserver();
|
||||
|
||||
mgr.promoteToParentProxy(document);
|
||||
mgr.promoteToParentProxy();
|
||||
|
||||
expect(files(mgr)).toEqual(["https://example.test/b.mov", "https://example.test/c.mov"]);
|
||||
});
|
||||
@@ -440,7 +441,7 @@ describe("ParentMediaManager takes cut from one joined file", () => {
|
||||
mgr.setupFromIframe(document);
|
||||
expect(mgr.entries).toHaveLength(audios.length);
|
||||
const tracks = mgr.entries.map((m) => trackSeeks(m.el));
|
||||
mgr.promoteToParentProxy(document);
|
||||
mgr.promoteToParentProxy();
|
||||
|
||||
let t = 0;
|
||||
const playing: boolean[][] = [];
|
||||
@@ -470,7 +471,7 @@ describe("ParentMediaManager takes cut from one joined file", () => {
|
||||
const mgr = makeManager({ isPaused: false });
|
||||
mgr.setupFromIframe(document);
|
||||
mgr.entries.forEach((m) => trackSeeks(m.el));
|
||||
mgr.promoteToParentProxy(document);
|
||||
mgr.promoteToParentProxy();
|
||||
|
||||
mgr.mirrorTime(12);
|
||||
expect(mgr.entries.map((m) => !m.el.paused)).toEqual([false, true, false]);
|
||||
@@ -495,7 +496,7 @@ describe("ParentMediaManager takes cut from one joined file", () => {
|
||||
const mgr = makeManager({ isPaused: false });
|
||||
mgr.setupFromIframe(document);
|
||||
const tracks = mgr.entries.map((m) => trackSeeks(m.el));
|
||||
mgr.promoteToParentProxy(document);
|
||||
mgr.promoteToParentProxy();
|
||||
|
||||
mgr.mirrorTime(6.4); // inside take 1's window, 1.6 s before take 2
|
||||
expect(tracks[1].seeks.at(-1)).toBeUndefined();
|
||||
@@ -608,7 +609,7 @@ describe("ParentMediaManager drift policy", () => {
|
||||
},
|
||||
});
|
||||
Object.defineProperty(el, "paused", { get: () => false });
|
||||
mgr.promoteToParentProxy(null, () => {}); // owner parent without the alignment seek
|
||||
mgr.promoteToParentProxy(() => {}); // owner parent without the alignment seek
|
||||
|
||||
mgr.mirrorTime(5); // 250 ms behind
|
||||
time = 4.85;
|
||||
@@ -646,15 +647,270 @@ describe("proxy crossorigin", () => {
|
||||
const parent = Object.create(ParentMediaManager.prototype) as ParentMediaManager;
|
||||
Object.assign(parent, {
|
||||
_entries: [],
|
||||
_urlTaken: () => false,
|
||||
_getMuted: () => false,
|
||||
_getVolume: () => 1,
|
||||
_getPlaybackRate: () => 1,
|
||||
});
|
||||
(parent as any)._createEntry("https://x/a.mp3", tag, 0, 5, source);
|
||||
(parent as any)._createEntry(
|
||||
{ kind: tag, src: "https://x/a.mp3", start: 0, duration: 5, mediaStart: 0 },
|
||||
source,
|
||||
);
|
||||
const proxy = created.find((e) => e.tagName.toLowerCase() === tag)!;
|
||||
globalThis.Audio = OrigAudio;
|
||||
vi.restoreAllMocks();
|
||||
expect(proxy.getAttribute("crossorigin")).toBe("anonymous");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ParentMediaManager for a sealed film, from its runtime's list", () => {
|
||||
const film = "https://films.test/f/index.html";
|
||||
const clip = (src: string, start = 0) => ({
|
||||
kind: "audio",
|
||||
src,
|
||||
start,
|
||||
duration: 5,
|
||||
mediaStart: 0,
|
||||
});
|
||||
|
||||
function makeSealedManager() {
|
||||
const events: CustomEvent[] = [];
|
||||
const setFrameMuted = vi.fn();
|
||||
const mgr = new ParentMediaManager({
|
||||
dispatchEvent: (e) => events.push(e as CustomEvent),
|
||||
getMuted: () => false,
|
||||
getVolume: () => 1,
|
||||
getPlaybackRate: () => 1,
|
||||
getCurrentTime: () => 0,
|
||||
isPaused: () => true,
|
||||
setFrameMuted,
|
||||
});
|
||||
return { mgr, events, setFrameMuted };
|
||||
}
|
||||
|
||||
// A copy's own state, as the browser reports it, then the event that says it changed.
|
||||
function becomes(el: HTMLMediaElement, state: "playing" | "pause" | "ended" | "error") {
|
||||
const define = (key: string, value: unknown) =>
|
||||
Object.defineProperty(el, key, { configurable: true, get: () => value });
|
||||
define("paused", state !== "playing");
|
||||
define("readyState", state === "playing" ? 4 : 1);
|
||||
define("ended", state === "ended");
|
||||
if (state === "error") define("error", { code: 2 });
|
||||
el.dispatchEvent(new Event(state));
|
||||
}
|
||||
|
||||
it("copies only files under the composition's own folder, without credentials, and reports the rest", () => {
|
||||
const { mgr, events } = makeSealedManager();
|
||||
|
||||
mgr.setupFromList(
|
||||
[
|
||||
clip("https://films.test/f/music/a.m4a"),
|
||||
clip("https://films.test/f/music/my%20take.m4a?v=3"),
|
||||
clip("https://other.test/f/a.m4a"),
|
||||
clip("https://films.test/g/a.m4a"),
|
||||
clip("https://films.test/f/../secret.m4a"),
|
||||
clip("data:audio/mp4;base64,AAAA"),
|
||||
],
|
||||
film,
|
||||
);
|
||||
|
||||
expect(mgr.entries.map((m) => m.el.src)).toEqual([
|
||||
"https://films.test/f/music/a.m4a",
|
||||
"https://films.test/f/music/my%20take.m4a?v=3",
|
||||
]);
|
||||
expect(mgr.entries.every((m) => m.el.getAttribute("crossorigin") === "anonymous")).toBe(true);
|
||||
const refusal = events.find((e) => e.type === "playbackerror");
|
||||
expect(refusal?.detail.refused).toEqual([
|
||||
"https://other.test/f/a.m4a",
|
||||
"https://films.test/g/a.m4a",
|
||||
"https://films.test/f/../secret.m4a",
|
||||
"data:audio/mp4;base64,AAAA",
|
||||
]);
|
||||
});
|
||||
|
||||
it("refuses every way out of the composition's folder, and copies a file in a folder under it", () => {
|
||||
const { mgr, events } = makeSealedManager();
|
||||
const escapes = [
|
||||
"https://films.test/f/%2e%2e/secret.m4a",
|
||||
"https://films.test/f/..%2Fsecret.m4a",
|
||||
"https://films.test/f/music%2F..%2F..%2Fsecret.m4a",
|
||||
"https://films.test/f/..%5Csecret.m4a",
|
||||
"https://films.test/f/..\\secret.m4a",
|
||||
"https://elsewhere.test/f/a.m4a",
|
||||
"//elsewhere.test/f/a.m4a",
|
||||
];
|
||||
|
||||
mgr.setupFromList(
|
||||
[...escapes, "https://films.test/f/music/loops/a.m4a"].map((src) => clip(src)),
|
||||
film,
|
||||
);
|
||||
|
||||
expect(mgr.entries.map((m) => m.el.src)).toEqual(["https://films.test/f/music/loops/a.m4a"]);
|
||||
expect(events.find((e) => e.type === "playbackerror")?.detail.refused).toEqual(escapes);
|
||||
});
|
||||
|
||||
it("copies nothing when the composition has no address of its own", () => {
|
||||
const { mgr } = makeSealedManager();
|
||||
mgr.setupFromList([clip("https://films.test/f/a.m4a")], null);
|
||||
expect(mgr.entries).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("skips a list entry that is not a well-formed clip", () => {
|
||||
const { mgr } = makeSealedManager();
|
||||
mgr.setupFromList(
|
||||
[
|
||||
{ kind: "audio", start: 0 },
|
||||
{ ...clip("https://films.test/f/a.m4a"), start: Number.NaN },
|
||||
"x",
|
||||
null,
|
||||
],
|
||||
film,
|
||||
);
|
||||
expect(mgr.entries).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("gives each clip on one file its own copy, and follows the list as it changes", () => {
|
||||
const { mgr } = makeSealedManager();
|
||||
mgr.setupFromList(
|
||||
[clip("https://films.test/f/a.m4a", 0), clip("https://films.test/f/a.m4a", 4)],
|
||||
film,
|
||||
);
|
||||
expect(mgr.entries.map((m) => m.start)).toEqual([0, 4]);
|
||||
const kept = mgr.entries[1];
|
||||
|
||||
mgr.setupFromList([clip("https://films.test/f/a.m4a", 4)], film);
|
||||
expect(mgr.entries).toEqual([kept]);
|
||||
});
|
||||
|
||||
it("mutes the film only once a copy is playing, not when the copy is made or told to play", () => {
|
||||
const { mgr, setFrameMuted } = makeSealedManager();
|
||||
|
||||
mgr.setupFromList([clip("https://films.test/f/a.m4a")], film);
|
||||
mgr.promoteToParentProxy();
|
||||
expect(setFrameMuted).not.toHaveBeenCalled();
|
||||
|
||||
becomes(mgr.entries[0]!.el, "playing");
|
||||
expect(setFrameMuted.mock.calls).toEqual([[true]]);
|
||||
});
|
||||
|
||||
it("gives the film its sound back when its last playing copy fails or is dropped", () => {
|
||||
const { mgr, setFrameMuted } = makeSealedManager();
|
||||
mgr.setupFromList(
|
||||
[clip("https://films.test/f/a.m4a"), clip("https://films.test/f/b.m4a")],
|
||||
film,
|
||||
);
|
||||
mgr.promoteToParentProxy();
|
||||
const [a, b] = mgr.entries.map((m) => m.el);
|
||||
becomes(a!, "playing");
|
||||
becomes(b!, "playing");
|
||||
|
||||
becomes(a!, "error");
|
||||
expect(setFrameMuted.mock.calls).toEqual([[true]]);
|
||||
|
||||
mgr.setupFromList([clip("https://films.test/f/a.m4a")], film);
|
||||
expect(setFrameMuted.mock.calls).toEqual([[true], [false]]);
|
||||
});
|
||||
|
||||
it("gives the film its sound back when the only copy still playing fails after the others stopped", () => {
|
||||
const { mgr, setFrameMuted } = makeSealedManager();
|
||||
mgr.setupFromList(
|
||||
["a", "b", "c"].map((f) => clip(`https://films.test/f/${f}.m4a`)),
|
||||
film,
|
||||
);
|
||||
mgr.promoteToParentProxy();
|
||||
const [a, b, c] = mgr.entries.map((m) => m.el);
|
||||
becomes(a!, "playing");
|
||||
becomes(b!, "playing");
|
||||
becomes(a!, "ended");
|
||||
becomes(c!, "playing");
|
||||
becomes(b!, "pause");
|
||||
|
||||
becomes(c!, "error");
|
||||
expect(setFrameMuted.mock.calls).toEqual([[true], [false]]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["before", true],
|
||||
["after", false],
|
||||
])(
|
||||
"gives the film its sound back when the next copy's play is refused, the old copy's pause event arriving %s the refusal",
|
||||
async (_order, pauseEventFirst) => {
|
||||
let now = 1;
|
||||
const setFrameMuted = vi.fn();
|
||||
const mgr = new ParentMediaManager({
|
||||
dispatchEvent: () => {},
|
||||
getMuted: () => false,
|
||||
getVolume: () => 1,
|
||||
getPlaybackRate: () => 1,
|
||||
getCurrentTime: () => now,
|
||||
isPaused: () => false,
|
||||
setFrameMuted,
|
||||
});
|
||||
mgr.setupFromList(
|
||||
[clip("https://films.test/f/a.m4a", 0), clip("https://films.test/f/b.m4a", 5)],
|
||||
film,
|
||||
);
|
||||
const [a, b] = mgr.entries.map((m) => m.el);
|
||||
let aPaused = true;
|
||||
Object.defineProperty(a, "paused", { get: () => aPaused });
|
||||
Object.defineProperty(a, "readyState", { get: () => 4 });
|
||||
a!.play = async () => {
|
||||
aPaused = false;
|
||||
};
|
||||
a!.pause = () => {
|
||||
aPaused = true;
|
||||
};
|
||||
b!.play = () => Promise.reject(new DOMException("refused", "NotAllowedError"));
|
||||
b!.pause = () => {};
|
||||
|
||||
mgr.promoteToParentProxy();
|
||||
a!.dispatchEvent(new Event("playing"));
|
||||
now = 6;
|
||||
mgr.mirrorTime(now, { force: true });
|
||||
if (pauseEventFirst) a!.dispatchEvent(new Event("pause"));
|
||||
await vi.waitFor(() => expect(setFrameMuted.mock.calls.length).toBeGreaterThan(1));
|
||||
if (!pauseEventFirst) a!.dispatchEvent(new Event("pause"));
|
||||
|
||||
expect(setFrameMuted.mock.calls).toEqual([[true], [false]]);
|
||||
mgr.destroy();
|
||||
},
|
||||
);
|
||||
|
||||
it("mutes an unsealed film's own media once a copy of it is playing", () => {
|
||||
const { mgr, setFrameMuted } = makeSealedManager();
|
||||
document.body.innerHTML = '<audio src="https://films.test/f/a.m4a" data-start="0"></audio>';
|
||||
mgr.setupFromIframe(document);
|
||||
mgr.promoteToParentProxy();
|
||||
expect(setFrameMuted).not.toHaveBeenCalled();
|
||||
|
||||
becomes(mgr.entries[0]!.el, "playing");
|
||||
expect(setFrameMuted.mock.calls).toEqual([[true]]);
|
||||
expect(document.querySelector("audio")!.muted).toBe(true);
|
||||
mgr.destroy();
|
||||
});
|
||||
|
||||
it("copies only what a render hears: no copy for a video marked as having no sound", () => {
|
||||
const { mgr } = makeSealedManager();
|
||||
document.body.innerHTML =
|
||||
'<video src="https://films.test/f/v.mp4" data-start="0" data-has-audio="false"></video>' +
|
||||
'<video src="https://films.test/f/w.mp4" data-start="0"></video>';
|
||||
mgr.setupFromIframe(document);
|
||||
expect(mgr.entries.map((m) => m.el.src)).toEqual(["https://films.test/f/w.mp4"]);
|
||||
mgr.destroy();
|
||||
});
|
||||
|
||||
it("never mutes the film for the player's own audio-src track alone", () => {
|
||||
const { mgr, setFrameMuted } = makeSealedManager();
|
||||
mgr.setupFromUrl("https://cdn.test/narration.mp3");
|
||||
mgr.promoteToParentProxy();
|
||||
becomes(mgr.entries[0]!.el, "playing");
|
||||
expect(setFrameMuted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("never copies from an opaque origin, even when the composition's own origin is opaque too", () => {
|
||||
const { mgr } = makeSealedManager();
|
||||
const opaque = [clip("data:audio/mp4;base64,AAAA"), clip("about:blank")];
|
||||
mgr.setupFromList(opaque, "about:blank");
|
||||
mgr.setupFromList(opaque, "data:audio/x,film");
|
||||
expect(mgr.entries).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,6 +14,7 @@ import { isRealmElement, isRealmHtmlMediaElement } from "./media-element-guards.
|
||||
import { isInClipWindow } from "@hyperframes/core/runtime/clip-window";
|
||||
import { readClipTiming } from "@hyperframes/core/composition-contract";
|
||||
import { readLinkTiming } from "@hyperframes/core/media-link";
|
||||
import { mediaFileOf, parentCopyOf, type ParentCopy } from "@hyperframes/core/audible-video";
|
||||
import { mediaElementTime, startsSoundOnlyInsideATap } from "@hyperframes/core/runtime/media-clock";
|
||||
import {
|
||||
MEDIA_SYNC_TOLERANCE_SECONDS,
|
||||
@@ -30,6 +31,8 @@ const SETTLED_OFFSET_DELTA_SECONDS = 0.004;
|
||||
*/
|
||||
const PRESEEK_SECONDS = 1.5;
|
||||
|
||||
const HAVE_FUTURE_DATA = 3;
|
||||
|
||||
export interface ProxyEntry {
|
||||
el: HTMLMediaElement;
|
||||
start: number;
|
||||
@@ -59,6 +62,9 @@ export class ParentMediaManager {
|
||||
* replaced or cleared instead of accumulating on every attribute change. */
|
||||
private _urlAudioEntry: ProxyEntry | null = null;
|
||||
private _urlAudioSrc: string | null = null;
|
||||
/** A sealed film's copies, keyed by the clip they play, from its runtime's list. */
|
||||
private _listed = new Map<string, ProxyEntry>();
|
||||
private _filmSilenced = false;
|
||||
|
||||
private readonly _dispatchEvent: (event: Event) => void;
|
||||
private readonly _getMuted: () => boolean;
|
||||
@@ -66,6 +72,7 @@ export class ParentMediaManager {
|
||||
private readonly _getPlaybackRate: () => number;
|
||||
private readonly _getCurrentTime: () => number;
|
||||
private readonly _isPaused: () => boolean;
|
||||
private readonly _setFrameMuted: (muted: boolean) => void;
|
||||
|
||||
constructor(opts: {
|
||||
dispatchEvent: (event: Event) => void;
|
||||
@@ -74,6 +81,8 @@ export class ParentMediaManager {
|
||||
getPlaybackRate: () => number;
|
||||
getCurrentTime: () => number;
|
||||
isPaused: () => boolean;
|
||||
/** Silences the film's own media while a copy plays it instead, and gives it back after. */
|
||||
setFrameMuted: (muted: boolean) => void;
|
||||
}) {
|
||||
this._dispatchEvent = opts.dispatchEvent;
|
||||
this._getMuted = opts.getMuted;
|
||||
@@ -81,6 +90,7 @@ export class ParentMediaManager {
|
||||
this._getPlaybackRate = opts.getPlaybackRate;
|
||||
this._getCurrentTime = opts.getCurrentTime;
|
||||
this._isPaused = opts.isPaused;
|
||||
this._setFrameMuted = opts.setFrameMuted;
|
||||
}
|
||||
|
||||
get audioOwner(): "runtime" | "parent" {
|
||||
@@ -99,8 +109,10 @@ export class ParentMediaManager {
|
||||
this.pauseAll();
|
||||
for (const m of this._entries) if (m !== this._urlAudioEntry) m.el.src = "";
|
||||
this._entries = this._urlAudioEntry ? [this._urlAudioEntry] : [];
|
||||
this._listed.clear();
|
||||
this._filmSilenced = false;
|
||||
if (this._urlAudioSrc && !this._urlAudioEntry)
|
||||
this._urlAudioEntry = this._createEntry(this._urlAudioSrc, "audio", 0, Infinity);
|
||||
this._urlAudioEntry = this._createEntry(urlAudio(this._urlAudioSrc));
|
||||
this.teardownObserver();
|
||||
if (wasPromoted) {
|
||||
this._dispatchEvent(
|
||||
@@ -118,6 +130,8 @@ export class ParentMediaManager {
|
||||
m.el.src = "";
|
||||
}
|
||||
this._entries = [];
|
||||
this._listed.clear();
|
||||
this._filmSilenced = false;
|
||||
this._urlAudioEntry = null;
|
||||
this._urlAudioSrc = null;
|
||||
this._audioOwner = "runtime";
|
||||
@@ -138,7 +152,10 @@ export class ParentMediaManager {
|
||||
|
||||
private _playEntry(m: ProxyEntry): void {
|
||||
if (!m.el.src) return;
|
||||
m.el.play().catch((err: unknown) => this._reportPlaybackError(err));
|
||||
m.el.play().catch((err: unknown) => {
|
||||
this._syncFrameMute();
|
||||
this._reportPlaybackError(err);
|
||||
});
|
||||
}
|
||||
|
||||
// Play only if the current playhead is inside the clip's (live) window, so
|
||||
@@ -234,9 +251,7 @@ export class ParentMediaManager {
|
||||
}
|
||||
|
||||
stopAdoptedMedia(): void {
|
||||
for (const m of this._entries) {
|
||||
if (m.source) m.el.pause();
|
||||
}
|
||||
for (const m of this._filmCopies()) m.el.pause();
|
||||
}
|
||||
|
||||
seekAll(timeInSeconds: number): void {
|
||||
@@ -305,32 +320,16 @@ export class ParentMediaManager {
|
||||
this._releaseSteering(m);
|
||||
}
|
||||
|
||||
/**
|
||||
* Take ownership of audible playback in response to the runtime's
|
||||
* `media-autoplay-blocked` signal. Idempotent.
|
||||
*
|
||||
* The caller is responsible for muting the iframe's own media output via the
|
||||
* postMessage bridge (`set-media-output-muted`) after calling this.
|
||||
*/
|
||||
/**
|
||||
* Take ownership of audible playback. Idempotent. The `onMirror` callback
|
||||
* is called with the current timeline time and `{ force: true }` so the
|
||||
* caller's mirror implementation runs (enabling test spies on the player
|
||||
* to fire). If omitted, `mirrorTime` is called directly.
|
||||
*/
|
||||
promoteToParentProxy(
|
||||
iframeDoc: Document | null,
|
||||
onMirror?: (t: number, opts: { force: boolean }) => void,
|
||||
): void {
|
||||
promoteToParentProxy(onMirror?: (t: number, opts: { force: boolean }) => void): void {
|
||||
if (this._audioOwner === "parent") return;
|
||||
this._audioOwner = "parent";
|
||||
|
||||
// Synchronously mute iframe media to close the race window.
|
||||
if (iframeDoc) {
|
||||
for (const el of iframeDoc.querySelectorAll("video, audio")) {
|
||||
if (isRealmHtmlMediaElement(el)) el.muted = true;
|
||||
}
|
||||
}
|
||||
for (const m of [...this._entries]) this._repointToSource(m);
|
||||
|
||||
// One-shot alignment — bypass jitter-coalescing gate.
|
||||
@@ -367,7 +366,7 @@ export class ParentMediaManager {
|
||||
setupFromUrl(audioSrc: string): void {
|
||||
if (this._urlAudioSrc === audioSrc && this._urlAudioEntry) return;
|
||||
this.teardownUrlAudio();
|
||||
const entry = this._createEntry(audioSrc, "audio", 0, Infinity);
|
||||
const entry = this._urlTaken(audioSrc) ? null : this._createEntry(urlAudio(audioSrc));
|
||||
// Null when the composition already has a proxy for this URL: that one stays the
|
||||
// composition's, and a reset creates ours once that document's proxies are gone.
|
||||
this._urlAudioEntry = entry;
|
||||
@@ -407,25 +406,43 @@ export class ParentMediaManager {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a parent-frame media element and start preloading it. A URL-driven
|
||||
* proxy returns `null` when the file already has one; a clip always gets its
|
||||
* own, since its window and media offset are its own.
|
||||
*/
|
||||
private _createEntry(
|
||||
src: string,
|
||||
tag: "audio" | "video",
|
||||
start: number,
|
||||
duration: number,
|
||||
source?: HTMLMediaElement | null,
|
||||
): ProxyEntry | null {
|
||||
if (!source && this._urlTaken(src)) return null;
|
||||
/** Copies for a sealed film, from its runtime's list: only files under the composition's own folder. */
|
||||
setupFromList(list: unknown, compositionUrl: string | null): void {
|
||||
const wanted = new Map<string, ParentCopy>();
|
||||
const refused: string[] = [];
|
||||
for (const copy of readCopies(list)) {
|
||||
const src = underComposition(copy.src, compositionUrl);
|
||||
if (src) wanted.set(JSON.stringify(copy), { ...copy, src });
|
||||
else refused.push(copy.src);
|
||||
}
|
||||
for (const [key, entry] of this._listed) {
|
||||
if (wanted.has(key)) continue;
|
||||
this._removeEntry(entry);
|
||||
this._listed.delete(key);
|
||||
}
|
||||
for (const [key, copy] of wanted) {
|
||||
if (this._listed.has(key)) continue;
|
||||
const entry = this._createEntry(copy, null, "anonymous");
|
||||
this._listed.set(key, entry);
|
||||
this._copyAdded(entry);
|
||||
}
|
||||
if (refused.length === 0) return;
|
||||
const error = new Error("a sealed film's media outside the composition's folder is not copied");
|
||||
this._dispatchEvent(
|
||||
new CustomEvent("playbackerror", { detail: { source: "parent-proxy", error, refused } }),
|
||||
);
|
||||
}
|
||||
|
||||
const el = tag === "video" ? document.createElement("video") : new Audio();
|
||||
/** Create a parent-frame media element and start preloading it. */
|
||||
private _createEntry(
|
||||
copy: ParentCopy,
|
||||
source?: HTMLMediaElement | null,
|
||||
crossOrigin = source?.getAttribute("crossorigin") ?? null,
|
||||
): ProxyEntry {
|
||||
const el = copy.kind === "video" ? document.createElement("video") : new Audio();
|
||||
el.preload = "auto";
|
||||
const crossOrigin = source?.getAttribute("crossorigin");
|
||||
if (crossOrigin != null) el.setAttribute("crossorigin", crossOrigin);
|
||||
el.src = src;
|
||||
el.src = copy.src;
|
||||
el.load();
|
||||
el.muted = this._getMuted();
|
||||
el.volume = this._getVolume();
|
||||
@@ -434,50 +451,53 @@ export class ParentMediaManager {
|
||||
|
||||
const entry: ProxyEntry = {
|
||||
el,
|
||||
start,
|
||||
duration,
|
||||
mediaStart: source ? readLinkTiming(source).mediaStart : 0,
|
||||
start: copy.start,
|
||||
duration: copy.duration,
|
||||
mediaStart: copy.mediaStart,
|
||||
source,
|
||||
};
|
||||
el.addEventListener("seeked", () => this._noteSeekLanded(entry));
|
||||
for (const change of ["playing", "waiting", "pause", "ended", "error"])
|
||||
el.addEventListener(change, () => this._syncFrameMute());
|
||||
this._entries.push(entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
/** Resolve an iframe media element's source to an absolute URL, or null. */
|
||||
private _resolveIframeMediaSrc(iframeEl: HTMLMediaElement): string | null {
|
||||
const rawSrc =
|
||||
iframeEl.getAttribute("src") || iframeEl.querySelector("source")?.getAttribute("src");
|
||||
return rawSrc ? new URL(rawSrc, iframeEl.ownerDocument.baseURI).href : null;
|
||||
/** Every copy of the film's own media: all but the player's `audio-src` track. */
|
||||
private _filmCopies(): ProxyEntry[] {
|
||||
return this._entries.filter((m) => m !== this._urlAudioEntry);
|
||||
}
|
||||
|
||||
// fallow-ignore-next-line complexity
|
||||
private _adoptIframeMedia(iframeEl: HTMLMediaElement): void {
|
||||
// Skip elements the preloader has demoted: the observer adopts one when its preload turns
|
||||
// "auto" and drops its proxy, which fetches the whole file, when it turns back.
|
||||
if (iframeEl.preload === "metadata" || iframeEl.preload === "none") return;
|
||||
|
||||
if (this._entries.some((m) => m.source === iframeEl)) return;
|
||||
|
||||
// A video authored muted is picture only: its file's audio belongs to the clip that plays it.
|
||||
if (iframeEl.tagName === "VIDEO" && iframeEl.hasAttribute("muted")) return;
|
||||
|
||||
const src = this._resolveIframeMediaSrc(iframeEl);
|
||||
if (!src) return;
|
||||
|
||||
const timing = readClipTiming(iframeEl);
|
||||
const start = timing.start ?? 0;
|
||||
const duration = timing.duration ?? Number.POSITIVE_INFINITY;
|
||||
const tag = iframeEl.tagName === "VIDEO" ? ("video" as const) : ("audio" as const);
|
||||
|
||||
const created = this._createEntry(src, tag, start, duration, iframeEl);
|
||||
|
||||
// If already under parent ownership and playing, the new proxy must catch
|
||||
// up immediately — bypass the jitter-coalescing gate.
|
||||
if (created && this._audioOwner === "parent") {
|
||||
this.mirrorTime(this._getCurrentTime(), { force: true });
|
||||
if (!this._isPaused()) this._playEntryIfActive(created);
|
||||
// The film is silent exactly while a copy of its media is heard instead, read from each
|
||||
// copy's own state so the order its events arrive in cannot leave the film muted.
|
||||
private _syncFrameMute(): void {
|
||||
const heard =
|
||||
this._audioOwner === "parent" &&
|
||||
this._filmCopies().some(
|
||||
({ el }) => !el.paused && !el.ended && !el.error && el.readyState >= HAVE_FUTURE_DATA,
|
||||
);
|
||||
if (heard === this._filmSilenced) return;
|
||||
this._filmSilenced = heard;
|
||||
const frameDoc = this._entries.find((m) => m.source)?.source?.ownerDocument;
|
||||
if (heard) {
|
||||
for (const el of frameDoc?.querySelectorAll("video, audio") ?? []) {
|
||||
if (isRealmHtmlMediaElement(el)) el.muted = true;
|
||||
}
|
||||
}
|
||||
this._setFrameMuted(heard);
|
||||
}
|
||||
|
||||
// A copy made while the parent owns playback catches up at once, past the jitter gate.
|
||||
private _copyAdded(entry: ProxyEntry): void {
|
||||
if (this._audioOwner !== "parent") return;
|
||||
this.mirrorTime(this._getCurrentTime(), { force: true });
|
||||
if (!this._isPaused()) this._playEntryIfActive(entry);
|
||||
}
|
||||
|
||||
private _adoptIframeMedia(iframeEl: HTMLMediaElement): void {
|
||||
if (this._entries.some((m) => m.source === iframeEl)) return;
|
||||
const copy = parentCopyOf(iframeEl);
|
||||
if (copy) this._copyAdded(this._createEntry(copy, iframeEl));
|
||||
}
|
||||
|
||||
// The runtime re-points a clip (its preview copy, a new bound file). A proxy that is not
|
||||
@@ -495,12 +515,12 @@ export class ParentMediaManager {
|
||||
private _urlTaken(src: string): boolean {
|
||||
return this._entries.some((m) => {
|
||||
if (m.source && !m.source.isConnected) return false;
|
||||
return ((m.source && this._resolveIframeMediaSrc(m.source)) || m.el.src) === src;
|
||||
return ((m.source && mediaFileOf(m.source)) || m.el.src) === src;
|
||||
});
|
||||
}
|
||||
|
||||
private _repointToSource(entry: ProxyEntry): boolean {
|
||||
const src = entry.source ? this._resolveIframeMediaSrc(entry.source) : null;
|
||||
const src = entry.source ? mediaFileOf(entry.source) : null;
|
||||
if (!src || entry.el.src === src) return false;
|
||||
entry.el.src = src;
|
||||
entry.el.load();
|
||||
@@ -516,6 +536,7 @@ export class ParentMediaManager {
|
||||
entry.el.pause();
|
||||
entry.el.src = "";
|
||||
this._entries.splice(this._entries.indexOf(entry), 1);
|
||||
this._syncFrameMute();
|
||||
}
|
||||
|
||||
private _observeDynamicMedia(doc: Document): void {
|
||||
@@ -595,3 +616,44 @@ export class ParentMediaManager {
|
||||
this._mediaObserver = obs;
|
||||
}
|
||||
}
|
||||
|
||||
function urlAudio(src: string): ParentCopy {
|
||||
return { kind: "audio", src, start: 0, duration: Number.POSITIVE_INFINITY, mediaStart: 0 };
|
||||
}
|
||||
|
||||
/** The well-formed clips of a list from the film; the frame is not trusted. */
|
||||
function readCopies(list: unknown): ParentCopy[] {
|
||||
if (!Array.isArray(list)) return [];
|
||||
return list.filter((item): item is ParentCopy => {
|
||||
if (typeof item !== "object" || item === null) return false;
|
||||
const c = item as Record<string, unknown>;
|
||||
return (
|
||||
(c.kind === "audio" || c.kind === "video") &&
|
||||
typeof c.src === "string" &&
|
||||
Number.isFinite(c.start) &&
|
||||
typeof c.duration === "number" &&
|
||||
c.duration >= 0 &&
|
||||
Number.isFinite(c.mediaStart)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** The file's address on the composition's own origin when it is under its folder; otherwise null. */
|
||||
function underComposition(src: string, compositionUrl: string | null): string | null {
|
||||
if (!compositionUrl) return null;
|
||||
try {
|
||||
const file = new URL(src);
|
||||
const base = new URL(compositionUrl);
|
||||
const web = /^https?:$/;
|
||||
if (!web.test(file.protocol) || !web.test(base.protocol)) return null;
|
||||
const folder = base.pathname.slice(0, base.pathname.lastIndexOf("/") + 1);
|
||||
if (file.origin !== base.origin || !file.pathname.startsWith(folder)) return null;
|
||||
const parts = file.pathname.slice(folder.length).split("/").map(decodeURIComponent);
|
||||
if (parts.some((part) => /[/\\]/.test(part) || part === "." || part === "..")) return null;
|
||||
const path = parts.map(encodeURIComponent).join("/");
|
||||
const query = file.search ? "?" + file.search.slice(1) : "";
|
||||
return base.origin + folder + path + query;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,12 @@ const makeCallbacks = (): MessageHandlerCallbacks => ({
|
||||
seek: vi.fn(),
|
||||
play: vi.fn(),
|
||||
getLoop: vi.fn(() => false),
|
||||
media: { mirrorTime: vi.fn(), promoteToParentProxy: vi.fn() } as unknown as ParentMediaManager,
|
||||
media: {
|
||||
mirrorTime: vi.fn(),
|
||||
promoteToParentProxy: vi.fn(),
|
||||
setupFromList: vi.fn(),
|
||||
} as unknown as ParentMediaManager,
|
||||
getCompositionUrl: vi.fn(() => null),
|
||||
getPlaybackState: vi.fn(() => ({ currentTime: 0, duration: 0, paused: true, lastUpdateMs: 0 })),
|
||||
setPlaybackState: vi.fn(),
|
||||
setScenes: vi.fn(),
|
||||
@@ -121,16 +126,43 @@ describe("handleRuntimeMessage media autoplay fallback", () => {
|
||||
data: { source: "hf-preview", type: "media-autoplay-blocked" },
|
||||
}) as unknown as MessageEvent;
|
||||
|
||||
it("promotes and mutes iframe output by default", () => {
|
||||
it("promotes, leaving the mute to the copies", () => {
|
||||
const frameWindow = {} as Window;
|
||||
const callbacks = makeCallbacks();
|
||||
|
||||
handleRuntimeMessage(autoplayBlockedEvent(frameWindow), frameWindow, callbacks);
|
||||
|
||||
expect(callbacks.media.promoteToParentProxy).toHaveBeenCalled();
|
||||
expect(callbacks.sendControl).toHaveBeenCalledWith("set-media-output-muted", {
|
||||
muted: true,
|
||||
});
|
||||
expect(callbacks.sendControl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("builds a sealed film's copies from the runtime's list, against the composition's own address", () => {
|
||||
const frameWindow = {} as Window;
|
||||
const callbacks = {
|
||||
...makeCallbacks(),
|
||||
getCompositionUrl: () => "https://films.test/f/index.html",
|
||||
};
|
||||
const media = [
|
||||
{ kind: "audio", src: "https://films.test/f/a.m4a", start: 0, duration: 5, mediaStart: 0 },
|
||||
];
|
||||
|
||||
handleRuntimeMessage(
|
||||
{
|
||||
source: frameWindow,
|
||||
data: { source: "hf-preview", type: "media-autoplay-blocked", media },
|
||||
} as unknown as MessageEvent,
|
||||
frameWindow,
|
||||
callbacks,
|
||||
);
|
||||
|
||||
expect(callbacks.media.setupFromList).toHaveBeenCalledWith(
|
||||
media,
|
||||
"https://films.test/f/index.html",
|
||||
);
|
||||
const order = (fn: unknown) => (fn as ReturnType<typeof vi.fn>).mock.invocationCallOrder[0]!;
|
||||
expect(order(callbacks.media.setupFromList)).toBeLessThan(
|
||||
order(callbacks.media.promoteToParentProxy),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not promote or mute iframe output when the host vetoes the fallback", () => {
|
||||
|
||||
@@ -41,6 +41,7 @@ export interface MessageHandlerCallbacks extends PlaybackStateCallbacks {
|
||||
setCompositionSize: (width: number, height: number) => void;
|
||||
sendControl: (action: string, extra?: Record<string, unknown>) => void;
|
||||
getIframeDoc: () => Document | null;
|
||||
getCompositionUrl: () => string | null;
|
||||
/** Invoked when the iframe runtime posts `{type: "ready"}` — the player
|
||||
* uses it to replay current bridge state (mute, volume, playback rate) so
|
||||
* control messages sent before the iframe's listener registered aren't lost. */
|
||||
@@ -160,10 +161,8 @@ export function handleRuntimeMessage(
|
||||
} catch {
|
||||
/* cross-origin */
|
||||
}
|
||||
callbacks.media.promoteToParentProxy(iframeDoc, (t, opts) =>
|
||||
callbacks.media.mirrorTime(t, opts),
|
||||
);
|
||||
callbacks.sendControl("set-media-output-muted", { muted: true });
|
||||
if (!iframeDoc) callbacks.media.setupFromList(data["media"], callbacks.getCompositionUrl());
|
||||
callbacks.media.promoteToParentProxy((t, opts) => callbacks.media.mirrorTime(t, opts));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -569,6 +569,7 @@ describe("handleRuntimeMessage scenes seam", () => {
|
||||
setCompositionSize: () => {},
|
||||
sendControl: () => {},
|
||||
getIframeDoc: () => null,
|
||||
getCompositionUrl: () => null,
|
||||
onRuntimeReady: () => {},
|
||||
onRuntimeTimelineReady: () => {},
|
||||
setScenes,
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { launchBrowser } from "../perf/runner.js";
|
||||
import { startServer } from "../perf/server.js";
|
||||
|
||||
const server = startServer();
|
||||
const browser = await launchBrowser({ autoplay: "gesture" });
|
||||
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
await page.goto(`${server.origin}/host.html?fixture=sealed-audio`, {
|
||||
waitUntil: "domcontentloaded",
|
||||
});
|
||||
await page.waitForFunction(() => window.__playerReady || window.__playerError, {
|
||||
timeout: 60_000,
|
||||
});
|
||||
await page.evaluate(() => {
|
||||
const player = document.getElementById("player")!;
|
||||
player.removeAttribute("muted");
|
||||
window.__playerReady = false;
|
||||
player.setAttribute("sandbox-origin", "opaque");
|
||||
});
|
||||
await page.waitForFunction(() => window.__playerReady || window.__playerError, {
|
||||
timeout: 60_000,
|
||||
});
|
||||
type Player = HTMLElement & {
|
||||
play: () => void;
|
||||
_audioOwner: string;
|
||||
_parentMedia: { el: HTMLMediaElement }[];
|
||||
};
|
||||
await page.evaluate(() => (document.getElementById("player") as Player).play());
|
||||
await page.waitForFunction(
|
||||
() => (document.getElementById("player") as Player)._audioOwner === "parent",
|
||||
{ timeout: 30_000 },
|
||||
);
|
||||
const copies = await page.evaluate(() =>
|
||||
(document.getElementById("player") as Player)._parentMedia.map((m) => m.el.src),
|
||||
);
|
||||
assert.deepEqual(
|
||||
copies,
|
||||
[`${server.origin}/fixtures/sealed-audio/tone.m4a`],
|
||||
"a sealed player loaded by src copies its film's sound into the page when the frame may not start it",
|
||||
);
|
||||
console.log("[sealed-audio] a refused sealed frame's sound plays from a copy in the page");
|
||||
} finally {
|
||||
await browser.close();
|
||||
await server.stop();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>perf fixture: sealed-audio</title>
|
||||
<script src="/vendor/gsap.min.js"></script>
|
||||
<script data-hyperframes-runtime="1" src="/vendor/hyperframe.runtime.iife.js"></script>
|
||||
</head>
|
||||
<body style="margin: 0; background: #050714">
|
||||
<div
|
||||
id="root"
|
||||
data-composition-id="main"
|
||||
data-width="640"
|
||||
data-height="360"
|
||||
data-duration="4"
|
||||
data-fps="30"
|
||||
>
|
||||
<div id="card" style="width: 640px; height: 360px; background: #2a6"></div>
|
||||
<audio id="tone" src="tone.m4a" data-start="0" data-duration="4" preload="auto"></audio>
|
||||
</div>
|
||||
<script>
|
||||
var tl = gsap.timeline({ paused: true });
|
||||
tl.fromTo("#card", { opacity: 0.5 }, { opacity: 1, duration: 4 }, 0);
|
||||
window.__timelines = window.__timelines || {};
|
||||
window.__timelines["main"] = tl;
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
@@ -10,6 +10,8 @@ export type LaunchOpts = {
|
||||
width?: number;
|
||||
height?: number;
|
||||
headless?: boolean;
|
||||
/** "gesture": Chrome's own rule, where a frame without a tap may not start sound. */
|
||||
autoplay?: "free" | "gesture";
|
||||
};
|
||||
|
||||
export type LoadOpts = {
|
||||
@@ -84,7 +86,7 @@ export async function launchBrowser(options: LaunchOpts = {}): Promise<Browser>
|
||||
"--use-angle=swiftshader",
|
||||
"--font-render-hinting=none",
|
||||
"--force-color-profile=srgb",
|
||||
"--autoplay-policy=no-user-gesture-required",
|
||||
`--autoplay-policy=${options.autoplay === "gesture" ? "user-gesture-required" : "no-user-gesture-required"}`,
|
||||
`--window-size=${width},${height}`,
|
||||
],
|
||||
};
|
||||
|
||||
@@ -194,7 +194,10 @@ export function startServer(options: ServeOptions = {}): RunningServer {
|
||||
if (!filePath.startsWith(PATHS.fixturesDir)) {
|
||||
return new Response("Forbidden", { status: 403 });
|
||||
}
|
||||
return applyCacheHeaders(await readBunFile(filePath), noCache);
|
||||
const res = applyCacheHeaders(await readBunFile(filePath), noCache);
|
||||
// A sealed film has an opaque origin, so it reads its own media as from a CORS host.
|
||||
res.headers.set("Access-Control-Allow-Origin", "*");
|
||||
return res;
|
||||
}
|
||||
|
||||
return new Response("Not found", { status: 404 });
|
||||
|
||||
Reference in New Issue
Block a user