@simba-dev/react-native-media-player 3.0.4 → 3.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.
package/CHANGELOG.md CHANGED
@@ -1,4 +1,101 @@
1
1
 
2
+ ## [3.1.0] - 2026-11-03
3
+
4
+ ### Fixed
5
+
6
+ - **The Picture-in-Picture action row did nothing.** The three platform buttons — Play/Pause,
7
+ Expand and Close — rendered at the correct size, right beside the platform's own settings /
8
+ expand / close buttons, and pressing ours produced no broadcast at all. The action's
9
+ `PendingIntent` carried an intent that named `PipActionReceiver` explicitly, and an
10
+ explicit broadcast is resolved through the **manifest**; the receiver was a runtime
11
+ registration, so the broadcast resolved to nothing and was dropped before it was ever
12
+ dispatched. Measured on emulator-5554 (API 37) on 2026-11-03: the same action sent
13
+ explicitly was never dispatched (`dispatchTime=--`, in the foreground and in PiP alike),
14
+ while the same action sent implicitly was dispatched in 0 ms. The action intent is now
15
+ implicit, which is what the runtime registration matches on.
16
+ - **A failure to deliver a PiP action was invisible.** `PipActionReceiver` swallowed the
17
+ exception silently — which is how a row of dead buttons could leave not one line in the
18
+ log. The failure is now logged, under the tag `PipActionReceiver`.
19
+
20
+ ### Changed
21
+
22
+ - **The library owns the PiP action receiver.** It is registered at runtime, once per
23
+ process, on the application context, at the moment the Picture-in-Picture parameters are
24
+ built — so the platform can never be handed a set of buttons that nothing is listening
25
+ for. Consumers no longer register it, and no longer need to know the class exists.
26
+
27
+ **Action required:** if you registered `PipActionReceiver` yourself, remove that
28
+ registration. Two registrations deliver every action twice, and a play/pause that toggles
29
+ twice leaves playback exactly where it was — the same dead-button symptom with a
30
+ different cause. `PipManager.intentFilter()` is now `internal`, so the compiler points
31
+ at the registration instead of letting it reach a runtime double-delivery bug.
32
+
33
+ ### Documentation
34
+
35
+ - The README described the **removed** mechanism: Android's own auto-enter switch, an API 31+
36
+ floor for auto-enter, a PiP action receiver "declared in the manifest", and 26 named
37
+ events where there are 27. It also pointed at a section for "the two lines of Kotlin and
38
+ the JS that goes with them" that did not contain them. All corrected; the auto-enter
39
+ section now carries the Kotlin and the JS a consumer needs, and explains why the consumer
40
+ performs the entry.
41
+
42
+ ### Added
43
+
44
+ - `PipActionDeliveryTest` — eight guard tests pinning the contract above: the intent stays
45
+ implicit, the library registers the receiver, the registration cannot happen twice, the
46
+ consumer cannot make it happen twice, a delivery failure is logged, and the manifest
47
+ neither declares the receiver nor duplicates the action strings.
48
+
49
+ ## [3.0.5] - 2026-11-03
50
+
51
+ ### Changed
52
+
53
+ - **The CONSUMER performs the PiP auto-enter; the platform's own switch is
54
+ gone.** `pip.autoEnterOnLeave` used to be honoured by arming
55
+ `PictureInPictureParams.Builder.setAutoEnterEnabled` (API 31+), which makes
56
+ the SYSTEM transition the activity into PiP when the user leaves the app,
57
+ with the consumer unable to do anything first. That is the wrong order for a
58
+ consumer that draws its own chrome over the picture, because **an Activity in
59
+ PiP does not redraw**: whatever its window held at the transition is what
60
+ the PiP window keeps showing. Measured on device on 2026-11-03, the
61
+ consumer's full expanded chrome was painted into the PiP window, its
62
+ buttons were dead, and its clock was frozen three minutes behind the real
63
+ position.
64
+
65
+ The library now says **WHEN** — through the new `onUserLeaveHint` event —
66
+ and the consumer removes its chrome, lets the frame that drew it go by, and
67
+ asks for the window itself. `pip.autoEnterOnLeave: true` keeps its public
68
+ meaning; only the performer changed. The consumer's side is two lines of
69
+ Kotlin (forward `onUserLeaveHint()` from the Activity) plus a subscription
70
+ to the `onUserLeaveHint` event in JS; both are in the README's
71
+ Picture-in-Picture section.
72
+
73
+ A side effect worth knowing: auto-enter now works on **every** API level.
74
+ The platform's switch never existed below Android 12; `onUserLeaveHint()`
75
+ does.
76
+
77
+ - **`onUserLeaveHint` is the 27th player event.** It is emitted with an empty
78
+ payload, and only when the auto-enter policy says yes — a consumer that
79
+ turned auto-enter off is never asked to enter PiP.
80
+
81
+ - **The bridge no longer stashes PiP params on the Activity.**
82
+ `Activity.setPictureInPictureParams` and the helper that pushed them
83
+ (`applyActivityPipParams`) are gone: they existed only to give the
84
+ platform's own auto-enter a shape to use, and that path no longer exists.
85
+ The params are now built at the moment the consumer asks for the window, so
86
+ the window's shape is the CURRENT video's shape.
87
+
88
+ ### Fixed
89
+
90
+ - **The PiP window could show the consumer's own chrome, frozen and dead.**
91
+ This is the library's half of that fix: it no longer arms the platform's
92
+ switch, so a consumer can remove its chrome before the window is asked for.
93
+ The consumer's half — hide the chrome, let one frame go by, then enter — is
94
+ the app's.
95
+
96
+ No public TypeScript API was removed. The config type, the command surface and
97
+ the event union are unchanged apart from the added event.
98
+
2
99
  ## [3.0.4] - 2026-11-03
