@simba-dev/react-native-media-player 2.0.1 → 2.1.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.
Files changed (34) hide show
  1. package/README.md +317 -560
  2. package/android/src/main/cpp/main.cpp +117 -17
  3. package/android/src/main/java/com/simba/player/PipManager.kt +13 -0
  4. package/android/src/main/java/com/simba/player/mpv/MpvBridgeModule.kt +177 -6
  5. package/android/src/main/java/com/simba/player/mpv/PipAutoEnterPolicy.kt +54 -0
  6. package/package.json +11 -2
  7. package/android/src/test/java/com/simba/player/PipActionReceiverTest.kt +0 -123
  8. package/android/src/test/java/com/simba/player/PipManagerTest.kt +0 -281
  9. package/android/src/test/java/com/simba/player/TestApplication.kt +0 -26
  10. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleNullInstanceTest.kt +0 -117
  11. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleTest.kt +0 -212
  12. package/android/src/test/java/com/simba/player/mpv/MpvRenderViewRegistryTest.kt +0 -120
  13. package/android/src/test/java/com/simba/player/mpv/MpvRenderViewTest.kt +0 -249
  14. package/scripts/override_react_methods.js +0 -184
  15. package/scripts/override_react_methods.py +0 -150
  16. package/src/bridge/__tests__/MpvPlayerModule.test.ts +0 -163
  17. package/src/bridge/__tests__/debugMode.test.ts +0 -138
  18. package/src/bridge/__tests__/errorContract.test.ts +0 -175
  19. package/src/bridge/__tests__/loadAndPlay.startPosition.test.tsx +0 -142
  20. package/src/components/__tests__/PlayerProvider.performance.test.tsx +0 -242
  21. package/src/components/__tests__/PlayerProvider.progressContext.test.tsx +0 -194
  22. package/src/components/__tests__/PlayerProvider.test.tsx +0 -558
  23. package/src/components/__tests__/PlayerRoot.test.tsx +0 -71
  24. package/src/components/__tests__/SimbaVideo.test.tsx +0 -164
  25. package/src/hooks/__tests__/resolveStreamType.test.ts +0 -159
  26. package/src/hooks/__tests__/useLaunchPlayback.test.tsx +0 -278
  27. package/src/hooks/__tests__/useResumeThumbnail.test.ts +0 -154
  28. package/src/stores/__tests__/playerQueueSelectionStore.test.ts +0 -73
  29. package/src/stores/__tests__/playerQueueStore.test.ts +0 -171
  30. package/src/types/__tests__/config.test.ts +0 -188
  31. package/src/types/__tests__/player.pipAnswer.test.tsx +0 -87
  32. package/src/types/__tests__/player.pipArity.test.tsx +0 -74
  33. package/src/types/__tests__/player.test.tsx +0 -1365
  34. package/src/types/__tests__/playerLoading.test.ts +0 -170
package/README.md CHANGED
@@ -1,6 +1,9 @@
1
1
  # @simba-dev/react-native-media-player
2
2
 
