@banou/media-player 0.10.27 → 0.10.29

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.
@@ -11,15 +11,16 @@
11
11
  // which is the only shape that satisfies a synchronous media over an asynchronous boundary.
12
12
 
13
13
  import type { Message, ReceiveHandler, Remote, Transport } from 'osra'
14
+ import type { MediaChapter } from '../engine'
14
15
  import type { PlayerMedia } from '../react/media'
15
16
  import type { Callable, PlayerEvent, PlayerService, PlayerSnapshot, PlayerUpdate, Writable } from './protocol'
16
17
 
17
18
  import { expose } from 'osra'
18
19
 
19
- import { CALLABLE, DEFAULT_PLAYER_ID, EMPTY_SNAPSHOT, PLAYER_CHANNEL, PLAYER_EVENTS, snapshotOf, syncEventsFor, toTimeRanges, WRITABLE } from './protocol'
20
+ import { CALLABLE, DEFAULT_PLAYER_ID, EMPTY_SNAPSHOT, PLAYER_CHANNEL, PLAYER_EVENTS, SERVED_EVENTS, snapshotOf, syncEventsFor, toTimeRanges, WRITABLE } from './protocol'
20
21
 
21
22
  export type { PlayerEvent, PlayerSnapshot, PlayerUpdate } from './protocol'
22
- export { DEFAULT_PLAYER_ID, PLAYER_CHANNEL, PLAYER_EVENTS } from './protocol'
23
+ export { DEFAULT_PLAYER_ID, PLAYER_CHANNEL, PLAYER_EVENTS, SERVED_EVENTS } from './protocol'
23
24
 
24
25
  /** How long a peer has to answer its handshake before the mirror stops waiting on it and moves on. */
25
26
  const HANDSHAKE_MS = 10_000
@@ -77,6 +78,19 @@ export type ExposePlayerOptions = {
77
78
  * and a channel that closed in between would drop every embedder listening to the others.
78
79
  */
79
80
  signal?: AbortSignal
81
+ /** What `<MediaPlayer expose>` serves beside its media. A document serving a bare element leaves it out. */
82
+ player?: ServedPlayer
83
+ }
84
+
85
+ /**
86
+ * The player around a served media, as `<MediaPlayer expose>` passes it: its chapters, sent with every snapshot and
87
+ * announced on its `chapterschange`, and its fullscreen, which a mirror made with `fullscreen: true` takes over. While
88
+ * one has it, `onHostFullscreen` is told the state that mirror sets, and null once none has it; the player then
89
+ * dispatches `fullscreenrequest` for each press of its fullscreen, which reaches the mirror.
90
+ */
91
+ export type ServedPlayer = EventTarget & {
92
+ readonly chapters: MediaChapter[]
93
+ onHostFullscreen: (active: boolean | null) => void
80
94
  }
81
95
 
