@simba-dev/react-native-media-player 3.2.0 → 3.3.1

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.
@@ -12,17 +12,17 @@ import android.graphics.drawable.Icon
12
12
  import android.os.Build
13
13
  import android.util.Rational
14
14
  import androidx.annotation.RequiresApi
15
- import com.facebook.react.ReactApplication
16
- import com.facebook.react.bridge.ReactContext
17
15
 
18
16
  /**
19
17
  * Manages Android Picture-in-Picture (PiP) overlay actions and parameters
20
18
  * for the `PlayerActivity` in `@simba/react-native-media-player`.
21
19
  *
22
- * v3 redesign (carried over from V11):
23
- * - 3 RemoteAction buttons max: [Play/Pause] [Expand] [Close]
20
+ * v3.3.0:
21
+ * - ONE RemoteAction: [Play/Pause], with a state-driven icon
24
22
  * - Notification text with chapter title + progress percentage (Android 12+)
25
23
  * - No NEXT/PREV actions (removed for simplicity)
24
+ * - The platform's own auto-enter switch, armed only while media is loaded
25
+ * (Android 12+)
26
26
  *
27
27
  * ## Who owns the action receiver
28
28
  *
@@ -31,12 +31,12 @@ import com.facebook.react.bridge.ReactContext
31
31
  * consumer app does NOT register it and does not need to know the class
32
32
  * exists.
33
33
  *
34
- * That ownership is not a preference — it is what makes the buttons
34
+ * That ownership is not a preference — it is what makes the button
35
35
  * work. See [buildRemoteAction] for the measured reason the broadcast
36
36
  * has to be IMPLICIT, and [registerActionReceiver] for why there must be
37
37
  * exactly ONE registration (two would deliver every action twice, and a
38
38
  * play/pause that toggles twice leaves playback exactly where it was —
39
- * buttons that look alive and do nothing).
39
+ * a button that looks alive and does nothing).
40
40
  *
41
41
  * V12 Phase 9 relocated this object from the consumer app to the module
42
42
  * so the consumer's Activity can call `buildPipParams(...)` without
@@ -49,29 +49,59 @@ object PipManager {
49
49
 
50
50
  // ── Action Constants ───────────────────────────────────────────────────
51
51
 
52
+ /**
53
+ * The ONE action the PiP row carries: play/pause.
54
+ *
55
+ * The expand and close actions this library used to build are GONE:
56
+ * the platform renders its own expand / close / settings affordances
57
+ * in the PiP window, and the library's row was a second copy of them.
58
+ */
52
59
  const val ACTION_PLAY_PAUSE = "com.simba.player.PIP_PLAY_PAUSE"
53
- const val ACTION_EXPAND = "com.simba.player.PIP_EXPAND"
54
- const val ACTION_CLOSE = "com.simba.player.PIP_CLOSE"
55
60
 
56
61
  private const val REQ_PLAY_PAUSE = 1001
57
- private const val REQ_EXPAND = 1002
58
- private const val REQ_CLOSE = 1003
59
62
 
60
63
  // ── PiP Params Builder ─────────────────────────────────────────────────
61
64
 
