Files
Echoion/EchoionWeb/frontend/src/lib/embedProtocols.ts
T
faumaray 24fecc90f3 making WEB
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-11 00:47:52 +03:00

973 lines
29 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Adapters for postMessage-controllable embed players in the Watch view.
//
// A generic iframe can only be driven if the player inside exposes a
// postMessage API — everything else stays view-only by browser design.
// Protocols supported (each is one self-contained entry in EMBED_PROTOCOLS):
// - kodik: JSON *strings* like {key:'kodik_player_time_update', value:sec};
// commands {key:'kodik_player_api', value:{method}}.
// - vimeo: {method:'play'|...} strings; events {event:'timeupdate',
// data:{seconds,duration}}. Hostname-selected (player.vimeo.com).
// - rutube / dailymotion / vk: hostname-selected; some need opt-in URL
// params (prepareUrl) and their command/event shapes are community-
// documented — flagged VERIFY, one-line fixes if a live embed differs.
// - player.js (embedly spec): {context:'player.js', ...} — Wistia & co.
// - playerjs (playerjs.com, many CIS hosters): {api:'play'|...} commands,
// {event, answer} events.
// Shapes marked VERIFY are community-documented, not official; dev builds
// console.debug every unrecognized frame message to reverse-engineer them.
//
// Detection: for a hostname-matched player only that protocol is probed;
// otherwise the generic set is probed until one `parse` recognizes a message
// and locks the adapter. On timeout the embed is uncontrollable and the
// caller keeps today's host-driven view-only behavior.
export interface EmbedAdapter {
protocol: string;
// True for players (Kodik) driven by reloading the iframe rather than
// postMessage commands: the caller should avoid drift-reconcile churn and
// not expect pause to work.
reloadBased: boolean;
play(): void;
pause(): void;
seekMs(ms: number): void;
setVolume(v01: number): void; // 0..1
positionMs(): number;
durationMs(): number;
paused(): boolean;
extras(): PlayerExtraControl[];
setExtra(id: string, value: string): void;
destroy(): void;
}
export interface ExtraControlOption {
value: string;
label: string;
}
export interface PlayerExtraControl {
id: string;
label: string;
kind: 'select' | 'button';
options: ExtraControlOption[];
current: string | null;
scope: 'local' | 'synced';
}
// Fired only for events NOT caused by our own commands (see suppression
// below) — i.e. gestures made inside the embed UI, which the host must relay
// to the room.
export interface EmbedCallbacks {
onPlay(positionMs: number): void;
onPause(positionMs: number): void;
onSeek(positionMs: number): void;
onDurationChange(durationMs: number): void;
onEnded(): void;
onExtraControls(controls: PlayerExtraControl[]): void;
}
export type EmbedEvent =
// `duration` piggybacks on time events for players (Vimeo, player.js, DM,
// VK) that bundle it into their timeupdate payload.
| { kind: 'time'; seconds: number; duration?: number }
| { kind: 'duration'; seconds: number }
| { kind: 'play' }
| { kind: 'pause' }
| { kind: 'ended' }
| { kind: 'extraList'; control: PlayerExtraControl }
| { kind: 'extraCurrent'; id: string; value: string }
// Recognized the protocol but the event carries no state we track; enough
// to lock detection.
| { kind: 'hello' };
export interface ProtocolDef {
name: string;
// Hostname-based selection: when a URL matches, only this protocol is
// probed (skips content-based detection). Left undefined for generic
// protocols detected purely by the messages they emit (kodik, player.js).
matchUrl?(url: string): boolean;
// Inject opt-in query params the player needs before the iframe loads
// (e.g. Dailymotion `?api=postMessage`, VK `?js_api=1`).
prepareUrl?(url: string): string;
// Some players (Kodik) expose no postMessage command API — the only way to
// seek is to reload the iframe at a start offset. When present, the adapter
// seeks by setting frame.src to this URL instead of posting a command.
reloadSeek?(currentSrc: string, seconds: number): string;
probe(win: Window): void;
parse(data: unknown): EmbedEvent | null;
play(win: Window): void;
pause(win: Window): void;
seek(win: Window, seconds: number): void;
volume(win: Window, v01: number): void;
probeExtras?(win: Window): void;
setExtra?(win: Window, id: string, value: string): void;
staticExtras?(url: string): PlayerExtraControl[];
}
// Embeds are served from many mirror domains (esp. Kodik), so the target
// origin can't be pinned; we never trust incoming data beyond parsing known
// shapes into numbers.
function post(win: Window, msg: unknown) {
try {
win.postMessage(msg, '*');
} catch {
/* frame navigating/gone */
}
}
const asNumber = (v: unknown): number =>
typeof v === 'number' ? v : Number(v);
// Embed URLs are absolute, so no base is needed; guard `location` so the
// helpers also work under the node test runner.
const baseHref = (): string | undefined =>
typeof location !== 'undefined' ? location.href : undefined;
function hostOf(url: string): string {
try {
return new URL(url, baseHref()).hostname.toLowerCase();
} catch {
return '';
}
}
function isHostOrSubdomain(host: string, domain: string): boolean {
return host === domain || host.endsWith(`.${domain}`);
}
function withParams(url: string, params: Record<string, string>): string {
try {
const u = new URL(url, baseHref());
for (const [k, v] of Object.entries(params)) {
if (!u.searchParams.has(k)) u.searchParams.set(k, v);
}
return u.toString();
} catch {
return url;
}
}
// Overwrite a single query param (preserves the rest, incl. Kodik's signed
// d_sign/ref_sign params).
function setParam(url: string, key: string, value: string): string {
try {
const u = new URL(url, baseHref());
u.searchParams.set(key, value);
return u.toString();
} catch {
return url;
}
}
// Normalize an object-or-JSON-string payload into a plain object, or null.
function asObj(data: unknown): Record<string, unknown> | null {
let obj: unknown = data;
if (typeof data === 'string') {
const s = data.trim();
if (!s.startsWith('{') && !s.startsWith('[')) return null;
try {
obj = JSON.parse(s);
} catch {
return null;
}
}
return obj && typeof obj === 'object'
? (obj as Record<string, unknown>)
: null;
}
function toOptions(value: unknown): ExtraControlOption[] {
const entries = Array.isArray(value)
? value.map((item, index) => [String(index), item] as const)
: value && typeof value === 'object'
? Object.entries(value as Record<string, unknown>)
: [];
return entries.flatMap(([fallback, item]) => {
if (item && typeof item === 'object') {
const option = item as Record<string, unknown>;
const raw = option.value ?? option.id ?? option.index ?? fallback;
const label = option.label ?? option.name ?? option.title ?? raw;
return [{ value: String(raw), label: String(label) }];
}
return item == null
? []
: [{ value: fallback, label: String(item) }];
});
}
function extraControl(
id: string,
label: string,
scope: PlayerExtraControl['scope'],
options: ExtraControlOption[],
current: string | null = null
): PlayerExtraControl {
return { id, label, scope, options, current, kind: 'select' };
}
const kodik: ProtocolDef = {
name: 'kodik',
// Kodik (kodikplayer.com and its mirrors). Hostname-pinned so it always
// locks as `kodik` and never falls back to view-only.
matchUrl: (url) => {
const host = hostOf(url);
return ['kodik.info', 'kodik.cc', 'kodik.biz', 'kodik.online', 'kodikplayer.com']
.some((domain) => isHostOrSubdomain(host, domain));
},
// Kodik has NO postMessage command API — the only way to seek is to reload
// the iframe at a start offset (preserving its signed params). start_from
// auto-resumes playback from that second.
reloadSeek: (src, seconds) =>
setParam(src, 'start_from', String(Math.max(0, Math.floor(seconds)))),
probe(win) {
// Community-documented; harmless if ignored by the player.
post(win, { key: 'kodik_player_api', value: { method: 'get_duration' } });
post(win, { key: 'kodik_player_api', value: { method: 'get_time' } });
},
parse(data) {
let obj: unknown = data;
if (typeof data === 'string') {
if (!data.includes('kodik_player')) return null;
try {
obj = JSON.parse(data);
} catch {
return null;
}
}
const m = obj as { key?: unknown; value?: unknown } | null;
if (!m || typeof m.key !== 'string' || !m.key.startsWith('kodik_player')) {
return null;
}
const n = asNumber(m.value);
switch (m.key) {
case 'kodik_player_time_update':
case 'kodik_player_current_time':
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
case 'kodik_player_duration_update':
case 'kodik_player_duration':
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
case 'kodik_player_play':
return { kind: 'play' };
case 'kodik_player_pause':
return { kind: 'pause' };
case 'kodik_player_video_ended':
return { kind: 'ended' };
default:
// Unmapped kodik_player_* event — still unambiguously Kodik.
return { kind: 'hello' };
}
},
play: (win) => post(win, { key: 'kodik_player_api', value: { method: 'play' } }),
pause: (win) => post(win, { key: 'kodik_player_api', value: { method: 'pause' } }),
seek: (win, seconds) =>
post(win, { key: 'kodik_player_api', value: { method: 'seek', seconds } }),
volume: (win, v01) =>
post(win, {
key: 'kodik_player_api',
value: { method: 'change_volume', volume: v01 },
}),
};
const playerjs: ProtocolDef = {
name: 'playerjs',
probe(win) {
post(win, { api: 'duration' });
post(win, { api: 'time' });
},
probeExtras(win) {
for (const api of ['qualities', 'audiotracks', 'subtitles']) {
post(win, { api });
}
},
staticExtras() {
return [
extraControl(
'speed',
'Speed',
'synced',
[0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map((speed) => ({
value: String(speed),
label: `${speed}×`,
})),
'1'
),
];
},
parse(data) {
let obj: unknown = data;
if (typeof data === 'string') {
if (!data.startsWith('{')) return null;
try {
obj = JSON.parse(data);
} catch {
return null;
}
}
const m = obj as
| { event?: unknown; answer?: unknown; context?: unknown }
| null;
if (!m || typeof m.event !== 'string') return null;
// A {context:'player.js'} message belongs to the embedly spec adapter,
// not this one.
if (m.context === 'player.js') return null;
const n = asNumber(m.answer);
// Only lock on events Playerjs actually emits — a bare {event:...}
// could belong to some other player's protocol.
switch (m.event) {
case 'qualities':
return {
kind: 'extraList',
control: extraControl(
'quality',
'Quality',
'local',
toOptions(m.answer)
),
};
case 'audiotracks':
return {
kind: 'extraList',
control: extraControl(
'audiotrack',
'Voiceover',
'synced',
toOptions(m.answer)
),
};
case 'subtitles':
return {
kind: 'extraList',
control: extraControl(
'subtitle',
'Subtitles',
'local',
[
{ value: '-1', label: 'Off' },
...toOptions(m.answer),
]
),
};
case 'episodes':
return {
kind: 'extraList',
control: extraControl(
'episode',
'Episode',
'synced',
toOptions(m.answer)
),
};
case 'quality':
case 'audiotrack':
case 'subtitle':
case 'speed':
case 'episode':
return {
kind: 'extraCurrent',
id: m.event,
value: String(m.answer ?? ''),
};
case 'time':
case 'updatetime':
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
case 'duration':
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
case 'play':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'end':
case 'ended':
return { kind: 'ended' };
case 'init':
case 'inited':
case 'ready':
case 'volume':
return { kind: 'hello' };
default:
return null;
}
},
play: (win) => post(win, { api: 'play' }),
pause: (win) => post(win, { api: 'pause' }),
seek: (win, seconds) => post(win, { api: 'seek', set: seconds }),
volume: (win, v01) => post(win, { api: 'volume', set: v01 }),
setExtra: (win, id, value) => {
if (!['quality', 'audiotrack', 'subtitle', 'speed', 'episode', 'next', 'prev'].includes(id)) {
return;
}
post(win, { api: id, set: value });
},
};
const alloha: ProtocolDef = {
...playerjs,
name: 'alloha',
matchUrl: (url) =>
['alloha.tv', 'alloha.video', 'alloha.online', 'allarknow.online'].some(
(domain) => isHostOrSubdomain(hostOf(url), domain)
),
};
// Vimeo (vimeo/player.js): well documented. Selected by hostname; disambiguated
// from playerjs.com by carrying `data`, not `answer`.
const vimeo: ProtocolDef = {
name: 'vimeo',
matchUrl: (url) => /(^|\.)vimeo\.com$/.test(hostOf(url)),
// Our overlay bar is the only control surface, so hide Vimeo's native chrome.
prepareUrl: (url) =>
withParams(url, {
controls: '0',
title: '0',
byline: '0',
portrait: '0',
}),
probe(win) {
for (const ev of ['timeupdate', 'play', 'pause', 'ended']) {
post(win, JSON.stringify({ method: 'addEventListener', value: ev }));
}
post(win, JSON.stringify({ method: 'getDuration' }));
},
probeExtras(win) {
post(win, JSON.stringify({ method: 'getQualities' }));
},
parse(data) {
const m = asObj(data);
if (!m) return null;
if (m.method === 'getDuration') {
const n = asNumber(m.value);
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
}
if (m.method === 'getQualities') {
return {
kind: 'extraList',
control: extraControl(
'quality',
'Quality',
'local',
toOptions(m.value)
),
};
}
if (typeof m.event !== 'string') return null;
if ('answer' in m) return null; // that's a playerjs.com message
const d = (m.data ?? {}) as { seconds?: unknown; duration?: unknown };
switch (m.event) {
case 'timeupdate': {
const sec = asNumber(d.seconds);
const dur = asNumber(d.duration);
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
}
case 'play':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'ended':
case 'finish':
return { kind: 'ended' };
case 'ready':
case 'loaded':
return { kind: 'hello' };
default:
return null; // bare {event} without vimeo markers → not ours
}
},
play: (w) => post(w, JSON.stringify({ method: 'play' })),
pause: (w) => post(w, JSON.stringify({ method: 'pause' })),
seek: (w, s) =>
post(w, JSON.stringify({ method: 'setCurrentTime', value: s })),
volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', value: v })),
setExtra: (w, id, value) => {
if (id === 'quality') {
post(w, JSON.stringify({ method: 'setQuality', value }));
}
},
};
// embedly player.js SPEC (github.com/embedly/player.js): the `context` field
// makes every message unambiguous. Generic (no matchUrl) — covers Wistia etc.
const PJS = { context: 'player.js', version: '0.0.11' } as const;
const playerjsSpec: ProtocolDef = {
name: 'player.js',
probe(win) {
for (const ev of ['timeupdate', 'play', 'pause', 'ended']) {
post(win, {
...PJS,
method: 'addEventListener',
listener: `ec_${ev}`,
value: ev,
});
}
},
parse(data) {
const m = asObj(data);
if (!m || m.context !== 'player.js' || typeof m.event !== 'string') {
return null;
}
const v = (m.value ?? {}) as { seconds?: unknown; duration?: unknown };
switch (m.event) {
case 'timeupdate': {
const sec = asNumber(v.seconds);
const dur = asNumber(v.duration);
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
}
case 'play':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'ended':
return { kind: 'ended' };
default:
return { kind: 'hello' }; // any context:'player.js' event is ours
}
},
play: (w) => post(w, { ...PJS, method: 'play' }),
pause: (w) => post(w, { ...PJS, method: 'pause' }),
seek: (w, s) => post(w, { ...PJS, method: 'setCurrentTime', value: s }),
volume: (w, v) => post(w, { ...PJS, method: 'setVolume', value: v }),
};
// Rutube (RutubePlayerJSAPI). VERIFY command/subscribe shapes on a live embed.
const rutube: ProtocolDef = {
name: 'rutube',
matchUrl: (url) => /(^|\.)rutube\.ru$/.test(hostOf(url)),
probe(win) {
// Rutube emits events only after an explicit subscribe. VERIFY payload.
post(win, JSON.stringify({ type: 'player:subscribe', data: {} }));
},
parse(data) {
const m = asObj(data);
if (!m || typeof m.type !== 'string' || !m.type.startsWith('player:')) {
return null;
}
const d = (m.data ?? {}) as {
time?: unknown;
duration?: unknown;
state?: unknown;
};
switch (m.type) {
case 'player:currentTime': {
const n = asNumber(d.time);
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
}
case 'player:durationChange': {
const n = asNumber(d.duration);
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
}
case 'player:changeState': {
const st = String(d.state);
if (st === 'playing') return { kind: 'play' };
if (st === 'paused' || st === 'stopped') return { kind: 'pause' };
if (st === 'ended') return { kind: 'ended' };
return { kind: 'hello' };
}
default:
return { kind: 'hello' }; // player:* is unambiguously Rutube
}
},
play: (w) => post(w, JSON.stringify({ type: 'player:play', data: {} })),
pause: (w) => post(w, JSON.stringify({ type: 'player:pause', data: {} })),
seek: (w, s) =>
post(w, JSON.stringify({ type: 'player:setCurrentTime', data: { time: s } })),
volume: (w, v) =>
post(w, JSON.stringify({ type: 'player:setVolume', data: { volume: v } })),
};
// Dailymotion classic embed (?api=postMessage → querystring events). VERIFY;
// the newer geo.dailymotion.com SDK uses JSON — add a branch here if needed.
const dailymotion: ProtocolDef = {
name: 'dailymotion',
matchUrl: (url) => /(^|\.)(dailymotion\.com|dai\.ly)$/.test(hostOf(url)),
// api=postMessage enables control; controls=0 + ui-* hide the native chrome
// (our overlay bar drives playback instead).
prepareUrl: (url) =>
withParams(url, {
api: 'postMessage',
controls: '0',
'ui-start-screen-info': 'false',
'ui-logo': 'false',
}),
probe() {
/* classic embed auto-emits once api=postMessage is set */
},
parse(data) {
if (typeof data !== 'string' || !data.includes('event=')) return null;
const p = new URLSearchParams(data);
const ev = p.get('event');
if (!ev) return null;
const sec = Number(p.get('time'));
const dur = Number(p.get('duration'));
switch (ev) {
case 'timeupdate':
case 'progress':
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
case 'durationchange':
return isFinite(dur) && dur > 0
? { kind: 'duration', seconds: dur }
: { kind: 'hello' };
case 'play':
case 'playing':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'video_end':
case 'ended':
return { kind: 'ended' };
default:
return { kind: 'hello' };
}
},
play: (w) => post(w, JSON.stringify({ command: 'play', parameters: [] })),
pause: (w) => post(w, JSON.stringify({ command: 'pause', parameters: [] })),
seek: (w, s) => post(w, JSON.stringify({ command: 'seek', parameters: [s] })),
volume: (w, v) =>
post(w, JSON.stringify({ command: 'setVolume', parameters: [v] })),
};
// VK Video (?js_api=1 → {type:'player_api', event}). VERIFY command shapes.
const vk: ProtocolDef = {
name: 'vk',
matchUrl: (url) => /(^|\.)(vk\.com|vkvideo\.ru|vk\.ru)$/.test(hostOf(url)),
prepareUrl: (url) => withParams(url, { js_api: '1' }),
probe(win) {
post(win, JSON.stringify({ method: 'addEventListener', event: '*' }));
},
parse(data) {
const m = asObj(data);
if (!m || m.type !== 'player_api' || typeof m.event !== 'string') {
return null;
}
const sec = asNumber(m.time ?? m.position);
const dur = asNumber(m.duration);
switch (m.event) {
case 'timeupdate':
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
case 'started':
case 'resumed':
return { kind: 'play' };
case 'paused':
return { kind: 'pause' };
case 'ended':
return { kind: 'ended' };
default:
return { kind: 'hello' }; // type:'player_api' is unambiguously VK
}
},
play: (w) => post(w, JSON.stringify({ method: 'play' })),
pause: (w) => post(w, JSON.stringify({ method: 'pause' })),
seek: (w, s) => post(w, JSON.stringify({ method: 'seek', time: s })),
volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', volume: v })),
};
// Hostname-selected protocols first (they're picked by URL, never by content);
// then the generic set probed by the messages they emit — kodik first (its
// keys are unambiguous), the embedly spec before the looser playerjs.com.
// Exported for the parse unit tests.
export const EMBED_PROTOCOLS: ProtocolDef[] = [
kodik,
alloha,
vimeo,
rutube,
dailymotion,
vk,
playerjsSpec,
playerjs,
];
// Inject any opt-in params a hostname-matched player needs, before iframe.src.
export function prepareEmbedUrl(url: string): string {
const p = EMBED_PROTOCOLS.find((x) => x.matchUrl?.(url));
// Signed players such as Kodik depend on their own origin for scripts,
// AJAX, cookies and anti-abuse checks. Keep them on the provider origin;
// Echoion controls them only through their postMessage surface.
return p?.prepareUrl ? p.prepareUrl(url) : url;
}
const PROBE_INTERVAL_MS = 750;
// Commands are echoed back as events by the player; ignore relay callbacks
// for this long after each command we send.
const SUPPRESS_MS = 800;
// A time event this far off the extrapolated position counts as a user seek.
const SEEK_JUMP_SEC = 2.5;
// Minimum gap between reload-based (Kodik) iframe reloads.
const RELOAD_DEBOUNCE_MS = 4000;
export function detectEmbedAdapter(
frame: HTMLIFrameElement,
cb: EmbedCallbacks,
timeoutMs = 5000
): Promise<EmbedAdapter | null> {
return new Promise((resolve) => {
let locked: ProtocolDef | null = null;
// A hostname-matched player is probed alone; otherwise probe the
// generic (content-detected) set. frame.src is the prepared URL.
const matched =
EMBED_PROTOCOLS.find((p) => p.matchUrl?.(frame.src)) ?? null;
const probeSet = matched
? [matched]
: EMBED_PROTOCOLS.filter((p) => !p.matchUrl);
// Normalized player state. Embeds push time updates rather than expose
// getters, so position is the last event extrapolated by wall clock.
let lastTimeSec = 0;
let lastTimeAt = performance.now();
let durationSec = 0;
let playing = false;
let suppressUntil = 0;
const extraControls = new Map<string, PlayerExtraControl>();
const positionMs = () =>
Math.floor(
(lastTimeSec +
(playing ? (performance.now() - lastTimeAt) / 1000 : 0)) *
1000
);
const suppressed = () => performance.now() < suppressUntil;
const applyEvent = (ev: EmbedEvent) => {
switch (ev.kind) {
case 'time': {
const jumped =
Math.abs(ev.seconds - positionMs() / 1000) >
SEEK_JUMP_SEC;
// Advancing time implies playing even when the protocol
// never sends an explicit play event.
const advancing = ev.seconds > lastTimeSec + 0.05;
lastTimeSec = ev.seconds;
lastTimeAt = performance.now();
// Some protocols bundle duration into the time event.
if (
ev.duration != null &&
Math.abs(ev.duration - durationSec) > 0.5
) {
durationSec = ev.duration;
cb.onDurationChange(Math.floor(ev.duration * 1000));
}
if (jumped && !suppressed()) {
cb.onSeek(Math.floor(ev.seconds * 1000));
}
if (!playing && advancing) {
playing = true;
if (!suppressed()) cb.onPlay(positionMs());
}
break;
}
case 'duration':
if (Math.abs(ev.seconds - durationSec) > 0.5) {
durationSec = ev.seconds;
cb.onDurationChange(Math.floor(ev.seconds * 1000));
}
break;
case 'play':
if (!playing) {
playing = true;
lastTimeAt = performance.now();
if (!suppressed()) cb.onPlay(positionMs());
}
break;
case 'pause':
if (playing) {
lastTimeSec = positionMs() / 1000;
playing = false;
if (!suppressed()) cb.onPause(positionMs());
}
break;
case 'ended':
playing = false;
cb.onEnded();
break;
case 'extraList':
if (ev.control.options.length > 0) {
extraControls.set(ev.control.id, ev.control);
cb.onExtraControls([...extraControls.values()]);
}
break;
case 'extraCurrent': {
const control = extraControls.get(ev.id);
if (control && control.current !== ev.value) {
extraControls.set(ev.id, { ...control, current: ev.value });
cb.onExtraControls([...extraControls.values()]);
}
break;
}
case 'hello':
break;
}
};
// contentWindow is read live on every use: it changes when the frame
// navigates, while ev.source comparison below stays valid because the
// browsing context object is stable for the life of the element.
const win = () => frame.contentWindow;
const makeAdapter = (p: ProtocolDef): EmbedAdapter => {
for (const control of p.staticExtras?.(frame.src) ?? []) {
extraControls.set(control.id, control);
}
if (extraControls.size > 0) {
cb.onExtraControls([...extraControls.values()]);
}
const probeExtras = () => {
const current = win();
if (current) p.probeExtras?.(current);
};
probeExtras();
const extraProbeTimers = [1500, 3000].map((delay) =>
window.setTimeout(probeExtras, delay)
);
// Reload-based (Kodik) seeking: replace frame.src at a start offset,
// debounced so drift-reconcile can't spam reloads (each reload
// re-buffers and may replay an ad).
let lastReloadAt = 0;
const reloadTo = (sec: number) => {
const now = performance.now();
if (now - lastReloadAt < RELOAD_DEBOUNCE_MS) return;
lastReloadAt = now;
suppressUntil = now + SUPPRESS_MS;
lastTimeSec = Math.max(0, sec);
lastTimeAt = now;
playing = true; // start_from auto-resumes
frame.src = p.reloadSeek!(frame.src, sec);
};
return {
protocol: p.name,
reloadBased: !!p.reloadSeek,
play() {
// Commands update state optimistically so positionMs()/paused()
// reflect intent immediately — otherwise the 3s sync heartbeat
// would fight the slow embed acknowledgement.
suppressUntil = performance.now() + SUPPRESS_MS;
playing = true;
lastTimeAt = performance.now();
if (p.reloadSeek) {
// No play command — resume by reloading at the current spot.
reloadTo(lastTimeSec);
return;
}
const w = win();
if (w) p.play(w);
},
pause() {
suppressUntil = performance.now() + SUPPRESS_MS;
lastTimeSec = positionMs() / 1000;
playing = false;
// Reload-based players (Kodik) have no pause — best-effort no-op.
if (p.reloadSeek) return;
const w = win();
if (w) p.pause(w);
},
seekMs(ms: number) {
if (p.reloadSeek) {
reloadTo(ms / 1000);
return;
}
suppressUntil = performance.now() + SUPPRESS_MS;
lastTimeSec = ms / 1000;
lastTimeAt = performance.now();
const w = win();
if (w) p.seek(w, ms / 1000);
},
setVolume(v01: number) {
const w = win();
if (w) p.volume(w, Math.max(0, Math.min(1, v01)));
},
extras: () => [...extraControls.values()],
setExtra(id, value) {
const control = extraControls.get(id);
if (!control || !p.setExtra) return;
suppressUntil = performance.now() + 1500;
extraControls.set(id, { ...control, current: value });
cb.onExtraControls([...extraControls.values()]);
const current = win();
if (current) p.setExtra(current, id, value);
},
positionMs,
durationMs: () => Math.floor(durationSec * 1000),
paused: () => !playing,
destroy() {
window.removeEventListener('message', handler);
clearInterval(probeTimer);
clearTimeout(giveUp);
for (const timer of extraProbeTimers) clearTimeout(timer);
},
};
};
const handler = (ev: MessageEvent) => {
if (ev.source !== frame.contentWindow) return;
if (locked) {
const e = locked.parse(ev.data);
if (e) applyEvent(e);
else if (import.meta.env.DEV) {
console.debug('[embed] unrecognized message', ev.data);
}
return;
}
for (const p of probeSet) {
const e = p.parse(ev.data);
if (e) {
locked = p;
clearInterval(probeTimer);
clearTimeout(giveUp);
applyEvent(e);
resolve(makeAdapter(p));
return;
}
}
if (import.meta.env.DEV) {
console.debug('[embed] unrecognized message', ev.data);
}
};
window.addEventListener('message', handler);
const sendProbes = () => {
const w = win();
if (!w || locked) return;
for (const p of probeSet) p.probe(w);
};
// The inner player may boot slowly; keep probing until lock or timeout.
const probeTimer = setInterval(sendProbes, PROBE_INTERVAL_MS);
frame.addEventListener('load', sendProbes);
sendProbes();
const giveUp = setTimeout(() => {
if (locked) return;
window.removeEventListener('message', handler);
clearInterval(probeTimer);
resolve(null);
}, timeoutMs);
});
}