@banou/media-player 0.10.31 → 0.10.33

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.
@@ -26,13 +26,13 @@ export type MediaChapter = { start: number, end: number, title: string }
26
26
 
27
27
  /**
28
28
  * What the remuxer produced, in the order it was appended: the init segment and the input audio stream it carries,
29
- * a run at load and at every remuxer seek (`pts` is the timestampOffset its fragments are appended at), each
30
- * fragment, and the end of the file once read. The buffers are playback's own and may be appended again, so a
31
- * consumer copies what it keeps.
29
+ * a run at load and at every remuxer seek (`pts` is the timestampOffset its fragments are appended at, the same for
30
+ * every run, and `from` the time the run starts at), each fragment, and the end of the file once read. The buffers
31
+ * are playback's own and may be appended again, so a consumer copies what it keeps.
32
32
  */
33
33
  export type PlaybackOutput =
34
34
  | { type: 'init', data: ArrayBuffer, audioMimeType: string, audioStreamIndex: number }
35
- | { type: 'run', pts: number }
35
+ | { type: 'run', pts: number, from: number }
36
36
  | { type: 'fragment', data: ArrayBuffer }
37
37
  | { type: 'end' }
38
38
 
@@ -126,10 +126,11 @@ const SOURCE_OPEN_TIMEOUT = 15_000
126
126
  * How far past the playhead a range may start and still count as the one holding it, which decides how
127
127
  * much to read and never whether to fetch.
128
128
  *
129
- * Firefox 151 reports a range from its first presented frame, the reorder delay past its keyframe: 82 ms
130
- * on most fixtures and 166 ms on anime-chapters, at load and after every remuxer seek, where Chrome 153
131
- * reports the keyframe itself. Without the slack a playhead paused at 0 reads the whole file, and a
132
- * prepared seek to a keyframe builds no runway (measured 2026-10-11).
129
+ * A range starts at its first presented frame. While libav-wasm moved every track by the reorder delay (before
130
+ * 0.9.0), Firefox 151 reported each range 82 ms past its keyframe on most fixtures and 166 ms on anime-chapters, and
131
+ * without the slack a playhead paused at 0 read the whole file and a prepared seek to a keyframe built no runway
132
+ * (measured 2026-10-11). Firefox 157 and Chrome 155 now report the keyframe or earlier (measured 2026-10-30), and the
133
+ * slack covers a file whose first picture comes after 0.
133
134
  */
134
135
  const BOUNDARY_SLACK = 1
135
136
  /*
@@ -264,6 +265,7 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
264
265
  try {
265
266
  const sb = mediaSource.addSourceBuffer(mime)
266
267
  sb.mode = 'segments'
268
+ sb.timestampOffset = metadata.timestampOffset
267
269
  const duration = metadata.info.input.duration
268
270
  if (Number.isFinite(duration) && duration > 0) mediaSource.duration = duration
269
271
  cleanup()
@@ -279,10 +281,10 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
279
281
  mediaSource.addEventListener('error', onFail, { once: true })
280
282
  })
281
283
 
282
- const { appendBuffer, unbufferRange, updateTimestampOffset, endOfStream } = updateSourceBuffer(sourceBuffer, mediaSource)
284
+ const { appendBuffer, unbufferRange, endOfStream } = updateSourceBuffer(sourceBuffer, mediaSource)
283
285
  await appendBuffer(metadata.data)
284
286
  onOutput?.({ type: 'init', data: metadata.data, audioMimeType: metadata.info.output.audioMimeType, audioStreamIndex: selectedAudio })
285
- onOutput?.({ type: 'run', pts: 0 })
287
+ onOutput?.({ type: 'run', pts: metadata.timestampOffset, from: 0 })
286
288
  if (metadata.subtitles?.length) subtitles.pushFragments(metadata.subtitles)
287
289
  onReady?.()
288
290
 
@@ -428,9 +430,7 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
428
430
  if (destroyed || generation !== seekGeneration) return
429
431
  if (done) finished = true
430
432
  if (fragments?.length) subtitles.pushFragments(fragments)
431
- await updateTimestampOffset(pts)
432
- if (destroyed || generation !== seekGeneration) return
433
- onOutput?.({ type: 'run', pts })
433
+ onOutput?.({ type: 'run', pts: metadata.timestampOffset, from: pts })
434
434
  if (data.byteLength) onOutput?.({ type: 'fragment', data })
435
435
  if (done) onOutput?.({ type: 'end' })
436
436
  if (data.byteLength) {
@@ -531,8 +531,7 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
531
531
  * Whether the element can play from a GIVEN time without a fetch.
532
532
  *
533
533
  * Exact. A seek that lands before a range waits there for good once the gap passes 60 to 90 ms in
534
- * Chrome 153, or 250 to 300 ms in Firefox 151, so Firefox's reorder delay cannot be allowed for here
535
- * and a target inside it costs a remuxer seek (24 fps fixtures, measured 2026-10-11).
534
+ * Chrome 153, or 250 to 300 ms in Firefox 151 (24 fps fixtures, measured 2026-10-11).
536
535
  */