3
100
 
4
101
  ### Changed
package/README.md CHANGED
@@ -62,7 +62,8 @@ video, and the two lanes meet in the same bridge:
62
62
  - **MediaSession and foreground service.** Title, artist and album reach the lock screen and the
63
63
  media notification; play, pause, stop, next, previous and seek are advertised to the session, so
64
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.
65
+ - **Picture-in-Picture.** Manual entry on demand, and auto-enter on leave on every Android
66
+ version - your app performs the entry itself, after taking its own chrome off screen.
66
67
  - **Typed surface.** Config, state, commands and hooks are all typed.
67
68
 
68
69
  ## What this is not
@@ -112,8 +113,13 @@ so re-running `npm install` is safe. Set `SKIP_DOWNLOAD_NATIVE=1` to skip the do
112
113
 
113
114
  ## Consumer setup
114
115
 
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.
116
+ The package's own manifest declares a foreground service and the media button receiver. It
117
+ declares no Activity: playback happens in the Activity your app already has.
118
+
119
+ The Picture-in-Picture action receiver is registered by this package at runtime, once per
120
+ process. You do not register it, and you must not: a second registration would deliver every
121
+ PiP action twice, and a play/pause that toggles twice does nothing at all.
122
+
117
123
 
118
124
  ### Picture-in-Picture
119
125
 
@@ -139,6 +145,10 @@ Your launcher Activity has to opt in:
139
145
  `resizeableActivity="true"` is not optional. An Activity that is not resizeable cannot enter
140
146
  Picture-in-Picture.
141
147
 