82
96
  /**
@@ -138,14 +152,20 @@ const channelFor = (options: ExposePlayerOptions): Channel => {
138
152
  // connection for the document, however many players it has: a second player must not take the
139
153
  // first's embedder away, which is what one shared `current` did.
140
154
  const medias = new Map<string, PlayerMedia>()
155
+ const players = new Map<string, ServedPlayer>()
141
156
  const ports = new Map<string, Set<MessagePort>>()
142
157
  const listeners = (id: string) => ports.get(id) ?? ports.set(id, new Set()).get(id)!
158
+ // the ports whose mirror took the player's fullscreen over, and the state they last set
159
+ const hosts = new Map<string, Set<MessagePort>>()
160
+ const hostActive = new Map<string, boolean>()
161
+ const tellHost = (id: string) => players.get(id)?.onHostFullscreen(hosts.get(id)?.size ? hostActive.get(id) ?? false : null)
143
162
  const drop = (id: string, port: MessagePort) => {
144
163
  ports.get(id)?.delete(port)
164
+ if (hosts.get(id)?.delete(port)) tellHost(id)
145
165
  try { port.onmessage = null; port.close() } catch {}
146
166
  }
147
- const post = (id: string, update: PlayerUpdate, only?: MessagePort) => {
148
- for (const port of only ? [only] : [...listeners(id)]) {
167
+ const post = (id: string, update: PlayerUpdate, to: Iterable<MessagePort> = listeners(id)) => {
168
+ for (const port of [...to]) {
149
169
  // posting to a port whose peer is gone is silently dropped, which is exactly what a vanished
150
170
  // embedder deserves; a port that throws is one this document already closed
151
171
  try { port.postMessage(update) } catch { drop(id, port) }
@@ -153,18 +173,20 @@ const channelFor = (options: ExposePlayerOptions): Channel => {
153
173
  }
154
174
  const snapshotAt = (id: string) => {
155
175
  const media = medias.get(id)
156
- return media ? snapshotOf(media) : undefined
176
+ return media ? snapshotOf(media, players.get(id)?.chapters) : undefined
157
177
  }
158
178
  const announce = (id: string, event: PlayerEvent) => {
179
+ // a press of the fullscreen is for the mirrors that took it over: another one toggling too would undo it
180
+ const to = event === 'fullscreenrequest' ? hosts.get(id) : ports.get(id)
159
181
  // nobody listening is the ordinary case for a player nobody mirrors, and `timeupdate` alone is
160
182
  // four snapshots a second for the life of the document
161
- if (!ports.get(id)?.size) return
183
+ if (!to?.size) return
162
184
  const snapshot = snapshotAt(id)
163
- if (snapshot) post(id, { event, snapshot })
185
+ if (snapshot) post(id, { event, snapshot }, to)
164
186
  }
165
187
 
166
188
  const service: PlayerService = {
167
- subscribe: (id, port) => {
189
+ subscribe: (id, port, options) => {
168
190
  // The peer's arguments, so they are checked: osra revives a plain object as a plain object and
169
191
  // a function as a callable, and either would sit in this set being posted to for ever.
170
192
  // Refused LOUDLY: a mirror whose subscribe was dropped in silence waits for ever, and a caller
@@ -176,6 +198,12 @@ const channelFor = (options: ExposePlayerOptions): Channel => {
176
198
  const set = listeners(id)
177
199
  if (set.size >= MAX_SUBSCRIBERS) throw new RangeError('too many embedders for this player')
178
200
  set.add(port)
201
+ const fullscreen = (options as { fullscreen?: unknown } | undefined)?.fullscreen
202
+ if (typeof fullscreen === 'boolean') {
203
+ ;(hosts.get(id) ?? hosts.set(id, new Set()).get(id)!).add(port)
204
+ hostActive.set(id, fullscreen)
205
+ tellHost(id)
206
+ }
179
207
  // A mirror says goodbye on its own port when it closes, and the port is dropped here. Without
180
208
  // it a closed mirror's port stays in this set for the document's life and every event is
181
209
  // posted to it, one more dead port per mirror that ever connected.
@@ -185,9 +213,16 @@ const channelFor = (options: ExposePlayerOptions): Channel => {
185
213
  // its answer is missed. Nothing at all when no player has that id: the mirror waits, and hears
186
214
  // this the moment one is served.
187
215
  const snapshot = snapshotAt(id)
188
- if (snapshot) post(id, { event: 'loadstart', snapshot }, port)
216
+ if (snapshot) post(id, { event: 'loadstart', snapshot }, [port])
189
217
  },
190
218
  set: (id, name, value) => {
219
+ if (name === 'fullscreen') {
220
+ // only for an id a mirror took over: the id is the peer's, and the map would otherwise grow with it
221
+ if (typeof value !== 'boolean' || !hosts.get(id)?.size) return
222
+ hostActive.set(id, value)
223
+ tellHost(id)
224
+ return
225
+ }
191
226
  const media = medias.get(id)
192
227
  if (!media || !WRITABLE.includes(name)) return
193
228
  try { (media as unknown as Record<Writable, unknown>)[name] = value } catch {}
@@ -222,6 +257,7 @@ const channelFor = (options: ExposePlayerOptions): Channel => {
222
257
  for (const [player, set] of ports) for (const port of [...set]) drop(player, port)
223
258
  ports.clear()
224
259
  medias.clear()
260
+ players.clear()
225
261
  }, { once: true })
226
262
 
227
263
  expose<unknown>(service, {
@@ -234,18 +270,31 @@ const channelFor = (options: ExposePlayerOptions): Channel => {
234
270
  const channel: Channel = {
235
271
  serve: (media, served) => {
236
272
  const player = served.id ?? DEFAULT_PLAYER_ID
237
- const handlers = PLAYER_EVENTS.map(event => [event, () => { if (medias.get(player) === media) announce(player, event) }] as const)
238
- for (const [event, handler] of handlers) media.addEventListener(event, handler)
273
+ const around = served.player
274
+ const handlers = [
275
+ ...PLAYER_EVENTS.map(event => [media, event] as const),
276
+ ...around ? SERVED_EVENTS.map(event => [around, event] as const) : [],
277
+ ].map(([target, event]) => [target, event, () => { if (medias.get(player) === media) announce(player, event) }] as const)
278
+ for (const [target, event, handler] of handlers) target.addEventListener(event, handler)
239
279
  const replaced = medias.has(player)
280
+ const previous = players.get(player)
281
+ if (previous && previous !== around) previous.onHostFullscreen(null)
240
282
  medias.set(player, media)
283
+ if (around) players.set(player, around)
284
+ else players.delete(player)
285
+ tellHost(player)
241
286
  // the switch, told the way an element tells it: what was there is gone, and here is the new
242
287
  // one's state, ready to be synced from
243
288
  if (replaced) post(player, { event: 'emptied', snapshot: { ...EMPTY_SNAPSHOT } })
244
- for (const event of syncEventsFor(snapshotOf(media))) announce(player, event)
289
+ for (const event of syncEventsFor(snapshotAt(player)!)) announce(player, event)
245
290
  const stop = () => {
246
- for (const [event, handler] of handlers) media.removeEventListener(event, handler)
291
+ for (const [target, event, handler] of handlers) target.removeEventListener(event, handler)
247
292
  if (medias.get(player) !== media) return
248
293
  medias.delete(player)
294
+ if (around && players.get(player) === around) {
295
+ players.delete(player)
296
+ around.onHostFullscreen(null)
297
+ }
249
298
  post(player, { event: 'emptied', snapshot: { ...EMPTY_SNAPSHOT } })
250
299
  }
251
300
  // this call's own signal stops this media AND closes the channel: it is the release for the
@@ -277,6 +326,13 @@ export type MediaPlayerHandle =
277
326
  & Readonly<Required<Pick<PlayerMedia, 'src' | 'currentSrc' | 'ended' | 'buffered' | 'seekable' | 'error' | 'videoWidth' | 'videoHeight'>>>
278
327
  & Required<Pick<PlayerMedia, Writable>>
279
328
  & {
329
+ /** The far player's chapters, empty for a bare element. A `chapterschange` event follows each change. */
330
+ readonly chapters: MediaChapter[]
331
+ /**
332
+ * With the `fullscreen` option, whether this page shows the far player fullscreen: its button and its `'player'`
333
+ * shortcuts follow it. Set it on every change. Without the option it stays here.
334
+ */
335
+ fullscreen: boolean
280
336
  /**
281
337
  * Settles once the far side has first answered with its state; reads before that answer the
282
338
  * empty defaults. Stays pending for as long as nobody answers, and rejects with an AbortError on
@@ -333,6 +389,12 @@ export type MediaPlayerHandleOptions = {
333
389
  channel?: string
334
390
  /** closes the mirror: `ready` rejects with an AbortError and nothing more is heard */
