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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,56 @@ 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. The
92
+ * platform crops the app's window to this rect, so
93
+ * it is what keeps the app's chrome out of the PiP
94
+ * window.
73
95
  * @param chapterTitle Current chapter title for notification text (Android 12+).
74
96
  * @param progressPercentage Percentage string like "45%" for notification text (Android 12+).
97
+ * @param playing Whether the video is playing right now — it picks
98
+ * the action's icon.
99
+ * @param autoEnter Whether the platform may enter PiP by itself when
100
+ * the user leaves the app (Android 12+). Armed only
101
+ * while media is loaded.
75
102
  */
76
103
  fun buildPipParams(
77
104
  context: Context,
@@ -79,10 +106,12 @@ object PipManager {
79
106
  sourceRectHint: Rect? = null,
80
107
  chapterTitle: String? = null,
81
108
  progressPercentage: String? = null,
109
+ playing: Boolean = false,
110
+ autoEnter: Boolean = false,
82
111
  ): 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.
112
+ // The params carry the RemoteAction, and the platform's PiP action
113
+ // row is the ONLY way it can ever be fired. So the receiver that
114
+ // serves it has to exist before these params do.
86
115
  //
87
116
  // Registering here — at the single place the params are built —
88
117
  // makes it impossible to hand the platform a set of buttons that
@@ -93,42 +122,22 @@ object PipManager {
93
122
 
94
123
  val actions = mutableListOf<RemoteAction>()
95
124
 
96
- // Play/Pause
125
+ // Play/Pause — the ONE action, with a state-driven icon.
97
126
  actions.add(
98
127
  buildRemoteAction(
99
128
  context = context,
100
- iconResId = android.R.drawable.ic_media_play,
101
- title = "Play/Pause",
102
- contentDescription = "Toggle playback",
129
+ iconResId = if (playing) {
130
+ android.R.drawable.ic_media_pause
131
+ } else {
132
+ android.R.drawable.ic_media_play
133
+ },
134
+ title = if (playing) "Pause" else "Play",
135
+ contentDescription = if (playing) "Pause playback" else "Resume playback",
103
136
  action = ACTION_PLAY_PAUSE,
104
137
  requestCode = REQ_PLAY_PAUSE,
105
138
  ),
106
139
  )
107
140
 
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
141
  // Aspect ratio: clamped to PiP-allowed range, then encoded as an
133
142
  // integer Rational. Android's `Rational` constructor only accepts
134
143
  // ints; multiplying by 100 gives ~1% precision (a 1920x1080
@@ -154,43 +163,38 @@ object PipManager {
154
163
  builder.setSeamlessResizeEnabled(true)
155
164
  }
156
165
 
157
- // NO `setAutoEnterEnabled` HERE, and that is deliberate.
166
+ // Auto-enter (Android 12+).
158
167
  //
159
168
  // 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.
169
+ // activity into PiP when the user leaves the app, and it does that
170
+ // from the LAST COMMITTED params — which is why the library commits
171
+ // them early and keeps them current.
163
172
  //
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.
173
+ // It is armed ONLY while media is loaded (`autoEnter`). Arming it
174
+ // with nothing playing would throw the user into a PiP window of a
175
+ // stopped session the moment they browsed the Home screen.
172
176
  //
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`.
177
+ // While it is armed, ATMS REFUSES an explicit
178
+ // `enterPictureInPictureMode()` — "auto-enter should take in place
179
+ // instead" — so the library's own entry path is a logged no-op on
180
+ // API 31+ and the explicit entry is kept for API 24-30.
181
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && autoEnter) {
182
+ builder.setAutoEnterEnabled(true)
183
+ }
184
+
185
+ // Source rect hint (Android 8.0+, API 26)
180
186
  //
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.
187
+ // `PictureInPictureParams.Builder.setSourceRectHint(Rect)` was added
188
+ // in API 26, not API 31 - the API 31 call is the TWO-rect overload.
189
+ // react-native-video and expo-video both hand the hint over from
190
+ // API 26, so gating it on API 31 threw away the entry animation on
191
+ // every device below Android 12 for no reason.
187
192
  //
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+).
191
-
192
- // Source rect hint for smooth entry animation (Android 12+)
193
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && sourceRectHint != null) {
193
+ // This is also the rect the platform CROPS the app's window to, so
194
+ // it is what keeps the app's chrome out of the PiP window. That is
195
+ // why the library commits the params early instead of handing them
196
+ // over only at the entry moment.
197
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && sourceRectHint != null) {
194
198
  builder.setSourceRectHint(sourceRectHint)
195
199
  }
196
200
 
@@ -265,23 +269,24 @@ object PipManager {
265
269
  * `internal` on purpose: registering the receiver is THIS library's
266
270
  * job (see [registerActionReceiver]), and a public helper would
267
271
  * 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.
272
+ * action. Two receivers means every action is delivered twice, and a
273
+ * play/pause that toggles twice leaves playback exactly where it was
274
+ * — a button that looks alive and does nothing.
275
+ *
276
+ * Only the play/pause action is filtered on: it is the ONLY action the
277
+ * params carry (the platform renders its own expand / close), so an
278
+ * expand / close broadcast can no longer arrive.
271
279
  */
272
280
  internal fun intentFilter(): IntentFilter {
273
281
  return IntentFilter().apply {
274
282
  addAction(ACTION_PLAY_PAUSE)
275
- addAction(ACTION_EXPAND)
276
- addAction(ACTION_CLOSE)
277
283
  }
278
284
  }
279
285
 
280
286
  // ── Receiver registration ─────────────────────────────────────────────
281
287
 
282
288
  /**
283
- * Registers [PipActionReceiver] for the three PiP actions — ONCE per
284
- * process.
289
+ * Registers [PipActionReceiver] for the PiP action — ONCE per process.
285
290
  *
286
291
  * The application context is used on purpose: the receiver has to
287
292
  * outlive any Activity, because the platform's PiP action row can
@@ -315,22 +320,33 @@ object PipManager {
315
320
  // ── BroadcastReceiver for PiP Actions ──────────────────────────────────────
316
321
 
317
322
  /**
318
- * Receives PiP RemoteAction broadcasts and forwards them to the React Native
319
- * event layer via [com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter].
323
+ * Receives the PiP RemoteAction broadcast and acts on it NATIVELY.
320
324
  *
321
325
  * Registered by THIS library, once per process, on the application context
322
326
  * — see [PipManager.registerActionReceiver]. The consumer app does not
323
327
  * register it and does not need to know the class exists.
324
328
  *
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.)
329
+ * It is a RUNTIME registration on purpose: the action string is owned by
330
+ * [PipManager] as a Kotlin constant, and a manifest declaration would have
331
+ * to repeat it as a literal — two owners for one fact. The broadcast that
332
+ * constant feeds is implicit, so it matches a runtime registration by
333
+ * action. (An EXPLICIT broadcast would need a manifest declaration instead;
334
+ * see [PipManager.buildRemoteAction] for the measured reason that shape
335
+ * never worked.)
336
+ *
337
+ * ## The action is handled IN THE ENGINE, with no JS round trip
332
338
  *
333
- * v3: Handles 3 actions — play/pause, expand (restore fullscreen), close (end session).
339
+ * The play/pause action used to travel broadcast → JS event → bridge →
340
+ * mpv, and this file's own comment recorded why that shape is fragile: the
341
+ * broadcast can arrive after the JS bundle has unloaded. So the action is
342
+ * delivered to the engine directly, through [PlaybackHost] and
343
+ * [com.simba.player.mpv.MPVLib] — the same way `MediaPlaybackService`'s
344
+ * session callbacks drive playback.
345
+ *
346
+ * The `onPipPlayPause` event still exists in the library's JS API, for
347
+ * consumers that listen to it, but it is NOT the mechanism that pauses
348
+ * playback: the engine call below is, and it happens whether or not there
349
+ * is a JS bundle to receive an event.
334
350
  */
335
351
  class PipActionReceiver : BroadcastReceiver() {
336
352
 
@@ -340,51 +356,43 @@ class PipActionReceiver : BroadcastReceiver() {
340
356
 
341
357
  override fun onReceive(context: Context, intent: Intent) {
342
358
  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
- }
359
+ PipManager.ACTION_PLAY_PAUSE -> togglePlayback()
352
360
  }
353
361
  }
354
362
 
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)
363
+ /**
364
+ * Toggle playback in the engine.
365
+ *
366
+ * The state is read from mpv at the moment of the tap, so the button
367
+ * toggles what is actually happening rather than what it last
368
+ * believed.
369
+ */
370
+ private fun togglePlayback() {
371
+ val ptr = PlaybackHost.handle()
372
+ if (ptr == 0L) {
373
+ android.util.Log.w(TAG, "cannot toggle playback: no engine handle")
374
+ return
370
375
  }
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) {
376
+ val state = try {
377
+ com.simba.player.mpv.MPVLib.nativeGetProperty(ptr, "playback-state")
378
+ } catch (t: Throwable) {
379
+ android.util.Log.w(TAG, "cannot read playback-state", t)
384
380
  null
385
381
  }
386
- if (bridgeless != null) return bridgeless
387
- return app.reactNativeHost?.reactInstanceManager?.currentReactContext
388
- ?: throw IllegalStateException("ReactContext not available")
382
+ try {
383
+ if (PipNativeEntry.isPlaying(state)) {
384
+ com.simba.player.mpv.MPVLib.nativePause(ptr)
385
+ android.util.Log.i(TAG, "play/pause: paused")
386
+ } else {
387
+ com.simba.player.mpv.MPVLib.nativePlay(ptr)
388
+ android.util.Log.i(TAG, "play/pause: played")
389
+ }
390
+ } catch (t: Throwable) {
391
+ android.util.Log.w(TAG, "cannot toggle playback", t)
392
+ return
393
+ }
394
+ // The action's icon is state-driven, so the committed params have
395
+ // to be re-committed for the platform to pick the new one up.
396
+ com.simba.player.mpv.MpvBridgeModule.onPlaybackStateChanged()
389
397
  }
390
398
  }
@@ -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,23 @@ 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
+
90
+ /**
91
+ * Whether mpv is PLAYING right now, from its `playback-state`.
92
+ *
93
+ * mpv's `playback-state` is one of `idle`, `loading`, `play`, `pause`,
94
+ * `stopped`, `eof-reached`. Only `play` means the picture is moving.
95
+ *
96
+ * `eof-reached` is NOT playing: the file ended, and the engine is
97
+ * sitting on its last frame. A play/pause button that shows "play"
98
+ * for an ended file is right, so the state has to be read, not
99
+ * guessed.
100
+ *
101
+ * The property arrives JSON-encoded, so it is trimmed of its quotes
102
+ * before it is compared.
103
+ */
104
+ fun isPlaying(playbackState: String?): Boolean {
105
+ val state = playbackState?.trim()?.trim('"')?.trim() ?: return false
106
+ return state.equals("play", ignoreCase = true)
107
+ }
86
108
  }