@simba-dev/react-native-media-player 1.1.0 → 1.3.0
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 +132 -39
- package/package.json +2 -2
- package/src/components/PlayerProvider.tsx +288 -7
- package/src/hooks/SimbaPlayer.tsx +144 -0
- package/src/hooks/SimbaPlayerRoot.tsx +73 -0
- package/src/hooks/useLaunchParams.tsx +64 -0
- package/src/hooks/useOpenFromUrl.tsx +174 -0
- package/src/hooks/useOpenWithResume.tsx +236 -0
- package/src/hooks/usePlayerActivity.ts +103 -0
- package/src/hooks/useSimbaPlayerLookup.tsx +58 -0
- package/src/index.ts +26 -0
- package/src/types/__tests__/player.test.tsx +494 -0
- package/src/types/player.ts +947 -72
- package/src/types/__tests__/player.test.ts +0 -166
package/README.md
CHANGED
|
@@ -105,37 +105,121 @@ getMpvPlayerModule().requestNotificationPermission?.(); // graceful no-op on old
|
|
|
105
105
|
## Basic usage
|
|
106
106
|
|
|
107
107
|
```tsx
|
|
108
|
-
// App.tsx
|
|
108
|
+
// App.tsx — V14+ (one wrapper, one import, zero glue code)
|
|
109
109
|
import React from 'react';
|
|
110
|
-
import {
|
|
110
|
+
import {
|
|
111
|
+
SimbaPlayer,
|
|
112
|
+
SimbaPlayerRoot,
|
|
113
|
+
useOpenFromUrl,
|
|
114
|
+
} from '@simba-dev/react-native-media-player';
|
|
111
115
|
|
|
112
116
|
export default function App() {
|
|
113
117
|
return (
|
|
114
|
-
<
|
|
115
|
-
|
|
116
|
-
|
|
118
|
+
<SimbaPlayer
|
|
119
|
+
getResumePosition={(uri) =>
|
|
120
|
+
store.getState().bookmarks.byFileUri[uri]?.positionMs
|
|
121
|
+
}
|
|
122
|
+
>
|
|
123
|
+
<AppContent />
|
|
124
|
+
</SimbaPlayer>
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function AppContent() {
|
|
129
|
+
// Deep links: open incoming content:// + file:// URIs in the player.
|
|
130
|
+
const openFromUrl = useOpenFromUrl();
|
|
131
|
+
React.useEffect(() => {
|
|
132
|
+
Linking.getInitialURL().then(url => url && openFromUrl(url));
|
|
133
|
+
const sub = Linking.addEventListener('url', ({ url }) => openFromUrl(url));
|
|
134
|
+
return () => sub.remove();
|
|
135
|
+
}, [openFromUrl]);
|
|
136
|
+
|
|
137
|
+
// <SimbaPlayerRoot> handles the activity-launch branch
|
|
138
|
+
// (renders <PlayerRoot /> when launchParams is set, otherwise children).
|
|
139
|
+
return (
|
|
140
|
+
<SimbaPlayerRoot>
|
|
141
|
+
<YourNavigator />
|
|
142
|
+
</SimbaPlayerRoot>
|
|
117
143
|
);
|
|
118
144
|
}
|
|
119
145
|
```
|
|
120
146
|
|
|
121
|
-
That's it — `<
|
|
147
|
+
That's it — `<SimbaPlayer>` is the one-import, one-wrapper integration point. It composes the `PlayerProvider` (config + state) and `PlayerResumeProvider` (bookmark-aware resume lookup). `<SimbaPlayerRoot>` (V14) absorbs the `useLaunchParams()` + activity-branch switch. `useOpenFromUrl()` (V14) absorbs the deep-link URI-scheme filter + title-derivation + extension-classification. `getResumePosition` (V14) is the new function-prop shape for the resume lookup (replaces V13's `lookup={...}` object shape).
|
|
122
148
|
|
|
123
149
|
### Launching a file from JS
|
|
124
150
|
|
|
125
151
|
```tsx
|
|
126
|
-
import {
|
|
127
|
-
|
|
128
|
-
const { MpvPlayerModule } = NativeModules;
|
|
152
|
+
import { usePlayerActivity } from '@simba-dev/react-native-media-player';
|
|
129
153
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
154
|
+
function TrackRow({ track }) {
|
|
155
|
+
const { openPlayer } = usePlayerActivity();
|
|
156
|
+
return (
|
|
157
|
+
<Pressable onPress={() => openPlayer({
|
|
158
|
+
uri: track.uri,
|
|
159
|
+
title: track.title,
|
|
160
|
+
type: 'audio', // 'video' | 'audio'
|
|
161
|
+
startPositionMs: 0, // optional
|
|
162
|
+
})}>
|
|
163
|
+
<Text>{track.title}</Text>
|
|
164
|
+
</Pressable>
|
|
165
|
+
);
|
|
166
|
+
}
|
|
136
167
|
// PlayerActivity launches, plays the file, supports PiP, etc.
|
|
137
168
|
```
|
|
138
169
|
|
|
170
|
+
### Resume-aware openPlayer (with bookmarks)
|
|
171
|
+
|
|
172
|
+
If your app has a bookmarks/history feature, wrap your tree in `<SimbaPlayer>` with a `lookup` adapter and use `useOpenWithResume()`. The hook accepts a `resumeId` and looks up the saved position via your adapter — no manual position plumbing in every call site.
|
|
173
|
+
|
|
174
|
+
```tsx
|
|
175
|
+
// App.tsx
|
|
176
|
+
import { SimbaPlayer, type PlayerResumeLookup } from '@simba-dev/react-native-media-player';
|
|
177
|
+
|
|
178
|
+
const resumeLookup: PlayerResumeLookup = {
|
|
179
|
+
getResumePosition: (resumeId) => {
|
|
180
|
+
// resolve the resume position (ms) for the given item
|
|
181
|
+
// — return undefined for "no saved position"
|
|
182
|
+
return store.getState().bookmarks.byFileUri[resumeId]?.positionMs;
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
<SimbaPlayer lookup={resumeLookup}>
|
|
187
|
+
<AppContent />
|
|
188
|
+
</SimbaPlayer>
|
|
189
|
+
|
|
190
|
+
// TrackRow.tsx
|
|
191
|
+
import { useOpenWithResume } from '@simba-dev/react-native-media-player';
|
|
192
|
+
|
|
193
|
+
function TrackRow({ track }) {
|
|
194
|
+
const openPlayer = useOpenWithResume();
|
|
195
|
+
return (
|
|
196
|
+
<Pressable onPress={() => openPlayer({
|
|
197
|
+
uri: track.uri,
|
|
198
|
+
title: track.title,
|
|
199
|
+
type: 'audio',
|
|
200
|
+
resumeId: track.uri, // module looks up the saved position
|
|
201
|
+
})}>
|
|
202
|
+
<Text>{track.title}</Text>
|
|
203
|
+
</Pressable>
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
### Mapping content kinds to V13 stream types
|
|
209
|
+
|
|
210
|
+
If your items have content kinds like `'music'`, `'movie'`, `'podcast'` (not the V13 stream types `'audio' | 'video'`), use the `resolveStreamType` helper:
|
|
211
|
+
|
|
212
|
+
```tsx
|
|
213
|
+
import { usePlayerActivity, resolveStreamType } from '@simba-dev/react-native-media-player';
|
|
214
|
+
|
|
215
|
+
const { openPlayer } = usePlayerActivity();
|
|
216
|
+
openPlayer({
|
|
217
|
+
uri: item.uri,
|
|
218
|
+
title: item.title,
|
|
219
|
+
type: resolveStreamType(item.kind), // 'music' -> 'audio', 'movie' -> 'video', etc.
|
|
220
|
+
});
|
|
221
|
+
```
|
|
222
|
+
|
|
139
223
|
## Custom UI
|
|
140
224
|
|
|
141
225
|
Two ways to swap the controls:
|
|
@@ -316,46 +400,52 @@ Default theme is dark with a golden accent (`DEFAULT_THEME`).
|
|
|
316
400
|
|
|
317
401
|
## API reference
|
|
318
402
|
|
|
319
|
-
Every public export lives in [`src/index.ts`](./src/index.ts).
|
|
403
|
+
Every public export lives in [`src/index.ts`](./src/index.ts). The **V13+ surface** is the recommended way to integrate; the V12 surface (`PlayerProvider` + `usePlayer()` directly) still works for backward compatibility but is undocumented for new consumers.
|
|
320
404
|
|
|
321
|
-
### Components
|
|
405
|
+
### Components (V13+ recommended, V14 additions in **bold**)
|
|
322
406
|
|
|
323
407
|
| Component | Purpose |
|
|
324
408
|
|---|---|
|
|
325
|
-
| `<
|
|
326
|
-
|
|
|
409
|
+
| `<SimbaPlayer>` | **One-import, one-wrapper integration.** Composes `PlayerProvider` + `PlayerResumeProvider`. V14 adds the `getResumePosition` function prop (alongside the legacy `lookup` object prop). Use this at the app root. |
|
|
410
|
+
| **`<SimbaPlayerRoot>`** | **V14 — activity-branch wrapper.** Calls `useLaunchParams()` internally; renders `<PlayerRoot />` when the activity was launched with playback params, otherwise renders its `children`. Replaces the V13 `if (launchParams) return <PlayerRoot />` boilerplate. |
|
|
411
|
+
| `<PlayerRoot>` | Renders `<PlayerSurface>` + the controls overlay (default `<DefaultControls>` or custom via `renderControls`). |
|
|
327
412
|
| `<PlayerSurface>` | `<View flex:1>` placeholder for the native SurfaceView. a11y-hidden. |
|
|
328
413
|
| `<DefaultControls>` | Pre-built controls (top bar, scrubber, transport, auto-hide). |
|
|
414
|
+
| `<PlayerProvider>` | (V12 surface) Wraps the app; provides resolved config + `renderControls` slot. Use `<SimbaPlayer>` instead unless you need the raw provider. |
|
|
329
415
|
|
|
330
|
-
### Hooks
|
|
416
|
+
### Hooks (V13+, V14 additions in **bold**)
|
|
331
417
|
|
|
332
418
|
| Hook | Returns | Throws outside provider? |
|
|
333
419
|
|---|---|---|
|
|
420
|
+
| `usePlayerActivity()` | `{ openPlayer(opts), getLaunchParams() }` | ❌ No (no-op fallback) |
|
|
421
|
+
| `useOpenWithResume()` | `(opts: OpenPlayerOptions & { resumeId? }) => Promise<boolean>` | ❌ No (no-op lookup) |
|
|
422
|
+
| **`useOpenFromUrl()`** | **`(uri: string) => Promise<boolean>`** — **deep-link helper** that filters `content://` + `file://` URIs, derives a title from the basename, classifies audio/video by extension, and forwards to `useOpenWithResume().openPlayer(...)` | ❌ No |
|
|
423
|
+
| **`useSimbaPlayerLookup(selector?)`** | **`PlayerResumeLookup`** — **factory hook** that wraps an optional `selector` in a memoized lookup object. Without a selector, returns no-op. | ❌ No |
|
|
424
|
+
| `usePlayItem()` | `(item, opts) => Promise<boolean>` | ❌ No (sugar on `useOpenWithResume`) |
|
|
425
|
+
| `useLaunchParams()` | `LaunchParams \| null` | ❌ No (returns null) |
|
|
426
|
+
| `usePlayer()` | `{ state: PlayerState, commands: PlayerCommands, progress: PlayerProgress }` | ❌ No (returns defaults) |
|
|
427
|
+
| `usePlayerProgress()` | `{ positionMs, durationMs, isBuffering, isSeeking, seekable, cacheRanges, cacheFill }` | ❌ No (returns 0/0) |
|
|
334
428
|
| `usePlayerConfig()` | `ResolvedPlayerConfig` | ✅ Yes (programmer error) |
|
|
335
429
|
| `useTheme()` | `PlayerTheme` | ✅ Yes (programmer error) |
|
|
336
430
|
| `useRenderControls()` | `RenderControlsFn \| null` | ❌ No (falls back to default controls) |
|
|
337
|
-
| `usePlayer()` | `{ state: PlayerState, commands: PlayerCommands }` | ❌ No (returns defaults) |
|
|
338
|
-
| `usePlayerProgress()` | `{ positionMs: number, durationMs: number }` | ❌ No (returns 0/0) |
|
|
339
431
|
|
|
340
|
-
### Types
|
|
432
|
+
### Types (V13+)
|
|
341
433
|
|
|
342
|
-
| Type |
|
|
434
|
+
| Type | Notes |
|
|
343
435
|
|---|---|
|
|
344
|
-
| `
|
|
345
|
-
| `
|
|
346
|
-
| `
|
|
347
|
-
| `
|
|
348
|
-
| `
|
|
349
|
-
| `
|
|
350
|
-
| `
|
|
351
|
-
|
|
|
352
|
-
| `
|
|
353
|
-
|
|
|
354
|
-
| `
|
|
355
|
-
| `
|
|
356
|
-
| `
|
|
357
|
-
| `RenderControlsFn` | `() => React.ReactNode` |
|
|
358
|
-
| `MpvPlayerModuleBridge` | Typed view of the native module |
|
|
436
|
+
| `PlayerState` | 20 fields: `isPlaying`, `title`, `artist`, `album`, `positionMs`, `durationMs`, `isBuffering`, `isSeeking`, `seekable`, `volume`, `isMuted`, `speed`, `loopMode`, `playlist`, `currentIndex`, `tracks`, `chapters`, `currentChapter`, `videoParams`, `error` |
|
|
437
|
+
| `PlayerProgress` | 7 fields: `positionMs`, `durationMs`, `isBuffering`, `isSeeking`, `seekable`, `cacheRanges`, `cacheFill` |
|
|
438
|
+
| `PlayerCommands` | 38 methods: `play`, `pause`, `seek`, `skipBackward`, `skipForward`, `togglePlayPause`, `stop`, `seekBy`, `seekToChapter`, `next`, `previous`, `setVolume`, `setMuted`, `toggleMute`, `setSpeed`, `setLoopMode`, `loadFile`, `loadPlaylist`, `playlistRemove`, `shuffle`, `clear`, `selectTrack`, `cycleTrack`, `setTrack`, `enterPip`, `exitPip`, `exitPipAndFinish`, `setKeepScreenOn`, `setOrientation`, `setImmersive`, `setScreenBrightness`, `requestNotificationPermission`, `openPlayer`, `getLaunchParams`, `getProperty`, `setProperty`, `observeProperty`, `unobserveProperty`, `grantPersistablePermission`, `verifyContentUri` |
|
|
439
|
+
| `OpenPlayerOptions` | `{ uri, title, type: 'video' \| 'audio', startPositionMs? }` — the V13 `openPlayer` arg shape (replaces V11's positional args) |
|
|
440
|
+
| `LaunchParams` | `{ uri, title, type, startPositionMs }` — read from the activity via `useLaunchParams()` |
|
|
441
|
+
| `ContentKind` | `'video' \| 'audio' \| 'music' \| 'movie' \| 'podcast' \| 'live-tv' \| 'radio' \| 'audiobook' \| 'archive-audio' \| 'episode' \| 'video-file' \| string` |
|
|
442
|
+
| `PlayerResumeLookup` | `{ getResumePosition(itemId: string): number \| undefined }` — adapter for the bookmark-aware resume lookup |
|
|
443
|
+
| **`GetResumePosition`** | **V14 — `(itemId: string) => number \| undefined`** — the function reference shape for `<SimbaPlayer getResumePosition={...}>` |
|
|
444
|
+
| `SimbaPlayerProps` | `{ config?, lookup?, getResumePosition?, children }` — V14 adds `getResumePosition` (function prop, recommended). If both `lookup` and `getResumePosition` are passed, `getResumePosition` wins. |
|
|
445
|
+
| **`SimbaPlayerRootProps`** | **V14 — `{ children: React.ReactNode }`** — the children are rendered when the activity was launched WITHOUT playback params |
|
|
446
|
+
| `MpvPlayerModuleBridge` | Typed view of the native module (78 methods) |
|
|
447
|
+
| `PlayerConfig`, `ResolvedPlayerConfig`, `PlayerTheme`, `PipConfig`, `AudioConfig`, `SubtitleConfig`, `NotificationConfig`, `DebugConfig`, `HardwareDecodingPolicy` | V12 surface — same as before |
|
|
448
|
+
| `MpvTrack`, `MpvChapter`, `MpvFileInfo`, `MpvVideoParams`, `MpvAudioDevice`, `MpvPlaybackState`, `MpvLoopMode`, `MpvEventName`, `MpvEvents`, `MpvEventPayloads`, `PlayerEventName`, `PlayerEventPayloads` | Low-level mpv types |
|
|
359
449
|
|
|
360
450
|
### Constants
|
|
361
451
|
|
|
@@ -370,6 +460,9 @@ Every public export lives in [`src/index.ts`](./src/index.ts).
|
|
|
370
460
|
|---|---|
|
|
371
461
|
| `resolvePlayerConfig(config)` | Merge a partial config with defaults — useful for tests / debug overlays |
|
|
372
462
|
| `getMpvPlayerModule()` | Typed wrapper over `NativeModules.MpvPlayerModule`. Returns a no-op stub on non-RN platforms (jest, web). |
|
|
463
|
+
| `resolveStreamType(kind: ContentKind): 'video' \| 'audio'` | Map a content kind to the V13 stream type. Idempotent — `'video'` and `'audio'` pass through unchanged. Use this when your items have `'music'`, `'movie'`, etc. but V13 `openPlayer` expects `'video' | 'audio'`. |
|
|
464
|
+
| `subscribePlayerEvent(name, handler)` → unsubscribe | Subscribe to a native mpv event (22 events). Returns an unsubscribe function. |
|
|
465
|
+
| `removeAllListeners(event?)` | Remove all listeners for an event (or all events if no arg). |
|
|
373
466
|
|
|
374
467
|
## Troubleshooting
|
|
375
468
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simba-dev/react-native-media-player",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "React Native video/audio player powered by libmpv — Picture-in-Picture, MediaSession, custom RN UI. **
|
|
3
|
+
"version": "1.3.0",
|
|
4
|
+
"description": "React Native video/audio player powered by libmpv — Picture-in-Picture, MediaSession, custom RN UI. **V14.0.0 stable release** (2026-09-04) — junior-dev-level integration surface. See [`SIMBA_PLAYER_MODULE_V14_FINAL_QA_REPORT.md`](X:/Development/SIMBA/MOBILE_APP_REACT_NATIVE/md/SIMBA_PLAYER_MODULE_V14_FINAL_QA_REPORT.md) for the QA report. Published under the `@simba-dev` org (the bare `simba` org-name on npmjs was reserved at publication time).",
|
|
5
5
|
"main": "src/index.ts",
|
|
6
6
|
"types": "src/index.ts",
|
|
7
7
|
"react-native": "src/index.ts",
|
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
import React, {
|
|
1
|
+
import React, {
|
|
2
|
+
createContext,
|
|
3
|
+
useContext,
|
|
4
|
+
useEffect,
|
|
5
|
+
useMemo,
|
|
6
|
+
useRef,
|
|
7
|
+
useState,
|
|
8
|
+
} from 'react';
|
|
2
9
|
import { NativeModules } from 'react-native';
|
|
3
10
|
import {
|
|
4
11
|
PlayerConfig,
|
|
@@ -6,6 +13,23 @@ import {
|
|
|
6
13
|
ResolvedPlayerConfig,
|
|
7
14
|
resolvePlayerConfig,
|
|
8
15
|
} from '../types/config';
|
|
16
|
+
import {
|
|
17
|
+
applyPlayerEvent,
|
|
18
|
+
DEFAULT_PROGRESS,
|
|
19
|
+
DEFAULT_STATE,
|
|
20
|
+
hydratePlayerState,
|
|
21
|
+
PlayerProgress,
|
|
22
|
+
PlayerProgressContext,
|
|
23
|
+
PlayerState,
|
|
24
|
+
PlayerStateContext,
|
|
25
|
+
} from '../types/player';
|
|
26
|
+
import {
|
|
27
|
+
getMpvPlayerModule,
|
|
28
|
+
PlayerEventName,
|
|
29
|
+
PlayerEventPayloads,
|
|
30
|
+
removeAllListeners,
|
|
31
|
+
subscribePlayerEvent,
|
|
32
|
+
} from '../bridge/MpvPlayerModule';
|
|
9
33
|
|
|
10
34
|
/**
|
|
11
35
|
* React Context carrying the resolved PlayerConfig. Consumers should
|
|
@@ -123,6 +147,83 @@ function getNativeModule():
|
|
|
123
147
|
return null;
|
|
124
148
|
}
|
|
125
149
|
|
|
150
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
151
|
+
// V13 Phase 51: PlayerStateContext + PlayerProgressContext + provider
|
|
152
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Internal: the state + progress context provider. The full
|
|
156
|
+
* `PlayerProvider` (below) is the public surface; this
|
|
157
|
+
* lower-level component just exposes the state + progress
|
|
158
|
+
* contexts with already-computed values, so the public
|
|
159
|
+
* provider can keep its config-push logic and just slot the
|
|
160
|
+
* state in.
|
|
161
|
+
*
|
|
162
|
+
* The contexts themselves are defined in `types/player.ts`
|
|
163
|
+
* (not here) so non-JSX consumers can import them without
|
|
164
|
+
* forcing the JSX transform on the whole module.
|
|
165
|
+
*/
|
|
166
|
+
function PlayerStateProvider({
|
|
167
|
+
state,
|
|
168
|
+
progress,
|
|
169
|
+
children,
|
|
170
|
+
}: {
|
|
171
|
+
state: PlayerState;
|
|
172
|
+
progress: PlayerProgress;
|
|
173
|
+
children: React.ReactNode;
|
|
174
|
+
}): React.ReactElement {
|
|
175
|
+
return (
|
|
176
|
+
<PlayerStateContext.Provider value={state}>
|
|
177
|
+
<PlayerProgressContext.Provider value={progress}>
|
|
178
|
+
{children}
|
|
179
|
+
</PlayerProgressContext.Provider>
|
|
180
|
+
</PlayerStateContext.Provider>
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* All 22 player event names. Must match `PlayerEventName` in
|
|
186
|
+
* `MpvPlayerModule.ts` (and the Kotlin `MpvBridgeModule.kt`
|
|
187
|
+
* `RCTDeviceEventEmitter` strings).
|
|
188
|
+
*
|
|
189
|
+
* Kept here (not in the bridge module) to avoid pulling the React
|
|
190
|
+
* context machinery into a pure-types module; the provider is the
|
|
191
|
+
* only consumer of this constant anyway.
|
|
192
|
+
*/
|
|
193
|
+
const ALL_PLAYER_EVENTS: readonly PlayerEventName[] = [
|
|
194
|
+
'onFileLoaded',
|
|
195
|
+
'onPlaybackStateChanged',
|
|
196
|
+
'onPositionChanged',
|
|
197
|
+
'onDurationChanged',
|
|
198
|
+
'onPropertyChanged',
|
|
199
|
+
'onTracksChanged',
|
|
200
|
+
'onChapterChanged',
|
|
201
|
+
'onVideoParamsChanged',
|
|
202
|
+
'onError',
|
|
203
|
+
'onBuffering',
|
|
204
|
+
'onCacheState',
|
|
205
|
+
'onSeekable',
|
|
206
|
+
'onSeeking',
|
|
207
|
+
'onEndFile',
|
|
208
|
+
'onPlaybackRestart',
|
|
209
|
+
'onEndReached',
|
|
210
|
+
'onAudioDeviceChanged',
|
|
211
|
+
'onVolumeChanged',
|
|
212
|
+
'onSpeedChanged',
|
|
213
|
+
'videoReconfig',
|
|
214
|
+
'onPipModeChanged',
|
|
215
|
+
'onPipPlayPause',
|
|
216
|
+
'onPipExpand',
|
|
217
|
+
'onPipClose',
|
|
218
|
+
];
|
|
219
|
+
|
|
220
|
+
/** How often the provider polls `getPosition` + `getDuration` from the bridge. */
|
|
221
|
+
const POSITION_POLL_INTERVAL_MS = 1000;
|
|
222
|
+
|
|
223
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
224
|
+
// PlayerProvider
|
|
225
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
226
|
+
|
|
126
227
|
export interface PlayerProviderProps {
|
|
127
228
|
/**
|
|
128
229
|
* Partial PlayerConfig — every field is optional and falls back to
|
|
@@ -161,7 +262,8 @@ export interface PlayerProviderProps {
|
|
|
161
262
|
|
|
162
263
|
/**
|
|
163
264
|
* Wraps the consumer app (or any subtree) and provides the resolved
|
|
164
|
-
* PlayerConfig + renderControls slot
|
|
265
|
+
* PlayerConfig + renderControls slot + live player state to all
|
|
266
|
+
* consumers below it.
|
|
165
267
|
*
|
|
166
268
|
* On mount and whenever the resolved config changes, the provider
|
|
167
269
|
* pushes the JSON-encoded config to the native side via
|
|
@@ -175,6 +277,22 @@ export interface PlayerProviderProps {
|
|
|
175
277
|
* tree with `<PlayerProvider renderControls={...}>` and the
|
|
176
278
|
* `<PlayerRoot>` component reads it via `useRenderControls()`.
|
|
177
279
|
*
|
|
280
|
+
* V13 Phase 51: in addition to config + renderControls, the provider
|
|
281
|
+
* now holds the live player state. The state is updated by:
|
|
282
|
+
* - **Initial hydration** (mount): synchronous bridge getters fill in
|
|
283
|
+
* position / duration / playback state / volume / mute / speed /
|
|
284
|
+
* loop / playlist / tracks / chapters / video params.
|
|
285
|
+
* - **Event subscriptions** (mount): all 22 mpv events are subscribed
|
|
286
|
+
* via `subscribePlayerEvent` and dispatched to `applyPlayerEvent`.
|
|
287
|
+
* - **1Hz position/duration poll** (mount): `setInterval` calls the
|
|
288
|
+
* sync `getPosition` / `getDuration` getters every 1000ms.
|
|
289
|
+
*
|
|
290
|
+
* State is held in a `useState` (rendered, for React) + `useRef`
|
|
291
|
+
* (current, for event handlers to read without stale closures) pair.
|
|
292
|
+
* On each event, we read the ref, compute the next state, write the
|
|
293
|
+
* ref, and call setState. This is the canonical "useRef + useState"
|
|
294
|
+
* pattern for "live state from imperative event sources".
|
|
295
|
+
*
|
|
178
296
|
* The provider is idempotent: re-rendering with the same config does
|
|
179
297
|
* not trigger an extra native push (the `JSON.stringify` dep is the
|
|
180
298
|
* cheap identity check).
|
|
@@ -184,10 +302,7 @@ export function PlayerProvider({
|
|
|
184
302
|
renderControls,
|
|
185
303
|
children,
|
|
186
304
|
}: PlayerProviderProps): React.ReactElement {
|
|
187
|
-
//
|
|
188
|
-
// consumers who create a fresh object on every render don't trigger
|
|
189
|
-
// a native push storm. The native side is a no-op when the JSON is
|
|
190
|
-
// identical to the previously-cached one.
|
|
305
|
+
// ── Config + renderControls (V12) ──────────────────────────────────────
|
|
191
306
|
const resolved = useMemo<ResolvedPlayerConfig>(
|
|
192
307
|
() => resolvePlayerConfig(config),
|
|
193
308
|
[JSON.stringify(config ?? {})],
|
|
@@ -212,10 +327,176 @@ export function PlayerProvider({
|
|
|
212
327
|
});
|
|
213
328
|
}, [resolved]);
|
|
214
329
|
|
|
330
|
+
// ── V13 Phase 51: live player state ────────────────────────────────────
|
|
331
|
+
const [state, setState] = useState<PlayerState>(DEFAULT_STATE);
|
|
332
|
+
const [progress, setProgress] = useState<PlayerProgress>(DEFAULT_PROGRESS);
|
|
333
|
+
// The refs are the source of truth for event handlers. They read the
|
|
334
|
+
// latest snapshot, apply their patch, and write back — this avoids
|
|
335
|
+
// the stale-closure trap of `useState` setters in long-lived event
|
|
336
|
+
// subscriptions.
|
|
337
|
+
const stateRef = useRef<PlayerState>(DEFAULT_STATE);
|
|
338
|
+
const progressRef = useRef<PlayerProgress>(DEFAULT_PROGRESS);
|
|
339
|
+
// Tracks whether the 1Hz poll should fire. The poll runs in a child
|
|
340
|
+
// effect that mounts the interval; the unmount cleanup is symmetric.
|
|
341
|
+
// We mount/unmount ONCE for the provider's lifetime (no deps), so
|
|
342
|
+
// the poll survives config changes.
|
|
343
|
+
|
|
344
|
+
// Initial hydration + event subscriptions + 1Hz poll all live in a
|
|
345
|
+
// single mount-only effect so they share the same lifecycle. (If we
|
|
346
|
+
// split them across multiple effects, the ref + state would briefly
|
|
347
|
+
// desync during the gap between hydration and subscription mount.)
|
|
348
|
+
useEffect(() => {
|
|
349
|
+
const bridge = getMpvPlayerModule();
|
|
350
|
+
|
|
351
|
+
// ── 1. Initial hydration from sync bridge getters ───────────────────
|
|
352
|
+
try {
|
|
353
|
+
const initial = hydratePlayerState(bridge);
|
|
354
|
+
stateRef.current = initial;
|
|
355
|
+
setState(initial);
|
|
356
|
+
const initialProgress: PlayerProgress = {
|
|
357
|
+
positionMs: initial.positionMs,
|
|
358
|
+
durationMs: initial.durationMs,
|
|
359
|
+
isBuffering: initial.isBuffering,
|
|
360
|
+
isSeeking: initial.isSeeking,
|
|
361
|
+
seekable: initial.seekable,
|
|
362
|
+
cacheRanges: [],
|
|
363
|
+
cacheFill: 0,
|
|
364
|
+
};
|
|
365
|
+
progressRef.current = initialProgress;
|
|
366
|
+
setProgress(initialProgress);
|
|
367
|
+
} catch (e) {
|
|
368
|
+
// Hydration is best-effort; if any getter throws we just keep
|
|
369
|
+
// the defaults. (A typical cause is a stub bridge in a test
|
|
370
|
+
// environment that doesn't implement every getter.)
|
|
371
|
+
// eslint-disable-next-line no-console
|
|
372
|
+
console.warn('[simba-player] hydratePlayerState failed:', e);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// ── 2. Subscribe to all 22 mpv events ───────────────────────────────
|
|
376
|
+
// Each event handler reads the current state + progress from the
|
|
377
|
+
// refs, applies the patch via the pure `applyPlayerEvent`
|
|
378
|
+
// reducer, writes back to the refs, and schedules a re-render
|
|
379
|
+
// via setState/setProgress. The functional setState form keeps
|
|
380
|
+
// the progress equality short-circuit correct under React's
|
|
381
|
+
// batching.
|
|
382
|
+
const unsubs: Array<() => void> = [];
|
|
383
|
+
for (const event of ALL_PLAYER_EVENTS) {
|
|
384
|
+
const unsub = subscribePlayerEvent(
|
|
385
|
+
event,
|
|
386
|
+
(payload: PlayerEventPayloads[typeof event]) => {
|
|
387
|
+
const { state: nextState, progress: nextProgress } =
|
|
388
|
+
applyPlayerEvent(
|
|
389
|
+
stateRef.current,
|
|
390
|
+
progressRef.current,
|
|
391
|
+
event,
|
|
392
|
+
payload,
|
|
393
|
+
);
|
|
394
|
+
// Skip the setState if the new state is reference-equal
|
|
395
|
+
// (a true no-op event for this state) — prevents
|
|
396
|
+
// re-render storms on `videoReconfig` / PiP no-ops.
|
|
397
|
+
if (nextState !== stateRef.current) {
|
|
398
|
+
stateRef.current = nextState;
|
|
399
|
+
setState(nextState);
|
|
400
|
+
}
|
|
401
|
+
// Progress: apply the patch via the functional setState
|
|
402
|
+
// form so we can compare against the previous value (the
|
|
403
|
+
// ref may have been updated by another event handler in
|
|
404
|
+
// the same batch).
|
|
405
|
+
setProgress((prev) => {
|
|
406
|
+
// Cheap reference + 7-field equality check.
|
|
407
|
+
if (
|
|
408
|
+
prev.positionMs === nextProgress.positionMs &&
|
|
409
|
+
prev.durationMs === nextProgress.durationMs &&
|
|
410
|
+
prev.isBuffering === nextProgress.isBuffering &&
|
|
411
|
+
prev.isSeeking === nextProgress.isSeeking &&
|
|
412
|
+
prev.seekable === nextProgress.seekable &&
|
|
413
|
+
prev.cacheFill === nextProgress.cacheFill &&
|
|
414
|
+
prev.cacheRanges.length === nextProgress.cacheRanges.length
|
|
415
|
+
) {
|
|
416
|
+
return prev;
|
|
417
|
+
}
|
|
418
|
+
progressRef.current = nextProgress;
|
|
419
|
+
return nextProgress;
|
|
420
|
+
});
|
|
421
|
+
},
|
|
422
|
+
);
|
|
423
|
+
unsubs.push(unsub);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// ── 3. 1Hz position/duration poll ───────────────────────────────────
|
|
427
|
+
// Both `getPosition` and `getDuration` are sync React methods
|
|
428
|
+
// on the bridge, so the poll doesn't queue microtasks. We
|
|
429
|
+
// also pick up the playback state (`getPlaybackState`) here
|
|
430
|
+
// as a backup for the event stream (e.g. if the consumer is
|
|
431
|
+
// mounted mid-playback and missed the `onPlaybackStateChanged`
|
|
432
|
+
// event).
|
|
433
|
+
const pollId = setInterval(() => {
|
|
434
|
+
try {
|
|
435
|
+
const posSec = bridge.getPosition();
|
|
436
|
+
const durSec = bridge.getDuration();
|
|
437
|
+
const positionMs = Number.isFinite(posSec)
|
|
438
|
+
? Math.round(posSec * 1000)
|
|
439
|
+
: stateRef.current.positionMs;
|
|
440
|
+
const durationMs = Number.isFinite(durSec)
|
|
441
|
+
? Math.round(durSec * 1000)
|
|
442
|
+
: stateRef.current.durationMs;
|
|
443
|
+
|
|
444
|
+
if (
|
|
445
|
+
positionMs === stateRef.current.positionMs &&
|
|
446
|
+
durationMs === stateRef.current.durationMs
|
|
447
|
+
) {
|
|
448
|
+
return; // no movement — skip the setState
|
|
449
|
+
}
|
|
450
|
+
const next: PlayerState = {
|
|
451
|
+
...stateRef.current,
|
|
452
|
+
positionMs,
|
|
453
|
+
durationMs,
|
|
454
|
+
};
|
|
455
|
+
stateRef.current = next;
|
|
456
|
+
setState(next);
|
|
457
|
+
const nextProgress: PlayerProgress = {
|
|
458
|
+
...progressRef.current,
|
|
459
|
+
positionMs,
|
|
460
|
+
durationMs,
|
|
461
|
+
};
|
|
462
|
+
progressRef.current = nextProgress;
|
|
463
|
+
setProgress(nextProgress);
|
|
464
|
+
} catch (e) {
|
|
465
|
+
// Bridge threw — keep the last known position. (The no-op
|
|
466
|
+
// bridge returns 0/0, which falls into the "no movement"
|
|
467
|
+
// early-return above, so it doesn't spam setState.)
|
|
468
|
+
// eslint-disable-next-line no-console
|
|
469
|
+
console.warn('[simba-player] position poll failed:', e);
|
|
470
|
+
}
|
|
471
|
+
}, POSITION_POLL_INTERVAL_MS);
|
|
472
|
+
|
|
473
|
+
// ── Cleanup ─────────────────────────────────────────────────────────
|
|
474
|
+
return () => {
|
|
475
|
+
for (const unsub of unsubs) {
|
|
476
|
+
try {
|
|
477
|
+
unsub();
|
|
478
|
+
} catch {
|
|
479
|
+
// never let a single bad unsub abort the rest
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
clearInterval(pollId);
|
|
483
|
+
// Best-effort: remove any lingering listeners from the emitter
|
|
484
|
+
// so the next mount of the provider starts clean. (Strict-mode
|
|
485
|
+
// double-invocation can otherwise leave phantom listeners.)
|
|
486
|
+
try {
|
|
487
|
+
removeAllListeners();
|
|
488
|
+
} catch {
|
|
489
|
+
// ignore — emitter may be absent in jest
|
|
490
|
+
}
|
|
491
|
+
};
|
|
492
|
+
}, []);
|
|
493
|
+
|
|
215
494
|
return (
|
|
216
495
|
<PlayerConfigContext.Provider value={resolved}>
|
|
217
496
|
<PlayerRenderControlsContext.Provider value={renderControls ?? null}>
|
|
218
|
-
{
|
|
497
|
+
<PlayerStateProvider state={state} progress={progress}>
|
|
498
|
+
{children}
|
|
499
|
+
</PlayerStateProvider>
|
|
219
500
|
</PlayerRenderControlsContext.Provider>
|
|
220
501
|
</PlayerConfigContext.Provider>
|
|
221
502
|
);
|