537
536
  const playableAt = (time: number) =>
538
537
  getTimeRanges(sourceBuffer).some((r) => r.start <= time && time < r.end)
@@ -692,8 +691,7 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
692
691
  * once its budget runs out, with the seek or the runway's reads still running. Without this, the
693
692
  * move fires `seeking`, which starts the identical read again and bumps the generation, throwing
694
693
  * away everything the first one had done. The benchmark caught it as a seek that took twice as
695
- * long as seeking the old way. It also covers a finished prepare to a keyframe in Firefox, whose
696
- * range starts the reorder delay past the target, so the target never counts as buffered.
694
+ * long as seeking the old way.
697
695
  */
698
696
  if (positioned && (seeking || runwayFrom(time) > 0) && Math.abs(time - lastSeekPosition) < 0.001) return
699
697
  finished = false
@@ -1,7 +1,6 @@
1
1
  import { labelledError } from '../labels'
2
2
 
3
- // appendBuffer, remove and timestampOffset must never overlap an in-flight update, so every op
4
- // goes through one chain
3
+ // appendBuffer and remove must never overlap an in-flight update, so every op goes through one chain
5
4
 
6
5
  export type TimeRange = { index: number, start: number, end: number }
7
6
 
@@ -49,9 +48,6 @@ export const updateSourceBuffer = (sourceBuffer: SourceBuffer, mediaSource: Medi
49
48
  return waitForUpdate(sourceBuffer)
50
49
  })
51
50
 
52
- const updateTimestampOffset = (timestampOffset: number) =>
53
- enqueue(async () => { sourceBuffer.timestampOffset = timestampOffset })
54
-
55
51
  /**
56
52
  * endOfStream throws mid-update and is undone by the next remove(), so the caller re-arms it.
57
53
  * `allowed` is asked when the call reaches the front of the queue, not when it is queued.
@@ -62,5 +58,5 @@ export const updateSourceBuffer = (sourceBuffer: SourceBuffer, mediaSource: Medi
62
58
  try { mediaSource.endOfStream() } catch {}
63
59
  })
64
60
 
65
- return { appendBuffer, unbufferRange, updateTimestampOffset, endOfStream }
61
+ return { appendBuffer, unbufferRange, endOfStream }
66
62
  }
@@ -137,10 +137,12 @@ export type ChromeProps = {
137
137
  shortcuts?: 'window' | 'player'
138
138
  /** Fullscreen kept by the host: a press calls its `request` instead of fullscreening the player. */
139
139
  fullscreen?: HostFullscreen
140
+ /** False leaves the last ending out of the skip offer. */
141
+ endingOffered: boolean
140
142
  children?: ReactNode
141
143
  }
142
144
 
