@banou/media-player 0.10.27 → 0.10.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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,6 +1,7 @@
1
1
  /// <reference types="@emotion/react/types/css-prop" />
2
2
  import type { ReactNode, Ref } from 'react'
3
3
  import type { ViewportBox } from '../source-feature'
4
+ import type { HostFullscreen } from '../video-player'
4
5
 
5
6
  import { Children, Fragment, isValidElement, useEffect, useRef } from 'react'
6
7
  import { css } from '@emotion/react'
@@ -9,6 +10,7 @@ import { usePlayer } from '../player'
9
10
  import { Overlay } from './overlay'
10
11
  import ControlBar from './control-bar'
11
12
  import BurnInHint from './burn-in-hint'
13
+ import { HostKeepsFullscreen } from './tooltip-display'
12
14
  import SkipChapter from './skip-chapter'
13
15
 
14
16
  const AUTO_HIDE_DELAY = 3_000
@@ -133,10 +135,12 @@ export type ChromeProps = {
133
135
  /** False draws no control bar at all, leaving the picture, the title and the overlay. */
134
136
  controls?: boolean
135
137
  shortcuts?: 'window' | 'player'
138
+ /** Fullscreen kept by the host: a press calls its `request` instead of fullscreening the player. */
139
+ fullscreen?: HostFullscreen
136
140
  children?: ReactNode
137
141
  }
138
142
 