62
65
  /**
63
- * Build PictureInPictureParams with 3 overlay actions:
64
- * [Pause/Resume] [Expand to Fullscreen] [Close].
66
+ * Build the PictureInPictureParams the platform builds the PiP window
67
+ * from.
68
+ *
69
+ * ## ONE action, and why
70
+ *
71
+ * The params carry exactly ONE RemoteAction: play/pause.
65
72
  *
66
- * On Android 12+, also sets notification subtitle with chapter/progress info.
73
+ * The platform renders its OWN expand / close / settings affordances in
74
+ * the PiP window. The library's own Expand and Close buttons were a
75
+ * SECOND row of the same three controls — the "two rows" symptom — and
76
+ * the platform's own copy is the one that works. Google's own
77
+ * `androidx.core-pip` ships exactly one custom action for the same
78
+ * reason.
79
+ *
80
+ * ## The icon is state-driven
81
+ *
82
+ * The play/pause action shows the PAUSE icon while the video is
83
+ * playing and the PLAY icon while it is paused, and the params are
84
+ * re-committed when the playback state changes so the platform picks
85
+ * the new icon up. A static icon is a lie the user can see.
67
86
  *
68
87
  * @param context Application or Activity context for PendingIntents.
69
88
  * @param aspect Video aspect ratio as a float (e.g., 16f / 9f for 16:9).
70
89
  * Clamped to the Android PiP-allowed range [0.42, 2.38]
71
90
  * before being encoded as an integer Rational.
72
- * @param sourceRectHint Optional bounds for smooth PiP entry animation.
91
+ * @param sourceRectHint The region of the window the VIDEO occupies. It is
92
+ * a TRANSITION hint: the platform animates the PiP
93
+ * window FROM that region. It does NOT crop the
94
+ * app's window — measured on emulator-5554 (API 37)
95
+ * on 2026-11-04, with the hint committed the PiP
96
+ * window showed the app's FULL chrome, scaled
97
+ * down.
73
98
  * @param chapterTitle Current chapter title for notification text (Android 12+).
74
99
  * @param progressPercentage Percentage string like "45%" for notification text (Android 12+).
100
+ * @param playing Whether the video is playing right now — it picks
101
+ * the action's icon.
102
+ * @param autoEnter Whether the platform may enter PiP by itself when
103
+ * the user leaves the app (Android 12+). Armed only
104
+ * while media is loaded.
75
105
  */
