@banou/media-player 0.10.49 → 0.10.51

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.
@@ -504,13 +504,13 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
504
504
  const write = (run, bin, energy, finger) => {
505
505
  if (bin < run.from || bin >= endBin) return
506
506
  run.last = bin
507
+ if (run.start && firstBin < 0) firstBin = bin
507
508
  if (spanAt(bin)) {
508
509
  if (run.wrote && ++run.skipped === MERGED_BINS) toPage({ type: 'merged', run: run.id, ...coverage() })
509
510
  return
510
511
  }
511
512
  run.skipped = 0
512
513
  run.wrote = true
513
- if (run.start && firstBin < 0) firstBin = bin
514
514
  const chunk = chunkOf(bin)
515
515
  chunk.energy[bin % BLOCK_BINS] = energy
516
516
  chunk.finger[bin % BLOCK_BINS] = finger
@@ -589,6 +589,7 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
589
589
 
590
590
  const coverage = () => ({
591
591
  spans: spans.map(([a, b]) => [a / BINS_PER_SECOND, b / BINS_PER_SECOND]),
592
+ start: firstBin >= 0 ? firstBin / BINS_PER_SECOND : null,
592
593
  end: Number.isFinite(endBin) ? endBin / BINS_PER_SECOND : null,
593
594
  normal: normal(),
594
595
  })
@@ -651,13 +652,13 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
651
652
  * SourceBuffer's timestampOffset adds it for playback; `start` for the one
652
653
  * from the start, and `join: true` for one whose first fragments went by
653
654
  * unseen, which starts at its first sample
654
- * { type: 'fragment', run, data } answered { type: 'ack', run, spans, end, normal } once its audio is queued
655
- * for decoding: the analysed seconds, the file's end once known, and the
656
- * level learned so far in LUFS
657
- * { type: 'end', run, finished } the run is over, answered { type: 'ended', run, spans, end, normal }
655
+ * { type: 'fragment', run, data } answered { type: 'ack', run, spans, start, end, normal } once its audio is
656
+ * queued for decoding: the analysed seconds, the first and last once known,
657
+ * and the level learned so far in LUFS
658
+ * { type: 'end', run, finished } the run is over, answered { type: 'ended', run, spans, start, end, normal }
658
659
  * { type: 'playhead', time }
659
660
  *
660
- * and posts { type: 'merged', run, spans, end, normal } when a run has met audio an earlier one analysed, and
661
+ * and posts { type: 'merged', run, spans, start, end, normal } when a run has met audio an earlier one analysed, and
661
662
  * { type: 'unsupported' } when this browser's WebCodecs cannot decode the track.
662
663
  */
663
664
  const serve = (scope) => {
@@ -727,7 +728,7 @@ const serve = (scope) => {
727
728
  joining = !!data.join
728
729
  if (!joining) analysis.startRun(runId, data.from, data.start)
729
730
  } else if (data.type === 'fragment') {
730
- if (data.run !== runId || decoder.state !== 'configured') return
731
+ if (data.run !== runId || decoder?.state !== 'configured') return
731
732
  const samples = audioSamplesOf(data.data, track)
732
733
  if (joining && samples.length) {
733
734
  joining = false
@@ -748,9 +749,11 @@ const serve = (scope) => {
748
749
  } else if (data.type === 'end') {
749
750
  if (data.run !== runId) return
750
751
  const ending = decoder
751
- if (ending.state === 'configured') await ending.flush().catch(() => {})
752
+ if (ending?.state === 'configured') await ending.flush().catch(() => {})
752
753
  if (data.run !== runId) return
753
- if (ending.state === 'configured') ending.close()
754
+ if (ending?.state === 'configured') ending.close()
755
+ if (decoder === ending) decoder = undefined
756
+ stamps = []
754
757
  analysis.endRun(data.finished)
755
758
  scope.postMessage({ type: 'ended', run: data.run, ...analysis.coverage() })
756
759
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@banou/media-player",
3
- "version": "0.10.49",
3
+ "version": "0.10.51",
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",
@@ -23,7 +23,7 @@ export type LoudnessAnalysis = {
23
23
  stop: () => void
24
24
  }
25
25
 
26
- type Coverage = { spans: [number, number][], end: number | null }
26
+ type Coverage = { spans: [number, number][], start: number | null, end: number | null }
27
27
 
28
28
  // a gap this close ahead of the playhead is analysed before anything else
29
29
  const LEAD_SECONDS = 20
@@ -85,7 +85,7 @@ export const startLoudnessAnalysis = ({ node, element, scriptUrl, source }: {
85
85
  worker.postMessage({ type: 'port', port: channel.port1 }, [channel.port1])
86
86
  node.port.postMessage({ analysis: channel.port2 }, [channel.port2])
87
87
 
88
- let coverage: Coverage = { spans: [], end: null }
88
+ let coverage: Coverage = { spans: [], start: null, end: null }
89
89
  let version = 0
90
90
  const replies = new Map<string, (data: Coverage) => void>()
91
91
  const reply = (type: string, run: number) => new Promise<Coverage>((resolve) => replies.set(`${type}:${run}`, resolve))
@@ -96,8 +96,9 @@ export const startLoudnessAnalysis = ({ node, element, scriptUrl, source }: {
96
96
  return
97
97
  }
98
98
  if (data.spans) {
99
- if (JSON.stringify(data.spans) !== JSON.stringify(coverage.spans) || data.end !== coverage.end) version++
100
- coverage = { spans: data.spans, end: data.end }
99
+ const start = data.start ?? null
100
+ if (JSON.stringify(data.spans) !== JSON.stringify(coverage.spans) || start !== coverage.start || data.end !== coverage.end) version++
101
+ coverage = { spans: data.spans, start, end: data.end }
101
102
  }
102
103
  if (data.type === 'merged') mergedRun = data.run
103
104
  replies.get(`${data.type}:${data.run}`)?.(coverage)
@@ -129,12 +130,18 @@ export const startLoudnessAnalysis = ({ node, element, scriptUrl, source }: {
129
130
 
130
131
  // the first time at or after `time` nothing analysed covers, or null when it is all analysed from there
131
132
  const gapFrom = (time: number) => {
132
- let at = time
133
+ let at = Math.max(time, coverage.start ?? 0)
133
134
  for (const [from, to] of coverage.spans) if (from <= at && at < to) at = to
134
135
  return at >= (coverage.end ?? duration) - 0.05 ? null : at
135
136
  }
136
137
  const attempt = (target: number) => tried.get(Math.round(target * 10)) === version ? 'idle' as const : target
138
+ const whole = () =>
139
+ coverage.start !== null && coverage.end !== null
140
+ && coverage.spans.length === 1
141
+ && coverage.spans[0]![0] <= coverage.start
142
+ && coverage.spans[0]![1] >= coverage.end
137
143
  const decide = (): 'read' | 'idle' | 'done' | number => {
144
+ if (whole()) return 'done'
138
145
  const time = element.currentTime
139
146
  const gap = gapFrom(time)
140
147
  const reading = active && mergedRun !== run
@@ -240,6 +247,8 @@ export const startLoudnessAnalysis = ({ node, element, scriptUrl, source }: {
240
247
  if (typeof decide() !== 'number') await changed()
241
248
  }
242
249
  }
250
+ if (!stopped) await endRun(false)
251
+ if (stopped) return
243
252
  // everything is analysed: the worker keeps serving the cut, and the remuxer is no longer needed
244
253
  terminateRemuxer(remuxer)
245
254
  remuxer = undefined
@@ -37,7 +37,7 @@ export type Analysis = {
37
37
  startRun: (id: number, time: number, start?: boolean) => void
38
38
  push: (planes: Float32Array[], frames: number, rate: number, time: number) => void
39
39
  endRun: (finished: boolean) => void
40
- coverage: () => { spans: [number, number][], end: number | null, normal: number }
40
+ coverage: () => { spans: [number, number][], start: number | null, end: number | null, normal: number }
41
41
  setPlayhead: (time: number) => void
42
42
  flushBlocks: () => void
43
43
  normal: () => number
@@ -45,5 +45,5 @@ export type Analysis = {
45
45
  }
46
46
  export const createAnalysis: (handlers: {
47
47
  toWorklet: (message: BlockMessage, transfer?: Transferable[]) => void
48
- toPage?: (message: { type: string, run?: number, spans?: [number, number][], end?: number | null, normal?: number }) => void
48
+ toPage?: (message: { type: string, run?: number, spans?: [number, number][], start?: number | null, end?: number | null, normal?: number }) => void
49
49
  }) => Analysis
@@ -504,13 +504,13 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
504
504
  const write = (run, bin, energy, finger) => {
505
505
  if (bin < run.from || bin >= endBin) return
506
506
  run.last = bin
507
+ if (run.start && firstBin < 0) firstBin = bin
507
508
  if (spanAt(bin)) {
508
509
  if (run.wrote && ++run.skipped === MERGED_BINS) toPage({ type: 'merged', run: run.id, ...coverage() })
509
510
  return
510
511
  }
511
512
  run.skipped = 0
512
513
  run.wrote = true
513
- if (run.start && firstBin < 0) firstBin = bin
514
514
  const chunk = chunkOf(bin)
515
515
  chunk.energy[bin % BLOCK_BINS] = energy
516
516
  chunk.finger[bin % BLOCK_BINS] = finger
@@ -589,6 +589,7 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
589
589
 
590
590
  const coverage = () => ({
591
591
  spans: spans.map(([a, b]) => [a / BINS_PER_SECOND, b / BINS_PER_SECOND]),
592
+ start: firstBin >= 0 ? firstBin / BINS_PER_SECOND : null,
592
593
  end: Number.isFinite(endBin) ? endBin / BINS_PER_SECOND : null,
593
594
  normal: normal(),
594
595
  })
@@ -651,13 +652,13 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
651
652
  * SourceBuffer's timestampOffset adds it for playback; `start` for the one
652
653
  * from the start, and `join: true` for one whose first fragments went by
653
654
  * unseen, which starts at its first sample
654
- * { type: 'fragment', run, data } answered { type: 'ack', run, spans, end, normal } once its audio is queued
655
- * for decoding: the analysed seconds, the file's end once known, and the
656
- * level learned so far in LUFS
657
- * { type: 'end', run, finished } the run is over, answered { type: 'ended', run, spans, end, normal }
655
+ * { type: 'fragment', run, data } answered { type: 'ack', run, spans, start, end, normal } once its audio is
656
+ * queued for decoding: the analysed seconds, the first and last once known,
657
+ * and the level learned so far in LUFS
658
+ * { type: 'end', run, finished } the run is over, answered { type: 'ended', run, spans, start, end, normal }
658
659
  * { type: 'playhead', time }
659
660
  *
660
- * and posts { type: 'merged', run, spans, end, normal } when a run has met audio an earlier one analysed, and
661
+ * and posts { type: 'merged', run, spans, start, end, normal } when a run has met audio an earlier one analysed, and
661
662
  * { type: 'unsupported' } when this browser's WebCodecs cannot decode the track.
662
663
  */
663
664
  const serve = (scope) => {
@@ -727,7 +728,7 @@ const serve = (scope) => {
727
728
  joining = !!data.join
728
729
  if (!joining) analysis.startRun(runId, data.from, data.start)
729
730
  } else if (data.type === 'fragment') {
730
- if (data.run !== runId || decoder.state !== 'configured') return
731
+ if (data.run !== runId || decoder?.state !== 'configured') return
731
732
  const samples = audioSamplesOf(data.data, track)
732
733
  if (joining && samples.length) {
733
734
  joining = false
@@ -748,9 +749,11 @@ const serve = (scope) => {
748
749
  } else if (data.type === 'end') {
749
750
  if (data.run !== runId) return
750
751
  const ending = decoder
751
- if (ending.state === 'configured') await ending.flush().catch(() => {})
752
+ if (ending?.state === 'configured') await ending.flush().catch(() => {})
752
753
  if (data.run !== runId) return
753
- if (ending.state === 'configured') ending.close()
754
+ if (ending?.state === 'configured') ending.close()
755
+ if (decoder === ending) decoder = undefined
756
+ stamps = []
754
757
  analysis.endRun(data.finished)
755
758
  scope.postMessage({ type: 'ended', run: data.run, ...analysis.coverage() })
756
759
  }
@@ -284,6 +284,9 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
284
284
 
285
285
  /** A paused mirror renders nothing, so a scrub would leave the old frame on screen forever. */
286
286
  const onVideoSeeked = () => {
287
+ // Subtitles repaint on `seeked` without waiting for a frame callback, so a seek while paused
288
+ // stays fresh even when no requestVideoFrameCallback fires after it.
289
+ frameTime = video.currentTime
287
290
  if (mode !== 'burn-in' || !session || !video.paused || flushing) return
288
291
  flushing = true
289
292
  const { mirror } = session
@@ -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,
@@ -131,17 +131,17 @@ export const usePlayback = (
131
131
 
132
132
  const controllerRef = useRef<PlaybackController | null>(null)
133
133
  /**
134
- * Where to pick playback back up, and WHICH media that position belongs to.
134
+ * Where to pick playback back up, whether it was running, and WHICH media that state belongs to.
135
135
  *
136
- * The position exists so a rebuild of the pipeline is invisible: switching audio track tears the
137
- * whole thing down and starts again, and dropping the viewer back at zero for that would be absurd.
138
- * But the same rebuild happens when the media itself changes, and then the position is meaningless:
139
- * dropping a second file in while the first was playing used to open it 40 minutes in.
136
+ * Both travel together so a rebuild of the pipeline is invisible: switching audio track or
137
+ * recovering from a MediaError tears the pipeline down and starts again. Without the position the
138
+ * viewer dropped back to zero; without `play`, an autoplay player started playing again after a
139
+ * rebuild while paused, and a non-autoplay player stayed paused after a rebuild while playing.
140
140
  *
141
141
  * `size` is the identity, because it is the one piece of the source in the effect's deps. `read` is
142
142
  * deliberately not, since a streaming consumer passes a fresh closure several times a second.
143
143
  */
144
- const resumeRef = useRef<{ time: number, size: number } | null>(null)
144
+ const resumeRef = useRef<{ time: number, size: number, play: boolean } | null>(null)
145
145
  // The size of the media the viewer picked subtitles for: until then each pipeline starts on the preferred track.
146
146
  const subtitleChoiceFor = useRef<number>(undefined)
147
147
  const sizeRef = useRef(size)
@@ -151,6 +151,8 @@ export const usePlayback = (
151
151
 
152
152
  const readRef = useRef(read)
153
153
  readRef.current = read
154
+ const autoplayRef = useRef(autoplay)
155
+ autoplayRef.current = autoplay
154
156
  const preferences = {
155
157
  audio: options?.preferredAudioLanguage,
156
158
  original: options?.originalLanguage,
@@ -327,7 +329,38 @@ export const usePlayback = (
327
329
 
328
330
  useEffect(() => {
329
331
  if (!video || !subtitles || !size || !read) return
332
+ // Discard stale resume state once another media starts loading, even if it aborts before onReady.
333
+ if (resumeRef.current && resumeRef.current.size !== size) resumeRef.current = null
330
334
  let cancelled = false
335
+ let reachedReady = false
336
+ // Chrome sets `video.paused = true` before dispatching `error` and then queues one `pause` event,
337
+ // while Firefox and WebKit leave `paused` false. Latch only that single error-induced pause so a
338
+ // real pause right before a MediaError or during recovery backoff is never dropped.
339
+ let wantPlaying = false
340
+ let pausedByError = false
341
+ let ignoreErrorPause = false
342
+ const onPlay = () => {
343
+ wantPlaying = true
344
+ pausedByError = false
345
+ ignoreErrorPause = false
346
+ }
347
+ const onPause = () => {
348
+ if (ignoreErrorPause) {
349
+ ignoreErrorPause = false
350
+ return
351
+ }
352
+ wantPlaying = false
353
+ pausedByError = false
354
+ }
355
+ const onError = () => {
356
+ if (wantPlaying && video.paused) {
357
+ pausedByError = true
358
+ ignoreErrorPause = true
359
+ }
360
+ }
361
+ video.addEventListener('play', onPlay)
362
+ video.addEventListener('pause', onPause)
363
+ video.addEventListener('error', onError)
331
364
  player.setSourceState({ playbackError: null, ready: false })
332
365
 
333
366
  /**
@@ -409,14 +442,18 @@ export const usePlayback = (
409
442
  chooseAudioStream: (audio) => audio[startingTracks(audio, [], preferencesRef.current).audio]?.streamIndex,
410
443
  onReady: () => {
411
444
  if (cancelled) return
445
+ reachedReady = true
412
446
  player.setSourceState({ ready: true })
413
447
  const resume = resumeRef.current
414
448
  resumeRef.current = null
449
+ const sameMedia = !!resume && resume.size === size
415
450
  // only a position belonging to THIS media, or a new file opens where the last one stopped
416
- if (resume && resume.size === size && resume.time > 0) video.currentTime = resume.time
451
+ if (sameMedia && resume.time > 0) video.currentTime = resume.time
417
452
  // a seek carried to 0 is where the new element already is, so no 'seeked' comes to take it off the clock
418
453
  else player.setSourceState({ seekingTo: undefined })
419
- if (autoplay) video.play().catch(() => {})
454
+ const shouldPlay = sameMedia ? resume.play : autoplayRef.current
455
+ wantPlaying = shouldPlay
456
+ if (shouldPlay) video.play().catch(() => { if (video.paused && !pausedByError) wantPlaying = false })
420
457
  },
421
458
  onError: fail,
422
459
  onRecovered: () => { if (!cancelled) player.setSourceState({ playbackError: null }) },
@@ -459,19 +496,28 @@ export const usePlayback = (
459
496
  })()
460
497
  return () => {
461
498
  cancelled = true
462
- // a seek still waiting for its data has not moved the element yet, and it is where the viewer asked to be
463
- resumeRef.current = { time: player.state.seekingTo ?? video.currentTime, size }
499
+ video.removeEventListener('play', onPlay)
500
+ video.removeEventListener('pause', onPause)
501
+ video.removeEventListener('error', onError)
502
+ if (reachedReady) {
503
+ // a seek still waiting for its data has not moved the element yet, and it is where the viewer asked to be
504
+ resumeRef.current = {
505
+ time: player.state.seekingTo ?? video.currentTime,
506
+ size,
507
+ play: !video.ended && (pausedByError ? wantPlaying : !video.paused),
508
+ }
509
+ } else if (resumeRef.current?.size === size && player.state.seekingTo !== undefined) {
510
+ resumeRef.current = { ...resumeRef.current, time: player.state.seekingTo }
511
+ }
464
512
  controllerRef.current?.destroy()
465
513
  controllerRef.current = null
466
514
  player.setSourceState({ ready: false })
467
515
  }
468
- // `read` is deliberately absent: the effect only ever calls `readRef.current`, so listing it here
469
- // would tear the whole pipeline down and rebuild it whenever the caller's reader changed
470
- // identity. A streaming consumer passes a fresh closure on every state update, which is several
471
- // times a second, and the restart loop reads as "Loading metadata" forever at a flat 0 B/s.
516
+ // `read` and `autoplay` are read through refs: `read` changes identity on streaming updates, and
517
+ // toggling `autoplay` does not need a full pipeline rebuild.
472
518
  }, [
473
519
  player, playingAudio, video, subtitles, size, publicPath, libavWorkerUrl, jassubWorkerUrl, jassubWasmUrl,
474
520
  jassubWasmWorkerUrl, jassubLegacyWasmUrl, jassubLegacyWasmWorkerUrl, defaultFontUrl, cjkFontUrl, bufferSize,
475
- audioStreamIndex, autoplay, restartToken,
521
+ audioStreamIndex, restartToken,
476
522
  ])
477
523
  }