148
+ If `config.pip.autoEnterOnLeave` is on, the Activity also has to forward the platform’s leave
149
+ hint to the library — see [Picture-in-Picture](#picture-in-picture) for the two lines of Kotlin
150
+ and the JS that goes with them.
151
+
142
152
  ### Background audio
143
153
 
144
154
  ```xml
@@ -326,8 +336,11 @@ import {PlayerProvider} from '@simba-dev/react-native-media-player';
326
336
  ```
327
337
 
328
338
  The resolved config is pushed to the native bridge as JSON. The native side acts on the PiP
329
- section (it drives the auto-enter switch); the remaining sections are values your app reads back
330
- with `usePlayerConfig()` and applies itself. `DEFAULT_PLAYER_CONFIG` and `DEFAULT_THEME` are
339
+ section (it decides whether your app is told that the user is leaving); the remaining
340
+ sections are values your app reads back with `usePlayerConfig()` and applies itself.
341
+ `DEFAULT_PLAYER_CONFIG` and `DEFAULT_THEME` are exported if you would rather spread and patch.
342
+
343
+
331
344
  exported if you would rather spread and patch.
332
345
 
333
346
  ## Picture-in-Picture
@@ -343,15 +356,48 @@ commands.exitPipAndFinish();
343
356
  `enterPip()` calls `enterPictureInPictureMode()` on the current Activity, so the Activity has to
344
357
  declare `android:supportsPictureInPicture="true"` (see [Consumer setup](#consumer-setup)).
345
358
 
346
- **Auto-enter on leave** is `config.pip.autoEnterOnLeave` (default `true`). It maps onto the
347
- Android 12 / API 31 platform feature `PictureInPictureParams.Builder.setAutoEnterEnabled`: the
348
- OS enters Picture-in-Picture for you when the user leaves the app. **Below API 31 the platform
349
- has no such feature** — the OS cannot auto-enter Picture-in-Picture there, and entry stays manual
350
- through `commands.enterPip()`.
359
+ **Auto-enter on leave** is `config.pip.autoEnterOnLeave` (default `true`): it means "enter
360
+ Picture-in-Picture when the user leaves the app".
361
+
362
+ **Your app performs the entry.** The library does not arm Android's own auto-enter switch
363
+ (`PictureInPictureParams.Builder.setAutoEnterEnabled`), because an Activity in
364
+ Picture-in-Picture does not redraw: whatever its window held at the moment of the transition is
365
+ what the PiP window keeps showing. Letting the OS transition the Activity first froze the
366
+ app's own controls into the PiP window, scaled down and dead - measured on device on
367
+ 2026-11-03.
368
+
369
+ So the order is yours to keep: take your chrome off screen, let the frame that drew it go by,
370
+ and only then ask for the window. The library tells you WHEN, with two pieces.
371
+
372
+ ```kotlin
373
+ // android/app/src/main/java/.../MainActivity.kt
374
+ override fun onUserLeaveHint() {
375
+ super.onUserLeaveHint()
376
+ com.simba.player.mpv.MpvBridgeModule.notifyUserLeaveHint()
377
+ }
378
+ ```
379
+
380
+ ```ts
381
+ // the consumer's JS - remove your chrome, then ask for the window
382
+ import {subscribePlayerEvent} from '@simba-dev/react-native-media-player';
383
+
384
+ useEffect(() => {
385
+ return subscribePlayerEvent('onUserLeaveHint', () => {
386
+ setChromeVisible(false); // your chrome, your state
387
+ requestAnimationFrame(() => {
388
+ commands.enterPip(); // only now
389
+ });
390
+ });
391
+ }, [commands]);
392
+ ```
393
+
394
+ This works on **every** Android version - `onUserLeaveHint()` exists everywhere, and the
395
+ platform's own switch never existed below Android 12.
351
396
 
352
397
  The two PiP flags combine: auto-enter needs `pip.enabled` and `pip.autoEnterOnLeave` to both be
353
398
  true.
354
399
 
400
+
355
401
  The Picture-in-Picture action row has three buttons: **Play/Pause**, **Expand** and **Close**.
356
402
  They arrive in JS as the `onPipPlayPause`, `onPipExpand` and `onPipClose` events, next to
357
403
  `onPipModeChanged`.
@@ -438,7 +484,7 @@ that position in that file. The defaults are 640×360 at quality 80, exported as
438
484
 
439
485
  `getMpvPlayerModule()` returns the native module, or a no-op stand-in when the native side is
440
486
  not wired (Jest, web previews) so consumer code stays renderable.
441
- `subscribePlayerEvent(name, handler)` subscribes to one of the 26 named events and returns an
487
+ `subscribePlayerEvent(name, handler)` subscribes to one of the 27 named events and returns an
442
488
  unsubscribe function; `removeAllListeners()`, `setDebugLogging()` and
443
489
  `dumpObservedProperties()` are also exported. The event names are typed as `PlayerEventName`.
444
490
 
@@ -454,8 +500,16 @@ unsubscribe function; `removeAllListeners()`, `setDebugLogging()` and
454
500
  before launching, and check `commands.isSurfaceMounted()`.
455
501
 
456
502
  **Picture-in-Picture does not start.** The Activity is missing
457
- `android:supportsPictureInPicture="true"` or `android:resizeableActivity="true"`. Auto-enter on
458
- leave additionally needs API 31+ — below that, enter PiP yourself with `commands.enterPip()`.
503
+ `android:supportsPictureInPicture="true"` or `android:resizeableActivity="true"`. If auto-enter
504
+ on leave does nothing, the Activity is not forwarding `onUserLeaveHint()` - see
505
+ [Picture-in-Picture](#picture-in-picture).
506
+
507
+ **The Picture-in-Picture action row shows three buttons and none of them work.** That was the
508
+ explicit-broadcast bug, fixed in 3.1.0: the action's PendingIntent named the receiver's
509
+ component, and an explicit broadcast is resolved through the manifest, where the receiver was
510
+ never declared. Check that you have not registered a receiver for the PiP actions yourself -
511
+ this package registers one, and a second registration delivers every action twice.
512
+
459
513
 
460
514
  **Gradle fails with `libmpv.so not found at android/src/main/jniLibs/…`.** The postinstall
461
515
  download did not run. Re-run `npm install` in the app, or run the script by hand; `SKIP_DOWNLOAD_NATIVE=1`
@@ -473,11 +527,13 @@ Call `commands.requestNotificationPermission()`.
473
527
 
474
528
  - **Android only.** There is no iOS implementation.
475
529
  - **No controls.** The library ships none; see [Controls](#controls).
476
- - **Auto-enter Picture-in-Picture needs Android 12 (API 31) or newer.** Below that the OS cannot
477
- do it and entry is manual.
530
+ - **Auto-enter on leave is the consumer's to perform.** The library tells your Activity when the
531
+ user is leaving; taking your chrome off screen before asking for the window is your app's
532
+ job, and it has to happen before the Activity is paused.
478
533
  - **Most config sections are consumed in JavaScript.** The native side receives the resolved
479
- config as JSON and acts on the PiP auto-enter switch; the rest are values your app reads back
534
+ config as JSON and acts on the PiP auto-enter policy; the rest are values your app reads back
480
535
  through `usePlayerConfig()`.
536
+ - **`notifications.channelId` is not read natively.**
481
537
  - **`notifications.channelId` is not read natively.** The foreground service creates its own
482
538
  notification channel, `simba_player_media_playback`.
483
539
  - **The bundled native binaries carry their own licence.** They are built by the mpv-android
@@ -24,14 +24,25 @@ import com.facebook.react.bridge.ReactContext
24
24
  * - Notification text with chapter title + progress percentage (Android 12+)
25
25
  * - No NEXT/PREV actions (removed for simplicity)
26
26
  *
27
- * V12 Phase 9: relocated from the consumer app to the module so
28
- * `PlayerActivity` can call `buildPipParams(...)` directly without
29
- * crossing the Gradle module boundary. The consumer app's
30
- * `MainActivity` continues to register / unregister [PipActionReceiver]
31
- * (since `MainActivity` is the activity that owns the foreground
32
- * during in-app video browsing — PiP can be entered from there too).
33
- * Both activities share the same `com.simba.player.PipManager` FQN,
34
- * which Gradle resolves to the module's copy at app build time.
27
+ * ## Who owns the action receiver
28
+ *
29
+ * THIS LIBRARY owns it, end to end: [registerActionReceiver] registers
30
+ * [PipActionReceiver] on the application context, once per process. The
31
+ * consumer app does NOT register it and does not need to know the class
32
+ * exists.
33
+ *
34
+ * That ownership is not a preference — it is what makes the buttons
35
+ * work. See [buildRemoteAction] for the measured reason the broadcast
36
+ * has to be IMPLICIT, and [registerActionReceiver] for why there must be
37
+ * exactly ONE registration (two would deliver every action twice, and a
38
+ * play/pause that toggles twice leaves playback exactly where it was —
39
+ * buttons that look alive and do nothing).
40
+ *
41
+ * V12 Phase 9 relocated this object from the consumer app to the module
42
+ * so the consumer's Activity can call `buildPipParams(...)` without
43
+ * crossing the Gradle module boundary. Both sides share the same
44
+ * `com.simba.player.PipManager` FQN, which Gradle resolves to the
45
+ * module's copy at app build time.
35
46
  */
36
47
  @RequiresApi(Build.VERSION_CODES.N)
37
48
  object PipManager {
@@ -68,8 +79,18 @@ object PipManager {
68
79
  sourceRectHint: Rect? = null,
69
80
  chapterTitle: String? = null,
70
81
  progressPercentage: String? = null,
71
- autoEnter: Boolean = false,
72
82
  ): PictureInPictureParams {
83
+ // The params carry the three RemoteActions, and the platform's PiP
84
+ // action row is the ONLY way they can ever be fired. So the
85
+ // receiver that serves them has to exist before these params do.
86
+ //
87
+ // Registering here — at the single place the params are built —
88
+ // makes it impossible to hand the platform a set of buttons that
89
+ // nothing is listening for. That was the measured defect on
90
+ // 2026-11-03: the row rendered three buttons at the right size
91
+ // and none of them did anything.
92
+ registerActionReceiver(context)
93
+
73
94
  val actions = mutableListOf<RemoteAction>()
74
95
 
75
96
  // Play/Pause
@@ -133,17 +154,39 @@ object PipManager {
133
154
  builder.setSeamlessResizeEnabled(true)
134
155
  }
135
156
 
136
- // Auto-enter PiP when the user leaves the app (Android 12+).
157
+ // NO `setAutoEnterEnabled` HERE, and that is deliberate.
137
158
  //
138
- // This is the platform's OWN switch: with it set, the system
139
- // transitions the activity into PiP when the user swipes home,
140
- // instead of the app having to request it. Below API 31 the
141
- // platform has no equivalent - an app would have to override
142
- // `onUserLeaveHint()` in its own Activity, and this library ships
143
- // no Activity - so PiP entry stays manual there.
144
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
145
- builder.setAutoEnterEnabled(autoEnter)
146
- }
159
+ // The platform's auto-enter switch makes the SYSTEM transition the
160
+ // activity into PiP when the user leaves the app, without the app
161
+ // being able to do anything first. That is the wrong order for a
162
+ // consumer that draws its own chrome over the picture.
163
+ //
164
+ // The reason is NOT that the window freezes - an Activity in PiP is
165
+ // "paused, but rendering" (source.android.com/docs/core/display/
166
+ // pip). What stops is REACT: RN pauses the React scheduler when
167
+ // the Activity is paused, so a React commit cannot land and no
168
+ // frame is produced. The switch transitions the Activity before
169
+ // the consumer can unmount its chrome, so the chrome is still
170
+ // mounted when the PiP window is created - and with no frame
171
+ // coming, it stays there: dead and scaled down.
172
+ //
173
+ // Measured on device on 2026-11-03: the consumer's full expanded
174
+ // chrome (header band, scrub row, +-10 buttons, the big pause
175
+ // button) was painted into the PiP window, its buttons were DEAD
176
+ // (tapping pause did not pause) and its clock was FROZEN at
177
+ // 51:09 while the real position was 54:15 - while the consumer's
178
+ // own state already said `pipActive: true` and `isExpanded:
179
+ // false`.
180
+ //
181
+ // So auto-enter on leave is the CONSUMER's to perform, in the only
182
+ // order that works: remove the chrome, let the frame that drew it
183
+ // go by, and only then ask for the window. The library's part is
184
+ // to tell the consumer WHEN the user is leaving - the
185
+ // `onUserLeaveHint` event - and to keep the params it hands the
186
+ // platform free of the platform's own auto-enter switch.
187
+ //
188
+ // The consumer's Activity overrides `onUserLeaveHint()`, which
189
+ // works on every API level, unlike the platform switch (API 31+).
147
190
 
148
191
  // Source rect hint for smooth entry animation (Android 12+)
149
192
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && sourceRectHint != null) {
@@ -169,9 +212,36 @@ object PipManager {
169
212
  action: String,
170
213
  requestCode: Int,
171
214
  ): RemoteAction {
172
- val intent = Intent(action).apply {
173
- setClass(context, PipActionReceiver::class.java)
174
- }
215
+ // The intent is IMPLICIT — it carries the action and NOTHING else.
216
+ //
217
+ // It used to name the component explicitly
218
+ // (`setClass(context, PipActionReceiver::class.java)`). THAT was
219
+ // the reason the PiP buttons did NOTHING, measured on
220
+ // emulator-5554 (API 37) on 2026-11-03:
221
+ //
222
+ // * The platform's PiP action row rendered at the correct size,
223
+ // right beside the platform's own settings / expand / close
224
+ // buttons — and all three of THOSE worked.
225
+ // * Tapping ours produced NO broadcast at all:
226
+ // `dumpsys activity broadcasts` held no record of the action,
227
+ // and the platform's own gear button opened the PiP settings
228
+ // screen in the very same gesture.
229
+ //
230
+ // The cause is how the framework resolves an EXPLICIT broadcast:
231
+ // it looks the component up through the MANIFEST.
232
+ // `PipActionReceiver` is not declared there — it is a runtime
233
+ // registration — so the explicit broadcast resolved to no
234
+ // receiver and was dropped before it was ever dispatched
235
+ // (`dumpsys` showed `dispatchTime=--`, foreground and background
236
+ // alike).
237
+ //
238
+ // The same action sent IMPLICITLY was dispatched in 0 ms, and
239
+ // that is the proof: the receiver was registered and matching the
240
+ // whole time. Only the component was the problem.
241
+ //
242
+ // An implicit intent is matched by ACTION, which is exactly what
243
+ // the runtime registration filters on.
244
+ val intent = Intent(action)
175
245
  val pendingIntent = PendingIntent.getBroadcast(
176
246
  context,
177
247
  requestCode,
@@ -188,13 +258,57 @@ object PipManager {
188
258
 
189
259
  // ── Intent Filter ──────────────────────────────────────────────────────
190
260
 
191
- fun intentFilter(): IntentFilter {
261
+ /**
262
+ * The filter the runtime registration matches on.
263
+ *
264
+ * `internal` on purpose: registering the receiver is THIS library's
265
+ * job (see [registerActionReceiver]), and a public helper would
266
+ * only invite a consumer to register a second receiver for the same
267
+ * three actions. Two receivers means every action is delivered
268
+ * twice, and a play/pause that toggles twice leaves playback exactly
269
+ * where it was — a row of buttons that look alive and do nothing.
270
+ */
271
+ internal fun intentFilter(): IntentFilter {
192
272
  return IntentFilter().apply {
193
273
  addAction(ACTION_PLAY_PAUSE)
194
274
  addAction(ACTION_EXPAND)
195
275
  addAction(ACTION_CLOSE)
196
276
  }
197
277
  }
278
+
279
+ // ── Receiver registration ─────────────────────────────────────────────
280
+
281
+ /**
282
+ * Registers [PipActionReceiver] for the three PiP actions — ONCE per
283
+ * process.
284
+ *
285
+ * The application context is used on purpose: the receiver has to
286
+ * outlive any Activity, because the platform's PiP action row can
287
+ * fire while the consumer's Activity is paused inside PiP, and long
288
+ * after a configuration change has replaced it.
289
+ *
290
+ * The once-per-process guard matters because the React context — and
291
+ * with it this module — can be recreated (a debug reload, a process
292
+ * restart), and registering again would deliver every action twice.
293
+ */
294
+ internal fun registerActionReceiver(context: Context) {
295
+ val appContext = context.applicationContext
296
+ synchronized(registrationLock) {
297
+ if (registered) return
298
+ val receiver = PipActionReceiver()
299
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
300
+ appContext.registerReceiver(receiver, intentFilter(), Context.RECEIVER_EXPORTED)
301
+ } else {
302
+ appContext.registerReceiver(receiver, intentFilter())
303
+ }
304
+ registered = true
305
+ }
306
+ }
307
+
308
+ private val registrationLock = Any()
309
+
310
+ @Volatile
311
+ private var registered = false
198
312
  }
199
313
 
200
314
  // ── BroadcastReceiver for PiP Actions ──────────────────────────────────────
@@ -203,18 +317,26 @@ object PipManager {
203
317
  * Receives PiP RemoteAction broadcasts and forwards them to the React Native
204
318
  * event layer via [com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter].
205
319
  *
206
- * Registered/unregistered in `MainActivity.onCreate` / `onDestroy` (since
207
- * `MainActivity` is where the in-app foreground session lives; `PlayerActivity`
208
- * shares the receiver registration via the merged module manifest).
320
+ * Registered by THIS library, once per process, on the application context
321
+ * — see [PipManager.registerActionReceiver]. The consumer app does not
322
+ * register it and does not need to know the class exists.
209
323
  *
210
- * V12: receiver class lives in the module (same FQN `com.simba.player.PipActionReceiver`).
211
- * The consumer app's `MainActivity` instantiates / registers it without any
212
- * import changes — Gradle merges the module's class into the app at build time.
324
+ * It is a RUNTIME registration on purpose: the three action strings are
325
+ * owned by [PipManager] as Kotlin constants, and a manifest declaration
326
+ * would have to repeat them as literals — two owners for one fact. The
327
+ * broadcast those constants feed is implicit, so it matches a runtime
328
+ * registration by action. (An EXPLICIT broadcast would need a manifest
329
+ * declaration instead; see [PipManager.buildRemoteAction] for the
330
+ * measured reason that shape never worked.)
213
331
  *
214
332
  * v3: Handles 3 actions — play/pause, expand (restore fullscreen), close (end session).
215
333
  */
216
334
  class PipActionReceiver : BroadcastReceiver() {
217
335
 
336
+ private companion object {
337
+ const val TAG = "PipActionReceiver"
338
+ }
339
+
218
340
  override fun onReceive(context: Context, intent: Intent) {
219
341
  when (intent.action) {
220
342
  PipManager.ACTION_PLAY_PAUSE -> {
@@ -235,9 +357,15 @@ class PipActionReceiver : BroadcastReceiver() {
235
357
  reactContext
236
358
  .getJSModule(com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
237
359
  ?.emit(eventName, params)
238
- } catch (_: Exception) {
239
- // React context not available — receiver may be triggered after
240
- // the JS bundle has unloaded. Silently swallow (no UI to update).
360
+ } catch (e: Exception) {
361
+ // The React context is not available — the broadcast can arrive
362
+ // after the JS bundle has unloaded, and there is no UI to update
363
+ // in that case.
364
+ //
365
+ // It is still LOGGED, and that is the point. A silent catch
366
+ // here is how the PiP action row could render three buttons
367
+ // that did nothing, with not one line in the log to say so.
368
+ android.util.Log.w(TAG, "cannot emit $eventName: no React context", e)
241
369
  }
242
370
  }
243
371
 
@@ -129,6 +129,20 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
129
129
  */
130
130
  private var pipAutoEnter: Boolean = false
131
131
 
132
+ /**
133
+ * The same policy, mirrored where the COMPANION can read it.
134
+ *
135
+ * `notifyUserLeaveHint()` is a companion function: it is called
136
+ * from the consumer's Activity, which has no reference to this
137
+ * module instance, so it cannot read the instance field above.
138
+ * The instance writes this mirror when it applies the policy.
139
+ *
140
+ * The same pattern `debugLoggingEnabled` uses.
141
+ */
142
+ @Volatile
143
+ var pipAutoEnterForCompanion: Boolean = false
144
+ private set
145
+
132
146
  /**
133
147
  * Phase 21: recursive JSONObject → Kotlin Map converter. Used
134
148
  * by [setConfig] so the stored config can be consumed
@@ -198,6 +212,51 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
198
212
  Log.w(TAG, "onPictureInPictureModeChanged: emit threw", e)
199
213
  }
200
214
  }
215
+
216
+ /**
217
+ * Called from the consumer's `Activity.onUserLeaveHint()` - the
218
+ * user is leaving the app (home, recents, app switcher).
219
+ *
220
+ * The consumer needs this because the PiP ENTRY has to be in the
221
+ * consumer's hands, not the platform's: an Activity in PiP does
222
+ * not redraw, so a consumer that draws its own chrome over the
223
+ * picture has to remove that chrome BEFORE the window is frozen.
224
+ * The platform's own auto-enter switch cannot give it that
225
+ * chance - see `PipManager.buildPipParams` for the measurement.
226
+ *
227
+ * So the library's job is to say WHEN, and the consumer decides
228
+ * whether to act: it removes its chrome, lets the frame that drew
229
+ * it go by, and then asks the OS for the window itself.
230
+ *
231
+ * The auto-enter policy is the consumer's own `pip.autoEnterOnLeave`
232
+ * config, so this is a no-op when the consumer does not want
233
+ * auto-enter.
234
+ */
235
+ fun notifyUserLeaveHint() {
236
+ Log.i(
237
+ TAG,
238
+ "companion.notifyUserLeaveHint: autoEnter=$pipAutoEnterForCompanion " +
239
+ "instance=${instance != null}",
240
+ )
241
+ if (!pipAutoEnterForCompanion) {
242
+ Log.i(
243
+ TAG,
244
+ "companion.notifyUserLeaveHint: auto-enter is off; not telling the consumer",
245
+ )
246
+ return
247
+ }
248
+ val ctx = instance ?: run {
249
+ Log.w(TAG, "notifyUserLeaveHint: module instance not initialized yet")
250
+ return
251
+ }
252
+ try {
253
+ ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
254
+ .emit("onUserLeaveHint", Arguments.createMap())
255
+ Log.i(TAG, "companion.notifyUserLeaveHint: emit succeeded")
256
+ } catch (e: Exception) {
257
+ Log.w(TAG, "notifyUserLeaveHint: emit threw", e)
258
+ }
259
+ }
201
260
  }
202
261
 
203
262
  init {
@@ -301,13 +360,13 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
301
360
  "surfaceAttached" -> "onSurfaceAttached"
302
361
  else -> event
303
362
  }
304
- // The video's dimensions just changed. The params the SYSTEM
305
- // reads for an auto-enter carry the aspect ratio, so they
306
- // have to be refreshed with the new one - otherwise the
307
- // auto-entered window has the shape of the previous video.
308
- if (event == "videoReconfig") {
309
- applyActivityPipParams()
310
- }
363
+ // The video's dimensions just changed. Nothing has to be
364
+ // refreshed here any more: the params the platform reads are
365
+ // the ones the CONSUMER's entry carries, and the consumer
366
+ // builds them at the moment it asks for the window - by then
367
+ // it knows the video's current shape. (The platform's own
368
+ // auto-enter switch, which used to read params stashed on the
369
+ // activity, is gone: see `PipManager.buildPipParams`.)
311
370
  try {
312
371
  val payload = JsonUtil.jsonStringToReactMap(jsonPayload)
313
372
  eventEmitter.emit(jsEvent, payload)
@@ -2294,20 +2353,33 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2294
2353
  }
2295
2354
 
2296
2355
  /**
2297
- * Apply `pip.autoEnterOnLeave` to the Activity.
2298
- *
2299
- * `Activity.setAutoEnterEnabled(true)` (API 31+ / Android 12) is the
2300
- * platform's own switch for "enter PiP when the user leaves the app".
2301
- *
2302
- * Below API 31 there is NO platform equivalent: an app has to
2303
- * override `onUserLeaveHint()` in its own Activity, and this library
2304
- * ships NO Activity - the consumer's launcher Activity hosts
2305
- * playback (the one-Activity architecture). So below Android 12 this
2306
- * is a documented no-op and PiP entry stays manual.
2307
- *
2308
- * The consumer's Activity must also declare
2309
- * `android:supportsPictureInPicture="true"` for the OS to honour it.
2310
- * That is the consumer's manifest, not this library's.
2356
+ * Apply `pip.autoEnterOnLeave` — remember the policy, and tell the
2357
+ * CONSUMER when the user leaves.
2358
+ *
2359
+ * What this does NOT do any more: arm the platform's own switch
2360
+ * (`PictureInPictureParams.Builder.setAutoEnterEnabled`, API 31+).
2361
+ * The platform's switch makes the SYSTEM transition the activity into
2362
+ * PiP without the consumer being able to do anything first. The
2363
+ * Activity in PiP is "paused, but rendering" - what stops is REACT:
2364
+ * its scheduler is paused with the Activity, so no commit lands and
2365
+ * no frame is produced. So a consumer that draws its own chrome over
2366
+ * the picture still had that chrome mounted when the PiP window was
2367
+ * created, and with no frame coming it stayed there: dead and scaled
2368
+ * down. Measured on device on 2026-11-03.
2369
+ * See `PipManager.buildPipParams` for the full account.
2370
+ *
2371
+ * What it does now: the policy is remembered (so
2372
+ * `notifyUserLeaveHint()` can decide whether to speak at all), and
2373
+ * when the consumer's Activity reports that the user is leaving, the
2374
+ * consumer is told through the `onUserLeaveHint` event. The consumer
2375
+ * then removes its chrome, lets the frame that drew it go by, and
2376
+ * asks the OS for the window itself.
2377
+ *
2378
+ * The consumer's Activity must override `onUserLeaveHint()` and
2379
+ * declare `android:supportsPictureInPicture="true"`. Both are the
2380
+ * consumer's, not this library's — it ships no Activity (the
2381
+ * one-Activity architecture). `onUserLeaveHint()` works on EVERY API
2382
+ * level, unlike the platform switch, which needed API 31+.
2311
2383
  *
2312
2384
  * @param config the RESOLVED config map, as parsed by `setConfig`.
2313
2385
  */
@@ -2315,7 +2387,15 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2315
2387
  try {
2316
2388
  val desired = PipAutoEnterPolicy.desiredAutoEnter(config) ?: return
2317
2389
  pipAutoEnter = desired
2318
- applyActivityPipParams()
2390
+ // The policy is remembered so `notifyUserLeaveHint()` knows
2391
+ // whether to tell the consumer that it should enter PiP. The
2392
+ // platform's OWN auto-enter switch is NOT armed: the system
2393
+ // would transition the activity before the consumer could
2394
+ // remove its chrome, and React cannot commit a frame while
2395
+ // the Activity is paused - so the consumer's chrome would be
2396
+ // still mounted in the PiP window, dead and scaled down. See
2397
+ // `PipManager.buildPipParams` for the measurement.
2398
+ pipAutoEnterForCompanion = desired
2319
2399
  } catch (t: Throwable) {
2320
2400
  // Never let this reject the `setConfig` promise: the config
2321
2401
  // itself was stored fine, and a rejected promise would tell
@@ -2379,77 +2459,6 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2379
2459
  )
2380
2460
  }
2381
2461
 
2382
- /**
2383
- * Push the PiP params the SYSTEM will use onto the Activity.
2384
- *
2385
- * `Activity.setPictureInPictureParams` is what the platform reads
2386
- * when it transitions the activity into PiP BY ITSELF - which is
2387
- * exactly the swipe-home path that `pip.autoEnterOnLeave` asks for.
2388
- * The params `enterPip` passes to `enterPictureInPictureMode` only
2389
- * describe a MANUAL entry.
2390
- *
2391
- * So the auto-enter flag has to live on the activity's params, and
2392
- * it has to carry the video's CURRENT aspect ratio - a stale aspect
2393
- * means the auto-entered window has the shape of the previous video.
2394
- * That is why this runs again on every `videoReconfig`: that is the
2395
- * moment mpv reports new dimensions.
2396
- *
2397
- * `Activity.setAutoEnterEnabled` does NOT exist - the platform's
2398
- * switch is `PictureInPictureParams.Builder.setAutoEnterEnabled`,
2399
- * which is API 31+. Below that the OS cannot auto-enter at all.
2400
- */
2401
- private fun applyActivityPipParams() {
2402
- try {
2403
- if (!pipAutoEnter) return
2404
- val activity = reactApplicationContext.currentActivity
2405
- if (activity == null) {
2406
- Log.w(
2407
- TAG,
2408
- "[PlaybackTrace][Bridge][pip] no activity yet; auto-enter PiP not applied",
2409
- )
2410
- return
2411
- }
2412
- if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.S) {
2413
- Log.w(
2414
- TAG,
2415
- "[PlaybackTrace][Bridge][pip] auto-enter PiP needs Android 12 (API 31)+; " +
2416
- "below that the OS cannot auto-enter, so PiP entry stays manual",
2417
- )
2418
- return
2419
- }
2420
- // The window's shape and the source rect hint are taken from the
2421
- // SAME frame, so they can never disagree. The system scales the
2422
- // hinted region to the window non-proportionally when the two
2423
- // shapes differ, and the video visibly arrives stretched.
2424
- //
2425
- // The frame's shape follows the picture's mode: with `contain`
2426
- // (the app's default) the frame inside the view IS the video,
2427
- // letterboxed into the view's own shape; with `cover` or
2428
- // `stretch` the picture fills the view, so the frame IS the
2429
- // view's rect and the window takes the view's shape. Either way
2430
- // the window's shape does not change here — only the hint does,
2431
- // from `null` (a black rectangle) to a real rect that points at
2432
- // the picture.
2433
- val frame = pipSourceRectInWindow()
2434
- val aspect = frame?.aspect ?: (currentVideoAspect() ?: (16f / 9f))
2435
- val params = com.simba.player.PipManager.buildPipParams(
2436
- context = activity,
2437
- aspect = aspect,
2438
- sourceRectHint = frame?.let { Rect(it.left, it.top, it.right, it.bottom) },
2439
- autoEnter = true,
2440
- )
2441
- activity.runOnUiThread {
2442
- activity.setPictureInPictureParams(params)
2443
- Log.i(
2444
- TAG,
2445
- "[PlaybackTrace][Bridge][pip] activity PiP params set, autoEnter=true",
2446
- )
2447
- }
2448
- } catch (t: Throwable) {
2449
- Log.w(TAG, "[PlaybackTrace][Bridge][pip] applying activity params failed", t)
2450
- }
2451
- }
2452
-
2453
2462
  // ── Picture-in-Picture ─────────────────────────────────────────────────
2454
2463
 
2455
2464
  /**
@@ -2554,7 +2563,6 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2554
2563
  sourceRectHint = sourceRect,
2555
2564
  chapterTitle = title,
2556
2565
  progressPercentage = pct,
2557
- autoEnter = pipAutoEnter,
2558
2566
  )
2559
2567
  // `enterPictureInPictureMode` ANSWERS whether the OS
2560
2568
  // accepted the request, and the answer was being
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "3.0.4",
3
+ "version": "3.1.0",
4
4
  "description": "React Native video & audio player powered by libmpv — Picture-in-Picture, MediaSession, foreground service, and a customizable TypeScript UI. Built for Android. Designed as a drop-in replacement for react-native-video / react-native-track-player / expo-av. See CHANGELOG.md for per-version notes.",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -112,7 +112,16 @@ export interface LaunchParams {
112
112
  readonly requestId?: string;
113
113
  }
114
114
 
115
- /** All 26 events emitted by the Kotlin bridge. */
115
+ /**
116
+ * All 27 events emitted by the Kotlin bridge.
117
+ *
118
+ * `onUserLeaveHint` is the 27th: the native side telling the consumer
119
+ * that the user is leaving the app. It exists because a consumer that
120
+ * draws its own chrome over the picture has to be able to remove that
121
+ * chrome BEFORE the Activity enters Picture-in-Picture. See
122
+ * `PipManager`'s note on why the OS-initiated transition cannot be used
123
+ * for that.
124
+ */
116
125
  export type PlayerEventName =
117
126
  | 'onFileLoaded'
118
127
  | 'onLoadRequested'
@@ -139,7 +148,8 @@ export type PlayerEventName =
139
148
  | 'onPipModeChanged'
140
149
  | 'onPipPlayPause'
141
150
  | 'onPipExpand'
142
- | 'onPipClose';
151
+ | 'onPipClose'
152
+ | 'onUserLeaveHint';
143
153
 
144
154
  /** Typed payload map for each event. */
145
155
  export interface PlayerEventPayloads {
@@ -198,6 +208,17 @@ export interface PlayerEventPayloads {
198
208
  onPipPlayPause: Record<string, never>;
199
209
  onPipExpand: Record<string, never>;
200
210
  onPipClose: Record<string, never>;
211
+ /**
212
+ * The user is leaving the app (home, recents, app switcher).
213
+ *
214
+ * A consumer that owns its own chrome over the picture uses this to
215
+ * remove that chrome and THEN enter Picture-in-Picture itself. The
216
+ * order is not negotiable: an Activity in PiP does not redraw, so
217
+ * whatever its window contained at the moment of the transition is
218
+ * what the PiP window keeps showing — frozen, dead and scaled down.
219
+ * See `PipManager`'s note on the same thing.
220
+ */
221
+ onUserLeaveHint: Record<string, never>;
201
222
  }
202
223
 
203
224
  // ═══════════════════════════════════════════════════════════════════════════
@@ -1054,7 +1075,7 @@ export function removeAllListeners(event?: PlayerEventName): void {
1054
1075
  }
1055
1076
 
1056
1077
  /**
1057
- * All 26 player event names — the ONE owner of this list.
1078
+ * All 27 player event names — the ONE owner of this list.
1058
1079
  *
1059
1080
  * `<PlayerProvider>` imports it to subscribe to every event on mount,
1060
1081
  * `removeAllListeners()` iterates it when no event is named, and the
@@ -1088,4 +1109,5 @@ export const ALL_PLAYER_EVENTS: readonly PlayerEventName[] = [
1088
1109
  'onPipPlayPause',
1089
1110
  'onPipExpand',
1090
1111
  'onPipClose',
1112
+ 'onUserLeaveHint',
1091
1113
  ];
@@ -460,7 +460,7 @@ export interface PlayerProviderProps {
460
460
  * - **Initial hydration** (mount): synchronous bridge getters fill in
461
461
  * position / duration / playback state / volume / mute / speed /
462
462
  * loop / playlist / tracks / chapters / video params.
463
- * - **Event subscriptions** (mount): all 26 mpv events are subscribed
463
+ * - **Event subscriptions** (mount): all 27 mpv events are subscribed
464
464
  * via `subscribePlayerEvent` and dispatched to `applyPlayerEvent`.
465
465
  * - **Mount-time level seeds** (mount): `seekable` and `mute` are read once
466
466
  * via the sync `getProperty` getter, because mpv emits those two as
@@ -601,7 +601,7 @@ export function PlayerProvider({
601
601
  console.warn('[simba-player] hydratePlayerState failed:', e);
602
602
  }
603
603
 
604
- // ── 2. Subscribe to all 26 mpv events ───────────────────────────────
604
+ // ── 2. Subscribe to all 27 mpv events ───────────────────────────────
605
605
  // Each event handler reads the current state + progress from the
606
606
  // refs, applies the patch via the pure `applyPlayerEvent`
607
607
  // reducer, writes back to the refs, and schedules a re-render
@@ -51,7 +51,18 @@ export const DEFAULT_THEME: PlayerTheme = {
51
51
  export interface PipConfig {
52
52
  /** Master switch — when false, all PiP entry requests are ignored. */
53
53
  enabled: boolean;
54
- /** When true, pressing home / recents / app-switcher auto-enters PiP. */
54
+ /**
55
+ * When true, the library reports that the user is leaving the app, through
56
+ * the `onUserLeaveHint` event, and the CONSUMER enters PiP itself.
57
+ *
58
+ * The library deliberately does NOT arm Android's own auto-enter switch
59
+ * (`PictureInPictureParams.Builder.setAutoEnterEnabled`): that makes the OS
60
+ * transition the Activity without giving the app a chance to remove its own
61
+ * chrome, and an Activity in Picture-in-Picture does not redraw — so the
62
+ * chrome is frozen into the PiP window as a dead layer. See the README's
63
+ * Picture-in-Picture section for the two lines of Kotlin and the JS that
64
+ * go with it.
65
+ */
55
66
  autoEnterOnLeave: boolean;
56
67
  }
57
68
 
@@ -1479,6 +1479,7 @@ export function applyPlayerEvent(
1479
1479
  case 'onPipPlayPause':
1480
1480
  case 'onPipExpand':
1481
1481
  case 'onPipClose':
1482
+ case 'onUserLeaveHint':
1482
1483
  // No state-field mapping for these in the V13 surface (PiP state
1483
1484
  // is owned by the activity; reconfig signals a video-parameter
1484
1485
  // change that's already covered by onVideoParamsChanged).