139
- export const Chrome = ({ ref, onVideoRef, onSubtitleRef, overlay, controls, shortcuts, children }: ChromeProps) => {
143
+ export const Chrome = ({ ref, onVideoRef, onSubtitleRef, overlay, controls, shortcuts, fullscreen, children }: ChromeProps) => {
140
144
  const player = usePlayer()
141
145
  const hideUI = usePlayer((state) => state.hideUI)
142
146
  const setHideUI = usePlayer((state) => state.setHideUI)
@@ -268,7 +272,8 @@ export const Chrome = ({ ref, onVideoRef, onSubtitleRef, overlay, controls, shor
268
272
  if (lastPointerType.current !== 'mouse') return
269
273
  if (pausedBeforeClick.current) player.pause()
270
274
  else void player.play().catch(() => {})
271
- void player.toggleFullscreen()
275
+ if (fullscreen) fullscreen.request()
276
+ else void player.toggleFullscreen()
272
277
  }
273
278
 
274
279
  // relatedTarget alone is not enough: the browser fires mouseout with a null one while the pointer
@@ -306,7 +311,11 @@ export const Chrome = ({ ref, onVideoRef, onSubtitleRef, overlay, controls, shor
306
311
  {item}
307
312
  </div>
308
313
  ))}
309
- {controls === false ? null : <ControlBar shortcuts={shortcuts} root={root} />}
314
+ {controls === false ? null : (
315
+ <HostKeepsFullscreen value={!!fullscreen}>
316
+ <ControlBar shortcuts={shortcuts} root={root} fullscreen={fullscreen} />
317
+ </HostKeepsFullscreen>
318
+ )}
310
319
  {/* Not tied to `hideUI`: it says what to do next, and it is on screen for nine seconds. */}
311
320
  <BurnInHint />
312
321
  <SkipChapter />
@@ -1,5 +1,6 @@
1
1
  /// <reference types="@emotion/react/types/css-prop" />
2
2
  import type { RefObject } from 'react'
3
+ import type { HostFullscreen } from '../video-player'
3
4
 
4
5
  import { useCallback, useEffect, useRef, useState } from 'react'
5
6
  import { css } from '@emotion/react'
@@ -160,7 +161,11 @@ const style = css`
160
161
  `
161
162
 
162
163
  export const ControlBar = (
163
- { shortcuts = 'window', root }: { shortcuts?: 'window' | 'player', root: RefObject<HTMLDivElement | null> },
164
+ { shortcuts = 'window', root, fullscreen: host }: {
165
+ shortcuts?: 'window' | 'player'
166
+ root: RefObject<HTMLDivElement | null>
167
+ fullscreen?: HostFullscreen
168
+ },
164
169
  ) => {
165
170
  const player = usePlayer()
166
171
  const paused = usePlayer((state) => state.paused)
@@ -168,7 +173,11 @@ export const ControlBar = (
168
173
  const duration = usePlayer((state) => state.duration)
169
174
  // a seek in flight reads as its destination, so the clock answers the click at once
170
175
  const seekingTo = usePlayer((state) => state.seekingTo)
171
- const fullscreen = usePlayer((state) => state.fullscreen)
176
+ const ownFullscreen = usePlayer((state) => state.fullscreen)
177
+ const fullscreen = host ? host.active : ownFullscreen
178
+ // through a ref, so the key listener below is not re-added for a host's inline object on every render
179
+ const latestHost = useRef(host)
180
+ latestHost.current = host
172
181
  const hideUI = usePlayer((state) => state.hideUI)
173
182
  const togglePictureInPicture = usePlayer((state) => state.togglePictureInPicture)
174
183
  const pictureInPictureMode = usePlayer((state) => state.pictureInPictureMode)
@@ -207,6 +216,11 @@ export const ControlBar = (
207
216
  // Opening, once pressed) leaves the focus on the body, and the shortcuts stay with the player through that
208
217
  const engaged = useRef(false)
209
218
 
219
+ const toggleFullscreen = useCallback(() => {
220
+ if (latestHost.current) latestHost.current.request()
221
+ else void player.toggleFullscreen()
222
+ }, [player])
223
+
210
224
  useEffect(() => {
211
225
  const seek = (time: number) => requestSeek ? requestSeek(time) : player.seek(time)
212
226
  // the path, not ev.target, which a shadow root around the player retargets to its host
@@ -220,11 +234,12 @@ export const ControlBar = (
220
234
  // layouts, as Ctrl and Alt
221
235
  if ((ev.ctrlKey || ev.metaKey || ev.altKey) && !ev.getModifierState('AltGraph')) return
222
236
  const fromPlayer = root.current?.contains(target ?? null) || (target === document.body && engaged.current)
223
- if (shortcuts === 'player' && !player.fullscreen && !fromPlayer) return
237
+ const fullscreen = latestHost.current ? latestHost.current.active : player.fullscreen
238
+ if (shortcuts === 'player' && !fullscreen && !fromPlayer) return
224
239
 
225
240
  let shouldPreventDefault = true
226
241
  // space would otherwise reach the browser's own shortcut
227
- if (ev.key === 'f') player.toggleFullscreen()
242
+ if (ev.key === 'f') toggleFullscreen()
228
243
  else if (ev.key === 'k') player.togglePaused()
229
244
  else if (ev.key === ' ') player.togglePaused()
230
245
  else if (ev.key === 'm') player.toggleMuted()
@@ -258,7 +273,7 @@ export const ControlBar = (
258
273
  window.removeEventListener('pointerdown', engage, true)
259
274
  window.removeEventListener('focusin', engage, true)
260
275
  }
261
- }, [player, modifyVolume, requestSeek, stepFrame, shortcuts, root])
276
+ }, [player, modifyVolume, requestSeek, stepFrame, shortcuts, root, toggleFullscreen])
262
277
 
263
278
  const handleWheel = useCallback((e: WheelEvent) => {
264
279
  e.preventDefault()
@@ -436,7 +451,7 @@ export const ControlBar = (
436
451
  <button
437
452
  className='full-screen'
438
453
  type='button'
439
- onClick={() => player.toggleFullscreen()}
454
+ onClick={toggleFullscreen}
440
455
  aria-label='Full screen'
441
456
  aria-pressed={fullscreen}
442
457
  >
@@ -1,7 +1,7 @@
1
1
  import type { ReactNode } from 'react'
2
2
  import type { TooltipRefProps } from 'react-tooltip'
3
3
 
4
- import { useEffect, useRef } from 'react'
4
+ import { createContext, useContext, useEffect, useRef } from 'react'
5
5
  import { css } from '@emotion/react'
6
6
  import { PlacesType, Tooltip } from 'react-tooltip'
7
7
 
@@ -78,6 +78,9 @@ const watchPointer = () => {
78
78
  }
79
79
  }
80
80
 
81
+ /** Whether the host page keeps the player's fullscreen: the `fullscreen` prop, or a mirror that took it over. */
82
+ export const HostKeepsFullscreen = createContext(false)
83
+
81
84
  interface TooltipDisplayProps {
82
85
  id: string
83
86
  toolTipText: ReactNode
@@ -103,6 +106,7 @@ export const TooltipDisplay = ({
103
106
  }: TooltipDisplayProps) => {
104
107
  const anchor = useRef<HTMLDivElement>(null)
105
108
  const tooltip = useRef<TooltipRefProps>(null)
109
+ const hostKeepsFullscreen = useContext(HostKeepsFullscreen)
106
110
 
107
111
  /**
108
112
  * Close on a fullscreen transition, unless the pointer really is still on the anchor.
@@ -124,6 +128,12 @@ export const TooltipDisplay = ({
124
128
  * That is the same test chrome.tsx's onMouseOut makes when relatedTarget comes back null. The rect
125
129
  * is already the post-transition one when fullscreenchange fires, where matches(':hover') is not,
126
130
  * which is why the pointer is tracked rather than asked for.
131
+ *
132
+ * A host that keeps the fullscreen fullscreens an element of its own document, so a player in a
133
+ * frame hears no fullscreenchange (measured 2026-10-26, Chromium) and the chip stayed through any
134
+ * later pointer move. Its window resizes with the frame, after the move, so that is what this
135
+ * listens to then. The host's `active` would not do: across origins it comes by a message, and no
136
+ * rule orders a message against the frame's new size.
127
137
  */
128
138
  useEffect(() => {
129
139
  const untrack = watchPointer()
@@ -138,11 +148,13 @@ export const TooltipDisplay = ({
138
148
  // as string so the prefixed name checks against the DOM lib's event map.
139
149
  const changeEvents: string[] = ['fullscreenchange', 'webkitfullscreenchange']
140
150
  for (const type of changeEvents) document.addEventListener(type, closeIfPointerLeft)
151
+ if (hostKeepsFullscreen) window.addEventListener('resize', closeIfPointerLeft)
141
152
  return () => {
142
153
  untrack()
143
154
  for (const type of changeEvents) document.removeEventListener(type, closeIfPointerLeft)
155
+ window.removeEventListener('resize', closeIfPointerLeft)
144
156
  }
145
- }, [])
157
+ }, [hostKeepsFullscreen])
146
158
 
147
159
  return (
148
160
  <>
@@ -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
- // `selectedAudioStream`, which is whatever is playing right now.
100
- const [audioStreamIndex, setAudioStreamIndex] = useState<number | undefined>(undefined)
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 renderer turns the first track on by itself, so the menu has to mirror that or it shows
142
- // "Disable" ticked over subtitles that are visibly on screen.
143
- const subtitleChoiceMade = useRef(false)
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
- subtitleChoiceMade.current = true
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
- setAudioStreamIndex(id)
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: (streams) => {
394
+ onSubtitleStreams: (subtitles) => {
364
395
  if (cancelled) return
396
+ streams.current.subtitles = subtitles
365
397
  player.setSourceState({
366
- subtitleTracks: toNamedTracks(streams),
367
- ...subtitleChoiceMade.current ? {} : { selectedSubtitleTrack: streams[0]?.streamIndex },
398
+ subtitleTracks: toNamedTracks(subtitles),
399
+ ...subtitleChoiceFor.current === size ? {} : { selectedSubtitleTrack: preferredSubtitle(preferredSubtitleRef.current, subtitles) },
368
400
  })
369
401
  },
370
- onAudioStreams: (streams, selected) => {
402
+ onAudioStreams: (audio, selected) => {
371
403
  if (cancelled) return
372
- player.setSourceState({ audioTracks: toNamedTracks(streams), selectedAudioTrack: selected })
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
- // a track chosen before this pipeline existed has to be re-applied to the new renderer
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
- if (typeof chosen === 'number') controller.selectSubtitleStream(chosen)
421
+ controller.selectSubtitleStream(typeof chosen === 'number' ? chosen : undefined)
389
422
  } catch (error) {
390
423
  fail(error)
391
424
  }
@@ -2,8 +2,8 @@
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'
6
- import type { ExposePlayerOptions } from '../remote'
5
+ import type { DelegatedSelection, DelegatedTracks, ExternalThumbnails, PassThroughPictureInPicture, PlayerMedia } from './media'
6
+ import type { ExposePlayerOptions, ServedPlayer } from '../remote'
7
7
 
8
8
  import { useEffect, useMemo, useRef, useState } from 'react'
9
9
  import { css } from '@emotion/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
@@ -31,6 +32,20 @@ export type MediaPlayerSource =
31
32
  | { read: (offset: number, size: number) => Promise<ArrayBuffer>, size: number, readsDownload?: boolean }
32
33
  | { read?: undefined, size?: undefined, readsDownload?: undefined }
33
34
 
35
+ /**
36
+ * Fullscreen kept by the host page rather than by the player, for a page that fullscreens an element of its own around
37
+ * the player, so that fullscreen outlasts the player in it.
38
+ */
39
+ export type HostFullscreen = {
40
+ /** Whether the host shows the player fullscreen: the button shows it, and the `'player'` shortcuts follow it. */
41
+ active: boolean
42
+ /**
43
+ * The viewer pressed fullscreen (the button, `f` or a double click): the host enters or leaves it. Called once per
44
+ * press, during that press's event, so the host's own `requestFullscreen` has the press's activation.
45
+ */
46
+ request: () => void
47
+ }
48
+
34
49
  /** Shared by both arms: nothing here depends on who owns the media. */
35
50
  type CommonOptions = {
36
51
  /**
@@ -87,6 +102,13 @@ type CommonOptions = {
87
102
  */
88
103
  shortcuts?: 'window' | 'player'
89
104
 
105
+ /**
106
+ * Hand fullscreen to the host page: the player then never calls `requestFullscreen`, each press of its fullscreen
107
+ * calls `request` once, and the button and the `'player'` shortcuts follow `active`. Read by value, so it may be
108
+ * written inline. Without it the player fullscreens itself.
109
+ */
110
+ fullscreen?: HostFullscreen
111
+
90
112
  /**
91
113
  * The app's own content over the video: a download readout, a badge, a logo, anything the player
92
114
  * itself has no opinion about.
@@ -122,6 +144,20 @@ type CommonOptions = {
122
144
  */
123
145
  onSeek?: (fraction: number) => void
124
146
  onPlaybackError?: (error: unknown) => void
147
+
148
+ /**
149
+ * The viewer picked an audio track in the settings menu, named by its language as the file or the source names it:
150
+ * its tag (`jpn`, `en-US`), else its title or label (`Japanese`). What an app saves to pass back as
151
+ * `preferredAudioLanguage`; the player saves nothing. A track that names no language reports nothing, and on a media
152
+ * the player does not own the report waits for the source's switch to succeed.
153
+ */
154
+ onPreferredAudioLanguageChange?: (language: string) => void
155
+ /**
156
+ * As `onPreferredAudioLanguageChange`, for the subtitles menu, with null for subtitles turned off. A track that names
157
+ * no language reports only when it turns subtitles on, by its title or label (else `und`), so the next media starts
158
+ * with them on too.
159
+ */
160
+ onPreferredSubtitleLanguageChange?: (language: string | null) => void
125
161
  }
126
162
 
127
163
  /**
@@ -204,6 +240,19 @@ export type MediaPlayerLocalOptions =
204
240
  normalizeVolume?: boolean
205
241
  /** The viewer flipped the switch, to `normalizeVolume`: what an app saves to pass back as `normalizeVolume`. */
206
242
  onNormalizeVolumeChange?: (normalizeVolume: boolean) => void
243
+
244
+ /**
245
+ * The language a file starts its audio in, as `onPreferredAudioLanguageChange` reported it or as any tag or name
246
+ * (`ja`, `jpn`, `Japanese`). Its full track wins over a commentary, and a file with none plays its default. A
247
+ * track the viewer picks wins for that file. Read when a file starts, so a change applies from the next one.
248
+ */
249
+ preferredAudioLanguage?: string
250
+ /**
251
+ * As `preferredAudioLanguage`, for subtitles, where signs and songs or forced tracks count as partial and a file
252
+ * with none starts on its first track. null starts every file with subtitles off, and a preference that names no
253
+ * language starts on the track titled as it is.
254
+ */
255
+ preferredSubtitleLanguage?: string | null
207
256
  }
208
257
 
209
258
  /**
@@ -259,6 +308,11 @@ export type MediaPlayerRemoteOptions =
259
308
 
260
309
  export type MediaPlayerOptions = MediaPlayerLocalOptions | MediaPlayerRemoteOptions
261
310
 
311
+ // a label is read as a name, never as a tag
312
+ const trackOf = (selection: DelegatedSelection, id: string) => ({ title: selection.options.find((option) => option.id === id)?.label })
313
+
314
+ const afterSwitch = (result: void | Promise<void>, then: () => void) => result instanceof Promise ? result.then(then) : then()
315
+
262
316
  const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, children?: ReactNode }) => {
263
317
  // Narrowed on the field that carries the difference: a remote arm brings its own media and, by
264
318
  // construction, no bytes. Both halves stay null-safe so the engine hooks below can be called
@@ -299,6 +353,12 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
299
353
  // Imported lazily, so `osra` is a dependency of `@banou/media-player/remote` and not of every app
300
354
  // that renders a player without ever exposing one.
301
355
  const { expose } = options
356
+ // What `expose` serves beside the media, the same object for the player's life. Its `onHostFullscreen` is how a
357
+ // mirror made with `fullscreen: true` takes the fullscreen over.
358
+ const [embedderFullscreen, setEmbedderFullscreen] = useState<boolean | null>(null)
359
+ const [served] = useState<ServedPlayer & { chapters: MediaChapter[] }>(
360
+ () => Object.assign(new EventTarget(), { chapters: [], onHostFullscreen: setEmbedderFullscreen }),
361
+ )
302
362
  const exposeOptions = expose === true ? {} : expose || undefined
303
363
  const latestExpose = useRef(exposeOptions)
304
364
  latestExpose.current = exposeOptions
@@ -312,12 +372,25 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
312
372
  import('../remote')
313
373
  .then(({ exposePlayer }) => {
314
374
  if (dropped) return
315
- stop = exposePlayer(media, latestExpose.current ?? {})
375
+ stop = exposePlayer(media, { ...latestExpose.current, player: served })
316
376
  })
317
377
  .catch(() => {})
318
378
  return () => { dropped = true; stop?.() }
319
379
  }, [media, !!expose, exposeId, exposeOrigin, exposeChannel])
320
380
 
381
+ // by value, since a caller's inline `chapters` is a new array on every render
382
+ const playerChapters = usePlayer((state) => state.chapters)
383
+ const chaptersKey = JSON.stringify(playerChapters)
384
+ useEffect(() => {
385
+ served.chapters = playerChapters
386
+ served.dispatchEvent(new Event('chapterschange'))
387
+ }, [chaptersKey])
388
+
389
+ const fullscreen = options.fullscreen ?? (embedderFullscreen === null ? undefined : {
390
+ active: embedderFullscreen,
391
+ request: () => served.dispatchEvent(new Event('fullscreenrequest')),
392
+ })
393
+
321
394
  // one per file, as `size` is the source's identity everywhere here
322
395
  const tap = useMemo(() => createPlaybackTap(), [size])
323
396
 
@@ -434,15 +507,24 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
434
507
  // the document, and it renders the result itself.
435
508
  const subtitles = remote?.subtitles?.selection
436
509
  const audio = remote?.audioTracks?.selection
437
- // `select` is published as-is rather than wrapped, so its promise reaches the menu: the menu is the
438
- // only place that can hold the popover open, keep the tick off an unfinished switch, and show a
439
- // failure, and a promise nothing awaits is an unhandled rejection.
510
+ // `select`'s promise reaches the menu, which is the only place that can hold the popover open, keep the tick off an
511
+ // unfinished switch, and show a failure, and a promise nothing awaits is an unhandled rejection.
512
+ const reports = useRef({ audio: options.onPreferredAudioLanguageChange, subtitles: options.onPreferredSubtitleLanguageChange })
513
+ reports.current = { audio: options.onPreferredAudioLanguageChange, subtitles: options.onPreferredSubtitleLanguageChange }
440
514
  useEffect(() => {
441
515
  if (!subtitles) return
442
516
  setSourceState({
443
517
  subtitleTracks: subtitles.options.map(({ id, label, disabled }) => ({ id, label, disabled })),
444
518
  selectedSubtitleTrack: subtitles.selectedId ?? undefined,
445
- selectSubtitleTrack: (id) => subtitles.select(id == null ? null : String(id)),
519
+ selectSubtitleTrack: (id) => {
520
+ const picked = id == null ? null : String(id)
521
+ const track = picked === null ? undefined : trackOf(subtitles, picked)
522
+ const wasOff = subtitles.selectedId === null
523
+ return afterSwitch(subtitles.select(picked), () => {
524
+ const language = picked === null ? null : languageOf(track) ?? (wasOff ? track?.title : undefined)
525
+ if (language !== undefined) reports.current.subtitles?.(language)
526
+ })
527
+ },
446
528
  subtitleOffLabel: subtitles.offLabel,
447
529
  })
448
530
  }, [setSourceState, subtitles])
@@ -452,7 +534,10 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
452
534
  setSourceState({
453
535
  audioTracks: audio.options.map(({ id, label, disabled }) => ({ id, label, disabled })),
454
536
  selectedAudioTrack: audio.selectedId ?? undefined,
455
- selectAudioTrack: (id) => audio.select(String(id)),
537
+ selectAudioTrack: (id) => afterSwitch(audio.select(String(id)), () => {
538
+ const language = languageOf(trackOf(audio, String(id)))
539
+ if (language !== undefined) reports.current.audio?.(language)
540
+ }),
456
541
  })
457
542
  }, [setSourceState, audio])
458
543
 
@@ -484,6 +569,7 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
484
569
  overlay={options.overlay}
485
570
  controls={options.controls}
486
571
  shortcuts={options.shortcuts}
572
+ fullscreen={fullscreen}
487
573
  >
488
574
  {children}
489
575
  </Chrome>