@full-self-browsing/phantom-stream 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -2
- package/dist/types/adapters/extension.d.ts.map +1 -1
- package/dist/types/adapters/playwright.d.ts.map +1 -1
- package/dist/types/capture/index.d.ts +150 -0
- package/dist/types/capture/index.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -0
- package/dist/types/player/index.d.ts +136 -0
- package/dist/types/player/index.d.ts.map +1 -0
- package/dist/types/protocol/constants.d.ts +22 -0
- package/dist/types/protocol/constants.d.ts.map +1 -1
- package/dist/types/protocol/index.d.ts +1 -0
- package/dist/types/protocol/media-reconcile.d.ts +53 -0
- package/dist/types/protocol/media-reconcile.d.ts.map +1 -0
- package/dist/types/protocol/messages.d.ts +326 -4
- package/dist/types/protocol/messages.d.ts.map +1 -1
- package/dist/types/recorder/index.d.ts +207 -0
- package/dist/types/recorder/index.d.ts.map +1 -0
- package/dist/types/renderer/asset-policy.d.ts +72 -0
- package/dist/types/renderer/asset-policy.d.ts.map +1 -0
- package/dist/types/renderer/diff.d.ts.map +1 -1
- package/dist/types/renderer/index.d.ts +61 -8
- package/dist/types/renderer/index.d.ts.map +1 -1
- package/dist/types/renderer/media-player.d.ts +114 -0
- package/dist/types/renderer/media-player.d.ts.map +1 -0
- package/dist/types/renderer/overlays.d.ts +12 -0
- package/dist/types/renderer/overlays.d.ts.map +1 -1
- package/dist/types/renderer/parser-safe.d.ts +26 -0
- package/dist/types/renderer/parser-safe.d.ts.map +1 -0
- package/dist/types/renderer/sanitize.d.ts +22 -0
- package/dist/types/renderer/sanitize.d.ts.map +1 -1
- package/dist/types/renderer/snapshot.d.ts +38 -0
- package/dist/types/renderer/snapshot.d.ts.map +1 -1
- package/dist/types/transport/websocket.d.ts.map +1 -1
- package/docs/ARCHITECTURE.md +83 -4
- package/docs/QUICKSTARTS.md +64 -0
- package/docs/SECURITY.md +279 -2
- package/docs/paper/OUTLINE.md +24 -91
- package/examples/bookmarklet-demo/viewer.html +12 -3
- package/examples/extension-mv3/viewer.html +10 -3
- package/package.json +25 -1
- package/src/adapters/extension.js +202 -7
- package/src/adapters/playwright-inject.js +645 -28
- package/src/adapters/playwright.js +176 -2
- package/src/capture/README.md +96 -1
- package/src/capture/index.js +1672 -40
- package/src/index.js +2 -0
- package/src/player/README.md +175 -0
- package/src/player/index.js +627 -0
- package/src/protocol/constants.js +24 -0
- package/src/protocol/index.js +1 -0
- package/src/protocol/media-reconcile.js +188 -0
- package/src/protocol/messages.js +195 -4
- package/src/recorder/README.md +225 -0
- package/src/recorder/index.js +487 -0
- package/src/renderer/README.md +111 -8
- package/src/renderer/asset-policy.js +172 -0
- package/src/renderer/diff.js +158 -15
- package/src/renderer/index.js +978 -21
- package/src/renderer/media-player.js +367 -0
- package/src/renderer/overlays.js +324 -0
- package/src/renderer/parser-safe.js +111 -0
- package/src/renderer/sanitize.js +25 -3
- package/src/renderer/snapshot.js +534 -3
- package/src/transport/websocket.js +36 -0
|
@@ -0,0 +1,627 @@
|
|
|
1
|
+
// PhantomStream player: seekable, speed-controlled, inert playback of a
|
|
2
|
+
// recording (see src/recorder/) through createViewer.
|
|
3
|
+
//
|
|
4
|
+
// The player creates a viewer in the host container over a private
|
|
5
|
+
// ViewerTransport and feeds it recorded messages. It writes no HTML itself:
|
|
6
|
+
// every recorded payload goes through the viewer's render sanitizers, the
|
|
7
|
+
// srcdoc CSP, the sandbox (which stays exactly allow-same-origin), and the
|
|
8
|
+
// fail-closed asset gate, exactly as a live stream would. A seek feeds the
|
|
9
|
+
// nearest snapshot at or before the target, waits for the viewer's 'loaded'
|
|
10
|
+
// event, then applies every later event up to the target. Play is a frame
|
|
11
|
+
// clock that reads only requestAnimationFrame timestamps.
|
|
12
|
+
//
|
|
13
|
+
// No DOM access at import: window, document, frames, and timers are touched
|
|
14
|
+
// only inside createPlayer and the functions it builds, so the module
|
|
15
|
+
// imports in bare Node.
|
|
16
|
+
|
|
17
|
+
import { createViewer } from '../renderer/index.js';
|
|
18
|
+
import { STREAM, CONTROL, isCurrentStream } from '../protocol/messages.js';
|
|
19
|
+
import { createRecording, validateRecording, HOST_MARK_TYPE } from '../recorder/index.js';
|
|
20
|
+
|
|
21
|
+
/** Slowest playback speed (a quarter of recorded time). */
|
|
22
|
+
export const PLAYER_MIN_SPEED = 0.25;
|
|
23
|
+
|
|
24
|
+
/** Fastest playback speed (16 times recorded time). */
|
|
25
|
+
export const PLAYER_MAX_SPEED = 16;
|
|
26
|
+
|
|
27
|
+
// Frame cadence when the window has no requestAnimationFrame (about 60 Hz).
|
|
28
|
+
var FRAME_FALLBACK_MS = 16;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @typedef {Object} PlayerOptions
|
|
32
|
+
* @property {Element} container
|
|
33
|
+
* Required. Host element the playback viewer is appended into. It must be
|
|
34
|
+
* connected to a document: the mirror only loads in a connected iframe.
|
|
35
|
+
* Otherwise the factory throws Error('player-container-required').
|
|
36
|
+
* @property {import('../recorder/index.js').Recording|import('../recorder/index.js').RecordingEvent[]} recording
|
|
37
|
+
* Required. A Recording (see the recorder module) or a bare array of
|
|
38
|
+
* RecordingEvent objects. Validated at creation; an invalid one throws
|
|
39
|
+
* Error('player-recording-invalid:' + reason).
|
|
40
|
+
* @property {{info: Function, warn: Function, error: Function}} [logger]
|
|
41
|
+
* Optional. Defaults to a console-backed logger. Shared with the viewer.
|
|
42
|
+
* @property {Document} [document]
|
|
43
|
+
* Optional construction-document fallback, passed to createViewer.
|
|
44
|
+
* @property {number} [skipIdleMs]
|
|
45
|
+
* Optional cap, in recording ms, on how long an idle gap plays. 0 (the
|
|
46
|
+
* default) plays every gap in full. Negative or non-finite values throw
|
|
47
|
+
* Error('player-skip-idle-invalid').
|
|
48
|
+
* @property {boolean} [inert]
|
|
49
|
+
* Optional. Default true: the mirror iframe gets the inert attribute,
|
|
50
|
+
* pointer-events none, and tabindex -1, so pointer and keyboard input
|
|
51
|
+
* never reach mirrored links or forms. Pass false only for trusted
|
|
52
|
+
* recordings.
|
|
53
|
+
* @property {string} [mediaMode]
|
|
54
|
+
* 'reference' (default), 'poster', or 'off'. Passed to createViewer, which
|
|
55
|
+
* throws Error('viewer-mediamode-invalid') for anything else.
|
|
56
|
+
* @property {Function} [assetOriginPolicy]
|
|
57
|
+
* Optional asset origin hook, passed to createViewer unchanged.
|
|
58
|
+
* @property {string[]} [allowAssetOrigins]
|
|
59
|
+
* Optional asset host allowlist, passed to createViewer unchanged.
|
|
60
|
+
*/
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* A host mark on the playback timeline: the recorded mark data plus its
|
|
64
|
+
* kind and its time in ms from the first event.
|
|
65
|
+
*
|
|
66
|
+
* @typedef {{t: number, kind: string} & Object<string, *>} PlayerMarker
|
|
67
|
+
*/
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @typedef {Object} PlayerTimeEvent
|
|
71
|
+
* @property {number} currentTime
|
|
72
|
+
* Playback position in ms from the first event.
|
|
73
|
+
* @property {number} duration
|
|
74
|
+
* Recording length in ms.
|
|
75
|
+
*/
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* @typedef {Object} PlayerStateEvent
|
|
79
|
+
* @property {'paused'|'playing'|'ended'} state
|
|
80
|
+
* @property {number} currentTime
|
|
81
|
+
*/
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* @typedef {Object} PlayerHandle
|
|
85
|
+
* @property {(ms: number) => Promise<void>} seek
|
|
86
|
+
* Show exactly the recorded state at ms (clamped to [0, duration]).
|
|
87
|
+
* Resolves once that state is applied, or once a newer seek supersedes
|
|
88
|
+
* this one.
|
|
89
|
+
* @property {(options?: {speed?: number}) => Promise<void>} play
|
|
90
|
+
* Start the frame clock. Throws Error('player-speed-invalid')
|
|
91
|
+
* synchronously for a bad speed. From the end, restarts at 0.
|
|
92
|
+
* @property {() => void} pause
|
|
93
|
+
* @property {(speed: number) => void} setSpeed
|
|
94
|
+
* Speed in [PLAYER_MIN_SPEED, PLAYER_MAX_SPEED]; otherwise throws
|
|
95
|
+
* Error('player-speed-invalid').
|
|
96
|
+
* @property {number} currentTime
|
|
97
|
+
* Read-only playback position in ms from the first event.
|
|
98
|
+
* @property {number} duration
|
|
99
|
+
* Read-only recording length in ms.
|
|
100
|
+
* @property {boolean} playing
|
|
101
|
+
* Read-only.
|
|
102
|
+
* @property {() => PlayerMarker[]} markers
|
|
103
|
+
* Fresh copies of every host mark, in timeline order.
|
|
104
|
+
* @property {(eventName: 'time'|'ended'|'marker'|'state'|'loaded', handler: (event: Object) => void) => (() => void)} on
|
|
105
|
+
* Subscribe to playback events. Returns unsubscribe. Only 'state' calls
|
|
106
|
+
* the handler immediately with the current value. Unknown names or
|
|
107
|
+
* non-function handlers throw Error('player-event-unsupported').
|
|
108
|
+
* @property {() => void} destroy
|
|
109
|
+
* Stop playback, resolve waiting seeks, and remove the viewer. Idempotent.
|
|
110
|
+
*/
|
|
111
|
+
|
|
112
|
+
function isFiniteNumber(value) {
|
|
113
|
+
return typeof value === 'number' && isFinite(value);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** A snapshot the viewer renders: a keyframe. Any other snapshot is skipped. */
|
|
117
|
+
function isKeyframeEvent(event) {
|
|
118
|
+
return event.type === STREAM.SNAPSHOT && !!event.payload &&
|
|
119
|
+
typeof event.payload.html === 'string';
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function assertSpeed(speed) {
|
|
123
|
+
if (!isFiniteNumber(speed) || speed < PLAYER_MIN_SPEED || speed > PLAYER_MAX_SPEED) {
|
|
124
|
+
throw new Error('player-speed-invalid');
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Create a player for one recording in a host container. Creation is
|
|
130
|
+
* synchronous and renders nothing: call seek() or play() to show a frame.
|
|
131
|
+
*
|
|
132
|
+
* @param {PlayerOptions} options
|
|
133
|
+
* @returns {PlayerHandle}
|
|
134
|
+
*/
|
|
135
|
+
export function createPlayer(options) {
|
|
136
|
+
var cfg = options || {};
|
|
137
|
+
|
|
138
|
+
// --- Factory-time validation: the only place the player throws (besides
|
|
139
|
+
// the synchronous speed checks). Nothing is attached until all pass. ---
|
|
140
|
+
var container = cfg.container;
|
|
141
|
+
if (!container || typeof container !== 'object' || typeof container.appendChild !== 'function') {
|
|
142
|
+
throw new Error('player-container-required');
|
|
143
|
+
}
|
|
144
|
+
var recording = Array.isArray(cfg.recording)
|
|
145
|
+
? createRecording({ events: cfg.recording })
|
|
146
|
+
: cfg.recording;
|
|
147
|
+
var verdict = validateRecording(recording);
|
|
148
|
+
if (!verdict.ok) {
|
|
149
|
+
throw new Error('player-recording-invalid:' + verdict.error);
|
|
150
|
+
}
|
|
151
|
+
var skipIdleMs = cfg.skipIdleMs === undefined ? 0 : cfg.skipIdleMs;
|
|
152
|
+
if (!isFiniteNumber(skipIdleMs) || skipIdleMs < 0) {
|
|
153
|
+
throw new Error('player-skip-idle-invalid');
|
|
154
|
+
}
|
|
155
|
+
var inert = cfg.inert !== false;
|
|
156
|
+
var logger = cfg.logger || {
|
|
157
|
+
info: function () { console.info.apply(console, arguments); },
|
|
158
|
+
warn: function () { console.warn.apply(console, arguments); },
|
|
159
|
+
error: function () { console.error.apply(console, arguments); }
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
// --- Timeline derived from the validated recording. Times are ms from
|
|
163
|
+
// the first event (rel). The events array is copied; payloads are shared
|
|
164
|
+
// and never mutated (media payloads are rebased on a copy). ---
|
|
165
|
+
var events = recording.events.slice();
|
|
166
|
+
var t0 = events[0].t;
|
|
167
|
+
var lastT = events[events.length - 1].t;
|
|
168
|
+
if (isFiniteNumber(recording.endedAt) && recording.endedAt > lastT) lastT = recording.endedAt;
|
|
169
|
+
var duration = lastT - t0;
|
|
170
|
+
var keyframeIndexes = [];
|
|
171
|
+
var markerAt = new Map(); // event index -> PlayerMarker
|
|
172
|
+
var markerList = [];
|
|
173
|
+
events.forEach(function (event, index) {
|
|
174
|
+
if (isKeyframeEvent(event)) {
|
|
175
|
+
keyframeIndexes.push(index);
|
|
176
|
+
} else if (event.type === HOST_MARK_TYPE) {
|
|
177
|
+
var marker = Object.assign({}, event.payload, { t: event.t - t0 });
|
|
178
|
+
markerAt.set(index, marker);
|
|
179
|
+
markerList.push(marker);
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
function rel(index) {
|
|
184
|
+
return events[index].t - t0;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The last keyframe at or before target, else the first keyframe. */
|
|
188
|
+
function keyframeFor(target) {
|
|
189
|
+
var chosen = keyframeIndexes[0];
|
|
190
|
+
for (var k = 0; k < keyframeIndexes.length; k++) {
|
|
191
|
+
if (rel(keyframeIndexes[k]) <= target) {
|
|
192
|
+
chosen = keyframeIndexes[k];
|
|
193
|
+
} else {
|
|
194
|
+
break;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return chosen;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// --- Playback state ---
|
|
201
|
+
var position = 0; // ms from the first event
|
|
202
|
+
var appliedIndex = -1; // newest event index reflected in the mirror
|
|
203
|
+
var loadedKeyframe = -1; // keyframe index whose document is loaded, or -1
|
|
204
|
+
var loadedIdentity = null; // { streamSessionId, snapshotId } of that keyframe
|
|
205
|
+
var pending = null; // the one in-flight snapshot load
|
|
206
|
+
var seekToken = 0; // bumped by every seek; stale seeks stop at their next await
|
|
207
|
+
var playing = false;
|
|
208
|
+
var speed = 1;
|
|
209
|
+
var framePending = false;
|
|
210
|
+
var frameHandle = null;
|
|
211
|
+
var frameKind = '';
|
|
212
|
+
var lastFrameTs = null; // null = rebase on the next frame
|
|
213
|
+
var overlayCache = null; // newest overlay payload for the loaded identity
|
|
214
|
+
var resyncedKeyframes = new Set();
|
|
215
|
+
var state = 'paused';
|
|
216
|
+
var destroyed = false;
|
|
217
|
+
var deliver = null; // the viewer's onMessage handler
|
|
218
|
+
var listeners = {
|
|
219
|
+
time: new Set(),
|
|
220
|
+
ended: new Set(),
|
|
221
|
+
marker: new Set(),
|
|
222
|
+
state: new Set(),
|
|
223
|
+
loaded: new Set()
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
// --- Private transport: the viewer's only link to "capture". The only
|
|
227
|
+
// control the player honors is CONTROL.START (the viewer's resync
|
|
228
|
+
// request), answered by a bounded re-seek. Subtree requests and every
|
|
229
|
+
// remote-control frame are ignored: a recording cannot answer them. ---
|
|
230
|
+
var privateTransport = {
|
|
231
|
+
send: function (type) {
|
|
232
|
+
if (type === CONTROL.START) requestResync();
|
|
233
|
+
},
|
|
234
|
+
onMessage: function (handler) {
|
|
235
|
+
deliver = handler;
|
|
236
|
+
return function () {
|
|
237
|
+
if (deliver === handler) deliver = null;
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
var viewer = createViewer({
|
|
243
|
+
container: container,
|
|
244
|
+
transport: privateTransport,
|
|
245
|
+
logger: logger,
|
|
246
|
+
document: cfg.document,
|
|
247
|
+
mediaMode: cfg.mediaMode,
|
|
248
|
+
assetOriginPolicy: cfg.assetOriginPolicy,
|
|
249
|
+
allowAssetOrigins: cfg.allowAssetOrigins
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
// createViewer appends its root as the container's last element child.
|
|
253
|
+
var root = container.lastElementChild;
|
|
254
|
+
var iframe = root && typeof root.querySelector === 'function'
|
|
255
|
+
? root.querySelector('iframe')
|
|
256
|
+
: null;
|
|
257
|
+
if (inert && iframe) {
|
|
258
|
+
// A sandboxed srcdoc frame runs no script, but it can still follow a
|
|
259
|
+
// link click (navigation needs no script) and accept keyboard focus,
|
|
260
|
+
// so the playback mirror is inert by default: no pointer input, no
|
|
261
|
+
// focus, no navigation. Only DOM attribute and style APIs are used
|
|
262
|
+
// here; the sandbox attribute is never touched.
|
|
263
|
+
iframe.setAttribute('inert', '');
|
|
264
|
+
iframe.style.pointerEvents = 'none';
|
|
265
|
+
iframe.setAttribute('tabindex', '-1');
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
viewer.on('loaded', onViewerLoaded);
|
|
269
|
+
|
|
270
|
+
// --- Events ---
|
|
271
|
+
|
|
272
|
+
function emit(name, payload) {
|
|
273
|
+
Array.from(listeners[name]).forEach(function (handler) {
|
|
274
|
+
try {
|
|
275
|
+
handler(Object.assign({}, payload));
|
|
276
|
+
} catch (err) {
|
|
277
|
+
logger.error('[Player] event handler failed', name, err);
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function emitTime() {
|
|
283
|
+
emit('time', { currentTime: position, duration: duration });
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function setState(next) {
|
|
287
|
+
if (state === next) return;
|
|
288
|
+
state = next;
|
|
289
|
+
emit('state', { state: state, currentTime: position });
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// --- Snapshot loading (at most one in flight) ---
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Hand one keyframe to the viewer and return a promise that resolves on
|
|
296
|
+
* its 'loaded' event (or on destroy). The pending record is created
|
|
297
|
+
* BEFORE delivery, so a synchronous load can never be missed.
|
|
298
|
+
*/
|
|
299
|
+
function feedSnapshot(index) {
|
|
300
|
+
overlayCache = null;
|
|
301
|
+
loadedKeyframe = -1;
|
|
302
|
+
loadedIdentity = null;
|
|
303
|
+
var payload = events[index].payload;
|
|
304
|
+
var resolveLoad;
|
|
305
|
+
var promise = new Promise(function (resolve) { resolveLoad = resolve; });
|
|
306
|
+
pending = {
|
|
307
|
+
index: index,
|
|
308
|
+
streamSessionId: payload.streamSessionId || '',
|
|
309
|
+
snapshotId: payload.snapshotId || 0,
|
|
310
|
+
promise: promise,
|
|
311
|
+
resolve: resolveLoad
|
|
312
|
+
};
|
|
313
|
+
if (deliver) deliver(STREAM.SNAPSHOT, payload);
|
|
314
|
+
return promise;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function onViewerLoaded(evt) {
|
|
318
|
+
if (destroyed) return;
|
|
319
|
+
var identity = {
|
|
320
|
+
streamSessionId: (evt && evt.streamSessionId) || '',
|
|
321
|
+
snapshotId: (evt && evt.snapshotId) || 0
|
|
322
|
+
};
|
|
323
|
+
var settled = null;
|
|
324
|
+
if (pending && pending.streamSessionId === identity.streamSessionId &&
|
|
325
|
+
pending.snapshotId === identity.snapshotId) {
|
|
326
|
+
settled = pending;
|
|
327
|
+
pending = null;
|
|
328
|
+
loadedKeyframe = settled.index;
|
|
329
|
+
appliedIndex = settled.index;
|
|
330
|
+
loadedIdentity = identity;
|
|
331
|
+
}
|
|
332
|
+
// Host listeners run synchronously, before the awaiting seek applies
|
|
333
|
+
// later events (resolve only queues its continuation).
|
|
334
|
+
emit('loaded', identity);
|
|
335
|
+
if (overlayCache && deliver && isCurrentStream(overlayCache, identity)) {
|
|
336
|
+
deliver(STREAM.OVERLAY, overlayCache);
|
|
337
|
+
}
|
|
338
|
+
if (settled) settled.resolve();
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// --- Applying recorded events ---
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Apply event index to the viewer as of playback time atMs. Host marks
|
|
345
|
+
* fire 'marker' only during play; READY, recorded subtree responses (they
|
|
346
|
+
* answer request ids this viewer never issued), and non-keyframe
|
|
347
|
+
* snapshots are never sent to the viewer.
|
|
348
|
+
*/
|
|
349
|
+
function dispatchAt(index, atMs, emitMarkers) {
|
|
350
|
+
var event = events[index];
|
|
351
|
+
appliedIndex = index;
|
|
352
|
+
var type = event.type;
|
|
353
|
+
if (type === HOST_MARK_TYPE) {
|
|
354
|
+
if (emitMarkers && markerAt.has(index)) emit('marker', markerAt.get(index));
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
if (type === STREAM.READY || type === STREAM.SUBTREE_RESPONSE || type === STREAM.SNAPSHOT) {
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
if (!deliver) return;
|
|
361
|
+
if (type === STREAM.MEDIA) {
|
|
362
|
+
// Rebase the capture-side clock onto the playback clock, on a copy:
|
|
363
|
+
// the viewer's reconciler then expects exactly the recorded media
|
|
364
|
+
// position at the current playback time.
|
|
365
|
+
deliver(type, Object.assign({}, event.payload, {
|
|
366
|
+
sentAt: Date.now() - Math.max(0, atMs - rel(index))
|
|
367
|
+
}));
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
if (type === STREAM.OVERLAY) {
|
|
371
|
+
if (loadedIdentity && isCurrentStream(event.payload, loadedIdentity)) {
|
|
372
|
+
overlayCache = event.payload;
|
|
373
|
+
}
|
|
374
|
+
deliver(type, event.payload);
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
deliver(type, event.payload);
|
|
378
|
+
if (type === STREAM.MUTATIONS && overlayCache && deliver) {
|
|
379
|
+
// An anchored highlight is placed when its overlay arrives; re-apply
|
|
380
|
+
// it after every batch so it follows its element, and hides once that
|
|
381
|
+
// element is removed.
|
|
382
|
+
deliver(STREAM.OVERLAY, overlayCache);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// --- Seeking ---
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Internal seek. Waits for any in-flight load to settle, then feeds the
|
|
390
|
+
* keyframe for target unless the forward fast path applies (same loaded
|
|
391
|
+
* keyframe, target not behind the current position), then applies every
|
|
392
|
+
* later event up to target. A newer seek makes this one stop at its next
|
|
393
|
+
* await, so the last seek wins.
|
|
394
|
+
* @param {number} target
|
|
395
|
+
* @param {boolean} force Always re-feed (the resync path).
|
|
396
|
+
*/
|
|
397
|
+
async function seekTo(target, force) {
|
|
398
|
+
var token = ++seekToken;
|
|
399
|
+
while (pending) {
|
|
400
|
+
await pending.promise;
|
|
401
|
+
if (token !== seekToken || destroyed) return;
|
|
402
|
+
}
|
|
403
|
+
var keyframe = keyframeFor(target);
|
|
404
|
+
if (force || keyframe !== loadedKeyframe || target < position) {
|
|
405
|
+
await feedSnapshot(keyframe);
|
|
406
|
+
if (token !== seekToken || destroyed) return;
|
|
407
|
+
}
|
|
408
|
+
for (var i = appliedIndex + 1; i < events.length && rel(i) <= target; i++) {
|
|
409
|
+
if (isKeyframeEvent(events[i])) break;
|
|
410
|
+
dispatchAt(i, target, false);
|
|
411
|
+
if (token !== seekToken || destroyed) return;
|
|
412
|
+
}
|
|
413
|
+
position = target;
|
|
414
|
+
emitTime();
|
|
415
|
+
if (playing) lastFrameTs = null;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function seek(ms) {
|
|
419
|
+
if (destroyed) return Promise.resolve();
|
|
420
|
+
var target = isFiniteNumber(ms) ? ms : 0;
|
|
421
|
+
target = Math.max(0, Math.min(duration, target));
|
|
422
|
+
resyncedKeyframes.clear();
|
|
423
|
+
if (state === 'ended') setState('paused');
|
|
424
|
+
return seekTo(target, false);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* The viewer asked capture for a fresh snapshot (stale misses). Re-seek
|
|
429
|
+
* the current time with a forced re-feed, at most once per keyframe
|
|
430
|
+
* window until the next host seek. Scheduled on a microtask so the viewer
|
|
431
|
+
* is never re-entered from inside its own dispatch.
|
|
432
|
+
*/
|
|
433
|
+
function requestResync() {
|
|
434
|
+
if (destroyed || loadedKeyframe < 0 || resyncedKeyframes.has(loadedKeyframe)) return;
|
|
435
|
+
resyncedKeyframes.add(loadedKeyframe);
|
|
436
|
+
Promise.resolve().then(function () {
|
|
437
|
+
if (!destroyed) return seekTo(position, true);
|
|
438
|
+
return undefined;
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// --- Frame clock ---
|
|
443
|
+
|
|
444
|
+
function frameWindow() {
|
|
445
|
+
var doc = container.ownerDocument || cfg.document;
|
|
446
|
+
return doc && doc.defaultView ? doc.defaultView : null;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function requestFrame() {
|
|
450
|
+
if (framePending || destroyed) return;
|
|
451
|
+
framePending = true;
|
|
452
|
+
var win = frameWindow();
|
|
453
|
+
if (win && typeof win.requestAnimationFrame === 'function') {
|
|
454
|
+
frameKind = 'raf';
|
|
455
|
+
frameHandle = win.requestAnimationFrame(onFrame);
|
|
456
|
+
} else {
|
|
457
|
+
frameKind = 'timeout';
|
|
458
|
+
frameHandle = setTimeout(function () { onFrame(Date.now()); }, FRAME_FALLBACK_MS);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function cancelFrame() {
|
|
463
|
+
if (!framePending) return;
|
|
464
|
+
framePending = false;
|
|
465
|
+
var handle = frameHandle;
|
|
466
|
+
frameHandle = null;
|
|
467
|
+
try {
|
|
468
|
+
if (frameKind === 'raf') {
|
|
469
|
+
var win = frameWindow();
|
|
470
|
+
if (win && typeof win.cancelAnimationFrame === 'function') win.cancelAnimationFrame(handle);
|
|
471
|
+
} else {
|
|
472
|
+
clearTimeout(handle);
|
|
473
|
+
}
|
|
474
|
+
} catch (err) { /* a torn-down window has nothing left to cancel */ }
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function onFrame(ts) {
|
|
478
|
+
framePending = false;
|
|
479
|
+
frameHandle = null;
|
|
480
|
+
if (!playing || destroyed) return;
|
|
481
|
+
if (pending) {
|
|
482
|
+
// A snapshot is loading: the clock is frozen until it lands.
|
|
483
|
+
requestFrame();
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
if (!isFiniteNumber(ts)) {
|
|
487
|
+
requestFrame();
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
if (lastFrameTs === null) {
|
|
491
|
+
lastFrameTs = ts; // rebase frame: no time passes
|
|
492
|
+
requestFrame();
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
var token = seekToken;
|
|
496
|
+
var target = Math.min(duration, position + Math.max(0, ts - lastFrameTs) * speed);
|
|
497
|
+
lastFrameTs = ts;
|
|
498
|
+
while (appliedIndex + 1 < events.length && rel(appliedIndex + 1) <= target) {
|
|
499
|
+
var next = appliedIndex + 1;
|
|
500
|
+
if (isKeyframeEvent(events[next])) {
|
|
501
|
+
// A reached snapshot holds the clock at its time until it loads,
|
|
502
|
+
// then the next frame rebases instead of jumping ahead.
|
|
503
|
+
position = rel(next);
|
|
504
|
+
feedSnapshot(next).then(function () {
|
|
505
|
+
if (destroyed) return;
|
|
506
|
+
if (token === seekToken) {
|
|
507
|
+
lastFrameTs = null;
|
|
508
|
+
emitTime();
|
|
509
|
+
}
|
|
510
|
+
if (playing) requestFrame();
|
|
511
|
+
});
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
dispatchAt(next, target, true);
|
|
515
|
+
// A marker handler may have sought or destroyed the player.
|
|
516
|
+
if (destroyed || token !== seekToken) return;
|
|
517
|
+
}
|
|
518
|
+
if (skipIdleMs > 0) {
|
|
519
|
+
var nextRel = appliedIndex + 1 < events.length ? rel(appliedIndex + 1) : duration;
|
|
520
|
+
if (nextRel - target > skipIdleMs) target = nextRel - skipIdleMs;
|
|
521
|
+
}
|
|
522
|
+
position = target;
|
|
523
|
+
emitTime();
|
|
524
|
+
if (destroyed || token !== seekToken) return;
|
|
525
|
+
if (position >= duration) {
|
|
526
|
+
if (playing) finish();
|
|
527
|
+
} else if (playing) {
|
|
528
|
+
requestFrame();
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function finish() {
|
|
533
|
+
playing = false;
|
|
534
|
+
cancelFrame();
|
|
535
|
+
setState('ended');
|
|
536
|
+
emit('ended', { currentTime: position, duration: duration });
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function play(opts) {
|
|
540
|
+
var o = opts || {};
|
|
541
|
+
if (o.speed !== undefined) {
|
|
542
|
+
assertSpeed(o.speed);
|
|
543
|
+
speed = o.speed;
|
|
544
|
+
}
|
|
545
|
+
if (destroyed || playing) return Promise.resolve();
|
|
546
|
+
playing = true;
|
|
547
|
+
lastFrameTs = null;
|
|
548
|
+
setState('playing');
|
|
549
|
+
var ready;
|
|
550
|
+
if (position >= duration) {
|
|
551
|
+
ready = seekTo(0, false);
|
|
552
|
+
} else if (loadedKeyframe < 0 && !pending) {
|
|
553
|
+
ready = seekTo(position, false);
|
|
554
|
+
} else {
|
|
555
|
+
ready = Promise.resolve();
|
|
556
|
+
}
|
|
557
|
+
return ready.then(function () {
|
|
558
|
+
if (playing && !destroyed) requestFrame();
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
function pause() {
|
|
563
|
+
if (!playing) return;
|
|
564
|
+
playing = false;
|
|
565
|
+
cancelFrame();
|
|
566
|
+
setState('paused');
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function setSpeed(next) {
|
|
570
|
+
assertSpeed(next);
|
|
571
|
+
speed = next;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function markers() {
|
|
575
|
+
return markerList.map(function (marker) { return Object.assign({}, marker); });
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
function on(eventName, handler) {
|
|
579
|
+
if (!Object.prototype.hasOwnProperty.call(listeners, eventName) ||
|
|
580
|
+
typeof handler !== 'function') {
|
|
581
|
+
throw new Error('player-event-unsupported');
|
|
582
|
+
}
|
|
583
|
+
var set = listeners[eventName];
|
|
584
|
+
set.add(handler);
|
|
585
|
+
if (eventName === 'state') {
|
|
586
|
+
try {
|
|
587
|
+
handler({ state: state, currentTime: position });
|
|
588
|
+
} catch (err) {
|
|
589
|
+
logger.error('[Player] event handler failed', 'state', err);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
return function unsubscribePlayerEvent() {
|
|
593
|
+
set.delete(handler);
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function destroy() {
|
|
598
|
+
if (destroyed) return;
|
|
599
|
+
destroyed = true;
|
|
600
|
+
playing = false;
|
|
601
|
+
cancelFrame();
|
|
602
|
+
if (pending) {
|
|
603
|
+
var waiting = pending;
|
|
604
|
+
pending = null;
|
|
605
|
+
waiting.resolve();
|
|
606
|
+
}
|
|
607
|
+
try {
|
|
608
|
+
viewer.destroy();
|
|
609
|
+
} catch (err) {
|
|
610
|
+
logger.error('[Player] viewer destroy failed', err);
|
|
611
|
+
}
|
|
612
|
+
Object.keys(listeners).forEach(function (name) { listeners[name].clear(); });
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
return {
|
|
616
|
+
seek: seek,
|
|
617
|
+
play: play,
|
|
618
|
+
pause: pause,
|
|
619
|
+
setSpeed: setSpeed,
|
|
620
|
+
get currentTime() { return position; },
|
|
621
|
+
get duration() { return duration; },
|
|
622
|
+
get playing() { return playing; },
|
|
623
|
+
markers: markers,
|
|
624
|
+
on: on,
|
|
625
|
+
destroy: destroy
|
|
626
|
+
};
|
|
627
|
+
}
|
|
@@ -29,6 +29,18 @@ export const TRUNCATION_VIEWPORT_MULTIPLIER = 3;
|
|
|
29
29
|
/** Scroll side-channel throttle: at most one event per this many ms. */
|
|
30
30
|
export const SCROLL_THROTTLE_MS = 200;
|
|
31
31
|
|
|
32
|
+
/**
|
|
33
|
+
* Media side-channel heartbeat throttle: while a tracked <video>/<audio> is
|
|
34
|
+
* playing, a `timeupdate` heartbeat (STREAM.MEDIA) is emitted at most once per
|
|
35
|
+
* this many ms for drift correction. 250 ms is a practice-based co-watching
|
|
36
|
+
* cadence (~4 Hz) -- frequent enough for the reconciler to converge sub-second
|
|
37
|
+
* drift, sparse enough to stay well under the relay cap. Discrete transitions
|
|
38
|
+
* (play/pause/seeked/ratechange/ended/volumechange/loadedmetadata) bypass this
|
|
39
|
+
* throttle and flush immediately; the value is tunable against the v2.1
|
|
40
|
+
* evaluation harness (Phase 13 concern).
|
|
41
|
+
*/
|
|
42
|
+
export const MEDIA_SYNC_THROTTLE_MS = 250;
|
|
43
|
+
|
|
32
44
|
/** Overlay side-channel throttle: at most one broadcast per this many ms. */
|
|
33
45
|
export const OVERLAY_THROTTLE_MS = 500;
|
|
34
46
|
|
|
@@ -47,3 +59,15 @@ export const READY_PROBE_BUDGET_MS = 5000;
|
|
|
47
59
|
|
|
48
60
|
/** Inline <style> tags larger than this are skipped during snapshot capture. */
|
|
49
61
|
export const INLINE_STYLE_MAX_BYTES = 500000;
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Maximum UTF-8 byte length of an inline `data:` image URI that capture will
|
|
65
|
+
* emit verbatim on the wire. 262144 = 256 KiB -- roughly a quarter of the
|
|
66
|
+
* per-message cap headroom (SNAPSHOT_BUDGET_BYTES is ~838 KiB, the 80%
|
|
67
|
+
* truncation budget of the 1 MiB relay cap), so a single inline asset cannot
|
|
68
|
+
* crowd out the rest of the snapshot. A `data:` image larger than this degrades
|
|
69
|
+
* to a dimensioned placeholder; small inline icons/sprites (<= cap) pass through
|
|
70
|
+
* byte-identical, preserving the existing `data:image/*` pass-through and the
|
|
71
|
+
* differential oracle. (Phase 12 ASST-04.)
|
|
72
|
+
*/
|
|
73
|
+
export const ASSET_DATA_URI_MAX_BYTES = 262144; // 256 KiB
|
package/src/protocol/index.js
CHANGED