143
- export const Chrome = ({ ref, onVideoRef, onSubtitleRef, overlay, controls, shortcuts, fullscreen, children }: ChromeProps) => {
145
+ export const Chrome = ({ ref, onVideoRef, onSubtitleRef, overlay, controls, shortcuts, fullscreen, endingOffered, children }: ChromeProps) => {
144
146
  const player = usePlayer()
145
147
  const hideUI = usePlayer((state) => state.hideUI)
146
148
  const setHideUI = usePlayer((state) => state.setHideUI)
@@ -327,7 +329,7 @@ export const Chrome = ({ ref, onVideoRef, onSubtitleRef, overlay, controls, shor
327
329
  )}
328
330
  {/* Not tied to `hideUI`: it says what to do next, and it is on screen for nine seconds. */}
329
331
  <BurnInHint />
330
- <SkipChapter />
332
+ <SkipChapter endingOffered={endingOffered} />
331
333
  {passThrough?.armed && root.current
332
334
  ? (
333
335
  <div
@@ -90,8 +90,10 @@ const style = css`
90
90
  * of the pair: the classifier reads titles written by whoever muxed the file, so it is sometimes
91
91
  * going to be wrong. Making the offer expire, and never acting on its own, is what makes being wrong
92
92
  * cheap. See the classifier for what it matches and the sample it was measured against.
93
+ *
94
+ * `endingOffered` false leaves the last ending out, for an embedder that fills this corner itself.
93
95
  */
94
- export const SkipChapter = () => {
96
+ export const SkipChapter = ({ endingOffered }: { endingOffered: boolean }) => {
95
97
  const chapters = usePlayer((state) => state.chapters)
96
98
  const currentTime = usePlayer((state) => state.currentTime)
97
99
  const requestSeek = usePlayer((state) => state.requestSeek)
@@ -104,7 +106,11 @@ export const SkipChapter = () => {
104
106
  const player = usePlayer()
105
107
  const { format } = useLabels()
106
108
 
107
- const kinds = useMemo(() => classifyChapters(chapters), [chapters])
109
+ const kinds = useMemo(() => {
110
+ const all = classifyChapters(chapters)
111
+ const left = endingOffered ? -1 : all.lastIndexOf('ending')
112
+ return all.map((kind, index) => index === left ? undefined : kind)
113
+ }, [chapters, endingOffered])
108
114
 
109
115
  /**
110
116
  * The chapter worth offering to skip, from a second before it starts until it ends.
@@ -367,8 +367,14 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
367
367
  // What `expose` serves beside the media, the same object for the player's life. Its `onHostFullscreen` is how a
368
368
  // mirror made with `fullscreen: true` takes the fullscreen over.
369
369
  const [embedderFullscreen, setEmbedderFullscreen] = useState<boolean | null>(null)
370
- const [served] = useState<ServedPlayer & { chapters: MediaChapter[] }>(
371
- () => Object.assign(new EventTarget(), { chapters: [], onHostFullscreen: setEmbedderFullscreen }),
370
+ const [endingOffered, setEndingOffered] = useState(true)
371
+ const [served] = useState<ServedPlayer & { chapters: MediaChapter[], endingOffered: boolean }>(
372
+ () => Object.assign(new EventTarget(), {
373
+ chapters: [],
374
+ endingOffered: true,
375
+ onHostFullscreen: setEmbedderFullscreen,
376
+ onEndingOffered: setEndingOffered,
377
+ }),
372
378
  )
373
379
  const exposeOptions = expose === true ? {} : expose || undefined
374
380
  const latestExpose = useRef(exposeOptions)
@@ -392,10 +398,12 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
392
398
  // by value, since a caller's inline `chapters` is a new array on every render
393
399
  const playerChapters = usePlayer((state) => state.chapters)
394
400
  const chaptersKey = JSON.stringify(playerChapters)
401
+ // after the commit, so a mirror that hears the ending is no longer offered finds the button already gone
395
402
  useEffect(() => {
396
403
  served.chapters = playerChapters
404
+ served.endingOffered = endingOffered
397
405
  served.dispatchEvent(new Event('chapterschange'))
398
- }, [chaptersKey])
406
+ }, [chaptersKey, endingOffered])
399
407
 
400
408
  const fullscreen = options.fullscreen ?? (embedderFullscreen === null ? undefined : {
401
409
  active: embedderFullscreen,
@@ -581,6 +589,7 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
581
589
  controls={options.controls}
582
590
  shortcuts={options.shortcuts}
583
591
  fullscreen={fullscreen}
592
+ endingOffered={endingOffered}
584
593
  >
585
594
  {children}
586
595
  </Chrome>
@@ -83,14 +83,17 @@ export type ExposePlayerOptions = {
83
83
  }
84
84
 
85
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.
86
+ * The player around a served media, as `<MediaPlayer expose>` passes it: its chapters and whether it offers to skip its
87
+ * last ending, sent with every snapshot and announced on its `chapterschange`, and its fullscreen, which a mirror made
88
+ * with `fullscreen: true` takes over. While one has it, `onHostFullscreen` is told the state that mirror sets, and null
89
+ * once none has it; the player then dispatches `fullscreenrequest` for each press of its fullscreen, which reaches the
90
+ * mirror. `onEndingOffered` is told what a mirror sets on `endingOffered`.
90
91
  */
91
92
  export type ServedPlayer = EventTarget & {
92
93
  readonly chapters: MediaChapter[]
94
+ readonly endingOffered: boolean
93
95
  onHostFullscreen: (active: boolean | null) => void
96
+ onEndingOffered: (offered: boolean) => void
94
97
  }
95
98
 
96
99
  /**
@@ -173,7 +176,8 @@ const channelFor = (options: ExposePlayerOptions): Channel => {
173
176
  }
174
177
  const snapshotAt = (id: string) => {
175
178
  const media = medias.get(id)
176
- return media ? snapshotOf(media, players.get(id)?.chapters) : undefined
179
+ const around = players.get(id)
180
+ return media ? snapshotOf(media, around?.chapters, around?.endingOffered) : undefined
177
181
  }
178
182
  const announce = (id: string, event: PlayerEvent) => {
179
183
  // a press of the fullscreen is for the mirrors that took it over: another one toggling too would undo it
@@ -223,6 +227,10 @@ const channelFor = (options: ExposePlayerOptions): Channel => {
223
227
  tellHost(id)
224
228
  return
225
229
  }
230
+ if (name === 'endingOffered') {
231
+ if (typeof value === 'boolean') players.get(id)?.onEndingOffered(value)
232
+ return
233
+ }
226
234
  const media = medias.get(id)
227
235
  if (!media || !WRITABLE.includes(name)) return
228
236
  try { (media as unknown as Record<Writable, unknown>)[name] = value } catch {}
@@ -333,6 +341,16 @@ export type MediaPlayerHandle =
333
341
  * shortcuts follow it. Set it on every change. Without the option it stays here.
334
342
  */
335
343
  fullscreen: boolean
344
+ /**
345
+ * Whether the far `<MediaPlayer expose>` offers to skip its last ending, as it last said. Set it to false to have
346
+ * that offer taken away, for a page with something of its own in that corner, and to true to have it back; a
347
+ * mirror's `destroy()` leaves it as it is, and a new player starts out offering.
348
+ *
349
+ * Unlike every other write here this one does NOT move the mirror: a read answers what the far player reports,
350
+ * from after its render, with a `chapterschange` event following each change. So a false here means the offer is
351
+ * off the far screen, and a player that cannot take it (a bare element, a version older than this) stays true.
352
+ */
353
+ endingOffered: boolean
336
354
  /**
337
355
  * Settles once the far side has first answered with its state; reads before that answer the
338
356
  * empty defaults. Stays pending for as long as nobody answers, and rejects with an AbortError on
@@ -417,7 +435,7 @@ type Subscriber = {
417
435
 
418
436
  type Link = {
419
437
  attach: (subscriber: Subscriber) => () => void
420
- set: (id: string, name: Writable | 'fullscreen', value: number | boolean) => Promise<unknown> | undefined
438
+ set: (id: string, name: Writable | 'fullscreen' | 'endingOffered', value: number | boolean) => Promise<unknown> | undefined
421
439
  call: (id: string, name: Callable) => Promise<void>
422
440
  }
423
441
 
@@ -628,6 +646,11 @@ export const mediaPlayer = (
628
646
  },
629
647
  enumerable: true,
630
648
  })
649
+ Object.defineProperty(player, 'endingOffered', {
650
+ get: () => state.endingOffered,
651
+ set: (value: boolean) => { void after(() => link.set(playerId, 'endingOffered', value)) },
652
+ enumerable: true,
653
+ })
631
654
 
632
655
  const call = (name: Callable) => ready.then(() => {
633
656
  if (signal.aborted) throw abortError()
@@ -31,6 +31,8 @@ export type PlayerSnapshot = {
31
31
  videoHeight: number
32
32
  /** A `<MediaPlayer expose>`'s chapters, empty for a bare element. */
33
33
  chapters: MediaChapter[]
34
+ /** Whether a `<MediaPlayer expose>` offers to skip its last ending. Set after its render, so false means the offer is off the screen. */
35
+ endingOffered: boolean
34
36
  }
35
37
 
36
38
  /**
@@ -93,7 +95,7 @@ export type PlayerService = {
93
95
  /** With `fullscreen`, the mirror takes the player's fullscreen over, in that state, until its port goes. */
94
96
  subscribe: (id: string, port: MessagePort, options?: { fullscreen?: boolean }) => void
95
97
  /** `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
98
+ set: (id: string, name: Writable | 'fullscreen' | 'endingOffered', value: number | boolean) => void
97
99
  call: (id: string, name: Callable) => Promise<void>
98
100
  }
99
101
 
@@ -124,7 +126,7 @@ const pairs = (ranges: TimeRangesLike | undefined): [number, number][] => {
124
126
  }
125
127
 
126
128
  /** A media as a snapshot. A NaN duration, which a bare element answers before it has metadata, is sent as 0. */
127
- export const snapshotOf = (media: PlayerMedia, chapters: MediaChapter[] = []): PlayerSnapshot => ({
129
+ export const snapshotOf = (media: PlayerMedia, chapters: MediaChapter[] = [], endingOffered = true): PlayerSnapshot => ({
128
130
  currentTime: finite(media.currentTime),
129
131
  duration: finite(media.duration),
130
132
  paused: media.paused,
@@ -142,6 +144,7 @@ export const snapshotOf = (media: PlayerMedia, chapters: MediaChapter[] = []): P
142
144
  videoWidth: media.videoWidth ?? 0,
143
145
  videoHeight: media.videoHeight ?? 0,
144
146
  chapters,
147
+ endingOffered,
145
148
  })
146
149
 
147
150
  // NaN only. A live media reports `duration: Infinity` and means it, so sending 0 for it would mirror
@@ -152,7 +155,7 @@ const finite = (value: number): number => Number.isNaN(value) ? 0 : value
152
155
  export const EMPTY_SNAPSHOT: PlayerSnapshot = {
153
156
  currentTime: 0, duration: 0, paused: true, ended: false, seeking: false, readyState: 0,
154
157
  volume: 1, muted: false, playbackRate: 1, src: '', currentSrc: '',
155
- buffered: [], seekable: [], error: null, videoWidth: 0, videoHeight: 0, chapters: [],
158
+ buffered: [], seekable: [], error: null, videoWidth: 0, videoHeight: 0, chapters: [], endingOffered: true,
156
159
  }
157
160
 
158
161
  /** Plain pairs back into the structural `TimeRanges` the player reads. */