@banou/media-player 0.10.21 → 0.10.24

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.
@@ -0,0 +1,14 @@
1
+ import type { PlayerMedia } from '../media';
2
+ /**
3
+ * Offers `stepFrame` for a media whose frames this document can see, one with `requestVideoFrameCallback`.
4
+ *
5
+ * Paused by a seek, the element shows the frame holding `currentTime` (Chrome 155 and Firefox 157), so a step is
6
+ * `currentTime` plus or minus a frame. Paused from playing, Chrome shows the frame after that one in 15 of 40 pauses,
7
+ * so the step starts from the last frame presented while playing and aims at the middle of the next one. A frame a
8
+ * seek presented is never read for its time: Firefox reports the seek's target as its `mediaTime`.
9
+ *
10
+ * The frame's length is learned from the gaps between frames presented one after another while playing at up to 1x:
11
+ * faster, a 60 Hz display presents every other frame of a 60 fps file. A step while a seek waits for its data starts
12
+ * from that seek's target.
13
+ */
14
+ export declare const useFrameStep: (media: PlayerMedia | null) => void;
@@ -1,3 +1,4 @@
1
+ import type { PlaybackOutput } from '../../engine';
1
2
  import type { MediaPlayerLocalOptions } from '../video-player';
2
3
  /**
3
4
  * Owns the engine for the life of a source: start, teardown, and every piece of state the pipeline
@@ -5,4 +6,4 @@ import type { MediaPlayerLocalOptions } from '../video-player';
5
6
  */
6
7
  export declare const usePlayback: (video: HTMLVideoElement | null, subtitles: HTMLElement | null,
7
8
  /** null when the media is remote: there are no bytes, so there is no pipeline to run. */
8
- options: MediaPlayerLocalOptions | null) => void;
9
+ options: MediaPlayerLocalOptions | null, onOutput?: (output: PlaybackOutput) => void) => void;
@@ -1,12 +1,16 @@
1
1
  import type { LoudnessSource } from '../../audio/loudness-analysis';
2
+ import type { PlaybackTap } from '../../audio/playback-tap';
2
3
  /**
3
4
  * Normalizes the element's volume while `enabled`. Nothing is built until it first is, and turning it off
4
5
  * afterwards bypasses rather than unroutes, since an element cannot be handed back. `refused` is true once the
5
6
  * engine turned the element down, which leaves it playing exactly as before.
6
7
  *
7
8
  * With a `source`, the file is also analysed ahead of the playhead while it is on, reading only the byte `ranges`
8
- * given (all of them when undefined).
9
+ * given (all of them when undefined), or with a `tap`, from the audio playback remuxed.
9
10
  */