335
391
  signal?: AbortSignal
392
+ /**
393
+ * Take the far player's fullscreen over, when it is a `<MediaPlayer expose>`: its button, `f` and double click then
394
+ * call no `requestFullscreen` and fire one `fullscreenrequest` on the handle each, inside the press's activation,
395
+ * and show the handle's `fullscreen`. Released on `destroy()`. A bare element ignores it.
396
+ */
397
+ fullscreen?: boolean
336
398
  }
337
399
 
338
400
  /**
@@ -349,11 +411,13 @@ type Subscriber = {
349
411
  /** the connection was replaced: whatever was asked of the old one will never be answered */
350
412
  reset: () => void
351
413
  port?: MessagePort
414
+ /** the fullscreen state to take the player's fullscreen over with, for a mirror that does */
415
+ fullscreen?: () => boolean
352
416
  }
353
417
 
354
418
  type Link = {
355
419
  attach: (subscriber: Subscriber) => () => void
356
- set: (id: string, name: Writable, value: number | boolean) => Promise<unknown> | undefined
420
+ set: (id: string, name: Writable | 'fullscreen', value: number | boolean) => Promise<unknown> | undefined
357
421
  call: (id: string, name: Callable) => Promise<void>
358
422
  }
359
423
 
@@ -389,7 +453,10 @@ const linkTo = (target: HTMLIFrameElement | Window | Transport, options: MediaPl
389
453
  // A peer that connects and then stops answering must not wedge the loop: osra leaves this
390
454
  // pending for ever if the far document was navigated away mid-handshake, and the next peer would
391
455
  // never be reached. A refusal lands here too, and takes the port with it.
392
- await withDeadline(() => service!.subscribe(subscriber.id, port2)).catch(error => {
456
+ const fullscreen = subscriber.fullscreen
457
+ await withDeadline(() => fullscreen
458
+ ? service!.subscribe(subscriber.id, port2, { fullscreen: fullscreen() })
459
+ : service!.subscribe(subscriber.id, port2)).catch(error => {
393
460
  unhook(subscriber)
394
461
  throw error
395
462
  })
@@ -494,21 +561,26 @@ export const mediaPlayer = (
494
561
  const pending = new Map<Writable, number | boolean>()
495
562
  // whether the far side has said anything about THIS player yet, which is what `ready` means
496
563
  let answered = false
564
+ let fullscreen = false
497
565
 
498
566
  const detach = linkTo(target, options).attach({
499
567
  id: playerId,
568
+ fullscreen: options.fullscreen ? () => fullscreen : undefined,
500
569
  reset: () => { answered = false; settleAll() },
501
570
  update: ({ event, snapshot }) => {
502
571
  const first = !answered
503
572
  answered = true
573
+ const chapters = JSON.stringify(state.chapters)
504
574
  Object.assign(state, snapshot)
505
575
  // a write the far side has not taken yet is the caller's intent, and outranks what the far
506
576
  // side is still reporting, first snapshot or any later one
507
577
  for (const [name, value] of pending) (state as Record<Writable, unknown>)[name] = value
508
- if (!first) { dispatch(event); return }
509
578
  // told as an element would tell it on load, so a store attached before this catches up
510
- for (const sync of syncEventsFor(state)) dispatch(sync)
511
- settleReady()
579
+ const events = first ? syncEventsFor(state) : [event]
580
+ // told for any update that changes them: a catch-up or a switch's `emptied` brings chapters with no word of them
581
+ if (!events.includes('chapterschange') && JSON.stringify(state.chapters) !== chapters) events.push('chapterschange')
582
+ for (const each of events) dispatch(each)
583
+ if (first) settleReady()
512
584
  },
513
585
  })
514
586
 
@@ -523,6 +595,7 @@ export const mediaPlayer = (
523
595
  for (const name of ['duration', 'paused', 'ended', 'seeking', 'readyState', 'src', 'currentSrc', 'error', 'videoWidth', 'videoHeight'] as const) readable(name)
524
596
  readable('buffered', toTimeRanges)
525
597
  readable('seekable', toTimeRanges)
598
+ readable('chapters')
526
599
 
527
600
  // Writes move the mirror at once, so a read in the same tick sees them (the seek bar reads its own
528
601
  // write back), and go out to be applied for real. Before the far side has answered they still go
@@ -547,6 +620,14 @@ export const mediaPlayer = (
547
620
  enumerable: true,
548
621
  })
549
622
  }
623
+ Object.defineProperty(player, 'fullscreen', {
624
+ get: () => fullscreen,
625
+ set: (value: boolean) => {
626
+ fullscreen = !!value
627
+ if (options.fullscreen) void after(() => link.set(playerId, 'fullscreen', fullscreen))
628
+ },
629
+ enumerable: true,
630
+ })
550
631
 
551
632
  const call = (name: Callable) => ready.then(() => {
552
633
  if (signal.aborted) throw abortError()
@@ -1,6 +1,7 @@
1
1
  // What crosses between a player and whoever embeds it. Pure and osra-free so the snapshot and the
2
2
  // mirror's arithmetic can be tested on values; ./index.ts is the half that talks.
3
3
 
4
+ import type { MediaChapter } from '../engine'
4
5
  import type { PlayerMedia, TimeRangesLike } from '../react/media'
5
6
 
6
7
  /**
@@ -28,6 +29,8 @@ export type PlayerSnapshot = {
28
29
  error: { code: number, message: string } | null
29
30
  videoWidth: number
30
31
  videoHeight: number
32
+ /** A `<MediaPlayer expose>`'s chapters, empty for a bare element. */
33
+ chapters: MediaChapter[]
31
34
  }
32
35
 
33
36
  /**
@@ -41,7 +44,12 @@ export const PLAYER_EVENTS = [
41
44
  'seeking', 'seeked', 'progress', 'ratechange', 'volumechange', 'ended', 'waiting', 'stalled', 'suspend',
42
45
  'canplay', 'canplaythrough', 'emptied', 'resize', 'error',
43
46
  ] as const
44
- export type PlayerEvent = typeof PLAYER_EVENTS[number]
47
+ /**
48
+ * The events a `<MediaPlayer expose>` raises beside its media's: its chapters changed, and its viewer pressed
49
+ * fullscreen while a mirror made with `fullscreen: true` has it.
50
+ */
51
+ export const SERVED_EVENTS = ['chapterschange', 'fullscreenrequest'] as const
52
+ export type PlayerEvent = typeof PLAYER_EVENTS[number] | typeof SERVED_EVENTS[number]
45
53
 
46
54
  /** The properties an embedder may set. Everything else is read-only on a media, here as there. */
47
55
  export const WRITABLE = ['currentTime', 'volume', 'muted', 'playbackRate'] as const
@@ -82,8 +90,10 @@ export type PlayerUpdate = { event: PlayerEvent, snapshot: PlayerSnapshot }
82
90
  * has not mounted yet.
83
91
  */
84
92
  export type PlayerService = {
85
- subscribe: (id: string, port: MessagePort) => void
86
- set: (id: string, name: Writable, value: number | boolean) => void
93
+ /** With `fullscreen`, the mirror takes the player's fullscreen over, in that state, until its port goes. */
94
+ subscribe: (id: string, port: MessagePort, options?: { fullscreen?: boolean }) => void
95
+ /** `fullscreen` is the state shown by a player whose fullscreen a mirror has taken over, and is ignored otherwise. */
96
+ set: (id: string, name: Writable | 'fullscreen', value: number | boolean) => void
87
97
  call: (id: string, name: Callable) => Promise<void>
88
98
  }
89
99
 
@@ -114,7 +124,7 @@ const pairs = (ranges: TimeRangesLike | undefined): [number, number][] => {
114
124
  }
115
125
 
116
126
  /** A media as a snapshot. A NaN duration, which a bare element answers before it has metadata, is sent as 0. */
117
- export const snapshotOf = (media: PlayerMedia): PlayerSnapshot => ({
127
+ export const snapshotOf = (media: PlayerMedia, chapters: MediaChapter[] = []): PlayerSnapshot => ({
118
128
  currentTime: finite(media.currentTime),
119
129
  duration: finite(media.duration),
120
130
  paused: media.paused,
@@ -131,6 +141,7 @@ export const snapshotOf = (media: PlayerMedia): PlayerSnapshot => ({
131
141
  error: media.error ? { code: media.error.code, message: media.error.message } : null,
132
142
  videoWidth: media.videoWidth ?? 0,
133
143
  videoHeight: media.videoHeight ?? 0,
144
+ chapters,
134
145
  })
135
146
 
136
147
  // NaN only. A live media reports `duration: Infinity` and means it, so sending 0 for it would mirror
@@ -141,7 +152,7 @@ const finite = (value: number): number => Number.isNaN(value) ? 0 : value
141
152
  export const EMPTY_SNAPSHOT: PlayerSnapshot = {
142
153
  currentTime: 0, duration: 0, paused: true, ended: false, seeking: false, readyState: 0,
143
154
  volume: 1, muted: false, playbackRate: 1, src: '', currentSrc: '',
144
- buffered: [], seekable: [], error: null, videoWidth: 0, videoHeight: 0,
155
+ buffered: [], seekable: [], error: null, videoWidth: 0, videoHeight: 0, chapters: [],
145
156
  }
146
157
 
147
158
  /** Plain pairs back into the structural `TimeRanges` the player reads. */