@banou/media-player 0.10.50 → 0.10.52

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.
@@ -278,7 +278,10 @@ var t = [
278
278
  let _ = () => new DOMException("the remote player was closed", "AbortError"), v = /* @__PURE__ */ new Set(), y = () => {
279
279
  for (let e of [...v]) e(_());
280
280
  v.clear();
281
- }, b = /* @__PURE__ */ new Map(), x = !1, S = !1, w = C(e, t).attach({
281
+ }, b = /* @__PURE__ */ new Map(), x = !1, S = !1, w = 0, T = /* @__PURE__ */ new Set(), D = () => {
282
+ w++;
283
+ for (let e of Array.from(T)) e();
284
+ }, O = C(e, t).attach({
282
285
  id: a,
283
286
  fullscreen: t.fullscreen ? () => S : void 0,
284
287
  reset: () => {
@@ -291,15 +294,15 @@ var t = [
291
294
  Object.assign(o, t);
292
295
  for (let [e, t] of b) o[e] = t;
293
296
  let a = n ? s(o) : [e];
294
- !a.includes("chapterschange") && JSON.stringify(o.chapters) !== r && a.push("chapterschange"), !a.includes("autoplaynextchange") && o.autoplayNext !== i && a.push("autoplaynextchange");
297
+ !a.includes("chapterschange") && JSON.stringify(o.chapters) !== r && a.push("chapterschange"), !a.includes("autoplaynextchange") && o.autoplayNext !== i && a.push("autoplaynextchange"), !n && e === "pause" && D();
295
298
  for (let e of a) l(e);
296
299
  n && u();
297
300
  }
298
- }), T = () => {
299
- w(), y(), p(_());
301
+ }), k = () => {
302
+ O(), y(), p(_());
300
303
  };
301
- i.aborted ? queueMicrotask(T) : i.addEventListener("abort", T, { once: !0 });
302
- let D = (e, t) => Object.defineProperty(c, e, {
304
+ i.aborted ? queueMicrotask(k) : i.addEventListener("abort", k, { once: !0 });
305
+ let A = (e, t) => Object.defineProperty(c, e, {
303
306
  get: () => t ? t(o[e]) : o[e],
304
307
  enumerable: !0
305
308
  });
@@ -314,14 +317,14 @@ var t = [
314
317
  "error",
315
318
  "videoWidth",
316
319
  "videoHeight"
317
- ]) D(e);
318
- D("buffered", f), D("seekable", f), D("chapters");
319
- let O = (e) => g.then(() => i.aborted ? void 0 : e()).catch(() => {}), k = C(e, t);
320
+ ]) A(e);
321
+ A("buffered", f), A("seekable", f), A("chapters");
322
+ let j = (e) => g.then(() => i.aborted ? void 0 : e()).catch(() => {}), M = C(e, t);
320
323
  for (let e of r) Object.defineProperty(c, e, {
321
324
  get: () => o[e],
322
325
  set: (t) => {
323
- o[e] = t, b.set(e, t), O(async () => {
324
- await k.set(a, e, t), b.get(e) === t && b.delete(e);
326
+ o[e] = t, b.set(e, t), j(async () => {
327
+ await M.set(a, e, t), b.get(e) === t && b.delete(e);
325
328
  });
326
329
  },
327
330
  enumerable: !0
@@ -329,25 +332,25 @@ var t = [
329
332
  Object.defineProperty(c, "fullscreen", {
330
333
  get: () => S,
331
334
  set: (e) => {
332
- S = !!e, t.fullscreen && O(() => k.set(a, "fullscreen", S));
335
+ S = !!e, t.fullscreen && j(() => M.set(a, "fullscreen", S));
333
336
  },
334
337
  enumerable: !0
335
338
  }), Object.defineProperty(c, "endingOffered", {
336
339
  get: () => o.endingOffered,
337
340
  set: (e) => {
338
- O(() => k.set(a, "endingOffered", e));
341
+ j(() => M.set(a, "endingOffered", e));
339
342
  },
340
343
  enumerable: !0
341
344
  }), Object.defineProperty(c, "autoplayNext", {
342
345
  get: () => o.autoplayNext,
343
346
  set: (e) => {
344
- typeof e == "boolean" && O(() => k.set(a, "autoplayNext", e));
347
+ typeof e == "boolean" && j(() => M.set(a, "autoplayNext", e));
345
348
  },
346
349
  enumerable: !0
347
350
  });
348
- let A = (e) => g.then(() => {
351
+ let N = (e) => g.then(() => {
349
352
  if (i.aborted) throw _();
350
- let t = k.call(a, e);
353
+ let t = M.call(a, e);
351
354
  return new Promise((e, n) => {
352
355
  v.add(n), t.then(() => {
353
356
  v.delete(n), e();
@@ -356,42 +359,60 @@ var t = [
356
359
  });
357
360
  });
358
361
  });
359
- c.play = () => (o.paused = !1, A("play").catch((e) => {
362
+ c.play = () => (o.paused = !1, N("play").catch((e) => {
360
363
  throw o.paused = !0, e;
361
364
  }));
362
- let j = () => new Promise((e) => {
363
- let t = (t) => {
364
- clearTimeout(r), c.removeEventListener("playing", n), c.removeEventListener("play", n), e(t);
365
- }, n = () => t(!0);
366
- c.addEventListener("playing", n), c.addEventListener("play", n);
367
- let r = setTimeout(() => t(!o.paused), m);
368
- }), M = async () => {
369
- let e = !o.paused, t;
365
+ let P = async () => {
366
+ let e = !o.paused, t = w, n = !1, r, a, s, l, u, d = () => {
367
+ s && (c.removeEventListener("playing", s), c.removeEventListener("play", s)), l && T.delete(l), u && i.removeEventListener("abort", u);
368
+ };
369
+ e || (a = new Promise((e) => {
370
+ r = (t) => {
371
+ d(), e(t);
372
+ };
373
+ }), s = () => {
374
+ n = !0, r?.(!0);
375
+ }, l = () => r?.(!1), u = () => r?.(!1), c.addEventListener("playing", s), c.addEventListener("play", s), T.add(l), i.addEventListener("abort", u, { once: !0 }));
376
+ let f;
370
377
  try {
371
378
  await c.play();
372
379
  } catch (e) {
373
- t = e;
380
+ f = e;
374
381
  }
375
- return e ? {
382
+ if (e) return {
376
383
  started: !0,
377
- refusal: t
378
- } : {
379
- started: await j(),
380
- refusal: t
384
+ paused: !1,
385
+ refusal: f
386
+ };
387
+ let p = () => w !== t;
388
+ if (n || p() || i.aborted) return d(), {
389
+ started: n && !p(),
390
+ paused: p(),
391
+ refusal: f
381
392
  };
393
+ let h = setTimeout(() => r?.(!o.paused && !p()), m);
394
+ try {
395
+ return {
396
+ started: await a && !p(),
397
+ paused: p(),
398
+ refusal: f
399
+ };
400
+ } finally {
401
+ clearTimeout(h), d();
402
+ }
382
403
  };
383
404
  return c.autoplay = async () => {
384
- let e = await M();
385
- if (e.started) return { muted: c.muted };
386
- if (c.muted || i.aborted) throw e.refusal ?? h();
405
+ let e = w, t = await P();
406
+ if (t.started) return { muted: c.muted };
407
+ if (t.paused || w !== e || c.muted || i.aborted) throw t.refusal ?? h();
387
408
  c.muted = !0;
388
- let t = await M();
389
- if (t.started) return { muted: !0 };
390
- throw c.muted = !1, e.refusal ?? t.refusal ?? h();
409
+ let n = await P();
410
+ if (n.started) return { muted: !0 };
411
+ throw c.muted = !1, t.refusal ?? n.refusal ?? h();
391
412
  }, c.pause = () => {
392
- o.paused = !0, A("pause").catch(() => {});
413
+ o.paused = !0, D(), N("pause").catch(() => {});
393
414
  }, c.load = () => {
394
- A("load").catch(() => {});
415
+ N("load").catch(() => {});
395
416
  }, Object.defineProperty(c, "ready", {
396
417
  value: g,
397
418
  enumerable: !1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@banou/media-player",
3
- "version": "0.10.50",
3
+ "version": "0.10.52",
4
4
  "description": "A video player for containers and codecs the browser cannot play natively, remuxed on the fly",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -160,6 +160,7 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
160
160
  /** The video's time at the last frame callback, which the subtitle surface was rendered for. */
161
161
  let frameTime = 0
162
162
  let syncing = false
163
+ let releaseSync: (() => void) | undefined
163
164
  /** Burn-in only: a deliberate play/pause pair to push one frame, which must not reach the video. */
164
165
  let flushing = false
165
166
  // Nothing can tell a session is being built until `enter` resolves, so without this a second click
@@ -245,6 +246,30 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
245
246
  void video.play().catch(() => {})
246
247
  }
247
248
 
249
+ /** Keeps `syncing` set past a mirror's queued `play` event so our own `mirror.play()` cannot resume `video`. */
250
+ const suppressNextMirrorPlay = (mirror: HTMLVideoElement) => {
251
+ releaseSync?.()
252
+ syncing = true
253
+ const release = () => {
254
+ if (releaseSync !== release) return
255
+ clearTimeout(timer)
256
+ mirror.removeEventListener('play', release)
257
+ releaseSync = undefined
258
+ syncing = false
259
+ }
260
+ releaseSync = release
261
+ const timer = setTimeout(release, FLUSH_FRAME_MS)
262
+ mirror.addEventListener('play', release, { once: true })
263
+ return release
264
+ }
265
+
266
+ const playMirrorSilently = (mirror: HTMLVideoElement) => {
267
+ const release = suppressNextMirrorPlay(mirror)
268
+ void mirror.play().catch((error: unknown) => {
269
+ if ((error as DOMException)?.name !== 'AbortError') release()
270
+ })
271
+ }
272
+
248
273
  /**
249
274
  * Reached on a browser whose window controls drive the popped out element directly instead of going
250
275
  * through the Media Session. Firefox is that browser, and in burn-in its window is driving the
@@ -258,13 +283,12 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
258
283
  if (!video.paused) video.pause()
259
284
  // In window mode the mirror must never be left paused; see `onVideoPause`.
260
285
  if (mode === 'burn-in') return
261
- syncing = true
262
- void session?.mirror.play().catch(() => {}).finally(() => { syncing = false })
286
+ if (session) playMirrorSilently(session.mirror)
263
287
  }
264
288
 
265
289
  const onVideoPlay = () => {
266
290
  publishState()
267
- void session?.mirror.play().catch(() => {})
291
+ if (session) playMirrorSilently(session.mirror)
268
292
  }
269
293
 
270
294
  /**
@@ -284,6 +308,9 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
284
308
 
285
309
  /** A paused mirror renders nothing, so a scrub would leave the old frame on screen forever. */
286
310
  const onVideoSeeked = () => {
311
+ // Subtitles repaint on `seeked` without waiting for a frame callback, so a seek while paused
312
+ // stays fresh even when no requestVideoFrameCallback fires after it.
313
+ frameTime = video.currentTime
287
314
  if (mode !== 'burn-in' || !session || !video.paused || flushing) return
288
315
  flushing = true
289
316
  const { mirror } = session
@@ -337,6 +364,7 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
337
364
 
338
365
  /** Lets go of the session, mirror and window left as they are. */
339
366
  const detach = () => {
367
+ releaseSync?.()
340
368
  stopLoop()
341
369
  bindMediaSession(false)
342
370
  video.removeEventListener('play', onVideoPlay)
@@ -429,7 +457,10 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
429
457
  ;(options.container ?? (mode === 'burn-in' ? video.parentElement : null) ?? document.body).appendChild(mirror)
430
458
 
431
459
  start()
432
- void mirror.play().catch(() => {})
460
+ let bootPlaying = true
461
+ const onBootPlay = () => { bootPlaying = false }
462
+ mirror.addEventListener('play', onBootPlay, { once: true })
463
+ void mirror.play().catch(onBootPlay)
433
464
 
434
465
  // requestPictureInPicture rejects while readyState is 0, and the wait is short enough that the
435
466
  // click's transient user activation survives it.
@@ -444,11 +475,14 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
444
475
  // A destroy or a re-entered toggle can land inside that wait. Binding anyway would leave listeners
445
476
  // and a Media Session handler pointing at a dead session for the rest of the page's life.
446
477
  if (destroyed || session !== mine) {
478
+ mirror.removeEventListener('play', onBootPlay)
447
479
  mirror.remove()
448
480
  return
449
481
  }
450
482
 
483
+ mirror.removeEventListener('play', onBootPlay)
451
484
  listen(mirror)
485
+ if (bootPlaying) suppressNextMirrorPlay(mirror)
452
486
 
453
487
  if (mode === 'burn-in') {
454
488
  // No window to open: the browser's own control does that, on the element now on screen.
@@ -126,6 +126,8 @@ const PRE_EVICT_TIGHT = -5
126
126
  const POST_EVICT_TIGHT = 20
127
127
  const MAX_APPEND_ATTEMPTS = 5
128
128
  const SOURCE_OPEN_TIMEOUT = 15_000
129
+ // MSE fires SourceBuffer `error` ahead of the media thread's element `error` event.
130
+ const INIT_ERROR_SETTLE_MS = 500
129
131
  /*
130
132
  * How far past the playhead a range may start and still count as the one holding it, which decides how
131
133
  * much to read and never whether to fetch.
@@ -233,6 +235,38 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
233
235
  const mime = `video/mp4; codecs="${codecs}"`
234
236
  if (!MediaSource.isTypeSupported(mime)) throw labelledError('This browser cannot play the codecs in this file: {codecs}', { codecs })
235
237
 
238
+ let outstandingError = false
239
+ // 'Cancelled' covers both an aborted task and a read that gave up, so it is only noise mid-seek
240
+ const reportError = (error: unknown, aborted: boolean, terminal = false) => {
241
+ const cancelled = (error as Error)?.message === 'Cancelled'
242
+ if (aborted && cancelled) return
243
+ console.error(error)
244
+ // A terminal failure of the element outranks whatever was already outstanding. It is the one
245
+ // error whose HANDLING differs, and the sequence that produces it starts with a starved
246
+ // buffer, which is also when a read is most likely to have reported first. Swallowing it
247
+ // behind that earlier report would leave the caller holding a dead element, able to fix it
248
+ // and never told to.
249
+ if (outstandingError && !terminal) return
250
+ outstandingError = true
251
+ onError?.(cancelled ? labelledError('Reading the video file failed', undefined, { cause: error }) : error)
252
+ }
253
+
254
+ /**
255
+ * A terminal failure of the media element, attached before the MediaSource is bound so an error
256
+ * during init append cannot pass unobserved and leave the interval stopped for good.
257
+ */
258
+ let elementFailed = false
259
+ const onElementError = () => {
260
+ if (elementFailed || destroyed) return
261
+ elementFailed = true
262
+ const error = videoElement.error
263
+ reportError(
264
+ new MediaElementError(`the media element failed: ${error?.message ?? 'unknown'}`, { cause: error }),
265
+ false,
266
+ true,
267
+ )
268
+ }
269
+
236
270
  const mediaSource = new MediaSource()
237
271
  const mediaSourceUrl = URL.createObjectURL(mediaSource)
238
272
  teardown.push(() => URL.revokeObjectURL(mediaSourceUrl))
@@ -259,6 +293,9 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
259
293
  // without firing `error`, so this cannot manufacture the failure it exists to prevent
260
294
  videoElement.load()
261
295
  })
296
+ // Pushed AFTER the load() reset so reversed teardown detaches the error listener first.
297
+ videoElement.addEventListener('error', onElementError)
298
+ teardown.push(() => videoElement.removeEventListener('error', onElementError))
262
299
 
263
300
  const sourceBuffer = await new Promise<SourceBuffer>((resolve, reject) => {
264
301
  const timeout = setTimeout(() => { cleanup(); reject(labelledError('The MediaSource never opened')) }, SOURCE_OPEN_TIMEOUT)
@@ -289,14 +326,29 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
289
326
  })
290
327
 
291
328
  const { appendBuffer, unbufferRange, endOfStream } = updateSourceBuffer(sourceBuffer, mediaSource)
292
- await appendBuffer(metadata.data)
293
- onOutput?.({ type: 'init', data: metadata.data, audioMimeType: metadata.info.output.audioMimeType, audioStreamIndex: selectedAudio })
294
- onOutput?.({ type: 'run', pts: metadata.timestampOffset, from: 0 })
295
- if (metadata.subtitles?.length) subtitles.pushFragments(metadata.subtitles)
296
- onReady?.()
329
+ try {
330
+ await appendBuffer(metadata.data)
331
+ } catch (error) {
332
+ // MSE fires SourceBuffer `error` before the media thread delivers the element `error` event,
333
+ // so wait briefly for it before deciding this was a plain append failure.
334
+ if (!elementFailed && !videoElement.error) {
335
+ await new Promise<void>((resolve) => {
336
+ const done = () => {
337
+ clearTimeout(timer)
338
+ videoElement.removeEventListener('error', done)
339
+ resolve()
340
+ }
341
+ const timer = setTimeout(done, INIT_ERROR_SETTLE_MS)
342
+ videoElement.addEventListener('error', done, { once: true })
343
+ })
344
+ }
345
+ if (!elementFailed && !videoElement.error) throw error
346
+ }
347
+ if (videoElement.error) onElementError()
297
348
 
298
349
  let reading = false
299
350
  let seeking = false
351
+ let dragTimer: ReturnType<typeof setTimeout> | undefined
300
352
  // how many prepares are in flight, so eviction knows not to delete what they are fetching
301
353
  let preparing = 0
302
354
  /*
@@ -318,54 +370,44 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
318
370
  let pending: ArrayBuffer | null = null
319
371
  let pendingAttempts = 0
320
372
  let lastAppendedEnd = 0
321
- let outstandingError = false
322
373
  // where the remuxer was last positioned, which is the floor of what it can still read forward from
323
374
  let lastSeekPosition = 0
324
375
  // whether nothing was removed since, so everything read forward from there is still buffered
325
376
  let positioned = true
326
-
327
- // 'Cancelled' covers both an aborted task and a read that gave up, so it is only noise mid-seek
328
- const reportError = (error: unknown, aborted: boolean, terminal = false) => {
329
- const cancelled = (error as Error)?.message === 'Cancelled'
330
- if (aborted && cancelled) return
331
- console.error(error)
332
- // A terminal failure of the element outranks whatever was already outstanding. It is the one
333
- // error whose HANDLING differs, and the sequence that produces it starts with a starved
334
- // buffer, which is also when a read is most likely to have reported first. Swallowing it
335
- // behind that earlier report would leave the caller holding a dead element, able to fix it
336
- // and never told to.
337
- if (outstandingError && !terminal) return
338
- outstandingError = true
339
- onError?.(cancelled ? labelledError('Reading the video file failed', undefined, { cause: error }) : error)
340
- }
377
+ let evicting = 0
341
378
 
342
379
  const evict = async (tight = false) => {
343
380
  /*
344
- * Hold off while data is being put in place for a position the playhead has not reached.
381
+ * Hold off while a prior eviction, a remuxer seek, or a seek prepare is in flight.
345
382
  *
346
383
  * Eviction is anchored on the playhead, and `prepareSeek` deliberately appends far from it, so
347
- * running now deletes exactly what was just fetched. The 100ms interval below made that a
348
- * certainty. The benchmark caught it as prepared seeks being the SLOWEST arm, which is the
349
- * opposite of the point.
384
+ * running now deletes exactly what was just fetched. The 100ms interval below also stacked
385
+ * duplicate removes onto the SourceBuffer queue whenever a remove or append took over 100ms.
350
386
  *
351
387
  * `tight` still runs, because that one is the answer to a quota refusal and has to be able to
352
388
  * free space no matter what else is happening.
353
389
  */
354
- if (preparing > 0 && !tight) return
355
- const ct = videoElement.currentTime
356
- const pre = tight ? PRE_EVICT_TIGHT : PRE_EVICT
357
- const post = tight ? POST_EVICT_TIGHT : POST_EVICT
358
- const ranges = getTimeRanges(sourceBuffer)
359
- const remove = (start: number, end: number) => {
360
- positioned = false
361
- return unbufferRange(start, end)
362
- }
363
- // From 0, never from the reported start: once a group is removed, Firefox 151 reports the start
364
- // 1 ms after the keyframe it still holds, so a remove from there keeps that frame for good
365
- // (measured 2026-10-11).
366
- if (ranges.length && ranges[0].start < ct + pre) await remove(0, ct + pre)
367
- for (const { end } of ranges) {
368
- if (end > ct + post) await remove(ct + post, end)
390
+ if (!tight && (evicting > 0 || preparing > 0 || seeking || videoElement.seeking || dragTimer !== undefined)) return
391
+ evicting++
392
+ try {
393
+ const ct = videoElement.currentTime
394
+ const pre = tight ? PRE_EVICT_TIGHT : PRE_EVICT
395
+ const post = tight ? POST_EVICT_TIGHT : POST_EVICT
396
+ const ranges = getTimeRanges(sourceBuffer)
397
+ const remove = (start: number, end: number) => {
398
+ positioned = false
399
+ return unbufferRange(start, end)
400
+ }
401
+ // From 0, never from the reported start: once a group is removed, Firefox 151 reports the start
402
+ // 1 ms after the keyframe it still holds, so a remove from there keeps that frame for good
403
+ // (measured 2026-10-11).
404
+ if (ranges.length && ranges[0].start < ct + pre) await remove(0, ct + pre)
405
+ if (destroyed || (!tight && (preparing > 0 || seeking || videoElement.seeking || dragTimer !== undefined))) return
406
+ const afterCt = videoElement.currentTime
407
+ const farEnd = getTimeRanges(sourceBuffer).at(-1)?.end ?? 0
408
+ if (farEnd > afterCt + post) await remove(afterCt + post, farEnd)
409
+ } finally {
410
+ evicting--
369
411
  }
370
412
  }
371
413
 
@@ -581,7 +623,7 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
581
623
  * takes, and over a torrent that is unbounded.
582
624
  */
583
625
  const prepareSeek = async (time: number) => {
584
- if (destroyed) return
626
+ if (destroyed || elementFailed || videoElement.error) return
585
627
  if (playableAt(time) && hasRunway(time)) return
586
628
  // A drag still settling holds every read, so the runway would never be read, and its settle would then position the
587
629
  // remuxer back where the drag stopped. A seek back under 250 ms after a seek forward is one (Firefox 153 and 157,
@@ -676,10 +718,10 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
676
718
  * moves is a drag, and a drag gets one seek when it settles, to wherever it actually stopped.
677
719
  */
678
720
  let lastSeekingAt = 0
679
- let dragTimer: ReturnType<typeof setTimeout> | undefined
680
721
  teardown.push(() => { if (dragTimer) clearTimeout(dragTimer) })
681
722
 
682
723
  const onSeeking = () => {
724
+ if (destroyed || elementFailed || videoElement.error) return
683
725
  const time = videoElement.currentTime
684
726
  const duration = metadata.info.input.duration || videoElement.duration
685
727
  if (duration > 0) reportSeek(Math.min(Math.max(time / duration, 0), 1))
@@ -718,52 +760,28 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
718
760
  void seekTo(settled)
719
761
  }, DRAG_SETTLE_MS)
720
762
  }
721
- videoElement.addEventListener('seeking', onSeeking)
722
- teardown.push(() => videoElement.removeEventListener('seeking', onSeeking))
723
-
724
- /**
725
- * A terminal failure of the media element, which NOTHING here used to observe.
726
- *
727
- * `MediaError` is set once and the element never plays again, but the pump below kept running,
728
- * and every `appendBuffer` after it throws `InvalidStateError: The HTMLMediaElement.error
729
- * attribute is not null`. `updateSourceBuffer`'s chain deliberately survives a rejection, so that
730
- * repeated forever, and `flushPending` swallows four attempts and rethrows the fifth. What
731
- * reached the viewer was therefore the FIFTH `InvalidStateError` rather than the real cause, and
732
- * the real cause never appeared anywhere at all.
733
- *
734
- * That cost a session: a decode failure presented as an append bug, which is a completely
735
- * different place to look. Report what actually happened, then stop.
736
- *
737
- * It is reported as a MediaElementError because the caller can do something about this one that
738
- * it cannot do about any other: nothing appended here will ever decode again, but a rebuilt
739
- * element gets a fresh decoder, and the pipeline already knows how to come back at the same
740
- * position. See `isMediaElementError`.
741
- */
742
- let elementFailed = false
743
- const onElementError = () => {
744
- if (elementFailed) return
745
- elementFailed = true
746
- const error = videoElement.error
747
- reportError(
748
- new MediaElementError(`the media element failed: ${error?.message ?? 'unknown'}`, { cause: error }),
749
- false,
750
- true,
751
- )
763
+ if (!elementFailed && !destroyed) {
764
+ videoElement.addEventListener('seeking', onSeeking)
765
+ teardown.push(() => videoElement.removeEventListener('seeking', onSeeking))
766
+ onOutput?.({ type: 'init', data: metadata.data, audioMimeType: metadata.info.output.audioMimeType, audioStreamIndex: selectedAudio })
767
+ onOutput?.({ type: 'run', pts: metadata.timestampOffset, from: 0 })
768
+ if (metadata.subtitles?.length) subtitles.pushFragments(metadata.subtitles)
769
+ onReady?.()
752
770
  }
753
- videoElement.addEventListener('error', onElementError)
754
- teardown.push(() => videoElement.removeEventListener('error', onElementError))
755
771
 
756
- const interval = setInterval(() => {
757
- // Nothing below can succeed against a failed element, and retrying only buries the real error.
758
- if (elementFailed || videoElement.error) return
759
- evict().catch(() => {})
760
- pump().catch((error) => reportError(error, false))
761
- // Every remove() puts the MediaSource back to 'open', so the end has to be re-armed, though not while a remuxer
762
- // seek runs: queued behind a remove() and run after a move had started one, it came before that seek's append over
763
- // the end, and Firefox 151 then sometimes waited at the end for good (4 of 1060 end moves, measured 2026-10-12)
764
- if (endInBuffer() && !pending && atEnd() && mediaSource.readyState === 'open') endOfStream(() => !seeking).catch(() => {})
765
- }, 100)
766
- teardown.push(() => clearInterval(interval))
772
+ if (!elementFailed && !destroyed) {
773
+ const interval = setInterval(() => {
774
+ // Nothing below can succeed against a failed element, and retrying only buries the real error.
775
+ if (elementFailed || videoElement.error) return
776
+ evict().catch(() => {})
777
+ pump().catch((error) => reportError(error, false))
778
+ // Every remove() puts the MediaSource back to 'open', so the end has to be re-armed, though not while a remuxer
779
+ // seek runs: queued behind a remove() and run after a move had started one, it came before that seek's append over
780
+ // the end, and Firefox 151 then sometimes waited at the end for good (4 of 1060 end moves, measured 2026-10-12)
781
+ if (endInBuffer() && !pending && atEnd() && mediaSource.readyState === 'open') endOfStream(() => !seeking).catch(() => {})
782
+ }, 100)
783
+ teardown.push(() => clearInterval(interval))
784
+ }
767
785
 
768
786
  return {
769
787
  destroy: runTeardown,