@banou/media-player 0.10.27 → 0.10.28
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/README.md +27 -1
- package/dist/engine/index.js +1 -1
- package/dist/engine/playback.d.ts +5 -0
- package/dist/{engine-AjFLuCdA.js → engine-DeEY2qao.js} +94 -92
- package/dist/index.js +745 -700
- package/dist/language/index.d.ts +25 -0
- package/dist/language/index.js +75 -0
- package/dist/react/video-player.d.ts +25 -0
- package/package.json +5 -1
- package/src/lib/engine/playback.ts +18 -6
- package/src/lib/language/index.ts +129 -0
- package/src/lib/react/hooks/use-playback.ts +50 -17
- package/src/lib/react/video-player.tsx +51 -6
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { DelegatedSelection } from '../react/media';
|
|
2
|
+
/** A track as far as its language goes: a tag (`jpn`, `en-US`) or a name (`Japanese`, `English (US)`), and its title. */
|
|
3
|
+
export type LanguageTrack = {
|
|
4
|
+
language?: string;
|
|
5
|
+
title?: string;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* What a track names its language by, to save as the viewer's preference: its tag, else its title, or undefined when
|
|
9
|
+
* neither names a language.
|
|
10
|
+
*/
|
|
11
|
+
export declare const languageOf: (track: LanguageTrack | undefined) => string | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* The index of the track to play for a preferred language (a tag or a name, as `languageOf` gives it), else of the
|
|
14
|
+
* track titled exactly as the preference, or -1 when there is neither. A full track wins over a signs, songs, forced
|
|
15
|
+
* or commentary one, then the track named exactly as the preference, then the one in the same region or script, then
|
|
16
|
+
* the first.
|
|
17
|
+
*/
|
|
18
|
+
export declare const preferredTrack: (preference: string, tracks: readonly LanguageTrack[]) => number;
|
|
19
|
+
/**
|
|
20
|
+
* For a media the player does not own, whose host applies the viewer's preference itself: the option of `selection`
|
|
21
|
+
* to select for `preference` (as `onPreferredAudioLanguageChange` or `onPreferredSubtitleLanguageChange` reported
|
|
22
|
+
* it), null for the row that turns the feature off, or undefined to leave the selection as it is: no preference,
|
|
23
|
+
* nothing in that language, or already selected. Options are matched by their labels; disabled ones are skipped.
|
|
24
|
+
*/
|
|
25
|
+
export declare const preferredSelection: (selection: Omit<DelegatedSelection, 'select'>, preference: string | null | undefined) => string | null | undefined;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
//#region src/lib/language/index.ts
|
|
2
|
+
var e = "aa ab ae af ak am an ar as av ay az ba be bg bi bm bn bo br bs ca ce ch co cr cs cu cv cy da de dv dz ee el en eo es et eu fa ff fi fj fo fr fy ga gd gl gn gu gv ha he hi ho hr ht hu hy hz ia id ie ig ii ik io is it iu ja jv ka kg ki kj kk kl km kn ko kr ks ku kv kw ky la lb lg li ln lo lt lu lv mg mh mi mk ml mn mr ms mt my na nb nd ne ng nl nn no nr nv ny oc oj om or os pa pi pl ps pt qu rm rn ro ru rw sa sc sd se sg si sk sl sm sn so sq sr ss st su sv sw ta te tg th ti tk tn to tr ts tt tw ty ug uk ur uz ve vi vo wa wo xh yi yo za zh zu fil yue".split(" "), t = [
|
|
3
|
+
"en-US",
|
|
4
|
+
"en-GB",
|
|
5
|
+
"es-419",
|
|
6
|
+
"es-ES",
|
|
7
|
+
"fr-CA",
|
|
8
|
+
"pt-BR",
|
|
9
|
+
"pt-PT",
|
|
10
|
+
"zh-Hans",
|
|
11
|
+
"zh-Hant"
|
|
12
|
+
], n = /* @__PURE__ */ new Set([
|
|
13
|
+
"und",
|
|
14
|
+
"zxx",
|
|
15
|
+
"mul",
|
|
16
|
+
"mis"
|
|
17
|
+
]), r = /sign|song|forced|commentary|karaoke|descri/i, i = /full|dialog/i, a = (e) => e.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim(), o = new Intl.DisplayNames(["en"], {
|
|
18
|
+
type: "language",
|
|
19
|
+
fallback: "none"
|
|
20
|
+
}), s = (e) => {
|
|
21
|
+
if (/^[a-z]{2,3}(?:[-_][a-z\d]{2,8})*$/i.test(e)) try {
|
|
22
|
+
let t = new Intl.Locale(e.replace(/_/g, "-"));
|
|
23
|
+
return n.has(t.language) || !o.of(t.language) ? void 0 : {
|
|
24
|
+
language: t.language,
|
|
25
|
+
variant: t.region ?? t.script
|
|
26
|
+
};
|
|
27
|
+
} catch {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
}, c, l = () => {
|
|
31
|
+
if (c) return c;
|
|
32
|
+
let n = /* @__PURE__ */ new Map(), r = [...new Set(["en", globalThis.navigator?.language].filter((e) => !!e))], i = (e, t, r) => {
|
|
33
|
+
try {
|
|
34
|
+
let i = new Intl.DisplayNames([t], {
|
|
35
|
+
type: "language",
|
|
36
|
+
languageDisplay: r,
|
|
37
|
+
fallback: "none"
|
|
38
|
+
}).of(e);
|
|
39
|
+
i && !n.has(a(i)) && n.set(a(i), e);
|
|
40
|
+
} catch {}
|
|
41
|
+
};
|
|
42
|
+
for (let e of t) for (let t of [...r, e]) for (let n of ["dialect", "standard"]) i(e, t, n);
|
|
43
|
+
for (let t of e) for (let e of [...r, t]) i(t, e, "dialect");
|
|
44
|
+
return c = n;
|
|
45
|
+
}, u = (e) => {
|
|
46
|
+
let t = e?.trim();
|
|
47
|
+
if (!t) return;
|
|
48
|
+
let n = l(), r = n.get(a(t));
|
|
49
|
+
if (r) return s(r);
|
|
50
|
+
let [, i, o] = /^([^([]+)(?:\(([^)]*)\))?/.exec(t.normalize("NFKC")) ?? [], c = i ? n.get(a(i)) : void 0;
|
|
51
|
+
if (!c) return;
|
|
52
|
+
let u = o?.trim();
|
|
53
|
+
return (u && /^(?:[A-Z]{2}|\d{3})$/.test(u) ? s(`${c}-${u}`) : void 0) ?? s(c);
|
|
54
|
+
}, d = (e) => {
|
|
55
|
+
let t = e?.trim();
|
|
56
|
+
return t ? s(t) ?? u(t) : void 0;
|
|
57
|
+
}, f = (e) => d(e?.language) ? e.language.trim() : u(e?.title) ? e.title.trim() : void 0, p = ({ language: e = "", title: t = "" }) => {
|
|
58
|
+
let n = `${e} ${t}`;
|
|
59
|
+
return r.test(n) && !i.test(n);
|
|
60
|
+
}, m = (e, t) => {
|
|
61
|
+
let n = d(e), r = -1, i = 0;
|
|
62
|
+
return n && t.forEach((t, o) => {
|
|
63
|
+
let s = d(t.language) ?? u(t.title);
|
|
64
|
+
if (s?.language !== n.language) return;
|
|
65
|
+
let c = f(t), l = 1 + +(s.variant === n.variant) + (c && a(c) === a(e) ? 2 : 0) + (p(t) ? 0 : 4);
|
|
66
|
+
l > i && (r = o, i = l);
|
|
67
|
+
}), r === -1 ? t.findIndex(({ title: t }) => !!t?.trim() && a(t) === a(e)) : r;
|
|
68
|
+
}, h = (e, t) => {
|
|
69
|
+
if (t === void 0) return;
|
|
70
|
+
if (t === null) return e.offLabel && e.selectedId !== null ? null : void 0;
|
|
71
|
+
let n = e.options.filter((e) => !e.disabled), r = n[m(t, n.map(({ label: e }) => ({ title: e })))]?.id;
|
|
72
|
+
return r !== void 0 && r !== e.selectedId ? r : void 0;
|
|
73
|
+
};
|
|
74
|
+
//#endregion
|
|
75
|
+
export { f as languageOf, h as preferredSelection, m as preferredTrack };
|
|
@@ -106,6 +106,19 @@ type CommonOptions = {
|
|
|
106
106
|
*/
|
|
107
107
|
onSeek?: (fraction: number) => void;
|
|
108
108
|
onPlaybackError?: (error: unknown) => void;
|
|
109
|
+
/**
|
|
110
|
+
* The viewer picked an audio track in the settings menu, named by its language as the file or the source names it:
|
|
111
|
+
* its tag (`jpn`, `en-US`), else its title or label (`Japanese`). What an app saves to pass back as
|
|
112
|
+
* `preferredAudioLanguage`; the player saves nothing. A track that names no language reports nothing, and on a media
|
|
113
|
+
* the player does not own the report waits for the source's switch to succeed.
|
|
114
|
+
*/
|
|
115
|
+
onPreferredAudioLanguageChange?: (language: string) => void;
|
|
116
|
+
/**
|
|
117
|
+
* As `onPreferredAudioLanguageChange`, for the subtitles menu, with null for subtitles turned off. A track that names
|
|
118
|
+
* no language reports only when it turns subtitles on, by its title or label (else `und`), so the next media starts
|
|
119
|
+
* with them on too.
|
|
120
|
+
*/
|
|
121
|
+
onPreferredSubtitleLanguageChange?: (language: string | null) => void;
|
|
109
122
|
};
|
|
110
123
|
/**
|
|
111
124
|
* Bytes in: the player owns the `<video>`, and libav feeds it a fragment at a time.
|
|
@@ -181,6 +194,18 @@ export type MediaPlayerLocalOptions = CommonOptions & MediaPlayerSource & {
|
|
|
181
194
|
normalizeVolume?: boolean;
|
|
182
195
|
/** The viewer flipped the switch, to `normalizeVolume`: what an app saves to pass back as `normalizeVolume`. */
|
|
183
196
|
onNormalizeVolumeChange?: (normalizeVolume: boolean) => void;
|
|
197
|
+
/**
|
|
198
|
+
* The language a file starts its audio in, as `onPreferredAudioLanguageChange` reported it or as any tag or name
|
|
199
|
+
* (`ja`, `jpn`, `Japanese`). Its full track wins over a commentary, and a file with none plays its default. A
|
|
200
|
+
* track the viewer picks wins for that file. Read when a file starts, so a change applies from the next one.
|
|
201
|
+
*/
|
|
202
|
+
preferredAudioLanguage?: string;
|
|
203
|
+
/**
|
|
204
|
+
* As `preferredAudioLanguage`, for subtitles, where signs and songs or forced tracks count as partial and a file
|
|
205
|
+
* with none starts on its first track. null starts every file with subtitles off, and a preference that names no
|
|
206
|
+
* language starts on the track titled as it is.
|
|
207
|
+
*/
|
|
208
|
+
preferredSubtitleLanguage?: string | null;
|
|
184
209
|
};
|
|
185
210
|
/**
|
|
186
211
|
* A media the caller owns and the player only drives.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@banou/media-player",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.28",
|
|
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",
|
|
@@ -18,6 +18,10 @@
|
|
|
18
18
|
"types": "./dist/remote/index.d.ts",
|
|
19
19
|
"import": "./dist/remote/index.js"
|
|
20
20
|
},
|
|
21
|
+
"./language": {
|
|
22
|
+
"types": "./dist/language/index.d.ts",
|
|
23
|
+
"import": "./dist/language/index.js"
|
|
24
|
+
},
|
|
21
25
|
"./volume-normalizer-worklet.js": "./dist/volume-normalizer-worklet.js",
|
|
22
26
|
"./noto-sans-jp.otf": "./src/lib/assets/noto-sans-jp.otf",
|
|
23
27
|
"./package.json": "./package.json"
|
|
@@ -58,6 +58,11 @@ export type PlaybackOptions = {
|
|
|
58
58
|
cjkFontUrl?: string
|
|
59
59
|
bufferSize?: number
|
|
60
60
|
audioStreamIndex?: number
|
|
61
|
+
/**
|
|
62
|
+
* Picks the audio stream from the file's own when `audioStreamIndex` names none, undefined for the default. A pick
|
|
63
|
+
* other than the default makes the remuxer again before anything plays, since libav fixes its stream when it is made.
|
|
64
|
+
*/
|
|
65
|
+
chooseAudioStream?: (streams: AudioStream[]) => number | undefined
|
|
61
66
|
onReady?: () => void
|
|
62
67
|
onError?: (error: unknown) => void
|
|
63
68
|
onRecovered?: () => void
|
|
@@ -159,19 +164,20 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
|
|
|
159
164
|
const {
|
|
160
165
|
videoElement, subtitleContainer, read, length, publicPath, libavWorkerUrl,
|
|
161
166
|
jassubWorkerUrl, jassubWasmUrl, jassubLegacyWasmUrl, defaultFontUrl, cjkFontUrl, bufferSize = DEFAULT_BUFFER_SIZE,
|
|
162
|
-
audioStreamIndex, onReady, onError, onRecovered, onSeek, onSubtitleStreams,
|
|
167
|
+
audioStreamIndex, chooseAudioStream, onReady, onError, onRecovered, onSeek, onSubtitleStreams,
|
|
163
168
|
onAudioStreams, onOutput,
|
|
164
169
|
} = options
|
|
165
170
|
|
|
166
|
-
const
|
|
171
|
+
const make = (streamIndex: number | undefined) => makeRemuxer({
|
|
167
172
|
publicPath,
|
|
168
173
|
workerUrl: libavWorkerUrl,
|
|
169
174
|
workerOptions: { type: 'module' },
|
|
170
175
|
bufferSize,
|
|
171
176
|
length,
|
|
172
|
-
audioStreamIndex,
|
|
177
|
+
audioStreamIndex: streamIndex,
|
|
173
178
|
read,
|
|
174
179
|
})
|
|
180
|
+
let remuxer = await make(audioStreamIndex)
|
|
175
181
|
|
|
176
182
|
const teardown: (() => void)[] = []
|
|
177
183
|
let destroyed = false
|
|
@@ -185,11 +191,17 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
|
|
|
185
191
|
teardown.push(() => terminateRemuxer(remuxer))
|
|
186
192
|
|
|
187
193
|
try {
|
|
188
|
-
|
|
194
|
+
let metadata = await remuxer.init()
|
|
195
|
+
const chosen = audioStreamIndex ?? chooseAudioStream?.(metadata.audioStreams ?? [])
|
|
196
|
+
if (audioStreamIndex === undefined && chosen !== undefined && chosen !== metadata.audioStreams?.[0]?.streamIndex) {
|
|
197
|
+
terminateRemuxer(remuxer)
|
|
198
|
+
remuxer = await make(chosen)
|
|
199
|
+
metadata = await remuxer.init()
|
|
200
|
+
}
|
|
189
201
|
|
|
190
202
|
const audioStreams = metadata.audioStreams ?? []
|
|
191
|
-
const selectedAudio = audioStreams.some((s) => s.streamIndex ===
|
|
192
|
-
?
|
|
203
|
+
const selectedAudio = audioStreams.some((s) => s.streamIndex === chosen)
|
|
204
|
+
? chosen!
|
|
193
205
|
: audioStreams[0]?.streamIndex ?? -1
|
|
194
206
|
onAudioStreams?.(audioStreams, selectedAudio)
|
|
195
207
|
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import type { DelegatedSelection } from '../react/media'
|
|
2
|
+
|
|
3
|
+
/** A track as far as its language goes: a tag (`jpn`, `en-US`) or a name (`Japanese`, `English (US)`), and its title. */
|
|
4
|
+
export type LanguageTrack = { language?: string, title?: string }
|
|
5
|
+
|
|
6
|
+
type Language = { language: string, variant?: string }
|
|
7
|
+
|
|
8
|
+
// ISO 639-1, Filipino and Cantonese, then the regional and script forms a label names in words
|
|
9
|
+
const CODES = (
|
|
10
|
+
'aa ab ae af ak am an ar as av ay az ba be bg bi bm bn bo br bs ca ce ch co cr cs cu cv cy da de dv dz ee el en eo es '
|
|
11
|
+
+ 'et eu fa ff fi fj fo fr fy ga gd gl gn gu gv ha he hi ho hr ht hu hy hz ia id ie ig ii ik io is it iu ja jv ka kg '
|
|
12
|
+
+ 'ki kj kk kl km kn ko kr ks ku kv kw ky la lb lg li ln lo lt lu lv mg mh mi mk ml mn mr ms mt my na nb nd ne ng nl nn '
|
|
13
|
+
+ 'no nr nv ny oc oj om or os pa pi pl ps pt qu rm rn ro ru rw sa sc sd se sg si sk sl sm sn so sq sr ss st su sv sw ta '
|
|
14
|
+
+ 'te tg th ti tk tn to tr ts tt tw ty ug uk ur uz ve vi vo wa wo xh yi yo za zh zu fil yue'
|
|
15
|
+
).split(' ')
|
|
16
|
+
const FORMS = ['en-US', 'en-GB', 'es-419', 'es-ES', 'fr-CA', 'pt-BR', 'pt-PT', 'zh-Hans', 'zh-Hant']
|
|
17
|
+
// tags Intl has a name for that are no language a track is spoken or written in
|
|
18
|
+
const NOT_LANGUAGES = new Set(['und', 'zxx', 'mul', 'mis'])
|
|
19
|
+
|
|
20
|
+
// sign and song tracks, forced subtitles, commentaries and described audio, unless the title says it is the full track
|
|
21
|
+
const PARTIAL = /sign|song|forced|commentary|karaoke|descri/i
|
|
22
|
+
const FULL = /full|dialog/i
|
|
23
|
+
|
|
24
|
+
const key = (text: string) => text.normalize('NFKC').toLowerCase().replace(/\s+/g, ' ').trim()
|
|
25
|
+
|
|
26
|
+
const english = new Intl.DisplayNames(['en'], { type: 'language', fallback: 'none' })
|
|
27
|
+
|
|
28
|
+
const fromTag = (tag: string): Language | undefined => {
|
|
29
|
+
if (!/^[a-z]{2,3}(?:[-_][a-z\d]{2,8})*$/i.test(tag)) return undefined
|
|
30
|
+
try {
|
|
31
|
+
const locale = new Intl.Locale(tag.replace(/_/g, '-'))
|
|
32
|
+
if (NOT_LANGUAGES.has(locale.language) || !english.of(locale.language)) return undefined
|
|
33
|
+
return { language: locale.language, variant: locale.region ?? locale.script }
|
|
34
|
+
} catch {
|
|
35
|
+
return undefined
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let names: Map<string, string> | undefined
|
|
40
|
+
// built once, on the first name read: a few hundred lookups, in English, in the page's language and in each language itself
|
|
41
|
+
const nameIndex = () => {
|
|
42
|
+
if (names) return names
|
|
43
|
+
const index = new Map<string, string>()
|
|
44
|
+
const locales = [...new Set(['en', globalThis.navigator?.language].filter((locale): locale is string => !!locale))]
|
|
45
|
+
const add = (tag: string, locale: string, languageDisplay: 'dialect' | 'standard') => {
|
|
46
|
+
try {
|
|
47
|
+
const name = new Intl.DisplayNames([locale], { type: 'language', languageDisplay, fallback: 'none' }).of(tag)
|
|
48
|
+
if (name && !index.has(key(name))) index.set(key(name), tag)
|
|
49
|
+
} catch {}
|
|
50
|
+
}
|
|
51
|
+
for (const tag of FORMS) for (const locale of [...locales, tag]) for (const display of ['dialect', 'standard'] as const) add(tag, locale, display)
|
|
52
|
+
for (const tag of CODES) for (const locale of [...locales, tag]) add(tag, locale, 'dialect')
|
|
53
|
+
return names = index
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// a title or a label is read by name only: as a tag, 'SDH' would be Southern Kurdish and 'UK' Ukrainian
|
|
57
|
+
const parseName = (text: string | undefined): Language | undefined => {
|
|
58
|
+
const trimmed = text?.trim()
|
|
59
|
+
if (!trimmed) return undefined
|
|
60
|
+
const index = nameIndex()
|
|
61
|
+
const whole = index.get(key(trimmed))
|
|
62
|
+
if (whole) return fromTag(whole)
|
|
63
|
+
const [, base, qualifier] = /^([^([]+)(?:\(([^)]*)\))?/.exec(trimmed.normalize('NFKC')) ?? []
|
|
64
|
+
const named = base ? index.get(key(base)) : undefined
|
|
65
|
+
if (!named) return undefined
|
|
66
|
+
const region = qualifier?.trim()
|
|
67
|
+
// through Intl.Locale, which reads the 'UK' of 'English (UK)' as GB
|
|
68
|
+
return (region && /^(?:[A-Z]{2}|\d{3})$/.test(region) ? fromTag(`${named}-${region}`) : undefined) ?? fromTag(named)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const parseLanguage = (text: string | undefined) => {
|
|
72
|
+
const trimmed = text?.trim()
|
|
73
|
+
return trimmed ? fromTag(trimmed) ?? parseName(trimmed) : undefined
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* What a track names its language by, to save as the viewer's preference: its tag, else its title, or undefined when
|
|
78
|
+
* neither names a language.
|
|
79
|
+
*/
|
|
80
|
+
export const languageOf = (track: LanguageTrack | undefined): string | undefined =>
|
|
81
|
+
parseLanguage(track?.language) ? track!.language!.trim() : parseName(track?.title) ? track!.title!.trim() : undefined
|
|
82
|
+
|
|
83
|
+
const isPartial = ({ language = '', title = '' }: LanguageTrack) => {
|
|
84
|
+
const text = `${language} ${title}`
|
|
85
|
+
return PARTIAL.test(text) && !FULL.test(text)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The index of the track to play for a preferred language (a tag or a name, as `languageOf` gives it), else of the
|
|
90
|
+
* track titled exactly as the preference, or -1 when there is neither. A full track wins over a signs, songs, forced
|
|
91
|
+
* or commentary one, then the track named exactly as the preference, then the one in the same region or script, then
|
|
92
|
+
* the first.
|
|
93
|
+
*/
|
|
94
|
+
export const preferredTrack = (preference: string, tracks: readonly LanguageTrack[]): number => {
|
|
95
|
+
const wanted = parseLanguage(preference)
|
|
96
|
+
let best = -1
|
|
97
|
+
let bestScore = 0
|
|
98
|
+
if (wanted) tracks.forEach((track, index) => {
|
|
99
|
+
const found = parseLanguage(track.language) ?? parseName(track.title)
|
|
100
|
+
if (found?.language !== wanted.language) return
|
|
101
|
+
const named = languageOf(track)
|
|
102
|
+
const score = 1
|
|
103
|
+
+ (found.variant === wanted.variant ? 1 : 0)
|
|
104
|
+
+ (named && key(named) === key(preference) ? 2 : 0)
|
|
105
|
+
+ (isPartial(track) ? 0 : 4)
|
|
106
|
+
if (score > bestScore) {
|
|
107
|
+
best = index
|
|
108
|
+
bestScore = score
|
|
109
|
+
}
|
|
110
|
+
})
|
|
111
|
+
return best !== -1 ? best : tracks.findIndex(({ title }) => !!title?.trim() && key(title) === key(preference))
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* For a media the player does not own, whose host applies the viewer's preference itself: the option of `selection`
|
|
116
|
+
* to select for `preference` (as `onPreferredAudioLanguageChange` or `onPreferredSubtitleLanguageChange` reported
|
|
117
|
+
* it), null for the row that turns the feature off, or undefined to leave the selection as it is: no preference,
|
|
118
|
+
* nothing in that language, or already selected. Options are matched by their labels; disabled ones are skipped.
|
|
119
|
+
*/
|
|
120
|
+
export const preferredSelection = (
|
|
121
|
+
selection: Omit<DelegatedSelection, 'select'>,
|
|
122
|
+
preference: string | null | undefined,
|
|
123
|
+
): string | null | undefined => {
|
|
124
|
+
if (preference === undefined) return undefined
|
|
125
|
+
if (preference === null) return selection.offLabel && selection.selectedId !== null ? null : undefined
|
|
126
|
+
const options = selection.options.filter((option) => !option.disabled)
|
|
127
|
+
const id = options[preferredTrack(preference, options.map(({ label }) => ({ title: label })))]?.id
|
|
128
|
+
return id !== undefined && id !== selection.selectedId ? id : undefined
|
|
129
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { PlaybackController, PlaybackOutput } from '../../engine'
|
|
1
|
+
import type { AudioStream, PlaybackController, PlaybackOutput, SubtitleStream } from '../../engine'
|
|
2
2
|
import type { PlaybackErrorEntry } from '../source-feature'
|
|
3
3
|
import type { MediaPlayerLocalOptions } from '../video-player'
|
|
4
4
|
|
|
@@ -7,6 +7,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'
|
|
|
7
7
|
import { isMediaElementError, startPlayback } from '../../engine'
|
|
8
8
|
import { usePlayer } from '../player'
|
|
9
9
|
import { toNamedTracks } from '../../utils/track-label'
|
|
10
|
+
import { languageOf, preferredTrack } from '../../language'
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* A wedged element is rebuilt, however many times it takes.
|
|
@@ -40,6 +41,13 @@ const SEEK_PREPARE_BUDGET_MS = 500
|
|
|
40
41
|
*/
|
|
41
42
|
const SEEK_DISPLAY_LIMIT_MS = 15_000
|
|
42
43
|
|
|
44
|
+
/** The subtitle stream a media starts on: the first in the preferred language, else the first; none when it is off. */
|
|
45
|
+
const preferredSubtitle = (preference: string | null | undefined, subtitles: SubtitleStream[]) => {
|
|
46
|
+
if (preference === null) return undefined
|
|
47
|
+
const index = preference === undefined ? 0 : preferredTrack(preference, subtitles)
|
|
48
|
+
return subtitles[Math.max(index, 0)]?.streamIndex
|
|
49
|
+
}
|
|
50
|
+
|
|
43
51
|
const messageOf = (error: unknown) =>
|
|
44
52
|
error instanceof Error ? error.message : String(error)
|
|
45
53
|
|
|
@@ -95,9 +103,10 @@ export const usePlayback = (
|
|
|
95
103
|
const chaptersRef = useRef(chapters)
|
|
96
104
|
chaptersRef.current = chapters
|
|
97
105
|
|
|
98
|
-
// The track the viewer picked, which is what a restart is keyed on. Distinct from the store's
|
|
99
|
-
// `
|
|
100
|
-
const [
|
|
106
|
+
// The track the viewer picked for this media, which is what a restart is keyed on. Distinct from the store's
|
|
107
|
+
// `selectedAudioTrack`, which is whatever is playing right now.
|
|
108
|
+
const [audioChoice, setAudioChoice] = useState<{ size: number, streamIndex: number }>()
|
|
109
|
+
const audioStreamIndex = audioChoice && audioChoice.size === size ? audioChoice.streamIndex : undefined
|
|
101
110
|
|
|
102
111
|
/**
|
|
103
112
|
* Bumped to rebuild the pipeline after the media element itself has failed.
|
|
@@ -138,12 +147,22 @@ export const usePlayback = (
|
|
|
138
147
|
* deliberately not, since a streaming consumer passes a fresh closure several times a second.
|
|
139
148
|
*/
|
|
140
149
|
const resumeRef = useRef<{ time: number, size: number } | null>(null)
|
|
141
|
-
// The
|
|
142
|
-
|
|
143
|
-
const
|
|
150
|
+
// The size of the media the viewer picked subtitles for: until then each pipeline starts on the preferred track.
|
|
151
|
+
const subtitleChoiceFor = useRef<number>(undefined)
|
|
152
|
+
const sizeRef = useRef(size)
|
|
153
|
+
sizeRef.current = size
|
|
154
|
+
const streams = useRef<{ audio: AudioStream[], subtitles: SubtitleStream[] }>({ audio: [], subtitles: [] })
|
|
144
155
|
|
|
145
156
|
const readRef = useRef(read)
|
|
146
157
|
readRef.current = read
|
|
158
|
+
const preferredAudioRef = useRef(options?.preferredAudioLanguage)
|
|
159
|
+
preferredAudioRef.current = options?.preferredAudioLanguage
|
|
160
|
+
const preferredSubtitleRef = useRef(options?.preferredSubtitleLanguage)
|
|
161
|
+
preferredSubtitleRef.current = options?.preferredSubtitleLanguage
|
|
162
|
+
const onAudioLanguageRef = useRef(options?.onPreferredAudioLanguageChange)
|
|
163
|
+
onAudioLanguageRef.current = options?.onPreferredAudioLanguageChange
|
|
164
|
+
const onSubtitleLanguageRef = useRef(options?.onPreferredSubtitleLanguageChange)
|
|
165
|
+
onSubtitleLanguageRef.current = options?.onPreferredSubtitleLanguageChange
|
|
147
166
|
const onSeekRef = useRef(options?.onSeek)
|
|
148
167
|
onSeekRef.current = options?.onSeek
|
|
149
168
|
const onPlaybackErrorRef = useRef(options?.onPlaybackError)
|
|
@@ -155,9 +174,15 @@ export const usePlayback = (
|
|
|
155
174
|
// that comes back is one of its own stream indices.
|
|
156
175
|
const selectSubtitleTrack = useCallback((id: string | number | undefined) => {
|
|
157
176
|
const streamIndex = typeof id === 'number' ? id : undefined
|
|
158
|
-
|
|
177
|
+
const wasOff = player.selectedSubtitleTrack === undefined
|
|
178
|
+
subtitleChoiceFor.current = sizeRef.current
|
|
159
179
|
player.setSourceState({ selectedSubtitleTrack: streamIndex })
|
|
160
180
|
controllerRef.current?.selectSubtitleStream(streamIndex)
|
|
181
|
+
const stream = streams.current.subtitles.find((subtitle) => subtitle.streamIndex === streamIndex)
|
|
182
|
+
const language = streamIndex === undefined
|
|
183
|
+
? null
|
|
184
|
+
: languageOf(stream) ?? (wasOff ? stream?.title?.trim() || 'und' : undefined)
|
|
185
|
+
if (language !== undefined) onSubtitleLanguageRef.current?.(language)
|
|
161
186
|
}, [player])
|
|
162
187
|
|
|
163
188
|
/**
|
|
@@ -252,9 +277,11 @@ export const usePlayback = (
|
|
|
252
277
|
}, [player, seekPrepareBudgetMs])
|
|
253
278
|
|
|
254
279
|
const selectAudioTrack = useCallback((id: string | number) => {
|
|
255
|
-
if (typeof id !== 'number') return
|
|
280
|
+
if (typeof id !== 'number' || sizeRef.current === undefined) return
|
|
256
281
|
player.setSourceState({ selectedAudioTrack: id })
|
|
257
|
-
|
|
282
|
+
setAudioChoice({ size: sizeRef.current, streamIndex: id })
|
|
283
|
+
const language = languageOf(streams.current.audio.find((stream) => stream.streamIndex === id))
|
|
284
|
+
if (language !== undefined) onAudioLanguageRef.current?.(language)
|
|
258
285
|
}, [player])
|
|
259
286
|
|
|
260
287
|
// Subscribed rather than read off the store, because it is a no-op until the media element
|
|
@@ -345,6 +372,10 @@ export const usePlayback = (
|
|
|
345
372
|
cjkFontUrl,
|
|
346
373
|
bufferSize,
|
|
347
374
|
audioStreamIndex,
|
|
375
|
+
chooseAudioStream: (audio) => {
|
|
376
|
+
const preference = preferredAudioRef.current
|
|
377
|
+
return preference === undefined ? undefined : audio[preferredTrack(preference, audio)]?.streamIndex
|
|
378
|
+
},
|
|
348
379
|
onReady: () => {
|
|
349
380
|
if (cancelled) return
|
|
350
381
|
player.setSourceState({ ready: true })
|
|
@@ -360,16 +391,18 @@ export const usePlayback = (
|
|
|
360
391
|
onRecovered: () => { if (!cancelled) player.setSourceState({ playbackError: null }) },
|
|
361
392
|
onSeek: (fraction) => onSeekRef.current?.(fraction),
|
|
362
393
|
onOutput: (output) => onOutputRef.current?.(output),
|
|
363
|
-
onSubtitleStreams: (
|
|
394
|
+
onSubtitleStreams: (subtitles) => {
|
|
364
395
|
if (cancelled) return
|
|
396
|
+
streams.current.subtitles = subtitles
|
|
365
397
|
player.setSourceState({
|
|
366
|
-
subtitleTracks: toNamedTracks(
|
|
367
|
-
...
|
|
398
|
+
subtitleTracks: toNamedTracks(subtitles),
|
|
399
|
+
...subtitleChoiceFor.current === size ? {} : { selectedSubtitleTrack: preferredSubtitle(preferredSubtitleRef.current, subtitles) },
|
|
368
400
|
})
|
|
369
401
|
},
|
|
370
|
-
onAudioStreams: (
|
|
402
|
+
onAudioStreams: (audio, selected) => {
|
|
371
403
|
if (cancelled) return
|
|
372
|
-
|
|
404
|
+
streams.current.audio = audio
|
|
405
|
+
player.setSourceState({ audioTracks: toNamedTracks(audio), selectedAudioTrack: selected })
|
|
373
406
|
},
|
|
374
407
|
})
|
|
375
408
|
if (cancelled) {
|
|
@@ -383,9 +416,9 @@ export const usePlayback = (
|
|
|
383
416
|
indexes: controller.indexes,
|
|
384
417
|
chapters: chaptersRef.current ?? controller.chapters,
|
|
385
418
|
})
|
|
386
|
-
//
|
|
419
|
+
// the renderer starts on the first track, so the one the store holds (off included) is applied to it
|
|
387
420
|
const chosen = player.selectedSubtitleTrack
|
|
388
|
-
|
|
421
|
+
controller.selectSubtitleStream(typeof chosen === 'number' ? chosen : undefined)
|
|
389
422
|
} catch (error) {
|
|
390
423
|
fail(error)
|
|
391
424
|
}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import type { ReactNode } from 'react'
|
|
3
3
|
import type { MediaChapter } from '../engine'
|
|
4
4
|
import type { DownloadedRange, VolumeNormalizerControl } from './source-feature'
|
|
5
|
-
import type { DelegatedTracks, ExternalThumbnails, PassThroughPictureInPicture, PlayerMedia } from './media'
|
|
5
|
+
import type { DelegatedSelection, DelegatedTracks, ExternalThumbnails, PassThroughPictureInPicture, PlayerMedia } from './media'
|
|
6
6
|
import type { ExposePlayerOptions } from '../remote'
|
|
7
7
|
|
|
8
8
|
import { useEffect, useMemo, useRef, useState } from 'react'
|
|
@@ -18,6 +18,7 @@ import { usePassThroughPictureInPicture } from './hooks/use-pass-through-picture
|
|
|
18
18
|
import { useVolumeNormalizer } from './hooks/use-volume-normalizer'
|
|
19
19
|
import { createPlaybackTap } from '../audio/playback-tap'
|
|
20
20
|
import Chrome from './components/chrome'
|
|
21
|
+
import { languageOf } from '../language'
|
|
21
22
|
|
|
22
23
|
/**
|
|
23
24
|
* The source, read a range at a time: the player never downloads the whole file. Both fields travel
|
|
@@ -122,6 +123,20 @@ type CommonOptions = {
|
|
|
122
123
|
*/
|
|
123
124
|
onSeek?: (fraction: number) => void
|
|
124
125
|
onPlaybackError?: (error: unknown) => void
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The viewer picked an audio track in the settings menu, named by its language as the file or the source names it:
|
|
129
|
+
* its tag (`jpn`, `en-US`), else its title or label (`Japanese`). What an app saves to pass back as
|
|
130
|
+
* `preferredAudioLanguage`; the player saves nothing. A track that names no language reports nothing, and on a media
|
|
131
|
+
* the player does not own the report waits for the source's switch to succeed.
|
|
132
|
+
*/
|
|
133
|
+
onPreferredAudioLanguageChange?: (language: string) => void
|
|
134
|
+
/**
|
|
135
|
+
* As `onPreferredAudioLanguageChange`, for the subtitles menu, with null for subtitles turned off. A track that names
|
|
136
|
+
* no language reports only when it turns subtitles on, by its title or label (else `und`), so the next media starts
|
|
137
|
+
* with them on too.
|
|
138
|
+
*/
|
|
139
|
+
onPreferredSubtitleLanguageChange?: (language: string | null) => void
|
|
125
140
|
}
|
|
126
141
|
|
|
127
142
|
/**
|
|
@@ -204,6 +219,19 @@ export type MediaPlayerLocalOptions =
|
|
|
204
219
|
normalizeVolume?: boolean
|
|
205
220
|
/** The viewer flipped the switch, to `normalizeVolume`: what an app saves to pass back as `normalizeVolume`. */
|
|
206
221
|
onNormalizeVolumeChange?: (normalizeVolume: boolean) => void
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* The language a file starts its audio in, as `onPreferredAudioLanguageChange` reported it or as any tag or name
|
|
225
|
+
* (`ja`, `jpn`, `Japanese`). Its full track wins over a commentary, and a file with none plays its default. A
|
|
226
|
+
* track the viewer picks wins for that file. Read when a file starts, so a change applies from the next one.
|
|
227
|
+
*/
|
|
228
|
+
preferredAudioLanguage?: string
|
|
229
|
+
/**
|
|
230
|
+
* As `preferredAudioLanguage`, for subtitles, where signs and songs or forced tracks count as partial and a file
|
|
231
|
+
* with none starts on its first track. null starts every file with subtitles off, and a preference that names no
|
|
232
|
+
* language starts on the track titled as it is.
|
|
233
|
+
*/
|
|
234
|
+
preferredSubtitleLanguage?: string | null
|
|
207
235
|
}
|
|
208
236
|
|
|
209
237
|
/**
|
|
@@ -259,6 +287,11 @@ export type MediaPlayerRemoteOptions =
|
|
|
259
287
|
|
|
260
288
|
export type MediaPlayerOptions = MediaPlayerLocalOptions | MediaPlayerRemoteOptions
|
|
261
289
|
|
|
290
|
+
// a label is read as a name, never as a tag
|
|
291
|
+
const trackOf = (selection: DelegatedSelection, id: string) => ({ title: selection.options.find((option) => option.id === id)?.label })
|
|
292
|
+
|
|
293
|
+
const afterSwitch = (result: void | Promise<void>, then: () => void) => result instanceof Promise ? result.then(then) : then()
|
|
294
|
+
|
|
262
295
|
const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, children?: ReactNode }) => {
|
|
263
296
|
// Narrowed on the field that carries the difference: a remote arm brings its own media and, by
|
|
264
297
|
// construction, no bytes. Both halves stay null-safe so the engine hooks below can be called
|
|
@@ -434,15 +467,24 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
|
|
|
434
467
|
// the document, and it renders the result itself.
|
|
435
468
|
const subtitles = remote?.subtitles?.selection
|
|
436
469
|
const audio = remote?.audioTracks?.selection
|
|
437
|
-
// `select`
|
|
438
|
-
//
|
|
439
|
-
|
|
470
|
+
// `select`'s promise reaches the menu, which is the only place that can hold the popover open, keep the tick off an
|
|
471
|
+
// unfinished switch, and show a failure, and a promise nothing awaits is an unhandled rejection.
|
|
472
|
+
const reports = useRef({ audio: options.onPreferredAudioLanguageChange, subtitles: options.onPreferredSubtitleLanguageChange })
|
|
473
|
+
reports.current = { audio: options.onPreferredAudioLanguageChange, subtitles: options.onPreferredSubtitleLanguageChange }
|
|
440
474
|
useEffect(() => {
|
|
441
475
|
if (!subtitles) return
|
|
442
476
|
setSourceState({
|
|
443
477
|
subtitleTracks: subtitles.options.map(({ id, label, disabled }) => ({ id, label, disabled })),
|
|
444
478
|
selectedSubtitleTrack: subtitles.selectedId ?? undefined,
|
|
445
|
-
selectSubtitleTrack: (id) =>
|
|
479
|
+
selectSubtitleTrack: (id) => {
|
|
480
|
+
const picked = id == null ? null : String(id)
|
|
481
|
+
const track = picked === null ? undefined : trackOf(subtitles, picked)
|
|
482
|
+
const wasOff = subtitles.selectedId === null
|
|
483
|
+
return afterSwitch(subtitles.select(picked), () => {
|
|
484
|
+
const language = picked === null ? null : languageOf(track) ?? (wasOff ? track?.title : undefined)
|
|
485
|
+
if (language !== undefined) reports.current.subtitles?.(language)
|
|
486
|
+
})
|
|
487
|
+
},
|
|
446
488
|
subtitleOffLabel: subtitles.offLabel,
|
|
447
489
|
})
|
|
448
490
|
}, [setSourceState, subtitles])
|
|
@@ -452,7 +494,10 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
|
|
|
452
494
|
setSourceState({
|
|
453
495
|
audioTracks: audio.options.map(({ id, label, disabled }) => ({ id, label, disabled })),
|
|
454
496
|
selectedAudioTrack: audio.selectedId ?? undefined,
|
|
455
|
-
selectAudioTrack: (id) => audio.select(String(id)),
|
|
497
|
+
selectAudioTrack: (id) => afterSwitch(audio.select(String(id)), () => {
|
|
498
|
+
const language = languageOf(trackOf(audio, String(id)))
|
|
499
|
+
if (language !== undefined) reports.current.audio?.(language)
|
|
500
|
+
}),
|
|
456
501
|
})
|
|
457
502
|
}, [setSourceState, audio])
|
|
458
503
|
|