@soffits/dsh-media-hub 0.0.0-stage → 0.7.1

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/web/player.js ADDED
@@ -0,0 +1,736 @@
1
+ /**
2
+ * The browser side of a room: the sync channel, the clock, and a player
3
+ * kept in step with the room.
4
+ *
5
+ * The room's state on the server is the truth. Each viewer measures its
6
+ * clock offset to the server, computes where the room is now, and corrects
7
+ * its own player toward that (src/sync.js). What the viewer does in the
8
+ * player (play, pause, seek, rate, end of an episode, a stall) goes to the
9
+ * server as an operation; the server's next state brings everyone along.
10
+ * While the room's ready gate is open (src/room.js) the player holds at the
11
+ * room's position and says `ready` once it can play a few seconds ahead;
12
+ * a start the server set slightly in the future is kept to the millisecond.
13
+ * A dropped socket leaves the local player alone; the next state resyncs it.
14
+ */
15
+ import { DRIFT, clockOffset, correction, expectedPosition, preloadDue } from './sync.js'
16
+ import { canStart, offerTap, shouldPrime } from './readiness.js'
17
+ import { defaultCaption, parseCaption } from './captions.js'
18
+
19
+ /** Reconcile the player with the room this often. */
20
+ const TICK_MS = 500
21
+ /** Clock pings: a quick burst on connect, then one this often. */
22
+ const PING_MS = 10_000
23
+ const PING_BURST = 5
24
+ const PING_SAMPLES = 8
25
+ /** After a seek, let the player settle this long before correcting again. */
26
+ const SEEK_SETTLE_MS = 1500
27
+ /** Buffering shorter than this does not stop the room. */
28
+ const STALL_GRACE_MS = 1000
29
+ /** A ready report the server has not acknowledged is sent again after this long (a reconnect lost it). */
30
+ const READY_RESEND_MS = 2000
31
+ /** After a start, the player gets this long to spin up before drift or stalls count. */
32
+ const START_SETTLE_MS = 1000
33
+ /** Events that count as a tap for letting media play (touchend on iOS, click elsewhere). */
34
+ const TAP_EVENTS = ['touchend', 'click']
35
+ /** Reconnect delays. */
36
+ const RETRY_MS = [500, 1000, 2000, 4000, 8000]
37
+ /** A seek in the native controls fires several events while dragging; report the last. */
38
+ const SEEK_DEBOUNCE_MS = 250
39
+ /** How long our own commands' events are not reported as the viewer's. */
40
+ const QUIET_MS = 1500
41
+ /** After the viewer acts, corrections wait this long for the server to echo it. */
42
+ const ECHO_WAIT_MS = 1500
43
+ /** Paused players are moved when this far from the room. */
44
+ const PAUSED_TOLERANCE_S = DRIFT.ignore
45
+ /** A priming play that has not started by then is given up. */
46
+ const PRIME_LIMIT_MS = 5000
47
+ /**
48
+ * WebKit lets a media element play with sound only once that very element was played from a tap; a second element swapped
49
+ * in would not be allowed to start. There the one element stays and is reused, and the next episode is not preloaded.
50
+ */
51
+ const swapKeepsPlayPermission = () => !('webkitSupportsPresentationMode' in HTMLVideoElement.prototype)
52
+
53
+ /** An HTML <video> as a media hub player, with hls.js where the browser has no native HLS. */
54
+ function createVideoPlayer(stage, events, { base, language, trackLabel }) {
55
+ let video = null
56
+ let hls = null
57
+ let src = null
58
+ /** The next episode loading in a second element, swapped in when the room gets there: { url, video }. */
59
+ let next = null
60
+ const expect = { play: 0, pause: 0, rate: null, seekTo: null, seekUntil: 0 }
61
+ let seekTimer = null
62
+ /** A muted play started only to make the browser load (see prime); its events are not the viewer's. */
63
+ let priming = false
64
+ /** When each element last fetched media data. */
65
+ const progressAt = new WeakMap()
66
+
67
+ const now = () => Date.now()
68
+ const absolute = item => new URL(item.src, document.baseURI).href
69
+
70
+ /** A <video> whose events are the player's: only the one in front reports. */
71
+ function makeVideo() {
72
+ const el = document.createElement('video')
73
+ el.className = 'vsync-media'
74
+ el.playsInline = true
75
+ el.preload = 'auto'
76
+ const front = () => el === video
77
+ const reports = () => front() && !priming
78
+ el.addEventListener('loadstart', () => progressAt.set(el, now()))
79
+ el.addEventListener('progress', () => progressAt.set(el, now()))
80
+ el.addEventListener('playing', () => { el.dataset.played = 'true' })
81
+ el.addEventListener('play', () => {
82
+ if (!reports() || now() <= expect.play) return
83
+ events.onPlay?.(el.currentTime)
84
+ })
85
+ el.addEventListener('pause', () => {
86
+ if (!reports() || el.ended || now() <= expect.pause) return
87
+ events.onPause?.(el.currentTime)
88
+ })
89
+ el.addEventListener('seeking', () => {
90
+ if (!reports()) return
91
+ if (expect.seekTo !== null && now() <= expect.seekUntil && Math.abs(el.currentTime - expect.seekTo) < 0.5) return
92
+ clearTimeout(seekTimer)
93
+ events.onLocal?.()
94
+ seekTimer = setTimeout(() => events.onSeek?.(el.currentTime), SEEK_DEBOUNCE_MS)
95
+ })
96
+ el.addEventListener('ratechange', () => {
97
+ if (!reports()) return
98
+ if (expect.rate !== null && Math.abs(el.playbackRate - expect.rate) < 1e-6) return
99
+ events.onRate?.(el.playbackRate)
100
+ })
101
+ el.addEventListener('ended', () => { if (front()) events.onEnded?.() })
102
+ el.addEventListener('loadedmetadata', () => { if (front() && Number.isFinite(el.duration)) events.onDuration?.(el.duration) })
103
+ el.addEventListener('error', () => { if (front()) events.onError?.(el.error?.message || 'This video could not be played.') })
104
+ return el
105
+ }
106
+
107
+ /** Every subtitle as a track the native controls offer; the one src/captions.js picks for the viewer is on, or none. */
108
+ function addTracks(el, item) {
109
+ for (const track of [...el.querySelectorAll('track')]) track.remove()
110
+ const on = defaultCaption(item.subtitles.map(sub => sub.label), language)
111
+ for (const [n, sub] of item.subtitles.entries()) {
112
+ const track = document.createElement('track')
113
+ const caption = parseCaption(sub.label)
114
+ track.kind = 'subtitles'
115
+ track.label = trackLabel(sub.label) || String(n + 1)
116
+ if (caption.language !== null) track.srclang = caption.tag
117
+ track.src = new URL(sub.src, document.baseURI).href
118
+ if (n === on) track.default = true
119
+ el.append(track)
120
+ }
121
+ }
122
+
123
+ const release = (el) => {
124
+ el.removeAttribute('src')
125
+ el.load()
126
+ el.remove()
127
+ }
128
+
129
+ function dropNext() {
130
+ if (next !== null) release(next.video)
131
+ next = null
132
+ }
133
+
134
+ video = makeVideo()
135
+ video.controls = true
136
+ stage.append(video)
137
+
138
+ /** A playlist that may still grow (an episode being fetched) starts where the room is, not at its newest segment. */
139
+ async function attachHls(url, startAt) {
140
+ const { default: Hls } = await import(new URL('hls.mjs', base).href)
141
+ if (!Hls.isSupported()) throw new Error('This browser cannot play HLS.')
142
+ hls = new Hls({ startPosition: startAt })
143
+ hls.loadSource(url)
144
+ hls.attachMedia(video)
145
+ }
146
+
147
+ /** Put the preloaded element in front of the finished one, keeping the viewer's volume. */
148
+ function swapIn(startAt) {
149
+ const old = video
150
+ video = next.video
151
+ next = null
152
+ video.controls = true
153
+ video.className = 'vsync-media'
154
+ video.dataset.swapped = 'true'
155
+ video.volume = old.volume
156
+ video.muted = old.muted
157
+ old.replaceWith(video)
158
+ release(old)
159
+ if (startAt > 0) video.currentTime = startAt
160
+ // Its metadata arrived while it was loading in the background, when it did not speak for the room.
161
+ if (Number.isFinite(video.duration)) events.onDuration?.(video.duration)
162
+ }
163
+
164
+ /** What readiness.js needs to know about an element. */
165
+ const media = el => ({
166
+ readyState: el.readyState,
167
+ seeking: el.seeking,
168
+ at: el.currentTime,
169
+ duration: el.duration,
170
+ ranges: Array.from({ length: el.buffered.length }, (_, n) => [el.buffered.start(n), el.buffered.end(n)]),
171
+ loadIdleMs: now() - (progressAt.get(el) ?? 0),
172
+ })
173
+
174
+ /**
175
+ * Play muted until playback really starts, then pause and go back to where it stood. Safari on iOS loads (almost)
176
+ * nothing for a paused element, so this is what gets the data in. Muted, it needs no tap; from a tap it also lets the
177
+ * element play with sound later. The play() call happens synchronously, so a tap that calls this still counts.
178
+ */
179
+ function prime() {
180
+ const el = video
181
+ if (priming || !el.paused) return Promise.resolve(false)
182
+ const at = el.currentTime
183
+ const muted = el.muted
184
+ priming = true
185
+ el.muted = true
186
+ return new Promise((resolve) => {
187
+ let settled = false
188
+ const done = (ok) => {
189
+ if (settled) return
190
+ settled = true
191
+ el.removeEventListener('playing', onPlaying)
192
+ clearTimeout(timer)
193
+ expect.pause = now() + QUIET_MS
194
+ if (!el.paused) el.pause()
195
+ el.muted = muted
196
+ if (Math.abs(el.currentTime - at) > 0.01) {
197
+ expect.seekTo = at
198
+ expect.seekUntil = now() + 5000
199
+ el.currentTime = at
200
+ }
201
+ // The pause and seek events above are still on their way; they are ours, not the viewer's.
202
+ setTimeout(() => { priming = false }, 0)
203
+ resolve(ok)
204
+ }
205
+ const onPlaying = () => done(true)
206
+ el.addEventListener('playing', onPlaying)
207
+ const timer = setTimeout(() => done(el.readyState >= 3), PRIME_LIMIT_MS)
208
+ Promise.resolve(el.play()).catch(() => done(false))
209
+ })
210
+ }
211
+
212
+ return {
213
+ kind: 'file',
214
+ /** Load the next episode in the background, so switching to it is near-instant. Not for HLS through hls.js, which is not preloaded. */
215
+ preload(item) {
216
+ const url = absolute(item)
217
+ if (next?.url === url || url === src || !swapKeepsPlayPermission()) return
218
+ if (item.kind === 'hls' && video.canPlayType('application/vnd.apple.mpegurl') === '') return
219
+ dropNext()
220
+ const el = makeVideo()
221
+ el.className = 'vsync-preload'
222
+ el.setAttribute('aria-hidden', 'true')
223
+ addTracks(el, item)
224
+ el.src = url
225
+ stage.append(el)
226
+ next = { url, video: el }
227
+ },
228
+ load(item, startAt = 0) {
229
+ const url = absolute(item)
230
+ if (url === src) return
231
+ src = url
232
+ hls?.destroy()
233
+ hls = null
234
+ expect.seekTo = startAt
235
+ expect.seekUntil = now() + 5000
236
+ // A preloaded episode that can play is swapped in (not while the old one is full screen or in a picture-in-picture window).
237
+ const usable = next?.url === url && next.video.readyState >= 3 && document.fullscreenElement !== video && document.pictureInPictureElement !== video
238
+ if (usable) return swapIn(startAt)
239
+ dropNext()
240
+ addTracks(video, item)
241
+ if (item.kind === 'hls' && video.canPlayType('application/vnd.apple.mpegurl') === '') {
242
+ attachHls(url, startAt).catch(error => events.onError?.(error.message))
243
+ } else {
244
+ video.src = url
245
+ }
246
+ if (startAt > 0) video.currentTime = startAt
247
+ return undefined
248
+ },
249
+ ready: () => video.readyState >= 1,
250
+ duration: () => video.duration,
251
+ /** The next episode is loaded far enough to start at once when its turn comes. */
252
+ nextReady: () => next !== null && next.video.currentTime < 0.05 && canStart(media(next.video)),
253
+ canStart: () => !priming && canStart(media(video)),
254
+ loadIdleMs: () => media(video).loadIdleMs,
255
+ prime,
256
+ get priming() { return priming },
257
+ /**
258
+ * On the viewer's first tap in the room, play and pause the element at once (muted, so nothing is heard). WebKit then
259
+ * lets this element play with sound from then on, which the room's later starts need.
260
+ */
261
+ warm() {
262
+ if (video.dataset.played === 'true' || !video.paused || priming) return
263
+ const muted = video.muted
264
+ expect.play = now() + QUIET_MS
265
+ expect.pause = now() + QUIET_MS
266
+ video.muted = true
267
+ Promise.resolve(video.play()).catch(() => {})
268
+ video.pause()
269
+ video.muted = muted
270
+ },
271
+ position: () => video.currentTime,
272
+ paused: () => video.paused,
273
+ buffering: () => !video.paused && video.readyState < 3,
274
+ rate: () => video.playbackRate,
275
+ play() {
276
+ expect.play = now() + QUIET_MS
277
+ return video.play()
278
+ },
279
+ pause() {
280
+ expect.pause = now() + QUIET_MS
281
+ video.pause()
282
+ },
283
+ seek(to) {
284
+ expect.seekTo = to
285
+ expect.seekUntil = now() + 5000
286
+ video.currentTime = to
287
+ },
288
+ setRate(rate) {
289
+ if (Math.abs(video.playbackRate - rate) < 1e-6) return
290
+ expect.rate = rate
291
+ video.playbackRate = rate
292
+ },
293
+ get element() { return video },
294
+ destroy() {
295
+ clearTimeout(seekTimer)
296
+ hls?.destroy()
297
+ dropNext()
298
+ release(video)
299
+ },
300
+ }
301
+ }
302
+
303
+ const randomId = () => Array.from(crypto.getRandomValues(new Uint8Array(9)), b => b.toString(16).padStart(2, '0')).join('')
304
+
305
+ /** One id per browser tab, kept across reconnects and reloads of the tab. */
306
+ function tabClientId() {
307
+ try {
308
+ const stored = sessionStorage.getItem('media-hub.clientId')
309
+ if (stored) return stored
310
+ const id = randomId()
311
+ sessionStorage.setItem('media-hub.clientId', id)
312
+ return id
313
+ } catch {
314
+ return randomId()
315
+ }
316
+ }
317
+
318
+ /**
319
+ * Join a room.
320
+ * @param {object} options
321
+ * @param {URL} options.base - the /media-hub/ base URL
322
+ * @param {string} options.roomId
323
+ * @param {string} options.name - shown to the others
324
+ * @param {HTMLElement} options.stage - element the player fills
325
+ * @param {(view: object) => void} options.onUpdate - connection, room, members, needsGesture, drift
326
+ * @param {(event: object) => void} options.onEvent - { kind: 'action', last } | { kind: 'joined' | 'left', name }
327
+ */
328
+ export function joinRoom({ base, roomId, name, language = '', trackLabel = label => label, stage, onUpdate, onEvent }) {
329
+ const clientId = tabClientId()
330
+ const samples = []
331
+ let offset = null
332
+ let ws = null
333
+ let retry = 0
334
+ let retryTimer = null
335
+ let pingTimer = null
336
+ let pingSeq = 0
337
+ let state = null
338
+ let player = null
339
+ let loadedIndex = null
340
+ let lastSeq = null
341
+ let lastMembers = null
342
+ let settleUntil = 0
343
+ let nudging = false
344
+ let needsGesture = false
345
+ let playAttempts = 0
346
+ let stalled = false
347
+ let bufferingSince = null
348
+ let readySent = { gate: null, at: 0 }
349
+ let startTimer = null
350
+ let connection = 'connecting'
351
+ let closed = false
352
+ let lastDrift = null
353
+ let localUntil = 0
354
+ let advancing = false
355
+ let advanceTimer = null
356
+ let nextSent = null
357
+ /** While the open gate waits for this viewer: { gate, since, primed }. */
358
+ let held = null
359
+
360
+ const serverNow = () => Date.now() + (offset?.offset ?? 0)
361
+
362
+ function view() {
363
+ onUpdate({
364
+ connection,
365
+ room: state?.room ?? null,
366
+ members: state?.members ?? [],
367
+ clientId,
368
+ needsGesture,
369
+ drift: lastDrift,
370
+ rtt: offset?.rtt ?? null,
371
+ wait: waitView(),
372
+ })
373
+ }
374
+
375
+ /** The open ready gate as the page shows it: whether it holds a playing room, for how long, whether "start without" is offered. */
376
+ function waitView() {
377
+ const gate = state?.room.gate ?? null
378
+ if (gate === null) return null
379
+ const now = serverNow()
380
+ const tap = held?.gate === gate.id && typeof player?.prime === 'function' && offerTap({ loadingMs: Date.now() - held.since })
381
+ return { reason: gate.reason, held: state.room.playing, age: now - gate.since, canSkip: now >= gate.skipAt, tap }
382
+ }
383
+
384
+ function send(message) {
385
+ if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message))
386
+ }
387
+
388
+ function op(message) {
389
+ send({ t: 'op', ...message })
390
+ }
391
+
392
+ function ping() {
393
+ send({ t: 'ping', id: ++pingSeq, client: Date.now() })
394
+ }
395
+
396
+ function connect() {
397
+ if (closed) return
398
+ const url = new URL(`ws?room=${encodeURIComponent(roomId)}`, base)
399
+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
400
+ ws = new WebSocket(url)
401
+ ws.addEventListener('open', () => {
402
+ retry = 0
403
+ nextSent = null
404
+ send({ t: 'hello', clientId, name })
405
+ for (let n = 0; n < PING_BURST; n++) setTimeout(ping, n * 150)
406
+ clearInterval(pingTimer)
407
+ pingTimer = setInterval(ping, PING_MS)
408
+ })
409
+ ws.addEventListener('message', (event) => {
410
+ let message
411
+ try {
412
+ message = JSON.parse(event.data)
413
+ } catch {
414
+ return
415
+ }
416
+ if (message.t === 'pong') {
417
+ samples.push({ sent: message.client, received: Date.now(), server: message.server })
418
+ if (samples.length > PING_SAMPLES) samples.shift()
419
+ offset = clockOffset(samples)
420
+ } else if (message.t === 'state') {
421
+ if (offset === null) offset = { offset: message.serverTime - Date.now(), rtt: Infinity }
422
+ receive(message)
423
+ }
424
+ })
425
+ ws.addEventListener('close', (event) => {
426
+ clearInterval(pingTimer)
427
+ if (closed) return
428
+ if (event.code === 4404 || event.code === 4410) {
429
+ connection = 'closed'
430
+ view()
431
+ return
432
+ }
433
+ connection = 'reconnecting'
434
+ view()
435
+ retryTimer = setTimeout(connect, RETRY_MS[Math.min(retry++, RETRY_MS.length - 1)])
436
+ })
437
+ }
438
+
439
+ function receive(message) {
440
+ const previous = state
441
+ state = message
442
+ connection = 'live'
443
+ const last = message.room.last
444
+ if (last !== null && lastSeq !== null && last.seq > lastSeq && last.clientId !== clientId) onEvent({ kind: 'action', last, item: message.room.items[last.index] })
445
+ if (last !== null && last.clientId === clientId && last.seq > (lastSeq ?? 0)) localUntil = 0
446
+ if (last !== null) lastSeq = Math.max(lastSeq ?? 0, last.seq)
447
+ else lastSeq ??= 0
448
+ const names = new Map(message.members.filter(m => m.clientId !== clientId).map(m => [m.clientId, m.name]))
449
+ if (lastMembers !== null) {
450
+ for (const [id, who] of names) if (!lastMembers.has(id)) onEvent({ kind: 'joined', name: who })
451
+ for (const [id, who] of lastMembers) if (!names.has(id)) onEvent({ kind: 'left', name: who })
452
+ }
453
+ lastMembers = names
454
+ if (previous?.room.index !== message.room.index) settleUntil = 0
455
+ scheduleAdvance(message.clock.advance)
456
+ reconcile()
457
+ view()
458
+ }
459
+
460
+ /** The viewer did something in the player: let the server's answer, not the old state, decide. */
461
+ const local = () => { localUntil = Date.now() + ECHO_WAIT_MS }
462
+ const events = {
463
+ onLocal: local,
464
+ onPlay: (position) => {
465
+ local()
466
+ op({ op: 'play', position })
467
+ },
468
+ onPause: (position) => {
469
+ local()
470
+ op({ op: 'pause', position })
471
+ },
472
+ onSeek: (position) => {
473
+ local()
474
+ settleUntil = Date.now() + SEEK_SETTLE_MS
475
+ op({ op: 'seek', position })
476
+ },
477
+ onRate: (rate) => {
478
+ local()
479
+ op({ op: 'rate', rate })
480
+ },
481
+ onEnded: () => op({ op: 'ended', from: state?.room.index }),
482
+ onDuration: duration => op({ op: 'duration', index: state?.room.index, duration }),
483
+ onError: message => onEvent({ kind: 'error', message }),
484
+ }
485
+
486
+ /**
487
+ * The server scheduled the switch to the next episode at the moment this one ends on the room's clock, because everyone
488
+ * has it loaded: make the switch here at that moment too, without waiting for the server's word to arrive.
489
+ */
490
+ function scheduleAdvance(advance) {
491
+ if (advance === null || advance === undefined) {
492
+ clearTimeout(advanceTimer?.id)
493
+ advanceTimer = null
494
+ return
495
+ }
496
+ if (advanceTimer?.at === advance.at && advanceTimer.to === advance.to) return
497
+ clearTimeout(advanceTimer?.id)
498
+ advanceTimer = {
499
+ at: advance.at,
500
+ to: advance.to,
501
+ id: setTimeout(() => {
502
+ advanceTimer = null
503
+ if (state === null || state.room.index !== advance.to - 1) return
504
+ const duration = state.room.items[advance.to]?.duration ?? null
505
+ advancing = true
506
+ state = { ...state, room: { ...state.room, index: advance.to }, clock: { ...state.clock, playing: true, position: 0, updatedAt: advance.at, duration, advance: null } }
507
+ reconcile()
508
+ view()
509
+ }, Math.max(0, advance.at - serverNow())),
510
+ }
511
+ }
512
+
513
+ /** Hold at the room's position until the start the server set, then start on the dot. */
514
+ function scheduleStart(at) {
515
+ if (startTimer?.at === at) return
516
+ clearTimeout(startTimer?.id)
517
+ startTimer = {
518
+ at,
519
+ id: setTimeout(() => {
520
+ startTimer = null
521
+ const current = player
522
+ if (current === null || !current.paused()) return
523
+ settleUntil = Date.now() + START_SETTLE_MS
524
+ Promise.resolve(current.play()).catch(() => {
525
+ needsGesture = true
526
+ view()
527
+ })
528
+ }, Math.max(0, at - serverNow())),
529
+ }
530
+ }
531
+
532
+ function cancelStart() {
533
+ clearTimeout(startTimer?.id)
534
+ startTimer = null
535
+ }
536
+
537
+ /** Tell the room this viewer can play from the gate's position. */
538
+ function reportReady(current) {
539
+ const gate = state.room.gate
540
+ if (gate === null) return
541
+ if (state.members.find(member => member.clientId === clientId)?.wait !== 'loading') return
542
+ if (Math.abs(current.position() - state.clock.position) > PAUSED_TOLERANCE_S || !current.canStart()) return
543
+ if (readySent.gate === gate.id && Date.now() - readySent.at < READY_RESEND_MS) return
544
+ readySent = { gate: gate.id, at: Date.now() }
545
+ op({ op: 'ready', gate: gate.id, ...(Number.isFinite(offset?.rtt) ? { rtt: Math.round(offset.rtt) } : {}) })
546
+ }
547
+
548
+ const ownWait = () => state.members.find(member => member.clientId === clientId)?.wait ?? null
549
+
550
+ /** Keep track of how long the gate has waited for this viewer, and prime a player that does not load while paused. */
551
+ function helpLoading(current) {
552
+ const gate = state.room.gate
553
+ if (gate === null || ownWait() !== 'loading') {
554
+ held = null
555
+ return
556
+ }
557
+ if (held?.gate !== gate.id) held = { gate: gate.id, since: Date.now(), primed: false }
558
+ if (typeof current.prime !== 'function') return
559
+ if (!shouldPrime({ heldMs: Date.now() - held.since, ready: current.canStart(), paused: current.paused(), loadIdleMs: current.loadIdleMs(), primed: held.primed })) return
560
+ held.primed = true
561
+ current.prime().then(() => reconcile())
562
+ }
563
+
564
+ function ensurePlayer() {
565
+ if (player !== null) return player
566
+ player = createVideoPlayer(stage, events, { base, language, trackLabel })
567
+ loadedIndex = null
568
+ return player
569
+ }
570
+
571
+ /**
572
+ * Report buffering that lasts, once per stall, so the room waits for this
573
+ * viewer. Buffering right after our own seek or a start is the player
574
+ * spinning up, not a stall; the server debounces as well.
575
+ */
576
+ function watchBuffering(current) {
577
+ const now = Date.now()
578
+ const buffering = current.buffering()
579
+ bufferingSince = buffering ? (bufferingSince ?? now) : null
580
+ if (!buffering) stalled = false
581
+ if (!buffering || stalled || now - bufferingSince < STALL_GRACE_MS || now < settleUntil) return
582
+ if (!state.clock.playing || serverNow() < state.clock.updatedAt) return
583
+ stalled = true
584
+ op({ op: 'stall', position: current.position() })
585
+ }
586
+
587
+ function reconcile() {
588
+ if (state === null) return
589
+ const { room, clock } = state
590
+ const item = room.items[room.index]
591
+ if (item === undefined || item.status !== 'ready') {
592
+ cancelStart()
593
+ if (player !== null && loadedIndex !== room.index) {
594
+ player.destroy()
595
+ player = null
596
+ loadedIndex = null
597
+ }
598
+ return
599
+ }
600
+ const target = expectedPosition(clock, serverNow())
601
+ const current = ensurePlayer()
602
+ if (loadedIndex !== room.index) {
603
+ loadedIndex = room.index
604
+ settleUntil = advancing ? 0 : Date.now() + SEEK_SETTLE_MS
605
+ current.load(item, advancing && target < 0.5 ? 0 : target)
606
+ advancing = false
607
+ nudging = false
608
+ }
609
+ helpLoading(current)
610
+ if (current.priming) return
611
+ if (!current.ready() || Date.now() < localUntil) return
612
+ watchBuffering(current)
613
+ // Held by a gate, paused, or a start still ahead: wait at the room's position (a paused player keeps loading).
614
+ const startsLater = clock.playing && serverNow() < clock.updatedAt
615
+ if (!clock.playing || startsLater) {
616
+ if (!current.paused()) current.pause()
617
+ current.setRate(clock.rate)
618
+ nudging = false
619
+ lastDrift = current.position() - target
620
+ if (Math.abs(lastDrift) > PAUSED_TOLERANCE_S && Date.now() > settleUntil) {
621
+ current.seek(target)
622
+ settleUntil = Date.now() + SEEK_SETTLE_MS
623
+ }
624
+ reportReady(current)
625
+ if (startsLater) scheduleStart(clock.updatedAt)
626
+ else cancelStart()
627
+ return
628
+ }
629
+ if (current.paused()) {
630
+ if (Date.now() < settleUntil) return
631
+ // A refused autoplay that the element did not report leaves it paused after its attempt.
632
+ if (playAttempts >= 2 && !needsGesture) {
633
+ needsGesture = true
634
+ view()
635
+ }
636
+ playAttempts += 1
637
+ if (Math.abs(current.position() - target) > PAUSED_TOLERANCE_S) current.seek(target)
638
+ settleUntil = Date.now() + SEEK_SETTLE_MS
639
+ Promise.resolve(current.play()).catch(() => {
640
+ if (!needsGesture) {
641
+ needsGesture = true
642
+ view()
643
+ }
644
+ })
645
+ return
646
+ }
647
+ playAttempts = 0
648
+ if (needsGesture) {
649
+ needsGesture = false
650
+ view()
651
+ }
652
+ if (current.buffering() || Date.now() < settleUntil) return
653
+ const fix = correction({ local: current.position(), expected: target, rate: clock.rate, nudging })
654
+ lastDrift = fix.drift
655
+ if (fix.action === 'seek') {
656
+ current.seek(fix.to)
657
+ current.setRate(clock.rate)
658
+ nudging = false
659
+ settleUntil = Date.now() + SEEK_SETTLE_MS
660
+ } else if (fix.action === 'rate') {
661
+ current.setRate(fix.rate)
662
+ nudging = true
663
+ } else {
664
+ current.setRate(clock.rate)
665
+ nudging = false
666
+ }
667
+ }
668
+
669
+ /** Start loading the next episode in the background once this one is close to its end (or short). */
670
+ function preloadNext() {
671
+ if (player === null || state === null) return
672
+ const next = state.room.items[state.room.index + 1]
673
+ if (next === undefined || next.status !== 'ready' || loadedIndex !== state.room.index) return
674
+ if (preloadDue({ duration: player.duration(), position: player.position() })) player.preload(next)
675
+ // Tell the room this viewer can switch with no waiting, so it can schedule the switch for the end of the episode.
676
+ if (nextSent !== state.room.index && player.nextReady?.()) {
677
+ nextSent = state.room.index
678
+ op({ op: 'nextready', from: state.room.index })
679
+ }
680
+ }
681
+
682
+ /** The viewer's first tap in the room lets the player start with sound later (WebKit asks for that per element). */
683
+ const firstTap = () => {
684
+ if (player === null || typeof player.warm !== 'function') return
685
+ player.warm()
686
+ for (const type of TAP_EVENTS) document.removeEventListener(type, firstTap, true)
687
+ }
688
+ for (const type of TAP_EVENTS) document.addEventListener(type, firstTap, true)
689
+
690
+ const tick = setInterval(() => {
691
+ reconcile()
692
+ preloadNext()
693
+ view()
694
+ }, TICK_MS)
695
+ connect()
696
+ view()
697
+
698
+ return {
699
+ clientId,
700
+ /** Switch the room to an episode. */
701
+ select(index) {
702
+ op({ op: 'select', index })
703
+ },
704
+ /** Start without the viewers the open gate still waits for. */
705
+ skip() {
706
+ const gate = state?.room.gate
707
+ if (gate) op({ op: 'skip', gate: gate.id })
708
+ },
709
+ /** From a tap: make a player that sits loading start fetching (a muted play, then back to the room's position). */
710
+ continueLoading() {
711
+ if (typeof player?.prime !== 'function') return
712
+ if (held !== null) held.primed = true
713
+ player.prime().then(() => reconcile())
714
+ view()
715
+ },
716
+ /** Start playback after the browser refused to without a click. */
717
+ unlock() {
718
+ needsGesture = false
719
+ playAttempts = 0
720
+ if (player !== null) Promise.resolve(player.play()).catch(() => { needsGesture = true; view() })
721
+ view()
722
+ },
723
+ destroy() {
724
+ closed = true
725
+ for (const type of TAP_EVENTS) document.removeEventListener(type, firstTap, true)
726
+ cancelStart()
727
+ clearTimeout(advanceTimer?.id)
728
+ clearInterval(tick)
729
+ clearInterval(pingTimer)
730
+ clearTimeout(retryTimer)
731
+ ws?.close(1000, 'left')
732
+ player?.destroy()
733
+ player = null
734
+ },
735
+ }
736
+ }