3
- React Native video & audio player powered by [libmpv](https://mpv.io/), with first-class **Picture-in-Picture**, **MediaSession**, **foreground service**, and a customizable TypeScript UI. Built for Android. Designed to be a drop-in replacement for `react-native-video` / `react-native-track-player` / `expo-av`.
3
+ React Native video and audio playback for Android, backed by [libmpv](https://mpv.io/).
4
+ One engine for both lanes: a MediaSession and a foreground service for audio, Picture-in-Picture for video.
5
+
6
+ The library renders the picture and exposes state and commands. It draws no controls of its own — your app supplies the chrome.
4
7
 
5
8
  ![Simba Player hero image — Android video player UI mockup](https://raw.githubusercontent.com/pavalep/react-native-media-player/main/assets/hero.svg)
6
9
 
@@ -17,48 +20,74 @@ React Native video & audio player powered by [libmpv](https://mpv.io/), with fir
17
20
  </p>
18
21
 
19
22
  <p align="left">
20
- <a href="https://github.com/pavalep/react-native-media-player/releases">📦 Releases</a>
23
+ <a href="https://github.com/pavalep/react-native-media-player/releases">Releases</a>
21
24
  &nbsp;·&nbsp;
22
- <a href="./CHANGELOG.md">📝 CHANGELOG</a>
25
+ <a href="https://github.com/pavalep/react-native-media-player/blob/main/CHANGELOG.md">CHANGELOG</a>
23
26
  &nbsp;·&nbsp;
24
- <a href="https://www.npmjs.com/package/@simba-dev/react-native-media-player">📦 npm package</a>
27
+ <a href="https://www.npmjs.com/package/@simba-dev/react-native-media-player">npm package</a>
25
28
  &nbsp;·&nbsp;
26
- <a href="https://github.com/pavalep/react-native-media-player/tags">🏷️ Tags</a>
29
+ <a href="https://github.com/pavalep/react-native-media-player/tags">Tags</a>
27
30
  </p>
28
31
 
29
- ## Table of contents
30
-
31
- 1. [What is `@simba-dev/react-native-media-player`?](#what-is-simbareact-native-media-player)
32
- 2. [Installation](#installation)
33
- 3. [Basic usage](#basic-usage)
34
- 4. [Custom UI](#custom-ui)
35
- 5. [Configuration](#configuration)
36
- 6. [Picture-in-Picture](#picture-in-picture)
37
- 7. [Background audio](#background-audio)
38
- 8. [Theming](#theming)
39
- 9. [API reference](#api-reference)
40
- 10. [Troubleshooting](#troubleshooting)
41
- 11. [Limitations](#limitations)
42
- 12. [Sponsor & support](#sponsor--support)
43
- 13. [Contributing](#contributing)
44
- 14. [License](#license)
32
+ ## Contents
33
+
34
+ 1. [What this is](#what-this-is)
35
+ 2. [What this is not](#what-this-is-not)
36
+ 3. [Requirements](#requirements)
37
+ 4. [Installation](#installation)
38
+ 5. [Consumer setup](#consumer-setup)
39
+ 6. [Quick start](#quick-start)
40
+ 7. [Controls](#controls)
41
+ 8. [Configuration](#configuration)
42
+ 9. [Picture-in-Picture](#picture-in-picture)
43
+ 10. [Background audio](#background-audio)
44
+ 11. [Theming](#theming)
45
+ 12. [API reference](#api-reference)
46
+ 13. [Troubleshooting](#troubleshooting)
47
+ 14. [Limitations](#limitations)
48
+ 15. [Contributing](#contributing)
49
+ 16. [License](#license)
45
50
 
46
51
  ---
47
52
 
48
- ## What is `@simba-dev/react-native-media-player`?
49
-
50
- A standalone NPM package that gives your React Native Android app a unified **video + audio** playback engine backed by **libmpv**. The same engine, the same MediaSession, the same foreground service — for both video and audio playback.
51
-
52
- **Highlights:**
53
-
54
- - **One Activity** — playback renders into a `SurfaceView` your app already hosts. There is no second player window to declare, and no second Activity to keep in sync with yours.
55
- - **Unified audio + video** — one engine, one set of controls. Audio files use the same `libmpv` instance with the surface hidden; no second player to maintain.
56
- - **In-window video** — the surface is mounted once and resized to whatever rect you give it, so a docked mini player shows a **live picture**, not a poster frame.
57
- - **Picture-in-Picture** — auto-enter on background (configurable), manual toggle, custom RemoteActions. Works correctly with the React Native view tree (no nested-SurfaceView surprises).
58
- - **MediaSession + lock-screen controls** — title / artist / album on the lock screen; play / pause / skip / seek from Bluetooth headphones, wired headsets, Android Auto, etc.
59
- - **Foreground service** — keeps audio alive when the activity backgrounds (Spotify-style behavior, opt-in).
60
- - **Customizable UI** — use `<DefaultControls>` out of the box, swap in your own via the `renderControls` prop, or build fully from scratch with `usePlayer` + `useTheme`.
61
- - **TypeScript-first** — every prop, hook, and config field is fully typed.
53
+ ## What this is
54
+
55
+ A playback engine for React Native on Android, backed by libmpv. One engine serves both audio and
56
+ video, and the two lanes meet in the same bridge:
57
+
58
+ - **One Activity.** The library declares no Activity. Playback happens inside the launcher Activity
59
+ your app already has; the video picture is `<SimbaVideo />` in your React tree.
60
+ - **One engine for audio and video.** Audio files play through the same libmpv instance with no
61
+ surface attached, so there is no second player to maintain.
62
+ - **MediaSession and foreground service.** Title, artist and album reach the lock screen and the
63
+ media notification; play, pause, stop, next, previous and seek are advertised to the session, so
64
+ headset buttons and Bluetooth controls work.
65
+ - **Picture-in-Picture.** Manual entry on demand, and OS-level auto-enter on leave from Android 12.
66
+ - **Typed surface.** Config, state, commands and hooks are all typed.
67
+
68
+ ## What this is not
69
+
70
+ - **Not a drop-in replacement for `react-native-video`, `expo-av` or `react-native-track-player`.**
71
+ Those expose a component you hand a `source` to. This one has a different shape: a provider, a
72
+ `<SimbaVideo />` picture, and `usePlayer()` for state and commands. There is no `<Video source={…} />`
73
+ here, and no adapter will make one.
74
+ - **Not a control surface.** Since 2.0.0 the library ships no controls at all — see
75
+ [Controls](#controls).
76
+ - **Not iOS.** `react-native.config.js` sets `ios: null`; there is no iOS implementation.
77
+ - **Not a legacy-bridge library.** The native package is a `TurboReactPackage`, so the New
78
+ Architecture is required (`newArchEnabled=true`).
79
+ - **Not a "clone the repo and build it" package.** The prebuilt libmpv binaries are downloaded at
80
+ install time — see [Installation](#installation).
81
+
82
+ ## Requirements
83
+
84
+ | | |
85
+ | --- | --- |
86
+ | React Native | `>= 0.76.0` (peer dependency) |
87
+ | React | `>= 18.0.0` (peer dependency) |
88
+ | Android | API 24+ (Android 7.0). PiP entry calls `Activity.enterPictureInPictureMode()`, which was added in API 24. `compileSdk` and `targetSdk` are inherited from your app's `rootProject.ext` — the library does not pin them. |
89
+ | JDK | 17. The library's Kotlin `jvmTarget` is 17. |
90
+ | New Architecture | Required. `PlayerPackage` extends `TurboReactPackage`. |
62
91
 
63
92
  ## Installation
64
93
 
@@ -66,22 +95,32 @@ A standalone NPM package that gives your React Native Android app a unified **vi
66
95
  npm install @simba-dev/react-native-media-player
67
96
  ```
68
97
 
69
- Autolinking handles the rest — RN's `react-native config` will find the package via the shipped [`react-native.config.js`](./react-native.config.js) and register `com.simba.player.PlayerPackage` in your `MainApplication.kt` automatically on next build.
98
+ Autolinking handles the rest: the shipped `react-native.config.js` tells React Native's CLI where
99
+ the Android module lives, so `com.simba.player.PlayerPackage` is registered in your
100
+ `MainApplication.kt` on the next build.
101
+
102
+ ### The native binaries
70
103
 
71
- ### Requirements
104
+ The `postinstall` script (`scripts/download-native.js`) downloads the prebuilt native libraries
105
+ (libmpv and friends) from the matching GitHub release, verifies the archive's SHA-256 and extracts
106
+ it into `android/src/main/jniLibs/<abi>/` inside the installed package. Four ABIs are published:
107
+ `arm64-v8a`, `armeabi-v7a`, `x86`, `x86_64`.
72
108
 
73
- - React Native **≥ 0.76** (bridgeless mode required)
74
- - Android `minSdk` **24** (Android 7.0 Nougat — needed for Picture-in-Picture)
75
- - Kotlin **1.9+** in the consumer app
109
+ The script is idempotent — if the binaries are already in place it exits without a network call,
110
+ so re-running `npm install` is safe. Set `SKIP_DOWNLOAD_NATIVE=1` to skip the download entirely
111
+ (this is what the release workflow does, because CI builds the binaries itself).
76
112
 
77
- ### Consumer setup
113
+ ## Consumer setup
78
114
 
79
- Nothing to register. The package ships its own `<service>` and `<receiver>` declarations, and playback renders into **your** existing launcher Activity — there is no player Activity to declare.
115
+ The package's own manifest declares a foreground service and a PiP action receiver. It declares no
116
+ Activity: playback happens in the Activity your app already has.
80
117
 
81
- Your launcher Activity does need the PiP prerequisites on Android 12+:
118
+ ### Picture-in-Picture
119
+
120
+ Your launcher Activity has to opt in:
82
121
 
83
122
  ```xml
84
- <!-- MOBILE_APP_REACT_NATIVE/android/app/src/main/AndroidManifest.xml -->
123
+ <!-- android/app/src/main/AndroidManifest.xml -->
85
124
  <activity
86
125
  android:name=".MainActivity"
87
126
  android:configChanges="orientation|screenSize|screenLayout|keyboardHidden|navigation"
@@ -97,9 +136,10 @@ Your launcher Activity does need the PiP prerequisites on Android 12+:
97
136
  </activity>
98
137
  ```
99
138
 
100
- `resizeableActivity="true"` is **not optional**. Its absence in an earlier release was misdiagnosed as "the SurfaceView is nested in React Native's view tree", which is what produced the original PiP black screen and the whole second-Activity architecture built on top of it.
139
+ `resizeableActivity="true"` is not optional. An Activity that is not resizeable cannot enter
140
+ Picture-in-Picture.
101
141
 
102
- If you plan to use **background audio**, declare the foreground-service permissions:
142
+ ### Background audio
103
143
 
104
144
  ```xml
105
145
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
@@ -107,621 +147,338 @@ If you plan to use **background audio**, declare the foreground-service permissi
107
147
  <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
108
148
  ```
109
149
 
110
- For **API 33+** (Android 13+) the app must request `POST_NOTIFICATIONS` at runtime before the first media-style notification is shown. The bridge's `requestNotificationPermission()` helper does this:
150
+ On Android 13+ (API 33) the app must hold `POST_NOTIFICATIONS` before the media notification is
151
+ shown. `commands.requestNotificationPermission()` asks for it; on older versions it does nothing.
111
152
 
112
- ```ts
113
- import { getMpvPlayerModule } from '@simba-dev/react-native-media-player';
114
- getMpvPlayerModule().requestNotificationPermission?.(); // graceful no-op on older APIs
115
- ```
153
+ ## Quick start
116
154
 
117
- ## Basic usage
155
+ The integration is **1 import + 1 wrapper + at most 1 optional adapter**.
118
156
 
119
157
  ```tsx
120
- // App.tsx — one wrapper, one import, zero glue code
158
+ // App.tsx
121
159
  import React from 'react';
122
- import {
123
- SimbaPlayer,
124
- useOpenFromUrl,
125
- } from '@simba-dev/react-native-media-player';
160
+ import {SimbaPlayer} from '@simba-dev/react-native-media-player';
126
161
 
127
162
  export default function App() {
128
163
  return (
129
- <SimbaPlayer
130
- getResumePosition={(uri) =>
131
- store.getState().bookmarks.byFileUri[uri]?.positionMs
132
- }
133
- >
134
- <AppContent />
164
+ <SimbaPlayer config={{audio: {backgroundPlayback: true}}}>
165
+ <RootNavigator />
135
166
  </SimbaPlayer>
136
167
  );
137
168
  }
138
-
139
- function AppContent() {
140
- // Deep links: open incoming content:// + file:// URIs in the player.
141
- const openFromUrl = useOpenFromUrl();
142
- React.useEffect(() => {
143
- Linking.getInitialURL().then(url => url && openFromUrl(url));
144
- const sub = Linking.addEventListener('url', ({ url }) => openFromUrl(url));
145
- return () => sub.remove();
146
- }, [openFromUrl]);
147
-
148
- return <YourNavigator />;
149
- }
150
169
  ```
151
170
 
152
- That's it — `<SimbaPlayer>` is the one-import, one-wrapper integration point. It composes the `PlayerProvider` (config + state) and `PlayerResumeProvider` (bookmark-aware resume lookup). `useOpenFromUrl()` absorbs the deep-link URI-scheme filter + title-derivation + extension-classification. `getResumePosition` is the function-prop shape for the resume lookup.
153
-
154
- To play media in-window, drive it with `useLaunchPlayback(payload)` from your own tree — it loads the payload into the surface you have mounted, exactly once per launch identity. There is no activity branch to switch on, because there is no second Activity.
155
-
156
- ### Per-screen usage (V15+)
171
+ `<SimbaPlayer>` composes `PlayerProvider` (config plus live player state) and
172
+ `PlayerResumeProvider` (the resume lookup). Its props are `config`, `resumePolicy` and
173
+ `children`.
157
174
 
158
- Every player-related call is a one-line module hook. No `useAppDispatch` in player files. No `useAppSelector(state => state.player.X)`. No V11-mirrored redux state.
175
+ ### Play something
159
176
 
160
177
  ```tsx
161
- import {
162
- usePlayerActivity, // single-track play
163
- useOpenPlaylist, // play all from a list
164
- useQueue, // add / remove / reorder queue items
165
- useSleepTimer, // arm a sleep timer
166
- useEqualizer, // 10-band EQ
167
- useIsLiked, // per-file "liked" state
168
- useShuffle, // shuffle flag
169
- } from '@simba-dev/react-native-media-player';
170
-
171
- // Single-track play (V14, unchanged)
172
- const {openPlayer} = usePlayerActivity();
173
- const handlePlay = (item) => openPlayer({uri: item.uri, title: item.title, type: 'audio'});
174
-
175
- // Play all from a list (V15 — the "play all" two-step absorption)
176
- const {openPlaylist} = useOpenPlaylist();
177
- const handlePlayAll = () => openPlaylist(sortedTracks, {type: 'audio'});
178
+ import {usePlayerActivity} from '@simba-dev/react-native-media-player';
178
179
 
179
- // Add to queue (V15 — zustand-backed, no Redux)
180
- const {addToQueue} = useQueue();
181
- const handleAddToQueue = (item) => addToQueue({uri: item.uri, title: item.title, ...});
180
+ const {openPlayer} = usePlayerActivity();
182
181
 
183
- // Set sleep timer (V15 — public surface; the consumer hasn't wired UI yet)
184
- const {endTime, setTimer, clear} = useSleepTimer();
185
- const handleSet30Min = () => setTimer(30 * 60); // 30 minutes
182
+ await openPlayer({
183
+ uri: 'https://example.com/movie.mkv',
184
+ title: 'Movie',
185
+ type: 'video',
186
+ });
186
187
  ```
187
188
 
188
- ### Launching a file from JS
189
+ `type: 'audio'` starts the foreground media service. `type: 'video'` loads into the mounted
190
+ `<SimbaVideo />` and resolves `false` when no surface is mounted — check `commands.isSurfaceMounted()`
191
+ if you expected it to work and it did not.
192
+
193
+ ### Render the picture
189
194
 
190
195
  ```tsx
191
- import { usePlayerActivity } from '@simba-dev/react-native-media-player';
196
+ import {SimbaVideo} from '@simba-dev/react-native-media-player';
192
197
 
193
- function TrackRow({ track }) {
194
- const { openPlayer } = usePlayerActivity();
195
- return (
196
- <Pressable onPress={() => openPlayer({
197
- uri: track.uri,
198
- title: track.title,
199
- type: 'audio', // 'video' | 'audio'
200
- startPositionMs: 0, // optional
201
- })}>
202
- <Text>{track.title}</Text>
203
- </Pressable>
204
- );
205
- }
206
- // Audio starts the foreground service; video loads into the surface
207
- // your app already has mounted. Either way you own the chrome.
198
+ <SimbaVideo style={{flex: 1}} resizeMode="contain" />;
208
199
  ```
209
200
 
210
- ### Resume-aware openPlayer (with bookmarks)
201
+ `resizeMode` is `'contain' | 'cover' | 'stretch'` and defaults to `'contain'`.
211
202
 
212
- 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.
203
+ ### Drive it
213
204
 
214
205
  ```tsx
215
- // App.tsx
216
- import { SimbaPlayer, type PlayerResumeLookup } from '@simba-dev/react-native-media-player';
217
-
218
- const resumeLookup: PlayerResumeLookup = {
219
- getResumePosition: (resumeId) => {
220
- // resolve the resume position (ms) for the given item
221
- // — return undefined for "no saved position"
222
- return store.getState().bookmarks.byFileUri[resumeId]?.positionMs;
223
- },
224
- };
225
-
226
- <SimbaPlayer lookup={resumeLookup}>
227
- <AppContent />
228
- </SimbaPlayer>
206
+ import {usePlayer, usePlayerProgress} from '@simba-dev/react-native-media-player';
229
207
 
230
- // TrackRow.tsx
231
- import { useOpenWithResume } from '@simba-dev/react-native-media-player';
208
+ function Controls() {
209
+ const {state, commands} = usePlayer();
210
+ const {positionMs, durationMs} = usePlayerProgress();
232
211
 
233
- function TrackRow({ track }) {
234
- const openPlayer = useOpenWithResume();
235
212
  return (
236
- <Pressable onPress={() => openPlayer({
237
- uri: track.uri,
238
- title: track.title,
239
- type: 'audio',
240
- resumeId: track.uri, // module looks up the saved position
241
- })}>
242
- <Text>{track.title}</Text>
243
- </Pressable>
213
+ <View>
214
+ <Text>
215
+ {Math.floor(positionMs / 1000)} / {Math.floor(durationMs / 1000)}
216
+ </Text>
217
+ <Button
218
+ title={state.isPlaying ? 'Pause' : 'Play'}
219
+ onPress={commands.togglePlayPause}
220
+ />
221
+ </View>
244
222
  );
245
223
  }
246
224
  ```
247
225
 
248
- ### Mapping content kinds to V13 stream types
226
+ `usePlayer()` returns `{state, commands}`. `usePlayerProgress()` returns the progress object
227
+ directly (`positionMs`, `durationMs`, `isBuffering`, `isSeeking`, `seekable`, `cacheRanges`,
228
+ `cacheFill`).
249
229
 
250
- If your items have content kinds like `'music'`, `'movie'`, `'podcast'` (not the V13 stream types `'audio' | 'video'`), use the `resolveStreamType` helper:
230
+ ### Optional adapter: resume positions
251
231
 
252
232
  ```tsx
253
- import { usePlayerActivity, resolveStreamType } from '@simba-dev/react-native-media-player';
254
-
255
- const { openPlayer } = usePlayerActivity();
256
- openPlayer({
257
- uri: item.uri,
258
- title: item.title,
259
- type: resolveStreamType(item.kind), // 'music' -> 'audio', 'movie' -> 'video', etc.
260
- });
233
+ <SimbaPlayer resumePolicy={(id) => bookmarks.byId[id]?.positionMs}>
234
+ <RootNavigator />
235
+ </SimbaPlayer>
261
236
  ```
262
237
 
263
- ## Custom UI
238
+ `resumePolicy` receives the `resumeId` you pass to `useOpenWithResume()` and returns a saved
239
+ position in milliseconds, or `undefined` when there is none.
264
240
 
265
- Two ways to swap the controls:
241
+ ## Controls
266
242
 
267
- ### 1. `renderControls` prop (recommended)
243
+ **The library draws no controls.** That has been the contract since 2.0.0.
268
244
 
269
- ```tsx
270
- import React from 'react';
271
- import { Pressable, Text, View } from 'react-native';
272
- import {
273
- PlayerProvider,
274
- PlayerRoot,
275
- usePlayer,
276
- useTheme,
277
- } from '@simba-dev/react-native-media-player';
278
-
279
- function MyCustomControls() {
280
- const { state, commands } = usePlayer();
281
- const theme = useTheme();
282
- return (
283
- <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
284
- <Text style={{ color: theme.text }}>{state.title}</Text>
285
- <Pressable onPress={state.isPlaying ? commands.pause : commands.play}>
286
- <Text style={{ color: theme.accent, fontSize: 24 }}>
287
- {state.isPlaying ? '⏸' : '▶'}
288
- </Text>
289
- </Pressable>
290
- </View>
291
- );
292
- }
293
-
294
- export default function App() {
295
- return (
296
- <PlayerProvider renderControls={() => <MyCustomControls />}>
297
- <PlayerRoot />
298
- </PlayerProvider>
299
- );
300
- }
301
- ```
245
+ `<DefaultControls>` — the default control bundle the package used to ship — was **removed in
246
+ 2.0.0**. The export no longer exists, and `<PlayerRoot>` no longer falls back to it. If you were
247
+ using it, keep your own copy in your app or render your own controls; the library will not supply
248
+ them.
302
249
 
303
- The `renderControls` function takes no arguments — your component reads what it needs (`usePlayer`, `useTheme`, `usePlayerProgress`) from the provider context. When omitted, `<PlayerRoot>` falls back to `<DefaultControls>`.
250
+ There are two ways to have chrome, and you can mix them:
304
251
 
305
- ### 2. Build fully from scratch
306
-
307
- Skip `<PlayerRoot>` entirely and lay out your own tree:
252
+ 1. **Render your own component** wherever you want it, reading `usePlayer()`,
253
+ `usePlayerProgress()` and `useTheme()`. Nothing else is needed.
254
+ 2. **Use the `renderControls` slot** on `<PlayerProvider>`. The function returns the tree to draw
255
+ over the picture, and `<PlayerRoot>` positions it in an absolutely positioned overlay:
308
256
 
309
257
  ```tsx
310
- import React from 'react';
311
- import { View } from 'react-native';
312
- import { PlayerProvider, PlayerSurface } from '@simba-dev/react-native-media-player';
313
- import { MyControls } from './MyControls';
314
-
315
- export default function App() {
316
- return (
317
- <PlayerProvider>
318
- <View style={{ flex: 1 }}>
319
- <PlayerSurface />
320
- {/* your own controls, positioned absolutely over the surface */}
321
- <View style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
322
- <MyControls />
323
- </View>
324
- </View>
325
- </PlayerProvider>
326
- );
327
- }
258
+ <PlayerProvider config={config} renderControls={() => <MyControls />}>
259
+ <PlayerRoot />
260
+ </PlayerProvider>
328
261
  ```
329
262
 
330
- ## Configuration
263
+ `renderControls` takes no arguments — read what you need from the hooks inside your component.
264
+ The slot is JS-only: it is never sent to the native side. `useRenderControls()` returns the slot,
265
+ or `null` when there is none.
331
266
 
332
- Pass a `config` prop to `<PlayerProvider>`:
267
+ `<PlayerRoot>` renders `<PlayerSurface />` — a transparent `flex: 1` layout placeholder — plus the
268
+ overlay. The picture itself is `<SimbaVideo />`; `<PlayerSurface>` is not the video surface.
333
269
 
334
- ```tsx
335
- <PlayerProvider
336
- config={{
337
- theme: { accent: '#00FF88' },
338
- pip: { enabled: true, autoEnterOnLeave: true },
339
- audio: { backgroundPlayback: true, respectAudioFocus: true },
340
- hardwareDecoding: 'auto', // 'auto' | 'mediacodec' | 'no'
341
- notifications: { enabled: true, channelId: 'my_app_media' },
342
- subtitle: { preferredLanguages: ['en'], fontSize: 18 },
343
- debug: { verboseLogging: false },
344
- }}
345
- >
346
- {children}
347
- </PlayerProvider>
348
- ```
349
-
350
- Every field is optional and falls back to the defaults in [`DEFAULT_PLAYER_CONFIG`](./src/types/config.ts). See the [API reference](#api-reference) for the full type definitions.
270
+ ## Configuration
351
271
 
352
- ### Spread-and-override pattern
272
+ `config` is a `PlayerConfig`. Every field is optional and merged with the defaults by
273
+ `resolvePlayerConfig`.
353
274
 
354
- For minor overrides, spread the defaults:
275
+ | Section | Fields | Default |
276
+ | --- | --- | --- |
277
+ | `theme` | `accent`, `background`, `text`, `textSecondary`, `surface`, `icon?` | `#FFD700`, `#121216`, `#FFFFFF`, `rgba(255,255,255,0.6)`, `rgba(255,255,255,0.1)` |
278
+ | `pip` | `enabled`, `autoEnterOnLeave` | `true`, `true` |
279
+ | `hardwareDecoding` | `'auto' \| 'mediacodec' \| 'no'` | `'auto'` |
280
+ | `notifications` | `enabled`, `channelId` | `true`, `'simba_player_media'` |
281
+ | `audio` | `backgroundPlayback`, `respectAudioFocus` | `true`, `true` |
282
+ | `subtitle` | `preferredLanguages`, `fontSize` | `[]`, `16` |
283
+ | `debug` | `verboseLogging` | `false` |
355
284
 
356
285
  ```tsx
357
- import { DEFAULT_PLAYER_CONFIG } from '@simba-dev/react-native-media-player';
286
+ import {PlayerProvider} from '@simba-dev/react-native-media-player';
358
287
 
359
288
  <PlayerProvider
360
289
  config={{
361
- ...DEFAULT_PLAYER_CONFIG,
362
- audio: { ...DEFAULT_PLAYER_CONFIG.audio, backgroundPlayback: false },
363
- }}
364
- >
290
+ theme: {accent: '#00FF88'},
291
+ pip: {enabled: true, autoEnterOnLeave: true},
292
+ audio: {backgroundPlayback: true, respectAudioFocus: true},
293
+ hardwareDecoding: 'auto',
294
+ }}>
295
+ <App />
296
+ </PlayerProvider>;
365
297
  ```
366
298
 
299
+ The resolved config is pushed to the native bridge as JSON. The native side acts on the PiP
300
+ section (it drives the auto-enter switch); the remaining sections are values your app reads back
301
+ with `usePlayerConfig()` and applies itself. `DEFAULT_PLAYER_CONFIG` and `DEFAULT_THEME` are
302
+ exported if you would rather spread and patch.
303
+
367
304
  ## Picture-in-Picture
368
305
 
369
- Picture-in-Picture is on by default. Two configuration knobs:
306
+ Manual entry:
370
307
 
371
308
  ```tsx
372
- <PlayerProvider
373
- config={{
374
- pip: {
375
- enabled: true, // master switch — when false, all PiP entry requests are ignored
376
- autoEnterOnLeave: true, // auto-enter on home/recents/app-switcher
377
- },
378
- }}
379
- >
309
+ commands.enterPip(); // chapter title and progress are optional arguments
310
+ commands.exitPip();
311
+ commands.exitPipAndFinish();
380
312
  ```
381
313
 
382
- ### Manual PiP control
314
+ `enterPip()` calls `enterPictureInPictureMode()` on the current Activity, so the Activity has to
315
+ declare `android:supportsPictureInPicture="true"` (see [Consumer setup](#consumer-setup)).
383
316
 
384
- ```tsx
385
- import { NativeModules } from 'react-native';
386
- const { MpvPlayerModule } = NativeModules;
317
+ **Auto-enter on leave** is `config.pip.autoEnterOnLeave` (default `true`). It maps onto the
318
+ Android 12 / API 31 platform feature `PictureInPictureParams.Builder.setAutoEnterEnabled`: the
319
+ OS enters Picture-in-Picture for you when the user leaves the app. **Below API 31 the platform
320
+ has no such feature** — the OS cannot auto-enter Picture-in-Picture there, and entry stays manual
321
+ through `commands.enterPip()`.
387
322
 
388
- MpvPlayerModule.enterPip(); // enter PiP right now
389
- MpvPlayerModule.exitPip(); // expand back to fullscreen
390
- MpvPlayerModule.exitPipAndFinish(); // close the player session
391
- ```
323
+ The two PiP flags combine: auto-enter needs `pip.enabled` and `pip.autoEnterOnLeave` to both be
324
+ true.
392
325
 
393
- ### PiP RemoteActions
326
+ The Picture-in-Picture action row has three buttons: **Play/Pause**, **Expand** and **Close**.
327
+ They arrive in JS as the `onPipPlayPause`, `onPipExpand` and `onPipClose` events, next to
328
+ `onPipModeChanged`.
394
329
 
395
- The module's lock-screen / PiP notification exposes Play / Pause / Skip-Back / Skip-Forward actions out of the box. Custom actions are not yet exposed via the public TS API — see the [Limitations](#limitations) section.
330
+ The media notification and lock screen are a separate surface. Its MediaSession advertises play,
331
+ pause, play/pause, stop, skip-to-next, skip-to-previous and seek-to, with title, artist and album
332
+ metadata.
396
333
 
397
334
  ## Background audio
398
335
 
399
- Audio files keep playing when the user backgrounds the app (Spotify-style). Video files always pause on background — this is intentional, see the [audio unification rationale](#limitations).
400
-
401
- To disable background audio:
402
-
403
- ```tsx
404
- <PlayerProvider
405
- config={{ audio: { backgroundPlayback: false } }}
406
- >
407
- ```
408
-
409
- When `backgroundPlayback` is enabled, the module starts a foreground service (`com.simba.player.MediaPlaybackService`) that hosts the MediaSession + media-style notification. The notification's transport controls work on the lock screen, in Android Auto, on Bluetooth headphones (play / pause / skip), and via Google Assistant.
336
+ `audio.backgroundPlayback` defaults to `true`: audio keeps playing when the app is backgrounded,
337
+ through the foreground media service. Video is the Picture-in-Picture lane instead — it does not
338
+ keep playing in the background.
410
339
 
411
340
  ## Theming
412
341
 
413
- Every color in `<DefaultControls>` comes from the `PlayerTheme` slice of the config:
414
-
415
342
  ```tsx
416
- <PlayerProvider
417
- config={{
418
- theme: {
419
- accent: '#FFD700', // play button, progress fill
420
- background: '#121216', // surface background
421
- text: '#FFFFFF', // primary text
422
- textSecondary: 'rgba(255,255,255,0.6)', // subtitles, time labels
423
- surface: 'rgba(255,255,255,0.1)', // floating cards, icon backgrounds
424
- icon: '#FFFFFF', // optional — defaults to `text`
425
- },
426
- }}
427
- >
428
- ```
429
-
430
- Read the theme from a custom component:
431
-
432
- ```tsx
433
- import { useTheme } from '@simba-dev/react-native-media-player';
343
+ import {useTheme} from '@simba-dev/react-native-media-player';
434
344
 
435
345
  const theme = useTheme();
436
- <View style={{ backgroundColor: theme.background }} />;
346
+ // {accent, background, text, textSecondary, surface, icon?}
437
347
  ```
438
348
 
439
- Default theme is dark with a golden accent (`DEFAULT_THEME`).
440
-
441
349
  ## API reference
442
350
 
443
- 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.
444
-
445
- ### Components (V13+ recommended, V14 additions in **bold**)
446
-
447
- | Component | Purpose |
448
- |---|---|
449
- | `<SimbaPlayer>` | **One-import, one-wrapper integration.** Composes `PlayerProvider` + `PlayerResumeProvider`. Adds the `getResumePosition` function prop (alongside the legacy `lookup` object prop). Use this at the app root. |
450
- | `<PlayerRoot>` | Renders `<PlayerSurface>` + the controls overlay (default `<DefaultControls>` or custom via `renderControls`). |
451
- | `<PlayerSurface>` | `<View flex:1>` placeholder for the native SurfaceView. a11y-hidden. |
452
- | `<DefaultControls>` | Pre-built controls (top bar, scrubber, transport, auto-hide). |
453
- | `<PlayerProvider>` | (V12 surface) Wraps the app; provides resolved config + `renderControls` slot. Use `<SimbaPlayer>` instead unless you need the raw provider. |
454
-
455
- ### Hooks (V13+, V14 additions in **bold**, V15 additions in __bold-italic__)
456
-
457
- | Hook | Returns | Throws outside provider? |
458
- |---|---|---|
459
- | `usePlayerActivity()` | `{ openPlayer(opts) }` - `audio` starts the foreground service; `video` loads into the mounted surface and resolves `false` if there is none. | ❌ No (no-op fallback) |
460
- | `useOpenWithResume()` | `(opts: OpenPlayerOptions & { resumeId? }) => Promise<boolean>` | ❌ No (no-op lookup) |
461
- | **`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 |
462
- | **`useOpenPlaylist()`** | __V15 — `{ openPlaylist(entries, opts) }` — "play all from a list" two-step absorption. `opts: { type?, startIndex?, startPositionMs?, shuffle?, startExtras? }`__ | ❌ No |
463
- | **`useSimbaPlayerLookup(selector?)`** | **`PlayerResumeLookup`** — **factory hook** that wraps an optional `selector` in a memoized lookup object. Without a selector, returns no-op. | ❌ No |
464
- | __`useQueue()` / `useQueueItems()` / `useQueueLength()` / `usePlaybackHistory()`__ | __V15 — queue + playback history state (zustand-backed). `useQueue()` returns the full store (queue, history, 9 actions: addToQueue, prependToQueue, removeFromQueue, reorderQueue, clearQueue, shuffleQueue, playFromQueue, addToPlaybackHistory, clearPlaybackHistory).__ | ❌ No |
465
- | __`useQueueSelection()` / `useQueueSelectedIndices()`__ | __V15 — multi-select state for the queue (selected indices + 4 actions: setSelection, clearSelection, removeSelected, moveSelectedToTop).__ | ❌ No |
466
- | __`useSleepTimer()` / `useSleepTimerEnd()` / `useSleepTimerMode()`__ | __V15 — sleep timer state (endTime + mode) + actions (setTimer, setMode, clear).__ | ❌ No |
467
- | __`useEqualizer()` / `useEqualizerEnabled()`__ | __V15 — 10-band equalizer (gains + enabled) + actions (setGains, toggle).__ | ❌ No |
468
- | __`useIsLiked(uri)` / `useToggleLiked()`__ | __V15 — per-file "liked" state (Record<uri, boolean>) + toggle action.__ | ❌ No |
469
- | __`useShuffle()` / `useShuffleEnabled()`__ | __V15 — shuffle flag + toggle action.__ | ❌ No |
470
- | `usePlayItem()` | `(item, opts) => Promise<boolean>` | ❌ No (sugar on `useOpenWithResume`) |
471
- | `usePlayer()` | `{ state: PlayerState, commands: PlayerCommands, progress: PlayerProgress }` | ❌ No (returns defaults) |
472
- | `usePlayerProgress()` | `{ positionMs, durationMs, isBuffering, isSeeking, seekable, cacheRanges, cacheFill }` | ❌ No (returns 0/0) |
473
- | `usePlayerConfig()` | `ResolvedPlayerConfig` | ✅ Yes (programmer error) |
474
- | `useTheme()` | `PlayerTheme` | ✅ Yes (programmer error) |
475
- | `useRenderControls()` | `RenderControlsFn \| null` | ❌ No (falls back to default controls) |
476
-
477
- ### Types (V13+)
478
-
479
- | Type | Notes |
480
- |---|---|
481
- | `PlayerState` | 20 fields: `isPlaying`, `title`, `artist`, `album`, `positionMs`, `durationMs`, `isBuffering`, `isSeeking`, `seekable`, `volume`, `isMuted`, `speed`, `loopMode`, `playlist`, `currentIndex`, `tracks`, `chapters`, `currentChapter`, `videoParams`, `error` |
482
- | `PlayerProgress` | 7 fields: `positionMs`, `durationMs`, `isBuffering`, `isSeeking`, `seekable`, `cacheRanges`, `cacheFill` |
483
- | `PlayerCommands` | 38 methods: `play`, `pause`, `seek`, `skipBackward`, `skipForward`, `togglePlayPause`, `stop`, `seekBy`, `seekToChapter`, `next`, `previous`, `setVolume`, `setMuted`, `toggleMute`, `setSpeed`, `setLoopMode`, `loadFile`, `loadPlaylist`, `playlistRemove`, `shuffle`, `clear`, `cycleTrack`, `setTrack`, `enterPip`, `exitPip`, `exitPipAndFinish`, `setKeepScreenOn`, `setOrientation`, `setImmersive`, `setScreenBrightness`, `requestNotificationPermission`, `openPlayer`, `getProperty`, `setProperty`, `observeProperty`, `unobserveProperty`, `grantPersistablePermission`, `verifyContentUri` |
484
- | `OpenPlayerOptions` | `{ uri, title, type: 'video' \| 'audio', startPositionMs? }` — the V13 `openPlayer` arg shape (replaces V11's positional args) |
485
- | `LaunchParams` | `{ uri, title, type, startPositionMs, requestId? }` - one playback launch payload. Pass it to `useLaunchPlayback(...)` to load it in-window. `requestId` gives the launch a unique identity so re-launching the same file at the same position still reloads. |
486
- | `ContentKind` | `'video' \| 'audio' \| 'music' \| 'movie' \| 'podcast' \| 'live-tv' \| 'radio' \| 'audiobook' \| 'archive-audio' \| 'episode' \| 'video-file' \| string` |
487
- | `PlayerResumeLookup` | `{ getResumePosition(itemId: string): number \| undefined }` — adapter for the bookmark-aware resume lookup |
488
- | **`GetResumePosition`** | **V14 — `(itemId: string) => number \| undefined`** — the function reference shape for `<SimbaPlayer getResumePosition={...}>` |
489
- | `SimbaPlayerProps` | `{ config?, lookup?, getResumePosition?, children }` — V14 adds `getResumePosition` (function prop, recommended). If both `lookup` and `getResumePosition` are passed, `getResumePosition` wins. |
490
- | `MpvPlayerModuleBridge` | Typed view of the native module (78 methods) |
491
- | `PlayerConfig`, `ResolvedPlayerConfig`, `PlayerTheme`, `PipConfig`, `AudioConfig`, `SubtitleConfig`, `NotificationConfig`, `DebugConfig`, `HardwareDecodingPolicy` | V12 surface — same as before |
492
- | `MpvTrack`, `MpvChapter`, `MpvFileInfo`, `MpvVideoParams`, `MpvAudioDevice`, `MpvPlaybackState`, `MpvLoopMode`, `MpvEventName`, `MpvEvents`, `MpvEventPayloads`, `PlayerEventName`, `PlayerEventPayloads` | Low-level mpv types |
493
-
494
- ### Constants
495
-
496
- | Constant | Description |
497
- |---|---|
498
- | `DEFAULT_THEME` | Dark theme with golden accent |
499
- | `DEFAULT_PLAYER_CONFIG` | Fully-resolved default config (useful for spread-and-override) |
500
-
501
- ### Functions
502
-
503
- | Function | Description |
504
- |---|---|
505
- | `resolvePlayerConfig(config)` | Merge a partial config with defaults — useful for tests / debug overlays |
506
- | `getMpvPlayerModule()` | Typed wrapper over `NativeModules.MpvPlayerModule`. Returns a no-op stub on non-RN platforms (jest, web). |
507
- | `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'`. |
508
- | `subscribePlayerEvent(name, handler)` → unsubscribe | Subscribe to a native mpv event (22 events). Returns an unsubscribe function. |
509
- | `removeAllListeners(event?)` | Remove all listeners for an event (or all events if no arg). |
351
+ ### Components
352
+
353
+ | Export | Props | Notes |
354
+ | --- | --- | --- |
355
+ | `<SimbaPlayer>` | `config?`, `resumePolicy?`, `children` | The one-import integration point. Composes `PlayerProvider` + `PlayerResumeProvider`. `resumePolicy: (itemId: string) => number \| undefined`. |
356
+ | `<PlayerProvider>` | `config?`, `renderControls?`, `children` | Resolved config, live player state, and the controls slot. |
357
+ | `<PlayerRoot>` | `launchParams?` | The surface placeholder plus the controls overlay. `launchParams` is a `{uri, title, type, startPositionMs, requestId?}` payload; it is loaded once per `(uri, startPositionMs)` pair. |
358
+ | `<SimbaVideo>` | `resizeMode?` + standard view props | The picture. `resizeMode`: `'contain' \| 'cover' \| 'stretch'`, default `'contain'`. |
359
+ | `<PlayerSurface>` | `backgroundColor?` | A transparent `flex: 1` layout placeholder. Not the video surface. |
360
+
361
+ ### Hooks
362
+
363
+ | Export | Returns |
364
+ | --- | --- |
365
+ | `usePlayer()` | `{state, commands}` |
366
+ | `usePlayerProgress()` | `PlayerProgress` — `positionMs`, `durationMs`, `isBuffering`, `isSeeking`, `seekable`, `cacheRanges`, `cacheFill` |
367
+ | `usePlayerConfig()` | The resolved `ResolvedPlayerConfig`. Throws outside a `<PlayerProvider>`. |
368
+ | `useTheme()` | The resolved `PlayerTheme`. |
369
+ | `useRenderControls()` | The `renderControls` slot, or `null`. |
370
+ | `usePlayerActivity()` | `{openPlayer(opts)}` → `Promise<boolean>` |
371
+ | `useOpenWithResume()` | `(opts & {resumeId?}) => Promise<boolean>` — resolves the resume position through the nearest `<SimbaPlayer>`'s `resumePolicy`. |
372
+ | `usePlayItem()` | `({id, uri, title}, {type}) => Promise<boolean>` |
373
+ | `useOpenFromUrl()` | `(uri: string) => Promise<boolean>` — accepts `content://` and `file://` URIs, derives a title, classifies the type and opens it. |
374
+ | `useOpenPlaylist()` | `{openPlaylist(entries, opts?)}` → `Promise<boolean>` |
375
+ | `useLaunchPlayback()` | `(launchParams)` — loads a payload once per `(uri, startPositionMs)` pair. |
376
+ | `useQueue()` / `useQueueLength()` / `useQueueItems()` / `useQueueItemsAs()` | The queue store and convenience selectors. |
377
+ | `usePlaybackHistory()` / `usePlaybackHistoryAs()` | The playback history. |
378
+ | `useQueueSelection()` / `useQueueSelectedIndices()` | The selection store. |
379
+
380
+ `openPlayer` accepts `{uri, title, type, startPositionMs?, artworkPath?, artist?, album?}`. The
381
+ artwork, artist and album fields apply to the audio lane only.
382
+
383
+ The queue store's actions are `addToQueue`, `prependToQueue`, `removeFromQueue`,
384
+ `removeFromQueueByIndex`, `reorderQueue`, `clearQueue`, `shuffleQueue`, `addToPlaybackHistory` and
385
+ `clearPlaybackHistory`.
386
+
387
+ `captureFrame(uri, positionMs, options?)` returns a `Promise<string | null>` — a JPEG written for
388
+ that position in that file. The defaults are 640×360 at quality 80, exported as
389
+ `DEFAULT_FRAME_WIDTH`, `DEFAULT_FRAME_HEIGHT` and `DEFAULT_FRAME_QUALITY`.
390
+
391
+ ### Commands
392
+
393
+ `commands` is a stable object; every method resolves the bridge at call time.
394
+
395
+ | Group | Methods |
396
+ | --- | --- |
397
+ | Transport | `play`, `pause`, `togglePlayPause`, `stop`, `stopPlayback`, `next`, `previous` |
398
+ | Seeking | `seek(positionMs)`, `seekBy(deltaMs)`, `skipForward(seconds)`, `skipBackward(seconds)`, `seekToChapter(index)` |
399
+ | Volume and speed | `setVolume(0..100)`, `setMuted(boolean)`, `toggleMute()`, `setSpeed(number)`, `setLoopMode('none' \| 'file' \| 'playlist')` |
400
+ | Playlist | `loadFile(uri, title?)`, `loadPlaylist(uris, startIndex?)`, `playlistRemove(index)`, `shuffle()`, `clear()`, `setShuffle(boolean)` |
401
+ | Tracks | `cycleTrack(type)`, `setTrack(type, trackId)` |
402
+ | Picture-in-Picture | `enterPip(chapterTitle?, progressPct?)`, `exitPip()`, `exitPipAndFinish()` |
403
+ | Screen | `setKeepScreenOn(boolean)`, `setOrientation(mode)`, `setImmersive(boolean)`, `setScreenBrightness(0..1)`, `getScreenBrightness()` |
404
+ | Surface | `setVideoBounds(x, y, width, height)`, `fillVideoBounds()`, `setSurfaceVisible(boolean)`, `isSurfaceMounted()` |
405
+ | Filters | `setAudioFilter(name, enabled)`, `setVideoFilter(name, enabled)` |
406
+ | Notifications | `requestNotificationPermission()` |
407
+ | mpv properties | `getProperty(name)`, `setProperty(name, value)`, `observeProperty(name)`, `unobserveProperty(name)` |
408
+ | Content URIs | `grantPersistablePermission(uri)`, `verifyContentUri(uri)` |
409
+
410
+ ### Bridge
411
+
412
+ `getMpvPlayerModule()` returns the native module, or a no-op stand-in when the native side is
413
+ not wired (Jest, web previews) so consumer code stays renderable.
414
+ `subscribePlayerEvent(name, handler)` subscribes to one of the 26 named events and returns an
415
+ unsubscribe function; `removeAllListeners()`, `setDebugLogging()` and
416
+ `dumpObservedProperties()` are also exported. The event names are typed as `PlayerEventName`.
417
+
418
+ ### State
419
+
420
+ `state` carries `isPlaying`, `isLoading`, `title`, `artist`, `album`, `positionMs`, `durationMs`,
421
+ `isBuffering`, `isSeeking`, `seekable`, `volume`, `isMuted`, `speed`, `loopMode`, `playlist`,
422
+ `currentIndex`, `tracks`, `chapters`, `currentChapter`, `videoParams`, `error` and `shuffle`.
510
423
 
511
424
  ## Troubleshooting
512
425
 
513
- ### "MpvPlayerModule is undefined" on JS side
426
+ **`openPlayer` resolves `false` for a video.** No surface is mounted. Render `<SimbaVideo />`
427
+ before launching, and check `commands.isSurfaceMounted()`.
514
428
 
515
- You probably haven't rebuilt the native side after `npm install`. Run:
429
+ **Picture-in-Picture does not start.** The Activity is missing
430
+ `android:supportsPictureInPicture="true"` or `android:resizeableActivity="true"`. Auto-enter on
431
+ leave additionally needs API 31+ — below that, enter PiP yourself with `commands.enterPip()`.
516
432
 
517
- ```bash
518
- cd android && ./gradlew :app:assembleDebug
519
- ```
433
+ **Gradle fails with `libmpv.so not found at android/src/main/jniLibs/…`.** The postinstall
434
+ download did not run. Re-run `npm install` in the app, or run the script by hand; `SKIP_DOWNLOAD_NATIVE=1`
435
+ is set somewhere in your environment or CI.
520
436
 
521
- Or do a full Metro reset:
437
+ **`NativeModules.MpvPlayerModule` is `undefined` at runtime.** The New Architecture is required.
438
+ Check `newArchEnabled=true` in the app's `android/gradle.properties`, and that the app's React
439
+ Native Gradle plugin runs `autolinkLibrariesWithApp()` — the library's own build file applies
440
+ `com.facebook.react` for that pipeline.
522
441
 
523
- ```bash
524
- npm start --reset-cache
525
- ```
526
-
527
- ### Player launches but video is black
528
-
529
- - **Permissions:** on API 33+ the app must request `POST_NOTIFICATIONS` before showing the media-style notification. Use `MpvPlayerModule.requestNotificationPermission()`.
530
- - **Codec:** if the device can't decode the format (rare - libmpv handles most), try `hardwareDecoding: 'no'` to force software decoding.
531
- - **HTTPS:** libmpv's curl backend rejects malformed URLs. Ensure your media URLs are valid `https://` (or `content://` for local files).
532
-
533
- ### App is stuck at a white screen after splash (no JS error, just white)
534
-
535
- This is almost always a **`dlopen failed: cannot locate symbol` on the libmpv.so** chain — visible in `adb logcat -d --pid=$(adb shell pidof <your.package>) | grep dlopen` as:
536
-
537
- ```
538
- dlopen failed: cannot locate symbol
539
- "_ZNSt6__ndk127__from_chars_floating_pointIfE..."
540
- referenced by ".../libmpv.so"
541
- ```
542
-
543
- Cause: the lib's bundled prebuilts (from `mpv-android` releases) are built against **LLVM 17+ libc++** (NDK r28+), which has `__from_chars_floating_point`. If your APK's `lib/<abi>/libc++_shared.so` is missing that symbol, `libsimbaplayer_mpv.so` fails to load, the `MpvBridgeModule` TurboModule never registers, and the app can't render past splash.
544
-
545
- Fix: **remove any `excludes += ["lib/*/libc++_shared.so"]` from your `android/app/build.gradle` `packagingOptions { jniLibs { } }` block** if you have one. The lib ships its own LLVM 17+ libc++_shared.so via the postinstall hook (`scripts/download-native.js` downloads the matching `jniLibs.tar.gz` from the GitHub release) and your APK should bundle that copy. Also **delete** any pre-v1.5.14 leftover `app/src/main/jniLibs/<abi>/<abi>/libc++_shared.so` (NDK r27 LLVM 16, missing the symbol) if you kept one around from a prior workaround.
546
-
547
- After this, `gradle :app:assembleDebug` will bundle the lib's libc++_shared.so and `libsimbaplayer_mpv.so` will resolve symbols cleanly.
548
-
549
- ### PiP doesn't auto-enter on home press
550
-
551
- Make sure:
552
-
553
- 1. The activity has `android:supportsPictureInPicture="true"` and `android:resizeableActivity="true"` in your `AndroidManifest.xml` (the consumer must declare these — the library doesn't force them).
554
- 2. `config.pip.autoEnterOnLeave === true` (the default).
555
- 3. The app targets API 24+ on a device that supports PiP (most modern Android devices do).
556
-
557
- ### Debug logging
558
-
559
- Enable verbose logging from JavaScript:
560
-
561
- ```tsx
562
- import { setDebugLogging } from '@simba-dev/react-native-media-player';
563
-
564
- // Enable verbose logging (sets mpv msg-level=all + logs every bridge call)
565
- setDebugLogging(true);
566
-
567
- // ... your code ...
568
-
569
- // Disable for production
570
- setDebugLogging(false);
571
- ```
572
-
573
- Or via the PlayerProvider config:
574
-
575
- ```tsx
576
- <PlayerProvider config={{ debug: { verboseLogging: true } }}>
577
- ```
578
-
579
- Then watch logcat:
580
-
581
- ```bash
582
- adb logcat -v color MpvBridgeModule:V MPVLib:V PipManager:V MediaPlaybackService:V ReactNativeJS:V *:S
583
- ```
584
-
585
- The `[PlaybackTrace]` prefix tags every bridge call so you can trace end-to-end.
586
-
587
- #### Property dump
588
-
589
- To dump all currently-observed mpv properties to logcat (useful for debugging state divergence between native and JS):
590
-
591
- ```tsx
592
- import { dumpObservedProperties } from '@simba-dev/react-native-media-player';
593
-
594
- const count = dumpObservedProperties();
595
- console.log(`Dumped ${count} properties to logcat`);
596
- ```
597
-
598
- Output looks like:
599
-
600
- ```
601
- [PlaybackTrace][Bridge][dumpObservedProperties] 12 properties observed:
602
- [PlaybackTrace][Bridge][dumpProperties] property=time-pos value="123.456" requested=true
603
- [PlaybackTrace][Bridge][dumpProperties] property=duration value="600" requested=true
604
- ...
605
- ```
606
-
607
- #### Memory-pressure response
608
-
609
- When the system signals memory pressure via `ComponentCallbacks2.onTrimMemory()`, the bridge automatically reduces mpv's cache:
610
-
611
- | Level | Cache-secs |
612
- |---|---|
613
- | `TRIM_MEMORY_RUNNING_MODERATE` | 10 |
614
- | `TRIM_MEMORY_RUNNING_LOW` | 5 |
615
- | `TRIM_MEMORY_RUNNING_CRITICAL` | 2 |
616
- | `TRIM_MEMORY_BACKGROUND` | 10 |
617
- | `TRIM_MEMORY_COMPLETE` | 0 |
618
-
619
- No configuration needed — the bridge adjusts `mpv.setPropertyString('cache-secs', ...)` from the host Activity's own `onTrimMemory` callbacks.
620
-
621
- #### Native module init log
622
-
623
- On every React Native init, the bridge logs:
624
-
625
- ```
626
- [PlaybackTrace][Bridge][initialize] MpvPlayerModule v0.1.0 init: package=com.simba.app isHeadlessJsTask=false debugLogging=false
627
- ```
628
-
629
- This confirms the module is wired + reports the package name + current debug-logging state. Use `adb logcat -s MpvBridgeModule` to filter.
630
-
631
- ### TypeScript "Cannot find module '@simba-dev/react-native-media-player'"
632
-
633
- Make sure the package is in your `dependencies` (not `devDependencies`) and Metro has been restarted. The `package.json` field `"react-native": "src/index.ts"` lets Metro resolve to the source directly without a build step.
442
+ **No media notification on Android 13+.** The app has not been granted `POST_NOTIFICATIONS`.
443
+ Call `commands.requestNotificationPermission()`.
634
444
 
635
445
  ## Limitations
636
446
 
637
- - **Android-only.** iOS is not supported (no plans — the libmpv backend is the only reason this package exists; iOS has `AVPlayer`). The `react-native.config.js` returns `ios: null` to skip iOS autolinking entirely.
638
- - **No DRM.** libmpv does not implement Widevine / FairPlay / PlayReady. Widevine is on the libmpv roadmap but not stable.
639
- - **No casting.** Chromecast and AirPlay are out of scope. The MediaSession integrates with Android Auto and Bluetooth headphones, but not Cast.
640
- - **GPL considerations.** libmpv is GPLv2+ by default. Bundling libmpv in your APK makes any consumer app that links against it subject to GPL terms unless you choose an LGPL-compatible build path. See the [License](#license) section below and the bundled [`MPV_NATIVE_PROVENANCE.md`](./android/src/main/jniLibs/MPV_NATIVE_PROVENANCE.md) for the exact provenance of the binary.
641
- - **Audio vs video background behavior.** Video files always pause on background (no PiP, no audio continuation) — this is intentional. The V11 codebase had separate engines for audio vs video; V12 unifies them on libmpv but keeps the "video = foreground-only" rule because the SurfaceView's GPU compositing stops when the activity backgrounds.
642
- - **PiP custom RemoteActions.** The lock-screen / PiP notification exposes a fixed set of actions (Play / Pause / Skip-Back / Skip-Forward). Custom actions are a W7+ feature.
643
- - **React Native ≥ 0.76 only.** Bridgeless mode is required (the TurboModule path uses `TurboReactPackage`, which doesn't work on the legacy bridge).
644
-
645
- ## Sponsor & support
646
-
647
- `@simba-dev/react-native-media-player` is free, open source software made possible by [Paval E P](https://github.com/pavalep) and the contributors who help maintain it. If you find it useful in your own work, consider supporting its continued development.
648
-
649
- <a href="https://buymeacoffee.com/pavalep"><img alt="Buy Me a Coffee" src="https://img.shields.io/badge/Buy%20Me%20a%20Coffee-ffdd00?style=for-the-badge&logo=buy-me-a-coffee&logoColor=black" /></a>
650
-
651
- Every contribution — large or small — helps me spend more time maintaining, experimenting, and shipping the next set of fixes and features. 🙏
652
-
653
- ### About the maintainer
654
-
655
- > I'm an independent developer building software, experimenting with ideas, and working on projects through **Varna Labs**, my sole proprietorship registered under India's Udyam/MSME framework. 🇮🇳
656
- >
657
- > If you like my projects, find something I've built useful, or simply want to support independent development, consider [making a contribution](https://buymeacoffee.com/pavalep). 🙌
658
- >
659
- > It doesn't have to be much — every little bit helps me spend more time building, experimenting, maintaining projects, and bringing new ideas to life. ✨
660
- >
661
- > 💡 Have a viable project or something interesting you'd like to build together?
662
- > Feel free to [reach out](https://github.com/pavalep). I'm always happy to discuss potential collaborations and see where a good idea can go. 🤝
663
- >
664
- > Your support keeps independent work moving. 🦋
665
- > Gracias for being here! ❤️
447
+ - **Android only.** There is no iOS implementation.
448
+ - **No controls.** The library ships none; see [Controls](#controls).
449
+ - **Auto-enter Picture-in-Picture needs Android 12 (API 31) or newer.** Below that the OS cannot
450
+ do it and entry is manual.
451
+ - **Most config sections are consumed in JavaScript.** The native side receives the resolved
452
+ config as JSON and acts on the PiP auto-enter switch; the rest are values your app reads back
453
+ through `usePlayerConfig()`.
454
+ - **`notifications.channelId` is not read natively.** The foreground service creates its own
455
+ notification channel, `simba_player_media_playback`.
456
+ - **The bundled native binaries carry their own licence.** They are built by the mpv-android
457
+ project and are subject to its terms (libmpv's default build is GPLv2+), so linking them into
458
+ your app is a licensing decision you own. The library's own JavaScript and Kotlin code is MIT.
666
459
 
667
460
  ## Contributing
668
461
 
669
- ### Local development
670
-
671
- The module is a sibling of the consumer app at `SIMBA/react-native-media-player/`. To work on the module and test it in the consumer app:
462
+ From the repository root:
672
463
 
673
464
  ```bash
674
- # 1. Make changes in react-native-media-player/
675
-
676
- # 2. Typecheck
677
- cd react-native-media-player
678
- npx tsc --noEmit -p .
679
-
680
- # 3. Build the AAR
681
- cd ../MOBILE_APP_REACT_NATIVE/android
682
- ./gradlew :react-native-media-player:assembleDebug
683
-
684
- # 4. Build the consumer APK (catches consumer-side regressions)
685
- ./gradlew :app:assembleDebug
686
-
687
- # 5. Run on device
688
- cd ..
689
- npm run android
465
+ npm install # postinstall downloads the native binaries
466
+ npm run typecheck # tsc --noEmit
467
+ npm test # jest
468
+ npm run build # tsc
469
+ npm run lint # placeholder — no linter is configured yet
690
470
  ```
691
471
 
692
- ### Tests
472
+ There is an `example/` app with `npm run android`, `npm start` and `npm run typecheck`. Its
473
+ sources still target the pre-2.0.0 API (they import the removed `DefaultControls` and demo
474
+ screens that no longer exist), so it does not currently typecheck — it is a work in progress, not
475
+ a reference implementation.
693
476
 
694
- Wave 7 (Phases 33-34) adds JUnit + Jest tests. Until then, manual testing via the consumer app is the gate.
695
-
696
- ```bash
697
- # Type check only
698
- cd react-native-media-player
699
- npx tsc --noEmit -p .
700
-
701
- # Verify the package is publishable (without actually publishing)
702
- npm pack --dry-run
703
- ```
704
-
705
- ### Pull request guidelines
706
-
707
- - One phase per PR (matches the spec's phase structure).
708
- - Update SPEC + TRACKER docs as part of the change.
709
- - Verify `./gradlew :react-native-media-player:assembleDebug :app:assembleDebug` passes.
710
- - Verify `npx tsc --noEmit -p .` passes from the module root.
477
+ Releases are cut by the `release.yml` workflow: it builds the native libraries from the pinned
478
+ mpv-android release, attaches them to the GitHub Release, and publishes to npm. Do not publish by
479
+ hand.
711
480
 
712
481
  ## License
713
482
 
714
- **MIT** for the Java/Kotlin/TypeScript code in this package. See [`LICENSE`](./LICENSE).
715
-
716
- **Note on bundled native libraries** (see [`LICENSE`](./LICENSE) for full text):
717
-
718
- - [libmpv](https://mpv.io/) — **GPLv2+** by default. Bundling it makes any consumer app that links against it subject to GPL terms unless an LGPL-compatible build path is chosen.
719
- - Bundled FFmpeg libraries (`libavcodec`, `libavformat`, `libavutil`, `libavfilter`, `libavdevice`, `libswresample`, `libswscale`) — **LGPLv2.1+** unless configured otherwise at build time.
720
- - `libOpenCL` — Apache-2.0.
721
- - `libc++_shared` — Apache-2.0 with LLVM exceptions.
722
-
723
- Consumers are responsible for ensuring their app's license obligations are met when shipping these binaries. See [`android/src/main/jniLibs/MPV_NATIVE_PROVENANCE.md`](./android/src/main/jniLibs/MPV_NATIVE_PROVENANCE.md) for the exact provenance of each bundled binary.
724
-
725
- ---
726
-
727
- **Status:** latest published version is **1.5.20** on [npmjs](https://www.npmjs.com/package/@simba-dev/react-native-media-player) and [GitHub Releases](https://github.com/pavalep/react-native-media-player/releases). See [CHANGELOG.md](./CHANGELOG.md) for the full per-version notes.
483
+ MIT — see [LICENSE](./LICENSE). The prebuilt native binaries are third-party builds of mpv and
484
+ carry their own licence terms; see [Limitations](#limitations).