76
106
  fun buildPipParams(
77
107
  context: Context,
@@ -79,10 +109,12 @@ object PipManager {
79
109
  sourceRectHint: Rect? = null,
80
110
  chapterTitle: String? = null,
81
111
  progressPercentage: String? = null,
112
+ playing: Boolean = false,
113
+ autoEnter: Boolean = false,
82
114
  ): 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.
115
+ // The params carry the RemoteAction, and the platform's PiP action
116
+ // row is the ONLY way it can ever be fired. So the receiver that
117
+ // serves it has to exist before these params do.
86
118
  //
87
119
  // Registering here — at the single place the params are built —
88
120
  // makes it impossible to hand the platform a set of buttons that
@@ -93,42 +125,22 @@ object PipManager {
93
125
 
94
126
  val actions = mutableListOf<RemoteAction>()
95
127
 
96
- // Play/Pause
128
+ // Play/Pause — the ONE action, with a state-driven icon.
97
129
  actions.add(
98
130
  buildRemoteAction(
99
131
  context = context,
100
- iconResId = android.R.drawable.ic_media_play,
101
- title = "Play/Pause",
102
- contentDescription = "Toggle playback",
132
+ iconResId = if (playing) {
133
+ android.R.drawable.ic_media_pause
134
+ } else {
135
+ android.R.drawable.ic_media_play
136
+ },
137
+ title = if (playing) "Pause" else "Play",
138
+ contentDescription = if (playing) "Pause playback" else "Resume playback",
103
139
  action = ACTION_PLAY_PAUSE,
104
140
  requestCode = REQ_PLAY_PAUSE,
105
141
  ),
106
142
  )
107
143
 
108
- // Expand to Fullscreen
109
- actions.add(
110
- buildRemoteAction(
111
- context = context,
112
- iconResId = android.R.drawable.ic_menu_zoom,
113
- title = "Expand",
114
- contentDescription = "Expand to fullscreen",
115
- action = ACTION_EXPAND,
116
- requestCode = REQ_EXPAND,
117
- ),
118
- )
119
-
120
- // Close
121
- actions.add(
122
- buildRemoteAction(
123
- context = context,
124
- iconResId = android.R.drawable.ic_menu_close_clear_cancel,
125
- title = "Close",
126
- contentDescription = "Close player",
127
- action = ACTION_CLOSE,
128
- requestCode = REQ_CLOSE,
129
- ),
130
- )
131
-
132
144
  // Aspect ratio: clamped to PiP-allowed range, then encoded as an
133
145
  // integer Rational. Android's `Rational` constructor only accepts
134
146
  // ints; multiplying by 100 gives ~1% precision (a 1920x1080
@@ -154,43 +166,47 @@ object PipManager {
154
166
  builder.setSeamlessResizeEnabled(true)
155
167
  }
156
168
 
157
- // NO `setAutoEnterEnabled` HERE, and that is deliberate.
169
+ // Auto-enter (Android 12+). DELIBERATELY NOT ARMED.
158
170
  //
159
171
  // 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
+ // activity into PiP when the user leaves the app. It does that
173
+ // through the Shell transition, and the app's own hooks are never
174
+ // consulted: `Activity.onUserLeaveHint()` did not fire at all on a
175
+ // HOME press (measured on emulator-5554, API 37, 2026-11-04 — zero
176
+ // log lines), and ATMS refuses an explicit entry while the switch
177
+ // is armed ("auto-enter should take in place instead").
172
178
  //
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`.
179
+ // So with the switch armed the library had NO pre-transition hook
180
+ // at all: the platform froze the window with the consumer's chrome
181
+ // still mounted, and the PiP window showed the whole chrome scaled
182
+ // down.
180
183
  //
181
- // So auto-enter on leave is performed by the LIBRARY, natively, in
182
- // the only order that works: hide the chrome, then ask for the
183
- // window. The library's part is to hide the consumer's chrome
184
- // natively (a View-system mutation, so it lands without a React
185
- // commit) and to keep the params it hands the platform free of
186
- // the platform's own auto-enter switch.
184
+ // AOSP's own hook for this case is
185
+ // `Activity.onPictureInPictureRequested()` (API 31+): the system
186
+ // asks the app, and the app enters PiP itself. Returning `true`
187
+ // from it also stops the framework from falling back to the legacy
188
+ // `onUserLeaveHint()` path.
187
189
  //
188
- // The consumer's Activity overrides `onUserLeaveHint()` and calls
189
- // `MpvBridgeModule.notifyUserLeaveHint(activity)`, which works on
190
- // every API level, unlike the platform switch (API 31+).
190
+ // `autoEnter` therefore stays a CONSUMER POLICY, checked by the
191
+ // library before it enters, and never a platform switch.
192
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && autoEnter) {
193
+ // Intentionally NOT `setAutoEnterEnabled(true)`.
194
+ builder.setAutoEnterEnabled(false)
195
+ }
191
196
 
192
- // Source rect hint for smooth entry animation (Android 12+)
193
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && sourceRectHint != null) {
197
+ // Source rect hint (Android 8.0+, API 26)
198
+ //
199
+ // `PictureInPictureParams.Builder.setSourceRectHint(Rect)` was added
200
+ // in API 26, not API 31 - the API 31 call is the TWO-rect overload.
201
+ // react-native-video and expo-video both hand the hint over from
202
+ // API 26, so gating it on API 31 threw away the entry animation on
203
+ // every device below Android 12 for no reason.
204
+ //
205
+ // This is the rect the PiP window ANIMATES FROM — a transition
206
+ // hint, nothing more. It does not crop the app's window, so it is
207
+ // NOT what keeps the app's chrome out of the PiP window; the
208
+ // consumer's chrome is hidden before the entry, in native code.
209
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && sourceRectHint != null) {
194
210
  builder.setSourceRectHint(sourceRectHint)
195
211
  }
196
212
 
@@ -265,23 +281,24 @@ object PipManager {
265
281
  * `internal` on purpose: registering the receiver is THIS library's
266
282
  * job (see [registerActionReceiver]), and a public helper would
267
283
  * only invite a consumer to register a second receiver for the same
268
- * three actions. Two receivers means every action is delivered
269
- * twice, and a play/pause that toggles twice leaves playback exactly
270
- * where it was — a row of buttons that look alive and do nothing.
284
+ * action. Two receivers means every action is delivered twice, and a
285
+ * play/pause that toggles twice leaves playback exactly where it was
286
+ * — a button that looks alive and does nothing.
287
+ *
288
+ * Only the play/pause action is filtered on: it is the ONLY action the
289
+ * params carry (the platform renders its own expand / close), so an
290
+ * expand / close broadcast can no longer arrive.
271
291
  */
272
292
  internal fun intentFilter(): IntentFilter {
273
293
  return IntentFilter().apply {
274
294
  addAction(ACTION_PLAY_PAUSE)
275
- addAction(ACTION_EXPAND)
276
- addAction(ACTION_CLOSE)
277
295
  }
278
296
  }
279
297
 
280
298
  // ── Receiver registration ─────────────────────────────────────────────
281
299
 
282
300
  /**
283
- * Registers [PipActionReceiver] for the three PiP actions — ONCE per
284
- * process.
301
+ * Registers [PipActionReceiver] for the PiP action — ONCE per process.
285
302
  *
286
303
  * The application context is used on purpose: the receiver has to
287
304
  * outlive any Activity, because the platform's PiP action row can
@@ -315,22 +332,33 @@ object PipManager {
315
332
  // ── BroadcastReceiver for PiP Actions ──────────────────────────────────────
316
333
 
317
334
  /**
318
- * Receives PiP RemoteAction broadcasts and forwards them to the React Native
319
- * event layer via [com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter].
335
+ * Receives the PiP RemoteAction broadcast and acts on it NATIVELY.
320
336
  *
321
337
  * Registered by THIS library, once per process, on the application context
322
338
  * — see [PipManager.registerActionReceiver]. The consumer app does not
323
339
  * register it and does not need to know the class exists.
324
340
  *
325
- * It is a RUNTIME registration on purpose: the three action strings are
326
- * owned by [PipManager] as Kotlin constants, and a manifest declaration
327
- * would have to repeat them as literals — two owners for one fact. The
328
- * broadcast those constants feed is implicit, so it matches a runtime
329
- * registration by action. (An EXPLICIT broadcast would need a manifest
330
- * declaration instead; see [PipManager.buildRemoteAction] for the
331
- * measured reason that shape never worked.)
341
+ * It is a RUNTIME registration on purpose: the action string is owned by
342
+ * [PipManager] as a Kotlin constant, and a manifest declaration would have
343
+ * to repeat it as a literal — two owners for one fact. The broadcast that
344
+ * constant feeds is implicit, so it matches a runtime registration by
345
+ * action. (An EXPLICIT broadcast would need a manifest declaration instead;
346
+ * see [PipManager.buildRemoteAction] for the measured reason that shape
347
+ * never worked.)
348
+ *
349
+ * ## The action is handled IN THE ENGINE, with no JS round trip
332
350
  *
333
- * v3: Handles 3 actions — play/pause, expand (restore fullscreen), close (end session).
351
+ * The play/pause action used to travel broadcast → JS event → bridge →
352
+ * mpv, and this file's own comment recorded why that shape is fragile: the
353
+ * broadcast can arrive after the JS bundle has unloaded. So the action is
354
+ * delivered to the engine directly, through [PlaybackHost] and
355
+ * [com.simba.player.mpv.MPVLib] — the same way `MediaPlaybackService`'s
356
+ * session callbacks drive playback.
357
+ *
358
+ * The `onPipPlayPause` event still exists in the library's JS API, for
359
+ * consumers that listen to it, but it is NOT the mechanism that pauses
360
+ * playback: the engine call below is, and it happens whether or not there
361
+ * is a JS bundle to receive an event.
334
362
  */
335
363
  class PipActionReceiver : BroadcastReceiver() {
336
364
 
@@ -340,51 +368,46 @@ class PipActionReceiver : BroadcastReceiver() {
340
368
 
341
369
  override fun onReceive(context: Context, intent: Intent) {
342
370
  when (intent.action) {
343
- PipManager.ACTION_PLAY_PAUSE -> {
344
- emitEvent(context, "onPipPlayPause", null)
345
- }
346
- PipManager.ACTION_EXPAND -> {
347
- emitEvent(context, "onPipExpand", null)
348
- }
349
- PipManager.ACTION_CLOSE -> {
350
- emitEvent(context, "onPipClose", null)
351
- }
371
+ PipManager.ACTION_PLAY_PAUSE -> togglePlayback()
352
372
  }
353
373
  }
354
374
 
355
- private fun emitEvent(context: Context, eventName: String, params: android.os.Bundle?) {
356
- try {
357
- val reactContext = getReactContext(context)
358
- reactContext
359
- .getJSModule(com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
360
- ?.emit(eventName, params)
361
- } catch (e: Exception) {
362
- // The React context is not available — the broadcast can arrive
363
- // after the JS bundle has unloaded, and there is no UI to update
364
- // in that case.
365
- //
366
- // It is still LOGGED, and that is the point. A silent catch
367
- // here is how the PiP action row could render three buttons
368
- // that did nothing, with not one line in the log to say so.
369
- android.util.Log.w(TAG, "cannot emit $eventName: no React context", e)
375
+ /**
376
+ * Toggle playback in the engine.
377
+ *
378
+ * The state is read from mpv at the moment of the tap, so the button
379
+ * toggles what is actually happening rather than what it last
380
+ * believed.
381
+ */
382
+ private fun togglePlayback() {
383
+ val ptr = PlaybackHost.handle()
384
+ if (ptr == 0L) {
385
+ android.util.Log.w(TAG, "cannot toggle playback: no engine handle")
386
+ return
370
387
  }
371
- }
372
-
373
- private fun getReactContext(context: Context): ReactContext {
374
- val app = context.applicationContext as? ReactApplication
375
- ?: throw IllegalStateException("Application is not a ReactApplication")
376
- // Bridgeless RN (0.76+): prefer `reactHost.currentReactContext`.
377
- // Legacy bridged: fall back to `reactNativeHost.reactInstanceManager.currentReactContext`.
378
- // We try bridgeless first because the consumer app runs in
379
- // bridgeless mode (per V12 plan), but the legacy fallback covers
380
- // any build that hasn't migrated yet.
381
- val bridgeless = try {
382
- app.reactHost?.currentReactContext
383
- } catch (_: Exception) {
384
- null
388
+ // The state is read through the ONE owner, from mpv's REAL
389
+ // properties (`idle-active`, `eof-reached`, `pause`).
390
+ //
391
+ // It used to read `playback-state` — a property mpv does NOT
392
+ // have. The read failed, the answer was "not playing", and the
393
+ // button called PLAY on an already-playing video: a button that
394
+ // looked alive and did nothing. Measured on emulator-5554
395
+ // (API 37) on 2026-11-04.
396
+ val state = com.simba.player.mpv.PlaybackState.live()
397
+ try {
398
+ if (com.simba.player.mpv.PlaybackState.isPlaying(state)) {
399
+ com.simba.player.mpv.MPVLib.nativePause(ptr)
400
+ android.util.Log.i(TAG, "play/pause: paused")
401
+ } else {
402
+ com.simba.player.mpv.MPVLib.nativePlay(ptr)
403
+ android.util.Log.i(TAG, "play/pause: played")
404
+ }
405
+ } catch (t: Throwable) {
406
+ android.util.Log.w(TAG, "cannot toggle playback", t)
407
+ return
385
408
  }
386
- if (bridgeless != null) return bridgeless
387
- return app.reactNativeHost?.reactInstanceManager?.currentReactContext
388
- ?: throw IllegalStateException("ReactContext not available")
409
+ // The action's icon is state-driven, so the committed params have
410
+ // to be re-committed for the platform to pick the new one up.
411
+ com.simba.player.mpv.MpvBridgeModule.onPlaybackStateChanged()
389
412
  }
390
413
  }
@@ -7,11 +7,14 @@ package com.simba.player
7
7
  *
8
8
  * The HOME path enters PiP from NATIVE code — `MpvBridgeModule`'s
9
9
  * companion, `notifyUserLeaveHint(activity)` — because by the time the
10
- * user presses HOME, React Native has already paused the React
11
- * scheduler with the Activity: a React commit cannot land and there is
12
- * no frame clock. Measured on emulator-5554 (API 37) on 2026-11-03: the
13
- * JS handler ran immediately, the effect that would have driven the
14
- * entry ran 5.7 s late, and the `requestAnimationFrame` never fired.
10
+ * user presses HOME, React Native has ALREADY frozen: `FabricUIManager
11
+ * .onHostPause()` removes the DISPATCH_UI frame callback, so mount items
12
+ * are never applied to native views, and `JavaTimerManager.onHostPause()`
13
+ * freezes the timer registry, so `requestAnimationFrame` never fires.
14
+ * The JS runtime itself keeps running. Measured on emulator-5554 (API
15
+ * 37) on 2026-11-03: the JS handler ran immediately, the effect that
16
+ * would have driven the entry ran 5.7 s late, and the
17
+ * `requestAnimationFrame` never fired.
15
18
  *
16
19
  * That native path has to produce the SAME two facts the JS path
17
20
  * produces — a title and a progress percentage — and it has to format
@@ -83,4 +86,5 @@ internal object PipNativeEntry {
83
86
  val ratio = (positionMs.toDouble() / durationMs.toDouble()) * 100.0
84
87
  return "${kotlin.math.floor(ratio + 0.5).toInt()} %"
85
88
  }
89
+
86
90
  }