10
- export declare const useVolumeNormalizer: (video: HTMLVideoElement | null, workletUrl: string | undefined, enabled: boolean, source?: LoudnessSource, ranges?: [number, number][]) => {
11
+ export declare const useVolumeNormalizer: (video: HTMLVideoElement | null, workletUrl: string | undefined, enabled: boolean, source?: LoudnessSource | {
12
+ tap: PlaybackTap;
13
+ audioStreamIndex: number;
14
+ }, ranges?: [number, number][]) => {
11
15
  refused: boolean;
12
16
  };
@@ -25,6 +25,7 @@ export declare const Player: import("@videojs/react").CreatePlayerResult<import(
25
25
  burnedInSubtitles: boolean;
26
26
  volumeNormalizer: import("./source-feature").VolumeNormalizerControl | null;
27
27
  requestSeek?: (time: number) => void;
28
+ stepFrame?: (direction: 1 | -1) => void;
28
29
  playbackError: unknown;
29
30
  playbackErrors: import("./source-feature").PlaybackErrorEntry[];
30
31
  ready: boolean;
@@ -218,6 +218,8 @@ export type SourceState = {
218
218
  * caller should seek directly.
219
219
  */
220
220
  requestSeek?: (time: number) => void;
221
+ /** One frame back or forward, pausing first. Undefined for a media whose frames this document cannot see. */
222
+ stepFrame?: (direction: 1 | -1) => void;
221
223
  /** Set when the pipeline fails. Cleared when it recovers. */
222
224
  playbackError: unknown;
223
225
  /**
@@ -365,6 +367,8 @@ export declare const sourceFeature: import("@videojs/react").PlayerFeature<{
365
367
  * caller should seek directly.
366
368
  */
367
369
  requestSeek?: (time: number) => void;
370
+ /** One frame back or forward, pausing first. Undefined for a media whose frames this document cannot see. */
371
+ stepFrame?: (direction: 1 | -1) => void;
368
372
  /** Set when the pipeline fails. Cleared when it recovers. */
369
373
  playbackError: unknown;
370
374
  /**
@@ -6,13 +6,19 @@ import type { ExposePlayerOptions } from '../remote';
6
6
  /**
7
7
  * The source, read a range at a time: the player never downloads the whole file. Both fields travel
8
8
  * together, so passing one without the other is a type error.
9
+ *
10
+ * `readsDownload` marks a source each read of which is a download, a file over HTTP, so the volume normalizer
11
+ * analyses the audio playback fetched instead of reading the file again. Without it, and with no
12
+ * `downloadedRanges`, every byte is taken to be readable for free, as a local file's are.
9
13
  */
10
14
  export type MediaPlayerSource = {
11
15
  read: (offset: number, size: number) => Promise<ArrayBuffer>;
12
16
  size: number;
17
+ readsDownload?: boolean;
13
18
  } | {
14
19
  read?: undefined;
15
20
  size?: undefined;
21
+ readsDownload?: undefined;
16
22
  };
17
23
  /** Shared by both arms: nothing here depends on who owns the media. */
18
24
  type CommonOptions = {
@@ -139,7 +145,8 @@ export type MediaPlayerLocalOptions = CommonOptions & MediaPlayerSource & {
139
145
  * They are the same by default so generation shares playback's fetch order. A consumer whose
140
146
  * reads are not free wants them apart: a torrent hands this a non-prioritising, fail-fast reader
141
147
  * so generating previews cannot steal download order from the bytes playback is blocked on. The
142
- * analysis asks it only for bytes inside `downloadedRanges`, and with none given, for the whole file.
148
+ * analysis asks it only for bytes inside `downloadedRanges`, with none given for the whole file, and for
149
+ * nothing when the source `readsDownload`.
143
150
  */
144
151
  thumbnailRead?: (offset: number, size: number) => Promise<ArrayBuffer>;
145
152
  /** Off entirely. A second wasm worker during pipeline boot is worth avoiding on a slow source. */
@@ -160,7 +167,8 @@ export type MediaPlayerLocalOptions = CommonOptions & MediaPlayerSource & {
160
167
  * `onNormalizeVolumeChange` reports and passes it back.
161
168
  *
162
169
  * While it is on the file is read a second time, in a worker, as far as `downloadedRanges` allows, to find the
163
- * loud parts ahead of the playhead. The sound plays 10 ms behind its input, on or off, once routed.
170
+ * loud parts ahead of the playhead; a source that `readsDownload` is not read again, and its loud parts are found
171
+ * in what playback fetched. The sound plays 10 ms behind its input, on or off, once routed.
164
172
  *
165
173
  * The first time it is on, the element is routed through Web Audio for the rest of its life (off then
166
174
  * bypasses). If autoplay rules hold the audio back, that waits for the page's next click, tap or key press, and
@@ -15,12 +15,17 @@ declare const fromUrl: ({ url, length: _length, name, credentials }: {
15
15
  length: number;
16
16
  name: string | undefined;
17
17
  read: (offset: number, size: number) => Promise<ArrayBuffer>;
18
+ readsDownload: boolean;
18
19
  }>;
19
- /** A source resolved down to what the remuxer needs: a total length and a byte-range reader. */
20
+ /**
21
+ * A source resolved down to what the remuxer needs: a total length and a byte-range reader, and whether each read
22
+ * is a download, which the player's `readsDownload` takes.
23
+ */
20
24
  export type RemuxerInput = {
21
25
  length: number;
22
26
  name?: string;
23
27
  read: (offset: number, size: number) => Promise<ArrayBuffer>;
28
+ readsDownload?: boolean;
24
29
  };
25
30
  export declare const inputToRemuxerInput: (params: Parameters<typeof fromBlob | typeof fromUrl>[0] | {
26
31
  length: number;
@@ -629,12 +629,15 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
629
629
  }
630
630
 
631
631
  /*
632
- * The worker's side: fragments from a second libav remuxer reading the same file, decoded with WebCodecs.
632
+ * The worker's side: fragments from a second libav remuxer reading the same file, or from playback's own, decoded with
633
+ * WebCodecs.
633
634
  *
634
635
  * { type: 'port', port } the worklet's end of a MessageChannel, for the blocks
635
636
  * { type: 'init', data, codec } the init segment and the codec string MediaSource was given
636
637
  * { type: 'run', run, pts, start } a run of fragments starts, `pts` added to their times as the SourceBuffer's
637
- * timestampOffset adds it for playback; `start` for the one from the start
638
+ * timestampOffset adds it for playback; `start` for the one from the start,
639
+ * and `join: true` for one whose first fragments went by unseen, which starts
640
+ * at its first sample
638
641
  * { type: 'fragment', run, data } answered { type: 'ack', run, spans, end, normal } once its audio is queued
639
642
  * for decoding: the analysed seconds, the file's end once known, and the
640
643
  * level learned so far in LUFS
@@ -651,6 +654,7 @@ const serve = (scope) => {
651
654
  let decoder
652
655
  let runId = -1
653
656
  let pts = 0
657
+ let joining = false
654
658
  const analysis = createAnalysis({
655
659
  toWorklet: (message, transfer) => port?.postMessage(message, transfer),
656
660
  toPage: (message) => scope.postMessage(message),
@@ -707,10 +711,16 @@ const serve = (scope) => {
707
711
  runId = data.run
708
712
  pts = data.pts
709
713
  open(runId)
710
- analysis.startRun(runId, pts, data.start)
714
+ joining = !!data.join
715
+ if (!joining) analysis.startRun(runId, pts, data.start)
711
716
  } else if (data.type === 'fragment') {
712
717
  if (data.run !== runId || decoder.state !== 'configured') return
713
- for (const sample of audioSamplesOf(data.data, track)) {
718
+ const samples = audioSamplesOf(data.data, track)
719
+ if (joining && samples.length) {
720
+ joining = false
721
+ analysis.startRun(runId, pts + samples[0].time / track.timescale)
722
+ }
723
+ for (const sample of samples) {
714
724
  const time = pts + sample.time / track.timescale
715
725
  stamps.push(time)
716
726
  decoder.decode(new EncodedAudioChunk({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@banou/media-player",
3
- "version": "0.10.21",
3
+ "version": "0.10.24",
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",
@@ -34,17 +34,17 @@
34
34
  "types": "tsc -p tsconfig.lib.json",
35
35
  "copy-assets": "shx mkdir -p public && npm run copy-libav",
36
36
  "copy-libav": "shx cp node_modules/libav-wasm/build/worker.js public/libav-worker.js && shx cp node_modules/libav-wasm/build/libav.wasm public/libav.wasm && shx cp node_modules/libav-wasm/build/libav-jspi.wasm public/libav-jspi.wasm",
37
- "test": "npm run fixtures && vp test run",
37
+ "test": "npm run copy-assets && npm run fixtures && vp test run",
38
38
  "fixtures": "node scripts/fixture.mjs"
39
39
  },
40
40
  "author": "Banou26",
41
41
  "dependencies": {
42
- "@banou/ponyfill": "^0.0.10",
42
+ "@banou/ponyfill": "^0.0.12",
43
43
  "@videojs/core": "10.0.0-beta.26",
44
44
  "@videojs/react": "10.0.0-beta.26",
45
45
  "ass-compiler": "^0.1.16",
46
- "jassub": "^2.5.16",
47
- "libav-wasm": "^0.8.9",
46
+ "jassub": "^2.5.23",
47
+ "libav-wasm": "^0.8.12",
48
48
  "lucide-react": "^0.536.0",
49
49
  "osra": "^0.6.12",
50
50
  "react-tooltip": "^5.28.0"
@@ -1,3 +1,5 @@
1
+ import type { PlaybackTap } from './playback-tap'
2
+
1
3
  import { makeRemuxer } from 'libav-wasm'
2
4
 
3
5
  import { terminateRemuxer } from '../engine/playback'
@@ -37,12 +39,16 @@ const CLOCK_MS = 50
37
39
  * nearest the playhead first, then the rest of the file, and drops nothing it learned on a seek. Until a stretch is
38
40
  * analysed, and for the whole file where this browser's WebCodecs cannot decode the track, the worklet's live stage
39
41
  * plays.
42
+ *
43
+ * Given a `tap` instead, it reads nothing and analyses the audio playback remuxed for `audioStreamIndex`, which runs
44
+ * as far ahead of the playhead as playback buffers. It starts at the next fragment playback fetches, so what was
45
+ * buffered before it attached is not analysed.
40
46
  */
41
47
  export const startLoudnessAnalysis = ({ node, element, scriptUrl, source }: {
42
48
  node: AudioWorkletNode
43
49
  element: HTMLMediaElement
44
50
  scriptUrl: string
45
- source: LoudnessSource
51
+ source: LoudnessSource | { tap: PlaybackTap, audioStreamIndex: number }
46
52
  }): LoudnessAnalysis => {
47
53
  let stopped = false
48
54
  let ranges: [number, number][] | undefined
@@ -54,14 +60,13 @@ export const startLoudnessAnalysis = ({ node, element, scriptUrl, source }: {
54
60
  }
55
61
  const changed = () => new Promise<void>((resolve) => wakers.add(resolve))
56
62
 
57
- const readable = (offset: number, size: number) =>
58
- !ranges || ranges.some(([from, to]) => from <= offset && Math.min(offset + size, source.length) <= to)
59
- const read = async (offset: number, size: number) => {
60
- while (!readable(offset, size)) {
63
+ const read = async (reader: LoudnessSource, offset: number, size: number) => {
64
+ const end = Math.min(offset + size, reader.length)
65
+ while (ranges && !ranges.some(([from, to]) => from <= offset && end <= to)) {
61
66
  // given up once the task waiting on it has been aborted, or the analysis stopped
62
67
  if (stopped || await new Promise<boolean>((resolve) => waiting.add(resolve))) throw new Error('Cancelled')
63
68
  }
64
- return source.read(offset, size)
69
+ return reader.read(offset, size)
65
70
  }
66
71
  const release = (abandon: boolean) => {
67
72
  for (const resolve of [...waiting]) resolve(abandon)
@@ -180,14 +185,14 @@ export const startLoudnessAnalysis = ({ node, element, scriptUrl, source }: {
180
185
  await acked
181
186
  }
182
187
 
183
- const loop = async () => {
188
+ const loop = async (reader: LoudnessSource) => {
184
189
  remuxer = await makeRemuxer({
185
- publicPath: source.publicPath,
186
- workerUrl: source.libavWorkerUrl,
190
+ publicPath: reader.publicPath,
191
+ workerUrl: reader.libavWorkerUrl,
187
192
  workerOptions: { type: 'module' },
188
- length: source.length,
189
- read,
190
- audioStreamIndex: source.audioStreamIndex,
193
+ length: reader.length,
194
+ read: (offset, size) => read(reader, offset, size),
195
+ audioStreamIndex: reader.audioStreamIndex,
191
196
  })
192
197
  // stopped while it was being made, which stop() could not end
193
198
  if (stopped) return terminateRemuxer(remuxer)
@@ -240,6 +245,30 @@ export const startLoudnessAnalysis = ({ node, element, scriptUrl, source }: {
240
245
  remuxer = undefined
241
246
  }
242
247
 
248
+ let detach = () => {}
249
+ const follow = (tap: PlaybackTap, audioStreamIndex: number) => {
250
+ let open = false
251
+ const end = (finished: boolean) => {
252
+ if (open) worker.postMessage({ type: 'end', run, finished })
253
+ open = false
254
+ }
255
+ detach = tap.attach(audioStreamIndex, (output, join) => {
256
+ if (output.type === 'init') {
257
+ end(false)
258
+ const data = output.data.slice(0)
259
+ worker.postMessage({ type: 'init', data, codec: output.audioMimeType }, [data])
260
+ } else if (output.type === 'run') {
261
+ end(false)
262
+ open = true
263
+ worker.postMessage({ type: 'run', run: ++run, pts: output.pts, start: !join && output.pts <= 0, join })
264
+ } else if (output.type === 'end') end(true)
265
+ else if (open) {
266
+ const data = output.data.slice(0)
267
+ worker.postMessage({ type: 'fragment', run, data }, [data])
268
+ }
269
+ })
270
+ }
271
+
243
272
  const stop = () => {
244
273
  if (stopped) return
245
274
  stopped = true
@@ -250,6 +279,7 @@ export const startLoudnessAnalysis = ({ node, element, scriptUrl, source }: {
250
279
  element.removeEventListener('seeking', onSeeking)
251
280
  element.removeEventListener('seeked', onTime)
252
281
  element.removeEventListener('timeupdate', onTime)
282
+ detach()
253
283
  if (remuxer) terminateRemuxer(remuxer)
254
284
  worker.terminate()
255
285
  node.port.postMessage({ analysis: null })
@@ -257,11 +287,14 @@ export const startLoudnessAnalysis = ({ node, element, scriptUrl, source }: {
257
287
  replies.clear()
258
288
  }
259
289
 
260
- loop().catch((error) => {
261
- if (stopped) return
262
- console.warn('[media-player] the volume normalizer cannot analyse ahead:', error)
263
- stop()
264
- })
290
+ if ('tap' in source) follow(source.tap, source.audioStreamIndex)
291
+ else {
292
+ loop(source).catch((error) => {
293
+ if (stopped) return
294
+ console.warn('[media-player] the volume normalizer cannot analyse ahead:', error)
295
+ stop()
296
+ })
297
+ }
265
298
  playhead()
266
299
 
267
300
  return {
@@ -0,0 +1,37 @@
1
+ import type { PlaybackOutput } from '../engine/playback'
2
+
3
+ /**
4
+ * Playback's output, for an analysis that reads nothing of its own: `push` takes what playback's remuxer produced,
5
+ * and `attach` hands a listener what follows for one input audio stream, starting with the last init segment and the
6
+ * run in progress. `join` marks a run some of whose fragments went by before the listener was attached.
7
+ */
8
+ export type PlaybackTap = {
9
+ push: (output: PlaybackOutput) => void
10
+ attach: (audioStreamIndex: number, listener: (output: PlaybackOutput, join?: boolean) => void) => () => void
11
+ }
12
+
13
+ export const createPlaybackTap = (): PlaybackTap => {
14
+ let init: Extract<PlaybackOutput, { type: 'init' }> | undefined
15
+ let run: { pts: number, begun: boolean } | undefined
16
+ let listener: { audioStreamIndex: number, take: (output: PlaybackOutput, join?: boolean) => void } | undefined
17
+ const live = () => listener && init?.audioStreamIndex === listener.audioStreamIndex ? listener : undefined
18
+ return {
19
+ push: (output) => {
20
+ if (output.type === 'init') {
21
+ init = output
22
+ run = undefined
23
+ } else if (output.type === 'run') run = { pts: output.pts, begun: false }
24
+ else if (output.type === 'fragment' && run) run.begun = true
25
+ live()?.take(output)
26
+ },
27
+ attach: (audioStreamIndex, take) => {
28
+ const mine = { audioStreamIndex, take }
29
+ listener = mine
30
+ if (live() && init) {
31
+ take(init)
32
+ if (run) take({ type: 'run', pts: run.pts }, run.begun)
33
+ }
34
+ return () => { if (listener === mine) listener = undefined }
35
+ },
36
+ }
37
+ }
@@ -629,12 +629,15 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
629
629
  }
630
630
 
631
631
  /*
632
- * The worker's side: fragments from a second libav remuxer reading the same file, decoded with WebCodecs.
632
+ * The worker's side: fragments from a second libav remuxer reading the same file, or from playback's own, decoded with
633
+ * WebCodecs.
633
634
  *
634
635
  * { type: 'port', port } the worklet's end of a MessageChannel, for the blocks
635
636
  * { type: 'init', data, codec } the init segment and the codec string MediaSource was given
636
637
  * { type: 'run', run, pts, start } a run of fragments starts, `pts` added to their times as the SourceBuffer's
637
- * timestampOffset adds it for playback; `start` for the one from the start
638
+ * timestampOffset adds it for playback; `start` for the one from the start,
639
+ * and `join: true` for one whose first fragments went by unseen, which starts
640
+ * at its first sample
638
641
  * { type: 'fragment', run, data } answered { type: 'ack', run, spans, end, normal } once its audio is queued
639
642
  * for decoding: the analysed seconds, the file's end once known, and the
640
643
  * level learned so far in LUFS
@@ -651,6 +654,7 @@ const serve = (scope) => {
651
654
  let decoder
652
655
  let runId = -1
653
656
  let pts = 0
657
+ let joining = false
654
658
  const analysis = createAnalysis({
655
659
  toWorklet: (message, transfer) => port?.postMessage(message, transfer),
656
660
  toPage: (message) => scope.postMessage(message),
@@ -707,10 +711,16 @@ const serve = (scope) => {
707
711
  runId = data.run
708
712
  pts = data.pts
709
713
  open(runId)
710
- analysis.startRun(runId, pts, data.start)
714
+ joining = !!data.join
715
+ if (!joining) analysis.startRun(runId, pts, data.start)
711
716
  } else if (data.type === 'fragment') {
712
717
  if (data.run !== runId || decoder.state !== 'configured') return
713
- for (const sample of audioSamplesOf(data.data, track)) {
718
+ const samples = audioSamplesOf(data.data, track)
719
+ if (joining && samples.length) {
720
+ joining = false
721
+ analysis.startRun(runId, pts + samples[0].time / track.timescale)
722
+ }
723
+ for (const sample of samples) {
714
724
  const time = pts + sample.time / track.timescale
715
725
  stamps.push(time)
716
726
  decoder.decode(new EncodedAudioChunk({
@@ -1,5 +1,5 @@
1
1
  export { startPlayback, terminateRemuxer, MediaElementError, isMediaElementError, DEFAULT_BUFFER_SIZE } from './playback'
2
- export type { PlaybackOptions, PlaybackController, MediaIndex, MediaChapter, AudioStream } from './playback'
2
+ export type { PlaybackOptions, PlaybackController, PlaybackOutput, MediaIndex, MediaChapter, AudioStream } from './playback'
3
3
 
4
4
  export { createSubtitleRenderer, SUBTITLES_OFF } from './subtitles'
5
5
  export type { SubtitleRenderer, SubtitleRendererOptions, SubtitleStream } from './subtitles'
@@ -23,6 +23,18 @@ export type MediaIndex = { pos: number, timestamp: number }
23
23
  */
24
24
  export type MediaChapter = { start: number, end: number, title: string }
25
25
 
26
+ /**
27
+ * What the remuxer produced, in the order it was appended: the init segment and the input audio stream it carries,
28
+ * a run at load and at every remuxer seek (`pts` is the timestampOffset its fragments are appended at), each
29
+ * fragment, and the end of the file once read. The buffers are playback's own and may be appended again, so a
30
+ * consumer copies what it keeps.
31
+ */
32
+ export type PlaybackOutput =
33
+ | { type: 'init', data: ArrayBuffer, audioMimeType: string, audioStreamIndex: number }
34
+ | { type: 'run', pts: number }
35
+ | { type: 'fragment', data: ArrayBuffer }
36
+ | { type: 'end' }
37
+
26
38
  export type PlaybackOptions = {
27
39
  videoElement: HTMLVideoElement
28
40
  /**
@@ -51,6 +63,7 @@ export type PlaybackOptions = {
51
63
  onSeek?: (fraction: number) => void
52
64
  onSubtitleStreams?: (streams: SubtitleStream[]) => void
53
65
  onAudioStreams?: (streams: AudioStream[], selected: number) => void
66
+ onOutput?: (output: PlaybackOutput) => void
54
67
  }
55
68
 
56
69
  export type PlaybackController = {
@@ -146,7 +159,7 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
146
159
  videoElement, subtitleContainer, read, length, publicPath, libavWorkerUrl,
147
160
  jassubWorkerUrl, jassubWasmUrl, jassubLegacyWasmUrl, defaultFontUrl, bufferSize = DEFAULT_BUFFER_SIZE,
148
161
  audioStreamIndex, onReady, onError, onRecovered, onSeek, onSubtitleStreams,
149
- onAudioStreams,
162
+ onAudioStreams, onOutput,
150
163
  } = options
151
164
 
152
165
  const remuxer = await makeRemuxer({
@@ -253,6 +266,8 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
253
266
 
254
267
  const { appendBuffer, unbufferRange, updateTimestampOffset, endOfStream } = updateSourceBuffer(sourceBuffer, mediaSource)
255
268
  await appendBuffer(metadata.data)
269
+ onOutput?.({ type: 'init', data: metadata.data, audioMimeType: metadata.info.output.audioMimeType, audioStreamIndex: selectedAudio })
270
+ onOutput?.({ type: 'run', pts: 0 })
256
271
  if (metadata.subtitles?.length) subtitles.pushFragments(metadata.subtitles)
257
272
  onReady?.()
258
273
 
@@ -400,6 +415,9 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
400
415
  if (fragments?.length) subtitles.pushFragments(fragments)
401
416
  await updateTimestampOffset(pts)
402
417
  if (destroyed || generation !== seekGeneration) return
418
+ onOutput?.({ type: 'run', pts })
419
+ if (data.byteLength) onOutput?.({ type: 'fragment', data })
420
+ if (done) onOutput?.({ type: 'end' })
403
421
  if (data.byteLength) {
404
422
  await appendBuffer(data)
405
423
  trackAppendedEnd()
@@ -458,6 +476,8 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
458
476
  if (stale()) return
459
477
  if (done) finished = true
460
478
  if (fragments?.length) subtitles.pushFragments(fragments)
479
+ if (data.byteLength) onOutput?.({ type: 'fragment', data })
480
+ if (done) onOutput?.({ type: 'end' })
461
481
  if (!data.byteLength) return
462
482
  pending = data
463
483
  pendingAttempts = 0
@@ -479,14 +499,18 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
479
499
  * BOTH the input and the output context and re-runs write_header, because the fragmented mp4 muxer
480
500
  * cannot rewind. Skipping it when the target is already playable is most of what a seek costs.
481
501
  *
482
- * Buffered alone is not enough: landing before the last remuxer position means the reader is
483
- * somewhere ahead, so the gap between here and it can never be filled without a seek, and playback
484
- * would stall at the end of this range instead. Nor is landing after it: the range holding the
485
- * target can be an island ahead of the reader, so the target also needs its runway, or the element
486
- * plays to the island's end and waits there until the reader has read the whole gap, which over a
487
- * torrent is as long as downloading it.
502
+ * Buffered alone is not enough: the range holding the target has to reach the last remuxer position,
503
+ * since the reader is somewhere ahead of it and a gap between them can never be filled without a seek,
504
+ * so playback would stall at the end of this range instead. A target behind that position is just as
505
+ * safe once its range reaches it: seeking there anyway re-read the target's whole GOP over buffered
506
+ * data, and a quick seek forward during that re-read showed a frame from 15 s away in Chrome 155
507
+ * (measured 2026-10-23).
508
+ * Nor is reaching it enough: the range can be an island ahead of the reader, so the target also needs
509
+ * its runway, or the element plays to the island's end and waits there until the reader has read the
510
+ * whole gap, which over a torrent is as long as downloading it.
488
511
  */
489
- const alreadyPlayable = (time: number) => time >= lastSeekPosition && playableAt(time) && hasRunway(time)
512
+ const alreadyPlayable = (time: number) =>
513
+ getTimeRanges(sourceBuffer).some((r) => r.start <= time && time < r.end && r.end >= lastSeekPosition) && hasRunway(time)
490
514
 
491
515
  /**
492
516
  * Whether the element can play from a GIVEN time without a fetch.
@@ -538,6 +562,11 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
538
562
  const prepareSeek = async (time: number) => {
539
563
  if (destroyed) return
540
564
  if (playableAt(time) && hasRunway(time)) return
565
+ // A drag still settling holds every read, so the runway would never be read, and its settle would then position the
566
+ // remuxer back where the drag stopped. A seek back under 250 ms after a seek forward is one (Firefox 153 and 157,
567
+ // 2026-10-23).
568
+ if (dragTimer) clearTimeout(dragTimer)
569
+ dragTimer = undefined
541
570
  finished = false
542
571
  preparing++
543
572
  prepareTarget = time
@@ -10,7 +10,7 @@ export type SubtitleStream = { streamIndex: number, title: string, language: str
10
10
  export const SUBTITLES_OFF = -1
11
11
 
12
12
  type SubtitleHeaderPart = { type: 'header', streamIndex: number, content: string, eventsContent: string, styles: Map<string, number> }
13
- type SubtitleDialoguePart = { type: 'dialogue', streamIndex: number, index: number, assEvent: ASSEvent }
13
+ type SubtitleDialoguePart = { type: 'dialogue', streamIndex: number, assEvent: ASSEvent }
14
14
 
15
15
  export type SubtitleRendererOptions = {
16
16
  video: HTMLVideoElement
@@ -125,7 +125,6 @@ const toDialoguePart = (header: SubtitleHeaderPart, fragment: SubtitleFragment &
125
125
  return {
126
126
  type: 'dialogue',
127
127
  streamIndex: fragment.streamIndex,
128
- index: dialogueIndex,
129
128
  assEvent: {
130
129
  Name: event.Name ?? '',
131
130
  // libass wants the raw effect field and ass-compiler has already destructured it into an
@@ -158,7 +157,7 @@ export const createSubtitleRenderer = (options: SubtitleRendererOptions) => {
158
157
  let attachments: [string, Uint8Array][] = []
159
158
  const headers = new Map<number, SubtitleHeaderPart>()
160
159
  const streams: SubtitleStream[] = []
161
- const dialogues = new Map<number, Map<number, SubtitleDialoguePart>>()
160
+ const dialogues = new Map<number, Map<string, SubtitleDialoguePart>>()
162
161
  let selected: number | undefined
163
162
  let onStreams = options.onStreams
164
163
  /**
@@ -333,11 +332,16 @@ export const createSubtitleRenderer = (options: SubtitleRendererOptions) => {
333
332
  } else {
334
333
  const header = headers.get(fragment.streamIndex)
335
334
  if (!header) continue
336
- let byIndex = dialogues.get(fragment.streamIndex)
337
- if (!byIndex) { byIndex = new Map(); dialogues.set(fragment.streamIndex, byIndex) }
335
+ let byLine = dialogues.get(fragment.streamIndex)
336
+ if (!byLine) { byLine = new Map(); dialogues.set(fragment.streamIndex, byLine) }
337
+ // Everything but the leading ReadOrder: a line libav converts from SubRip, WebVTT or mov_text
338
+ // takes it from a counter in FFmpeg's decoder, so the same cue read again after a seek comes
339
+ // back under a new one. The cost: an ASS line repeating another in every other field draws
340
+ // once, where libass draws both.
341
+ const key = `${fragment.start},${fragment.end},${fragment.content.slice(fragment.content.indexOf(',') + 1)}`
342
+ if (byLine.has(key)) continue
338
343
  const part = toDialoguePart(header, fragment)
339
- if (byIndex.has(part.index)) continue
340
- byIndex.set(part.index, part)
344
+ byLine.set(key, part)
341
345
  if (selected === fragment.streamIndex) incoming.push(part.assEvent)
342
346
  }
343
347
  }
package/src/lib/index.tsx CHANGED
@@ -43,6 +43,7 @@ export type {
43
43
  PictureInPictureController,
44
44
  PlaybackController,
45
45
  PlaybackOptions,
46
+ PlaybackOutput,
46
47
  SubtitleStream,
47
48
  ThumbnailImage,
48
49
  } from './engine'
@@ -178,6 +178,7 @@ export const ControlBar = (
178
178
  // Keyboard seeks go through the same door as the seek bar: data first, then the playhead. See
179
179
  // `requestSeek` on the source state for why an element that seeks into a hole is the problem.
180
180
  const requestSeek = usePlayer((state) => state.requestSeek)
181
+ const stepFrame = usePlayer((state) => state.stepFrame)
181
182
  const [volumeElement, setVolumeElement] = useState<HTMLButtonElement | null>(null)
182
183
  const passThroughButton = useRef<HTMLButtonElement>(null)
183
184
  const refocus = useRef<ReturnType<typeof setInterval>>(undefined)
@@ -215,6 +216,9 @@ export const ControlBar = (
215
216
  // on the window, so typing into a consumer's own input opts out
216
217
  const target = targetOf(ev)
217
218
  if (target?.isContentEditable || /^(input|textarea|select)$/i.test(target?.tagName ?? '')) return
219
+ // Ctrl+F, Alt+Left and the like are the browser's, but Windows reports AltGr, which types < and > on some
220
+ // layouts, as Ctrl and Alt
221
+ if ((ev.ctrlKey || ev.metaKey || ev.altKey) && !ev.getModifierState('AltGraph')) return
218
222
  const fromPlayer = root.current?.contains(target ?? null) || (target === document.body && engaged.current)
219
223
  if (shortcuts === 'player' && !player.fullscreen && !fromPlayer) return
220
224
 
@@ -237,6 +241,7 @@ export const ControlBar = (
237
241
  else if (ev.key === 'ArrowLeft') {
238
242
  seek(Math.max(player.currentTime - SEEK_STEP, 0))
239
243
  }
244
+ else if ((ev.key === '<' || ev.key === '>') && stepFrame) stepFrame(ev.key === '>' ? 1 : -1)
240
245
  else {
241
246
  shouldPreventDefault = false
242
247
  }
@@ -253,7 +258,7 @@ export const ControlBar = (
253
258
  window.removeEventListener('pointerdown', engage, true)
254
259
  window.removeEventListener('focusin', engage, true)
255
260
  }
256
- }, [player, modifyVolume, requestSeek, shortcuts, root])
261
+ }, [player, modifyVolume, requestSeek, stepFrame, shortcuts, root])
257
262
 
258
263
  const handleWheel = useCallback((e: WheelEvent) => {
259
264
  e.preventDefault()