@banou/media-player 0.10.31 → 0.10.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,7 +12,9 @@ export type ChromeProps = {
12
12
  shortcuts?: 'window' | 'player';
13
13
  /** Fullscreen kept by the host: a press calls its `request` instead of fullscreening the player. */
14
14
  fullscreen?: HostFullscreen;
15
+ /** False leaves the last ending out of the skip offer. */
16
+ endingOffered: boolean;
15
17
  children?: ReactNode;
16
18
  };
17
- export declare const Chrome: ({ ref, onVideoRef, onSubtitleRef, overlay, controls, shortcuts, fullscreen, children }: ChromeProps) => import("@emotion/react/jsx-runtime").JSX.Element;
19
+ export declare const Chrome: ({ ref, onVideoRef, onSubtitleRef, overlay, controls, shortcuts, fullscreen, endingOffered, children }: ChromeProps) => import("@emotion/react/jsx-runtime").JSX.Element;
18
20
  export default Chrome;
@@ -5,6 +5,10 @@
5
5
  * of the pair: the classifier reads titles written by whoever muxed the file, so it is sometimes
6
6
  * going to be wrong. Making the offer expire, and never acting on its own, is what makes being wrong
7
7
  * cheap. See the classifier for what it matches and the sample it was measured against.
8
+ *
9
+ * `endingOffered` false leaves the last ending out, for an embedder that fills this corner itself.
8
10
  */
9
- export declare const SkipChapter: () => import("@emotion/react/jsx-runtime").JSX.Element | null;
11
+ export declare const SkipChapter: ({ endingOffered }: {
12
+ endingOffered: boolean;
13
+ }) => import("@emotion/react/jsx-runtime").JSX.Element | null;
10
14
  export default SkipChapter;
@@ -46,14 +46,17 @@ export type ExposePlayerOptions = {
46
46
  player?: ServedPlayer;
47
47
  };
48
48
  /**
49
- * The player around a served media, as `<MediaPlayer expose>` passes it: its chapters, sent with every snapshot and
50
- * announced on its `chapterschange`, and its fullscreen, which a mirror made with `fullscreen: true` takes over. While
51
- * one has it, `onHostFullscreen` is told the state that mirror sets, and null once none has it; the player then
52
- * dispatches `fullscreenrequest` for each press of its fullscreen, which reaches the mirror.
49
+ * The player around a served media, as `<MediaPlayer expose>` passes it: its chapters and whether it offers to skip its
50
+ * last ending, sent with every snapshot and announced on its `chapterschange`, and its fullscreen, which a mirror made
51
+ * with `fullscreen: true` takes over. While one has it, `onHostFullscreen` is told the state that mirror sets, and null
52
+ * once none has it; the player then dispatches `fullscreenrequest` for each press of its fullscreen, which reaches the
53
+ * mirror. `onEndingOffered` is told what a mirror sets on `endingOffered`.
53
54
  */
54
55
  export type ServedPlayer = EventTarget & {
55
56
  readonly chapters: MediaChapter[];
57
+ readonly endingOffered: boolean;
56
58
  onHostFullscreen: (active: boolean | null) => void;
59
+ onEndingOffered: (offered: boolean) => void;
57
60
  };
58
61
  /**
59
62
  * Serve `media` to this document's embedder. Returns the teardown for THIS media.
@@ -92,6 +95,16 @@ export type MediaPlayerHandle = {
92
95
  * shortcuts follow it. Set it on every change. Without the option it stays here.
93
96
  */
94
97
  fullscreen: boolean;
