@banou/media-player 0.10.25 → 0.10.27

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.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { c as e, l as t, n, o as r, r as i, s as a, t as o, u as s } from "./engine-BdouHadr.js";
1
+ import { c as e, l as t, n, o as r, r as i, s as a, t as o, u as s } from "./engine-AjFLuCdA.js";
2
2
  import { Children as c, Fragment as l, isValidElement as u, useCallback as d, useEffect as f, useMemo as p, useRef as m, useState as h, useSyncExternalStore as g } from "react";
3
3
  import { css as _, keyframes as v } from "@emotion/react";
4
4
  import { createPlayer as y, useContainerAttach as b, useMediaAttach as x } from "@videojs/react";
@@ -87,32 +87,32 @@ var U = {
87
87
  }
88
88
  return t.length ? t.join("\n") : void 0;
89
89
  }, le = (e, t, n, i) => {
90
- let o = K(), { read: s, size: c, publicPath: l = "", libavWorkerUrl: u = "", jassubWorkerUrl: p = "", jassubWasmUrl: g = "", jassubLegacyWasmUrl: _, defaultFontUrl: v, bufferSize: y, autoplay: b = !1, chapters: x, seekPrepareBudgetMs: S = X } = n ?? {}, C = m(x);
91
- C.current = x;
92
- let [w, T] = h(void 0), [E, D] = h(0), O = m({
90
+ let o = K(), { read: s, size: c, publicPath: l = "", libavWorkerUrl: u = "", jassubWorkerUrl: p = "", jassubWasmUrl: g = "", jassubLegacyWasmUrl: _, defaultFontUrl: v, cjkFontUrl: y, bufferSize: b, autoplay: x = !1, chapters: S, seekPrepareBudgetMs: C = X } = n ?? {}, w = m(S);
91
+ w.current = S;
92
+ let [T, E] = h(void 0), [D, O] = h(0), k = m({
93
93
  count: 0,
94
94
  at: 0
95
- }), k = m(void 0);
96
- f(() => (O.current = {
95
+ }), A = m(void 0);
96
+ f(() => (k.current = {
97
97
  count: 0,
98
98
  at: 0
99
99
  }, o.setSourceState({ playbackErrors: [] }), () => {
100
- k.current && clearTimeout(k.current);
100
+ A.current && clearTimeout(A.current);
101
101
  }), [c]);
102
- let A = m(null), j = m(null), M = m(!1), N = m(s);
103
- N.current = s;
104
- let P = m(n?.onSeek);
105
- P.current = n?.onSeek;
106
- let F = m(n?.onPlaybackError);
107
- F.current = n?.onPlaybackError;
108
- let I = m(i);
109
- I.current = i;
110
- let L = d((e) => {
102
+ let j = m(null), M = m(null), N = m(!1), P = m(s);
103
+ P.current = s;
104
+ let F = m(n?.onSeek);
105
+ F.current = n?.onSeek;
106
+ let I = m(n?.onPlaybackError);
107
+ I.current = n?.onPlaybackError;
108
+ let L = m(i);
109
+ L.current = i;
110
+ let R = d((e) => {
111
111
  let t = typeof e == "number" ? e : void 0;
112
- M.current = !0, o.setSourceState({ selectedSubtitleTrack: t }), A.current?.selectSubtitleStream(t);
113
- }, [o]), R = d((e) => {
114
- let t = A.current;
115
- if (!t || S <= 0) {
112
+ N.current = !0, o.setSourceState({ selectedSubtitleTrack: t }), j.current?.selectSubtitleStream(t);
113
+ }, [o]), z = d((e) => {
114
+ let t = j.current;
115
+ if (!t || C <= 0) {
116
116
  o.seek(e);
117
117
  return;
118
118
  }
@@ -130,24 +130,24 @@ var U = {
130
130
  c?.addEventListener("seeked", l);
131
131
  let d = setTimeout(() => {
132
132
  a = "deadline", s();
133
- }, S);
133
+ }, C);
134
134
  t.prepareSeek(e).catch(() => {}).finally(() => {
135
135
  clearTimeout(d), s();
136
136
  });
137
- }, [o, S]), z = d((e) => {
138
- typeof e == "number" && (o.setSourceState({ selectedAudioTrack: e }), T(e));
139
- }, [o]), B = K((e) => e.setSourceState);
137
+ }, [o, C]), B = d((e) => {
138
+ typeof e == "number" && (o.setSourceState({ selectedAudioTrack: e }), E(e));
139
+ }, [o]), V = K((e) => e.setSourceState);
140
140
  f(() => {
141
- B({
142
- selectSubtitleTrack: L,
143
- selectAudioTrack: z,
144
- requestSeek: R
141
+ V({
142
+ selectSubtitleTrack: R,
143
+ selectAudioTrack: B,
144
+ requestSeek: z
145
145
  });
146
146
  }, [
147
+ V,
148
+ R,
147
149
  B,
148
- L,
149
- z,
150
- R
150
+ z
151
151
  ]), f(() => {
152
152
  if (!e || !t || !c || !s) return;
153
153
  let n = !1;
@@ -181,25 +181,25 @@ var U = {
181
181
  let t = r(e);
182
182
  if (i(e, t), t) {
183
183
  let t = performance.now();
184
- t - O.current.at > ae && (O.current = {
184
+ t - k.current.at > ae && (k.current = {
185
185
  count: 0,
186
186
  at: t
187
187
  });
188
- let n = Y[Math.min(O.current.count, Y.length - 1)];
189
- O.current = {
190
- count: O.current.count + 1,
188
+ let n = Y[Math.min(k.current.count, Y.length - 1)];
189
+ k.current = {
190
+ count: k.current.count + 1,
191
191
  at: t
192
- }, console.warn(`the media element failed; rebuilding the pipeline${n ? ` in ${n}ms` : ""}`, e), k.current && clearTimeout(k.current), k.current = setTimeout(() => D((e) => e + 1), n);
192
+ }, console.warn(`the media element failed; rebuilding the pipeline${n ? ` in ${n}ms` : ""}`, e), A.current && clearTimeout(A.current), A.current = setTimeout(() => O((e) => e + 1), n);
193
193
  return;
194
194
  }
195
- console.error("playback failed", e), o.setSourceState({ playbackError: e }), F.current?.(e);
195
+ console.error("playback failed", e), o.setSourceState({ playbackError: e }), I.current?.(e);
196
196
  };
197
197
  return (async () => {
198
198
  try {
199
199
  let r = await a({
200
200
  videoElement: e,
201
201
  subtitleContainer: t,
202
- read: (e, t) => N.current(e, t),
202
+ read: (e, t) => P.current(e, t),
203
203
  length: c,
204
204
  publicPath: l,
205
205
  libavWorkerUrl: u,
@@ -207,24 +207,25 @@ var U = {
207
207
  jassubWasmUrl: g,
208
208
  jassubLegacyWasmUrl: _,
209
209
  defaultFontUrl: v,
210
- bufferSize: y,
211
- audioStreamIndex: w,
210
+ cjkFontUrl: y,
211
+ bufferSize: b,
212
+ audioStreamIndex: T,
212
213
  onReady: () => {
213
214
  if (n) return;
214
215
  o.setSourceState({ ready: !0 });
215
- let t = j.current;
216
- j.current = null, t && t.size === c && t.time > 0 && (e.currentTime = t.time), b && e.play().catch(() => {});
216
+ let t = M.current;
217
+ M.current = null, t && t.size === c && t.time > 0 && (e.currentTime = t.time), x && e.play().catch(() => {});
217
218
  },
218
219
  onError: d,
219
220
  onRecovered: () => {
220
221
  n || o.setSourceState({ playbackError: null });
221
222
  },
222
- onSeek: (e) => P.current?.(e),
223
- onOutput: (e) => I.current?.(e),
223
+ onSeek: (e) => F.current?.(e),
224
+ onOutput: (e) => L.current?.(e),
224
225
  onSubtitleStreams: (e) => {
225
226
  n || o.setSourceState({
226
227
  subtitleTracks: J(e),
227
- ...M.current ? {} : { selectedSubtitleTrack: e[0]?.streamIndex }
228
+ ...N.current ? {} : { selectedSubtitleTrack: e[0]?.streamIndex }
228
229
  });
229
230
  },
230
231
  onAudioStreams: (e, t) => {
@@ -238,9 +239,9 @@ var U = {
238
239
  r.destroy();
239
240
  return;
240
241
  }
241
- A.current = r, o.setSourceState({
242
+ j.current = r, o.setSourceState({
242
243
  indexes: r.indexes,
243
- chapters: C.current ?? r.chapters
244
+ chapters: w.current ?? r.chapters
244
245
  });
245
246
  let i = o.selectedSubtitleTrack;
246
247
  typeof i == "number" && r.selectSubtitleStream(i);
@@ -248,10 +249,10 @@ var U = {
248
249
  d(e);
249
250
  }
250
251
  })(), () => {
251
- n = !0, j.current = {
252
+ n = !0, M.current = {
252
253
  time: e.currentTime,
253
254
  size: c
254
- }, A.current?.destroy(), A.current = null, o.setSourceState({ ready: !1 });
255
+ }, j.current?.destroy(), j.current = null, o.setSourceState({ ready: !1 });
255
256
  };
256
257
  }, [
257
258
  o,
@@ -265,9 +266,10 @@ var U = {
265
266
  _,
266
267
  v,
267
268
  y,
268
- w,
269
269
  b,
270
- E
270
+ T,
271
+ x,
272
+ D
271
273
  ]);
272
274
  }, ue = 1001 / 24e3, de = (e, t) => new Promise((n) => {
273
275
  let r = setTimeout(n, t);
@@ -128,6 +128,8 @@ export type MediaPlayerLocalOptions = CommonOptions & MediaPlayerSource & {
128
128
  jassubLegacyWasmUrl?: string;
129
129
  /** Fallback face for `liberation sans`, used when a subtitle track names a font the file does not carry. */
130
130
  defaultFontUrl?: string;
131
+ /** `@banou/media-player/noto-sans-jp.otf`, the face for CJK text, fetched once the selected track shows some. */
132
+ cjkFontUrl?: string;
131
133
  bufferSize?: number;
132
134
  /**
133
135
  * How long a seek waits for its own data before the playhead moves anyway, in ms. Default 500.
@@ -20,6 +20,13 @@
20
20
  const BINS_PER_SECOND = 1000
21
21
  // the analysis's unit of work and of what the worklet holds: 10 s of 1 ms bins
22
22
  const BLOCK_BINS = 10_000
23
+ /*
24
+ * The blocks the worklet keeps, those it was sent nearest the playhead, 4.8 MB of cut and fingerprint: as it plays,
25
+ * the 30 to 40 s sent ahead of it and 560 to 570 s behind. Under load Chrome plays a seek into audio it still has
26
+ * buffered before a block let go of is computed again: kept only 20 to 30 s behind and 30 to 40 s ahead, 3 to 32 ms of
27
+ * such a seek played on the live stage alone, in 51 of 75 seeks 24 to 44 s away on 4 loaded CPUs (HOR-681, 2026-10-25).
28
+ */
29
+ const KEPT_BLOCKS = 60
23
30
  /*
24
31
  * How far a cut reaches from the audio that asks for it, in bins. The slow stage reads 1.85 s ahead and 1.65 s
25
32
  * behind, and its exponential attack (0.3 s, backward) and release (0.5 s, forward) fall under 0.01 dB of a 20 dB cut
@@ -433,7 +440,8 @@ export const audioSamplesOf = (fragment, track) => {
433
440
  /**
434
441
  * The analysis: 1 ms bins of whatever audio it is given, the normal level learned from them, and the cut for the
435
442
  * blocks around the playhead. `toWorklet` takes `{ block, gain, finger }` (10 s of bins from `block * 10` s, NaN where
436
- * the cut or the audio is not known) and `{ drop }`; `toPage` takes the coverage reports the page schedules reads on.
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.
437
445
  * Separate from the worker's messages so a test can drive it with decoded audio.
438
446
  */
439
447
  export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
@@ -557,13 +565,8 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
557
565
  const update = () => {
558
566
  timer = undefined
559
567
  const level = normal()
560
- const here = Math.floor(playhead * BINS_PER_SECOND / BLOCK_BINS)
561
- for (const block of [...sent.keys()]) {
562
- if (block >= here - 2 && block <= here + 4) continue
563
- sent.delete(block)
564
- toWorklet({ drop: block })
565
- }
566
568
  if (!Number.isFinite(level)) return
569
+ const here = Math.floor(playhead * BINS_PER_SECOND / BLOCK_BINS)
567
570
  // the playhead's own block first: under load each took 21 to 43 ms, and sent after the one before it, a seek's
568
571
  // cut over HTTP reached the worklet 64 to 75 ms after the seek, its audio 72 to 83 ms (HOR-888, 2026-10-23)
569
572
  for (const block of [here, here - 1, here + 1, here + 2, here + 3]) {
@@ -577,6 +580,11 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
577
580
  sent.set(block, { known, level })
578
581
  toWorklet({ block, gain, finger }, [gain.buffer, finger.buffer])
579
582
  }
583
+ const nearest = [...sent.keys()].sort((a, b) => Math.abs(a - here) - Math.abs(b - here))
584
+ for (const block of nearest.slice(KEPT_BLOCKS)) {
585
+ sent.delete(block)
586
+ toWorklet({ drop: block })
587
+ }
580
588
  }
581
589
  const schedule = () => { timer ??= setTimeout(update, 250) }
582
590
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@banou/media-player",
3
- "version": "0.10.25",
3
+ "version": "0.10.27",
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",
@@ -19,6 +19,7 @@
19
19
  "import": "./dist/remote/index.js"
20
20
  },
21
21
  "./volume-normalizer-worklet.js": "./dist/volume-normalizer-worklet.js",
22
+ "./noto-sans-jp.otf": "./src/lib/assets/noto-sans-jp.otf",
22
23
  "./package.json": "./package.json"
23
24
  },
24
25
  "files": [
@@ -0,0 +1,92 @@
1
+ This Font Software is licensed under the SIL Open Font License,
2
+ Version 1.1.
3
+
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+ -----------------------------------------------------------
8
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
9
+ -----------------------------------------------------------
10
+
11
+ PREAMBLE
12
+ The goals of the Open Font License (OFL) are to stimulate worldwide
13
+ development of collaborative font projects, to support the font
14
+ creation efforts of academic and linguistic communities, and to
15
+ provide a free and open framework in which fonts may be shared and
16
+ improved in partnership with others.
17
+
18
+ The OFL allows the licensed fonts to be used, studied, modified and
19
+ redistributed freely as long as they are not sold by themselves. The
20
+ fonts, including any derivative works, can be bundled, embedded,
21
+ redistributed and/or sold with any software provided that any reserved
22
+ names are not used by derivative works. The fonts and derivatives,
23
+ however, cannot be released under any other type of license. The
24
+ requirement for fonts to remain under this license does not apply to
25
+ any document created using the fonts or their derivatives.
26
+
27
+ DEFINITIONS
28
+ "Font Software" refers to the set of files released by the Copyright
29
+ Holder(s) under this license and clearly marked as such. This may
30
+ include source files, build scripts and documentation.
31
+
32
+ "Reserved Font Name" refers to any names specified as such after the
33
+ copyright statement(s).
34
+
35
+ "Original Version" refers to the collection of Font Software
36
+ components as distributed by the Copyright Holder(s).
37
+
38
+ "Modified Version" refers to any derivative made by adding to,
39
+ deleting, or substituting -- in part or in whole -- any of the
40
+ components of the Original Version, by changing formats or by porting
41
+ the Font Software to a new environment.
42
+
43
+ "Author" refers to any designer, engineer, programmer, technical
44
+ writer or other person who contributed to the Font Software.
45
+
46
+ PERMISSION & CONDITIONS
47
+ Permission is hereby granted, free of charge, to any person obtaining
48
+ a copy of the Font Software, to use, study, copy, merge, embed,
49
+ modify, redistribute, and sell modified and unmodified copies of the
50
+ Font Software, subject to the following conditions:
51
+
52
+ 1) Neither the Font Software nor any of its individual components, in
53
+ Original or Modified Versions, may be sold by itself.
54
+
55
+ 2) Original or Modified Versions of the Font Software may be bundled,
56
+ redistributed and/or sold with any software, provided that each copy
57
+ contains the above copyright notice and this license. These can be
58
+ included either as stand-alone text files, human-readable headers or
59
+ in the appropriate machine-readable metadata fields within text or
60
+ binary files as long as those fields can be easily viewed by the user.
61
+
62
+ 3) No Modified Version of the Font Software may use the Reserved Font
63
+ Name(s) unless explicit written permission is granted by the
64
+ corresponding Copyright Holder. This restriction only applies to the
65
+ primary font name as presented to the users.
66
+
67
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
68
+ Software shall not be used to promote, endorse or advertise any
69
+ Modified Version, except to acknowledge the contribution(s) of the
70
+ Copyright Holder(s) and the Author(s) or with their explicit written
71
+ permission.
72
+
73
+ 5) The Font Software, modified or unmodified, in part or in whole,
74
+ must be distributed entirely under this license, and must not be
75
+ distributed under any other license. The requirement for fonts to
76
+ remain under this license does not apply to any document created using
77
+ the Font Software.
78
+
79
+ TERMINATION
80
+ This license becomes null and void if any of the above conditions are
81
+ not met.
82
+
83
+ DISCLAIMER
84
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
85
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
86
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
87
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
88
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
89
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
90
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
91
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
92
+ OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file
@@ -20,6 +20,13 @@
20
20
  const BINS_PER_SECOND = 1000
21
21
  // the analysis's unit of work and of what the worklet holds: 10 s of 1 ms bins
22
22
  const BLOCK_BINS = 10_000
23
+ /*
24
+ * The blocks the worklet keeps, those it was sent nearest the playhead, 4.8 MB of cut and fingerprint: as it plays,
25
+ * the 30 to 40 s sent ahead of it and 560 to 570 s behind. Under load Chrome plays a seek into audio it still has
26
+ * buffered before a block let go of is computed again: kept only 20 to 30 s behind and 30 to 40 s ahead, 3 to 32 ms of
27
+ * such a seek played on the live stage alone, in 51 of 75 seeks 24 to 44 s away on 4 loaded CPUs (HOR-681, 2026-10-25).
28
+ */
29
+ const KEPT_BLOCKS = 60
23
30
  /*
24
31
  * How far a cut reaches from the audio that asks for it, in bins. The slow stage reads 1.85 s ahead and 1.65 s
25
32
  * behind, and its exponential attack (0.3 s, backward) and release (0.5 s, forward) fall under 0.01 dB of a 20 dB cut
@@ -433,7 +440,8 @@ export const audioSamplesOf = (fragment, track) => {
433
440
  /**
434
441
  * The analysis: 1 ms bins of whatever audio it is given, the normal level learned from them, and the cut for the
435
442
  * blocks around the playhead. `toWorklet` takes `{ block, gain, finger }` (10 s of bins from `block * 10` s, NaN where
436
- * the cut or the audio is not known) and `{ drop }`; `toPage` takes the coverage reports the page schedules reads on.
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.
437
445
  * Separate from the worker's messages so a test can drive it with decoded audio.
438
446
  */
439
447
  export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
@@ -557,13 +565,8 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
557
565
  const update = () => {
558
566
  timer = undefined
559
567
  const level = normal()
560
- const here = Math.floor(playhead * BINS_PER_SECOND / BLOCK_BINS)
561
- for (const block of [...sent.keys()]) {
562
- if (block >= here - 2 && block <= here + 4) continue
563
- sent.delete(block)
564
- toWorklet({ drop: block })
565
- }
566
568
  if (!Number.isFinite(level)) return
569
+ const here = Math.floor(playhead * BINS_PER_SECOND / BLOCK_BINS)
567
570
  // the playhead's own block first: under load each took 21 to 43 ms, and sent after the one before it, a seek's
568
571
  // cut over HTTP reached the worklet 64 to 75 ms after the seek, its audio 72 to 83 ms (HOR-888, 2026-10-23)
569
572
  for (const block of [here, here - 1, here + 1, here + 2, here + 3]) {
@@ -577,6 +580,11 @@ export const createAnalysis = ({ toWorklet, toPage = () => {} }) => {
577
580
  sent.set(block, { known, level })
578
581
  toWorklet({ block, gain, finger }, [gain.buffer, finger.buffer])
579
582
  }
583
+ const nearest = [...sent.keys()].sort((a, b) => Math.abs(a - here) - Math.abs(b - here))
584
+ for (const block of nearest.slice(KEPT_BLOCKS)) {
585
+ sent.delete(block)
586
+ toWorklet({ drop: block })
587
+ }
580
588
  }
581
589
  const schedule = () => { timer ??= setTimeout(update, 250) }
582
590
 
@@ -55,6 +55,7 @@ export type PlaybackOptions = {
55
55
  /** jassub's non-SIMD build; without it subtitles fail rather than degrade on Safari before 16.4 */
56
56
  jassubLegacyWasmUrl?: string
57
57
  defaultFontUrl?: string
58
+ cjkFontUrl?: string
58
59
  bufferSize?: number
59
60
  audioStreamIndex?: number
60
61
  onReady?: () => void
@@ -157,7 +158,7 @@ export const terminateRemuxer = (remuxer: { worker: Worker, destroy: () => Promi
157
158
  export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackController> => {
158
159
  const {
159
160
  videoElement, subtitleContainer, read, length, publicPath, libavWorkerUrl,
160
- jassubWorkerUrl, jassubWasmUrl, jassubLegacyWasmUrl, defaultFontUrl, bufferSize = DEFAULT_BUFFER_SIZE,
161
+ jassubWorkerUrl, jassubWasmUrl, jassubLegacyWasmUrl, defaultFontUrl, cjkFontUrl, bufferSize = DEFAULT_BUFFER_SIZE,
161
162
  audioStreamIndex, onReady, onError, onRecovered, onSeek, onSubtitleStreams,
162
163
  onAudioStreams, onOutput,
163
164
  } = options
@@ -199,6 +200,7 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
199
200
  wasmUrl: jassubWasmUrl,
200
201
  legacyWasmUrl: jassubLegacyWasmUrl,
201
202
  defaultFontUrl,
203
+ cjkFontUrl,
202
204
  onStreams: onSubtitleStreams,
203
205
  })
204
206
  teardown.push(() => subtitles.destroy())
@@ -44,6 +44,14 @@ export type SubtitleRendererOptions = {
44
44
  * given on `workerFetched`.
45
45
  */
46
46
  defaultFontUrl?: string
47
+ /**
48
+ * Noto Sans JP, `@banou/media-player/noto-sans-jp.otf`, for Japanese text the file's own fonts cannot draw.
49
+ *
50
+ * Fetched only once a line on the selected track holds CJK text, after `defaultFontUrl`. It draws only the
51
+ * glyphs `liberation sans` lacks, so a url that fails to load leaves those as boxes and changes nothing
52
+ * else. May be relative, as `defaultFontUrl`.
53
+ */
54
+ cjkFontUrl?: string
47
55
  onStreams?: (streams: SubtitleStream[]) => void
48
56
  }
49
57
 
@@ -63,6 +71,16 @@ const workerFetched = (url: string | undefined) =>
63
71
 
64
72
  const convertTimestamp = (ms: number) => new Date(ms).toISOString().slice(11, 22)
65
73
 
74
+ /**
75
+ * jassub's libass has no system font fallback (`ASS_FONTPROVIDER_NONE`): a glyph the style's face lacks
76
+ * is looked for in the default family and nowhere else, and `liberation sans` has no CJK at all. Releases
77
+ * set song lyrics in a Latin-only font and rely on the player's fallback, so without the CJK face a line
78
+ * of hiragana draws as a row of empty boxes. That face carries `liberation sans` as a second family name
79
+ * (scripts/cjk-font.py), and libass takes the first face of a family that has the glyph, so it is loaded
80
+ * after the default face and is never made the default itself.
81
+ */
82
+ const CJK_TEXT = /[\u3000-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef]/
83
+
66
84
  /**
67
85
  * How many styles libass keeps in front of the ones the file declares.
68
86
  *
@@ -153,6 +171,9 @@ export const createSubtitleRenderer = (options: SubtitleRendererOptions) => {
153
171
  const wasmUrl = workerFetched(options.wasmUrl)!
154
172
  const legacyWasmUrl = workerFetched(options.legacyWasmUrl)
155
173
  const defaultFontUrl = workerFetched(options.defaultFontUrl)
174
+ const cjkFontUrl = workerFetched(options.cjkFontUrl)
175
+ let cjkFontRequested = false
176
+ let defaultFontLoaded: Promise<unknown> = Promise.resolve()
156
177
  let jassub: JASSUB | undefined
157
178
  let attachments: [string, Uint8Array][] = []
158
179
  const headers = new Map<number, SubtitleHeaderPart>()
@@ -307,12 +328,22 @@ export const createSubtitleRenderer = (options: SubtitleRendererOptions) => {
307
328
  */
308
329
  if (defaultFontUrl) {
309
330
  onRenderer((renderer) => {
310
- void Promise.resolve(renderer.addFonts([defaultFontUrl])).then(repaint, rendererFailed)
331
+ defaultFontLoaded = Promise.resolve(renderer.addFonts([defaultFontUrl])).then(repaint, rendererFailed)
311
332
  })
312
333
  }
313
334
  repaint()
314
335
  }
315
336
 
337
+ const loadCjkFontFor = (events: ASSEvent[]) => {
338
+ if (!cjkFontUrl || cjkFontRequested || !events.some((event) => CJK_TEXT.test(event.Text))) return
339
+ cjkFontRequested = true
340
+ onRenderer(async (renderer) => {
341
+ await defaultFontLoaded
342
+ await renderer.addFonts([cjkFontUrl])
343
+ repaint()
344
+ })
345
+ }
346
+
316
347
  const pushAttachments = (incoming: Attachment[]) => {
317
348
  attachments = [...attachments, ...incoming.map((a) => [a.filename, new Uint8Array(a.data)] as [string, Uint8Array])]
318
349
  }
@@ -348,6 +379,7 @@ export const createSubtitleRenderer = (options: SubtitleRendererOptions) => {
348
379
  if (!incoming.length) return
349
380
  // one hop for the whole burst rather than one per event
350
381
  onRenderer((renderer) => Promise.all(incoming.map((event) => renderer.createEvent(event))))
382
+ loadCjkFontFor(incoming)
351
383
  repaint()
352
384
  }
353
385
 
@@ -365,6 +397,7 @@ export const createSubtitleRenderer = (options: SubtitleRendererOptions) => {
365
397
  }
366
398
  return Promise.all(calls)
367
399
  })
400
+ loadCjkFontFor(events)
368
401
  // outside the callback so that turning subtitles OFF while paused clears the picture too
369
402
  repaint()
370
403
  }
@@ -81,7 +81,7 @@ export const usePlayback = (
81
81
  // null, and the effect below returns before touching them in that case.
82
82
  const {
83
83
  read, size, publicPath = '', libavWorkerUrl = '', jassubWorkerUrl = '', jassubWasmUrl = '',
84
- jassubLegacyWasmUrl, defaultFontUrl, bufferSize, autoplay = false, chapters,
84
+ jassubLegacyWasmUrl, defaultFontUrl, cjkFontUrl, bufferSize, autoplay = false, chapters,
85
85
  seekPrepareBudgetMs = SEEK_PREPARE_BUDGET_MS,
86
86
  } = options ?? ({} as Partial<MediaPlayerLocalOptions>)
87
87
 
@@ -342,6 +342,7 @@ export const usePlayback = (
342
342
  jassubWasmUrl,
343
343
  jassubLegacyWasmUrl,
344
344
  defaultFontUrl,
345
+ cjkFontUrl,
345
346
  bufferSize,
346
347
  audioStreamIndex,
347
348
  onReady: () => {
@@ -402,6 +403,6 @@ export const usePlayback = (
402
403
  // times a second, and the restart loop reads as "Loading metadata" forever at a flat 0 B/s.
403
404
  }, [
404
405
  player, video, subtitles, size, publicPath, libavWorkerUrl, jassubWorkerUrl, jassubWasmUrl,
405
- jassubLegacyWasmUrl, defaultFontUrl, bufferSize, audioStreamIndex, autoplay, restartToken,
406
+ jassubLegacyWasmUrl, defaultFontUrl, cjkFontUrl, bufferSize, audioStreamIndex, autoplay, restartToken,
406
407
  ])
407
408
  }
@@ -148,6 +148,8 @@ export type MediaPlayerLocalOptions =
148
148
  jassubLegacyWasmUrl?: string
149
149
  /** Fallback face for `liberation sans`, used when a subtitle track names a font the file does not carry. */
150
150
  defaultFontUrl?: string
151
+ /** `@banou/media-player/noto-sans-jp.otf`, the face for CJK text, fetched once the selected track shows some. */
152
+ cjkFontUrl?: string
151
153
  bufferSize?: number
152
154
  /**
153
155
  * How long a seek waits for its own data before the playhead moves anyway, in ms. Default 500.