98
+ /**
99
+ * Whether the far `<MediaPlayer expose>` offers to skip its last ending, as it last said. Set it to false to have
100
+ * that offer taken away, for a page with something of its own in that corner, and to true to have it back; a
101
+ * mirror's `destroy()` leaves it as it is, and a new player starts out offering.
102
+ *
103
+ * Unlike every other write here this one does NOT move the mirror: a read answers what the far player reports,
104
+ * from after its render, with a `chapterschange` event following each change. So a false here means the offer is
105
+ * off the far screen, and a player that cannot take it (a bare element, a version older than this) stays true.
106
+ */
107
+ endingOffered: boolean;
95
108
  /**
96
109
  * Settles once the far side has first answered with its state; reads before that answer the
97
110
  * empty defaults. Stays pending for as long as nobody answers, and rejects with an AbortError on
@@ -49,7 +49,7 @@ var t = [
49
49
  let t = [];
50
50
  for (let n = 0; n < e.length; n++) t.push([e.start(n), e.end(n)]);
51
51
  return t;
52
- }, l = (e, t = []) => ({
52
+ }, l = (e, t = [], n = !0) => ({
53
53
  currentTime: u(e.currentTime),
54
54
  duration: u(e.duration),
55
55
  paused: e.paused,
@@ -69,7 +69,8 @@ var t = [
69
69
  } : null,
70
70
  videoWidth: e.videoWidth ?? 0,
71
71
  videoHeight: e.videoHeight ?? 0,
72
- chapters: t
72
+ chapters: t,
73
+ endingOffered: n
73
74
  }), u = (e) => Number.isNaN(e) ? 0 : e, d = {
74
75
  currentTime: 0,
75
76
  duration: 0,
@@ -87,7 +88,8 @@ var t = [
87
88
  error: null,
88
89
  videoWidth: 0,
89
90
  videoHeight: 0,
90
- chapters: []
91
+ chapters: [],
92
+ endingOffered: !0
91
93
  }, f = (e) => ({
92
94
  length: e.length,
93
95
  start: (t) => e[t]?.[0] ?? 0,
@@ -111,8 +113,8 @@ var t = [
111
113
  T(e, r);
112
114
  }
113
115
  }, D = (e) => {
114
- let t = m.get(e);
115
- return t ? l(t, h.get(e)?.chapters) : void 0;
116
+ let t = m.get(e), n = h.get(e);
117
+ return t ? l(t, n?.chapters, n?.endingOffered) : void 0;
116
118
  }, O = (e, t) => {
117
119
  let n = t === "fullscreenrequest" ? S.get(e) : v.get(e);
118
120
  if (!n?.size) return;
@@ -143,6 +145,10 @@ var t = [
143
145
  C.set(e, n), w(e);
144
146
  return;
145
147
  }
148
+ if (t === "endingOffered") {
149
+ typeof n == "boolean" && h.get(e)?.onEndingOffered(n);
150
+ return;
151
+ }
146
152
  let i = m.get(e);
147
153
  if (i && r.includes(t)) try {
148
154
  i[t] = n;
@@ -315,6 +321,12 @@ var t = [
315
321
  S = !!e, t.fullscreen && O(() => k.set(a, "fullscreen", S));
316
322
  },
317
323
  enumerable: !0
324
+ }), Object.defineProperty(c, "endingOffered", {
325
+ get: () => o.endingOffered,
326
+ set: (e) => {
327
+ O(() => k.set(a, "endingOffered", e));
328
+ },
329
+ enumerable: !0
318
330
  });
319
331
  let A = (e) => g.then(() => {
320
332
  if (i.aborted) throw _();
@@ -30,6 +30,8 @@ export type PlayerSnapshot = {
30
30
  videoHeight: number;
31
31
  /** A `<MediaPlayer expose>`'s chapters, empty for a bare element. */
32
32
  chapters: MediaChapter[];
33
+ /** Whether a `<MediaPlayer expose>` offers to skip its last ending. Set after its render, so false means the offer is off the screen. */
34
+ endingOffered: boolean;
33
35
  };
34
36
  /**
35
37
  * The events a player raises that an embedder can hear, each carrying a fresh snapshot.
@@ -86,7 +88,7 @@ export type PlayerService = {
86
88
  fullscreen?: boolean;
87
89
  }) => void;
88
90
  /** `fullscreen` is the state shown by a player whose fullscreen a mirror has taken over, and is ignored otherwise. */
89
- set: (id: string, name: Writable | 'fullscreen', value: number | boolean) => void;
91
+ set: (id: string, name: Writable | 'fullscreen' | 'endingOffered', value: number | boolean) => void;
90
92
  call: (id: string, name: Callable) => Promise<void>;
91
93
  };
92
94
  /**
@@ -96,7 +98,7 @@ export type PlayerService = {
96
98
  */
97
99
  export declare const syncEventsFor: (snapshot: PlayerSnapshot) => PlayerEvent[];
98
100
  /** A media as a snapshot. A NaN duration, which a bare element answers before it has metadata, is sent as 0. */
99
- export declare const snapshotOf: (media: PlayerMedia, chapters?: MediaChapter[]) => PlayerSnapshot;
101
+ export declare const snapshotOf: (media: PlayerMedia, chapters?: MediaChapter[], endingOffered?: boolean) => PlayerSnapshot;
100
102
  /** The snapshot an embedder holds before the player's document has said anything. */
101
103
  export declare const EMPTY_SNAPSHOT: PlayerSnapshot;
102
104
  /** Plain pairs back into the structural `TimeRanges` the player reads. */
@@ -440,8 +440,9 @@ export const audioSamplesOf = (fragment, track) => {
440
440
  /**
441
441
  * The analysis: 1 ms bins of whatever audio it is given, the normal level learned from them, and the cut for the
442
442
  * blocks around the playhead. `toWorklet` takes `{ block, gain, finger }` (10 s of bins from `block * 10` s, NaN where
443
- * the cut or the audio is not known) and `{ drop }` for each block past the 60 sent nearest the playhead, which is all
444
- * the worklet keeps; `toPage` takes the coverage reports the page schedules reads on.
443
+ * the cut or the audio is not known), `{ drop }` for each block past the 60 sent nearest the playhead, which is all
444
+ * the worklet keeps, and `{ end }`, the bin the file's audio ends at, once a run reaches it; `toPage` takes the
445
+ * coverage reports the page schedules reads on.
445
446
  * Separate from the worker's messages so a test can drive it with decoded audio.
446
447
  */
447
448
  export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
@@ -556,8 +557,6 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
556
557
  finger[bin - start] = Math.log(chunk.finger[bin % BLOCK_BINS] + 1e-10)
557
558
  if (bin < known) gain[bin - start] = curve[bin - from]
558
559
  }
559
- // the last cut holds past the end of the file, where playback's audio can run on by its offset
560
- if (b >= endBin && b > start && b < end) gain.fill(gain[b - 1 - start], b - start)
561
560
  }
562
561
  return { gain, finger }
563
562
  }
@@ -616,7 +615,10 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
616
615
  endRun: (finished) => {
617
616
  if (!run) return
618
617
  run.binner?.flush()
619
- if (finished && run.last >= 0) endBin = run.last + 1
618
+ if (finished && run.last >= 0) {
619
+ endBin = run.last + 1
620
+ toWorklet({ end: endBin })
621
+ }
620
622
  run = null
621
623
  schedule()
622
624
  },
@@ -644,10 +646,11 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
644
646
  *
645
647
  * { type: 'port', port } the worklet's end of a MessageChannel, for the blocks
646
648
  * { type: 'init', data, codec } the init segment and the codec string MediaSource was given
647
- * { type: 'run', run, pts, start } a run of fragments starts, `pts` added to their times as the SourceBuffer's
648
- * timestampOffset adds it for playback; `start` for the one from the start,
649
- * and `join: true` for one whose first fragments went by unseen, which starts
650
- * at its first sample
649
+ * { type: 'run', run, pts, from, start }
650
+ * a run of fragments starts at `from` s, `pts` added to their times as the
651
+ * SourceBuffer's timestampOffset adds it for playback; `start` for the one
652
+ * from the start, and `join: true` for one whose first fragments went by
653
+ * unseen, which starts at its first sample
651
654
  * { type: 'fragment', run, data } answered { type: 'ack', run, spans, end, normal } once its audio is queued
652
655
  * for decoding: the analysed seconds, the file's end once known, and the
653
656
  * level learned so far in LUFS
@@ -682,10 +685,10 @@ const serve = (scope) => {
682
685
  })
683
686
  /*
684
687
  * Each output is placed by its own chunk's timestamp, never the one AudioData carries: Chrome 155 stamps outputs by
685
- * counting samples from the first chunk, and libav's first audio sample in a run lasts until the video's first frame
686
- * is due (62 ms more than its own length in Matroska and mp4 with B-frames, 82 ms in FLAC), which MediaSource plays
687
- * as a gap; counted, what follows came out that much early, too far for the first match to find (HOR-498 build,
688
- * 2026-10-17).
688
+ * counting samples from the first chunk, so past a gap in the timestamps, which MediaSource plays as a gap, what
689
+ * follows comes out early by the gap. Before 0.9.0 libav-wasm's first audio sample of a run lasted until the video's
690
+ * first frame, 62 ms more than its own length in Matroska and mp4 with B-frames and 82 ms in FLAC, too far for the
691
+ * first match to find (HOR-498 build, 2026-10-17).
689
692
  */
690
693
  let stamps = []
691
694
  const open = (id) => {
@@ -722,7 +725,7 @@ const serve = (scope) => {
722
725
  pts = data.pts
723
726
  open(runId)
724
727
  joining = !!data.join
725
- if (!joining) analysis.startRun(runId, pts, data.start)
728
+ if (!joining) analysis.startRun(runId, data.from, data.start)
726
729
  } else if (data.type === 'fragment') {
727
730
  if (data.run !== runId || decoder.state !== 'configured') return
728
731
  const samples = audioSamplesOf(data.data, track)
@@ -781,13 +784,14 @@ const HANDOVER_SECONDS = 0.05
781
784
  const CROSSFADE_SECONDS = 0.05
782
785
  /*
783
786
  * How far either way the live audio is searched for in the analysed audio, in ms: first, and after a seek, against
784
- * where the last match put it. Played from the start, the fixtures matched 21 to 60 ms off, and FLAC past 60 ms (HOR-498
785
- * build, 2026-10-17), as long as libav's first audio sample stretches to the video's first frame, which B-frames set.
787
+ * where the last match put it. Played from the start, the fixtures matched 21 to 60 ms off, and FLAC past 60 ms, while
788
+ * libav-wasm stretched each run's first audio sample to the video's first frame (HOR-498 build, 2026-10-17); with each
789
+ * track at its own time (0.9.0), within 3.4 ms (2026-10-30).
786
790
  */
787
791
  const LOCK_RANGE_MS = 250
788
792
  const RELOCK_RANGE_MS = 30
789
793
  // how far from the last match a seek may move the audio, which the deepest cut in doubt covers, in ms: FLAC moved 82 ms
790
- // across the first remuxer seek, from the stream's start, where MediaSource plays libav's first sample short
794
+ // across the first remuxer seek while libav-wasm stretched a run's first audio sample, and at most 3 ms since 0.9.0
791
795
  const DOUBT_MS = 100
792
796
  // how far from the best offset another must come close for the match to be in question, in ms
793
797
  const CLEAR_MS = 60
@@ -805,14 +809,15 @@ const SCORES_PER_QUANTUM = 40_000
805
809
  * context.currentTime read in one task names the media time of the audio reaching a worklet that same render frame,
806
810
  * to the sample for a 48 kHz file and within about 2 ms for a 44.1 kHz one, except for the odd pair off by up to
807
811
  * 13 ms; so a jump of more than 25 ms re-anchors the timeline, and the median of the next five pairs settles it. Where
808
- * playback's audio sits against the analysed audio changes with each run of the remuxer behind it: -18 to +44 ms on
809
- * the fixtures, the same file 44 ms apart before and after a seek (HOR-498 build, 2026-10-17). So the offset is found
810
- * from the audio itself: the live fingerprint against the analysed one, every 250 ms at normal speed, to a fraction of
811
- * a millisecond. The same match catches the rare stall (once, 60 ms of silence came in mid-file and the audio after it
812
- * ran 11 ms ahead of the clock). Nothing is cut ahead until the first match, which also proves the blocks belong to
813
- * this audio; after a seek, until the next one, each quantum gets the deepest cut within the doubt, never less than
814
- * the cut asks, as it does away from normal speed (Chrome's time stretching moves the audio up to about 30 ms either
815
- * way).
812
+ * playback's audio sits against the analysed audio changed with each run of the remuxer behind it while libav-wasm
813
+ * moved each run by its own amount: -18 to +44 ms on the fixtures, the same file 44 ms apart before and after a seek
814
+ * (HOR-498 build, 2026-10-17); with each track at its own time, -3.4 to +1.2 ms (0.9.0, 2026-10-30). So the offset
815
+ * is found from the audio itself: the live fingerprint against the analysed one, every 250 ms at normal speed, to a
816
+ * fraction of a millisecond. The same match catches the rare stall (once, 60 ms of silence came in mid-file and the
817
+ * audio after it ran 11 ms ahead of the clock). Nothing is cut ahead until the first match, which also proves the
818
+ * blocks belong to this audio; after a seek, until the next one, each quantum gets the deepest cut within the doubt,
819
+ * never less than the cut asks, as it does away from normal speed (Chrome's time stretching moves the audio up to
820
+ * about 30 ms either way).
816
821
  */
817
822
  const defineProcessor = () => class VolumeNormalizer extends AudioWorkletProcessor {
818
823
  constructor({ processorOptions = {} } = {}) {
@@ -867,6 +872,8 @@ const defineProcessor = () => class VolumeNormalizer extends AudioWorkletProcess
867
872
  this.shortTime = 0
868
873
 
869
874
  this.blocks = new Map()
875
+ // the bin the file's audio ends at; the last cut holds past it, where playback's audio can run on
876
+ this.end = Infinity
870
877
  this.analysis = null
871
878
  this.fingerFilter = fingerprintFilter(sampleRate)
872
879
  this.fingerState = []
@@ -909,6 +916,7 @@ const defineProcessor = () => class VolumeNormalizer extends AudioWorkletProcess
909
916
  if (data?.analysis !== undefined) {
910
917
  this.analysis?.close()
911
918
  this.blocks.clear()
919
+ this.end = Infinity
912
920
  this.search = null
913
921
  this.analysis = data.analysis
914
922
  if (this.analysis) this.analysis.onmessage = ({ data: block }) => this.receive(block)
@@ -930,6 +938,7 @@ const defineProcessor = () => class VolumeNormalizer extends AudioWorkletProcess
930
938
  receive(message) {
931
939
  if (typeof message?.drop === 'number') this.blocks.delete(message.drop)
932
940
  else if (typeof message?.block === 'number') this.blocks.set(message.block, message)
941
+ else if (typeof message?.end === 'number') this.end = message.end
933
942
  this.lastBlock = undefined
934
943
  }
935
944
 
@@ -937,7 +946,11 @@ const defineProcessor = () => class VolumeNormalizer extends AudioWorkletProcess
937
946
  const frame = ctx * sampleRate
938
947
  const model = this.model
939
948
  if (paused) {
940
- this.model = { paused: true, media: model && !model.paused ? this.mediaAt(frame) : media }
949
+ // More than 25 ms from where the clock had it, the media is where the pair says: a seek moved it, its audio
950
+ // already playing (10 to 27 ms after the move in Chrome 155, where the main thread once took 52 ms to say so,
951
+ // 2026-10-30), or a pause was told late. The seek's reset, posted on the same event, is what puts it in doubt.
952
+ const held = model && !model.paused ? this.mediaAt(frame) : media
953
+ this.model = { paused: true, media: Math.abs(media - held) <= 0.025 ? held : media }
941
954
  this.liveCount = 0
942
955
  return
943
956
  }
@@ -973,6 +986,7 @@ const defineProcessor = () => class VolumeNormalizer extends AudioWorkletProcess
973
986
  }
974
987
 
975
988
  gainBin(i) {
989
+ if (i >= this.end) i = this.end - 1
976
990
  const block = this.blockOf(i)
977
991
  return block.gain ? block.gain[i - block.block * BLOCK_BINS] : NaN
978
992
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@banou/media-player",
3
- "version": "0.10.31",
3
+ "version": "0.10.33",
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",
@@ -54,7 +54,7 @@
54
54
  "@videojs/react": "10.0.0-beta.26",
55
55
  "ass-compiler": "^0.1.16",
56
56
  "jassub": "^2.5.23",
57
- "libav-wasm": "^0.8.12",
57
+ "libav-wasm": "^0.8.14",
58
58
  "lucide-react": "^0.536.0",
59
59
  "osra": "^0.6.12",
60
60
  "react-tooltip": "^5.28.0"
@@ -202,7 +202,7 @@ export const startLoudnessAnalysis = ({ node, element, scriptUrl, source }: {
202
202
  worker.postMessage({ type: 'init', data: init.data, codec: init.info.output.audioMimeType }, [init.data])
203
203
  active = true
204
204
  started = true
205
- worker.postMessage({ type: 'run', run, pts: 0, start: true })
205
+ worker.postMessage({ type: 'run', run, pts: init.timestampOffset, from: 0, start: true })
206
206
  while (!stopped) {
207
207
  const next = decide()
208
208
  if (next === 'done') break
@@ -229,7 +229,7 @@ export const startLoudnessAnalysis = ({ node, element, scriptUrl, source }: {
229
229
  run++
230
230
  active = true
231
231
  runStart = result.pts
232
- worker.postMessage({ type: 'run', run, pts: result.pts, start: result.pts <= 0 })
232
+ worker.postMessage({ type: 'run', run, pts: init.timestampOffset, from: result.pts, start: result.pts <= 0 })
233
233
  await send(result)
234
234
  if (result.finished) await endRun(true)
235
235
  }
@@ -260,7 +260,7 @@ export const startLoudnessAnalysis = ({ node, element, scriptUrl, source }: {
260
260
  } else if (output.type === 'run') {
261
261
  end(false)
262
262
  open = true
263
- worker.postMessage({ type: 'run', run: ++run, pts: output.pts, start: !join && output.pts <= 0, join })
263
+ worker.postMessage({ type: 'run', run: ++run, pts: output.pts, from: output.from, start: !join && output.from <= 0, join })
264
264
  } else if (output.type === 'end') end(true)
265
265
  else if (open) {
266
266
  const data = output.data.slice(0)
@@ -12,7 +12,7 @@ export type PlaybackTap = {
12
12
 
13
13
  export const createPlaybackTap = (): PlaybackTap => {
14
14
  let init: Extract<PlaybackOutput, { type: 'init' }> | undefined
15
- let run: { pts: number, begun: boolean } | undefined
15
+ let run: { output: Extract<PlaybackOutput, { type: 'run' }>, begun: boolean } | undefined
16
16
  let listener: { audioStreamIndex: number, take: (output: PlaybackOutput, join?: boolean) => void } | undefined
17
17
  const live = () => listener && init?.audioStreamIndex === listener.audioStreamIndex ? listener : undefined
18
18
  return {
@@ -20,7 +20,7 @@ export const createPlaybackTap = (): PlaybackTap => {
20
20
  if (output.type === 'init') {
21
21
  init = output
22
22
  run = undefined
23
- } else if (output.type === 'run') run = { pts: output.pts, begun: false }
23
+ } else if (output.type === 'run') run = { output, begun: false }
24
24
  else if (output.type === 'fragment' && run) run.begun = true
25
25
  live()?.take(output)
26
26
  },
@@ -29,7 +29,7 @@ export const createPlaybackTap = (): PlaybackTap => {
29
29
  listener = mine
30
30
  if (live() && init) {
31
31
  take(init)
32
- if (run) take({ type: 'run', pts: run.pts }, run.begun)
32
+ if (run) take(run.output, run.begun)
33
33
  }
34
34
  return () => { if (listener === mine) listener = undefined }
35
35
  },
@@ -32,7 +32,7 @@ export type AudioTrack = {
32
32
  export const audioTrackOf: (init: ArrayBuffer) => AudioTrack | undefined
33
33
  export const audioSamplesOf: (fragment: ArrayBuffer, track: AudioTrack) => { time: number, duration: number, data: Uint8Array }[]
34
34
 
35
- export type BlockMessage = { block: number, gain: Float32Array, finger: Float32Array } | { drop: number }
35
+ export type BlockMessage = { block: number, gain: Float32Array, finger: Float32Array } | { drop: number } | { end: number }
36
36
  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
@@ -440,8 +440,9 @@ export const audioSamplesOf = (fragment, track) => {
440
440
  /**
441
441
  * The analysis: 1 ms bins of whatever audio it is given, the normal level learned from them, and the cut for the
442
442
  * blocks around the playhead. `toWorklet` takes `{ block, gain, finger }` (10 s of bins from `block * 10` s, NaN where
443
- * the cut or the audio is not known) and `{ drop }` for each block past the 60 sent nearest the playhead, which is all
444
- * the worklet keeps; `toPage` takes the coverage reports the page schedules reads on.
443
+ * the cut or the audio is not known), `{ drop }` for each block past the 60 sent nearest the playhead, which is all
444
+ * the worklet keeps, and `{ end }`, the bin the file's audio ends at, once a run reaches it; `toPage` takes the
445
+ * coverage reports the page schedules reads on.
445
446
  * Separate from the worker's messages so a test can drive it with decoded audio.
446
447
  */
447
448
  export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
@@ -556,8 +557,6 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
556
557
  finger[bin - start] = Math.log(chunk.finger[bin % BLOCK_BINS] + 1e-10)
557
558
  if (bin < known) gain[bin - start] = curve[bin - from]
558
559
  }
559
- // the last cut holds past the end of the file, where playback's audio can run on by its offset
560
- if (b >= endBin && b > start && b < end) gain.fill(gain[b - 1 - start], b - start)
561
560
  }
562
561
  return { gain, finger }
563
562
  }
@@ -616,7 +615,10 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
616
615
  endRun: (finished) => {
617
616
  if (!run) return
618
617
  run.binner?.flush()
619
- if (finished && run.last >= 0) endBin = run.last + 1
618
+ if (finished && run.last >= 0) {
619
+ endBin = run.last + 1
620
+ toWorklet({ end: endBin })
621
+ }
620
622
  run = null
621
623
  schedule()
622
624
  },
@@ -644,10 +646,11 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
644
646
  *
645
647
  * { type: 'port', port } the worklet's end of a MessageChannel, for the blocks
646
648
  * { type: 'init', data, codec } the init segment and the codec string MediaSource was given
647
- * { type: 'run', run, pts, start } a run of fragments starts, `pts` added to their times as the SourceBuffer's
648
- * timestampOffset adds it for playback; `start` for the one from the start,
649
- * and `join: true` for one whose first fragments went by unseen, which starts
650
- * at its first sample
649
+ * { type: 'run', run, pts, from, start }
650
+ * a run of fragments starts at `from` s, `pts` added to their times as the
651
+ * SourceBuffer's timestampOffset adds it for playback; `start` for the one
652
+ * from the start, and `join: true` for one whose first fragments went by
653
+ * unseen, which starts at its first sample
651
654
  * { type: 'fragment', run, data } answered { type: 'ack', run, spans, end, normal } once its audio is queued
652
655
  * for decoding: the analysed seconds, the file's end once known, and the
653
656
  * level learned so far in LUFS
@@ -682,10 +685,10 @@ const serve = (scope) => {
682
685
  })
683
686
  /*
684
687
  * Each output is placed by its own chunk's timestamp, never the one AudioData carries: Chrome 155 stamps outputs by
685
- * counting samples from the first chunk, and libav's first audio sample in a run lasts until the video's first frame
686
- * is due (62 ms more than its own length in Matroska and mp4 with B-frames, 82 ms in FLAC), which MediaSource plays
687
- * as a gap; counted, what follows came out that much early, too far for the first match to find (HOR-498 build,
688
- * 2026-10-17).
688
+ * counting samples from the first chunk, so past a gap in the timestamps, which MediaSource plays as a gap, what
689
+ * follows comes out early by the gap. Before 0.9.0 libav-wasm's first audio sample of a run lasted until the video's
690
+ * first frame, 62 ms more than its own length in Matroska and mp4 with B-frames and 82 ms in FLAC, too far for the
691
+ * first match to find (HOR-498 build, 2026-10-17).
689
692
  */
690
693
  let stamps = []
691
694
  const open = (id) => {
@@ -722,7 +725,7 @@ const serve = (scope) => {
722
725
  pts = data.pts
723
726
  open(runId)
724
727
  joining = !!data.join
725
- if (!joining) analysis.startRun(runId, pts, data.start)
728
+ if (!joining) analysis.startRun(runId, data.from, data.start)
726
729
  } else if (data.type === 'fragment') {
727
730
  if (data.run !== runId || decoder.state !== 'configured') return
728
731
  const samples = audioSamplesOf(data.data, track)
@@ -781,13 +784,14 @@ const HANDOVER_SECONDS = 0.05
781
784
  const CROSSFADE_SECONDS = 0.05
782
785
  /*
783
786
  * How far either way the live audio is searched for in the analysed audio, in ms: first, and after a seek, against
784
- * where the last match put it. Played from the start, the fixtures matched 21 to 60 ms off, and FLAC past 60 ms (HOR-498
785
- * build, 2026-10-17), as long as libav's first audio sample stretches to the video's first frame, which B-frames set.
787
+ * where the last match put it. Played from the start, the fixtures matched 21 to 60 ms off, and FLAC past 60 ms, while
788
+ * libav-wasm stretched each run's first audio sample to the video's first frame (HOR-498 build, 2026-10-17); with each
789
+ * track at its own time (0.9.0), within 3.4 ms (2026-10-30).
786
790
  */
787
791
  const LOCK_RANGE_MS = 250
788
792
  const RELOCK_RANGE_MS = 30
789
793
  // how far from the last match a seek may move the audio, which the deepest cut in doubt covers, in ms: FLAC moved 82 ms
790
- // across the first remuxer seek, from the stream's start, where MediaSource plays libav's first sample short
794
+ // across the first remuxer seek while libav-wasm stretched a run's first audio sample, and at most 3 ms since 0.9.0
791
795
  const DOUBT_MS = 100
792
796
  // how far from the best offset another must come close for the match to be in question, in ms
793
797
  const CLEAR_MS = 60
@@ -805,14 +809,15 @@ const SCORES_PER_QUANTUM = 40_000
805
809
  * context.currentTime read in one task names the media time of the audio reaching a worklet that same render frame,
806
810
  * to the sample for a 48 kHz file and within about 2 ms for a 44.1 kHz one, except for the odd pair off by up to
807
811
  * 13 ms; so a jump of more than 25 ms re-anchors the timeline, and the median of the next five pairs settles it. Where
808
- * playback's audio sits against the analysed audio changes with each run of the remuxer behind it: -18 to +44 ms on
809
- * the fixtures, the same file 44 ms apart before and after a seek (HOR-498 build, 2026-10-17). So the offset is found
810
- * from the audio itself: the live fingerprint against the analysed one, every 250 ms at normal speed, to a fraction of
811
- * a millisecond. The same match catches the rare stall (once, 60 ms of silence came in mid-file and the audio after it
812
- * ran 11 ms ahead of the clock). Nothing is cut ahead until the first match, which also proves the blocks belong to
813
- * this audio; after a seek, until the next one, each quantum gets the deepest cut within the doubt, never less than
814
- * the cut asks, as it does away from normal speed (Chrome's time stretching moves the audio up to about 30 ms either
815
- * way).
812
+ * playback's audio sits against the analysed audio changed with each run of the remuxer behind it while libav-wasm
813
+ * moved each run by its own amount: -18 to +44 ms on the fixtures, the same file 44 ms apart before and after a seek
814
+ * (HOR-498 build, 2026-10-17); with each track at its own time, -3.4 to +1.2 ms (0.9.0, 2026-10-30). So the offset
815
+ * is found from the audio itself: the live fingerprint against the analysed one, every 250 ms at normal speed, to a
816
+ * fraction of a millisecond. The same match catches the rare stall (once, 60 ms of silence came in mid-file and the
817
+ * audio after it ran 11 ms ahead of the clock). Nothing is cut ahead until the first match, which also proves the
818
+ * blocks belong to this audio; after a seek, until the next one, each quantum gets the deepest cut within the doubt,
819
+ * never less than the cut asks, as it does away from normal speed (Chrome's time stretching moves the audio up to
820
+ * about 30 ms either way).
816
821
  */
817
822
  const defineProcessor = () => class VolumeNormalizer extends AudioWorkletProcessor {
818
823
  constructor({ processorOptions = {} } = {}) {
@@ -867,6 +872,8 @@ const defineProcessor = () => class VolumeNormalizer extends AudioWorkletProcess
867
872
  this.shortTime = 0
868
873
 
869
874
  this.blocks = new Map()
875
+ // the bin the file's audio ends at; the last cut holds past it, where playback's audio can run on
876
+ this.end = Infinity
870
877
  this.analysis = null
871
878
  this.fingerFilter = fingerprintFilter(sampleRate)
872
879
  this.fingerState = []
@@ -909,6 +916,7 @@ const defineProcessor = () => class VolumeNormalizer extends AudioWorkletProcess
909
916
  if (data?.analysis !== undefined) {
910
917
  this.analysis?.close()
911
918
  this.blocks.clear()
919
+ this.end = Infinity
912
920
  this.search = null
913
921
  this.analysis = data.analysis
914
922
  if (this.analysis) this.analysis.onmessage = ({ data: block }) => this.receive(block)
@@ -930,6 +938,7 @@ const defineProcessor = () => class VolumeNormalizer extends AudioWorkletProcess
930
938
  receive(message) {
931
939
  if (typeof message?.drop === 'number') this.blocks.delete(message.drop)
932
940
  else if (typeof message?.block === 'number') this.blocks.set(message.block, message)
941
+ else if (typeof message?.end === 'number') this.end = message.end
933
942
  this.lastBlock = undefined
934
943
  }
935
944
 
@@ -937,7 +946,11 @@ const defineProcessor = () => class VolumeNormalizer extends AudioWorkletProcess
937
946
  const frame = ctx * sampleRate
938
947
  const model = this.model
939
948
  if (paused) {
940
- this.model = { paused: true, media: model && !model.paused ? this.mediaAt(frame) : media }
949
+ // More than 25 ms from where the clock had it, the media is where the pair says: a seek moved it, its audio
950
+ // already playing (10 to 27 ms after the move in Chrome 155, where the main thread once took 52 ms to say so,
951
+ // 2026-10-30), or a pause was told late. The seek's reset, posted on the same event, is what puts it in doubt.
952
+ const held = model && !model.paused ? this.mediaAt(frame) : media
953
+ this.model = { paused: true, media: Math.abs(media - held) <= 0.025 ? held : media }
941
954
  this.liveCount = 0
942
955
  return
943
956
  }
@@ -973,6 +986,7 @@ const defineProcessor = () => class VolumeNormalizer extends AudioWorkletProcess
973
986
  }
974
987
 
975
988
  gainBin(i) {
989
+ if (i >= this.end) i = this.end - 1
976
990
  const block = this.blockOf(i)
977
991
  return block.gain ? block.gain[i - block.block * BLOCK_BINS] : NaN
978
992
  }