@simba-dev/react-native-media-player 1.13.1 → 1.13.3

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.
@@ -1282,27 +1282,85 @@ class PlayerActivity : ReactActivity() {
1282
1282
  }
1283
1283
 
1284
1284
  /**
1285
- * Phase 10.7: back-button behaviour. V11's contract was: pressing
1286
- * back while in PiP finishes the activity (exits PiP, returns to
1287
- * the parent app) — back from fullscreen does default behaviour.
1288
- * V12 keeps the same contract.
1285
+ * Back-button behaviour.
1289
1286
  *
1290
- * NOTE: `onBackPressed` is deprecated in API 33+; the platform
1291
- * wants apps to use `OnBackInvokedCallback` (predictive back
1292
- * gesture). For Phase 10 we keep the V11 approach and guard by
1293
- * `isInPictureInPictureMode`; a Phase 35 hardening pass will move
1294
- * to the new API for API 33+ targets.
1287
+ * ## Why this does the teardown itself
1288
+ *
1289
+ * This used to be:
1290
+ *
1291
+ * ```kotlin
1292
+ * if (isInPictureInPictureMode) { finish(); return }
1293
+ * super.onBackPressed()
1294
+ * ```
1295
+ *
1296
+ * which finishes the Activity **natively**. The event never reaches
1297
+ * React Native, so a JS `BackHandler` cannot run — which left two back
1298
+ * paths that disagreed:
1299
+ *
1300
+ * - the header chevron -> JS `exitPlayer()` -> stop the engine,
1301
+ * release the foreground service, then finish;
1302
+ * - the hardware key -> `super.onBackPressed()` -> finish only.
1303
+ *
1304
+ * Since the mpv engine is a process-global C++ handle that outlives any
1305
+ * Activity, the second path closed the window while the media carried
1306
+ * on: audio still audible, notification still posted, no window left to
1307
+ * stop it. Verified on device — after the hardware key the media
1308
+ * session was still `PLAYING` with zero `stopPlayback` / `nativeStop`
1309
+ * lines in logcat, even with a JS BackHandler registered.
1310
+ *
1311
+ * ## Why natively rather than delegating to JS
1312
+ *
1313
+ * Delegating would make the player un-closable whenever the bundle is
1314
+ * unhealthy — a JS crash would strand a playing session with no window
1315
+ * and no working dismiss. The Activity already owns the engine through
1316
+ * `PlaybackHost`, so the teardown here is both shorter and strictly
1317
+ * more robust.
1318
+ *
1319
+ * The JS `BackHandler` in `VideoPlayer.tsx` is KEPT: it covers whatever
1320
+ * does reach React (notably predictive back, where `onBackPressed` is
1321
+ * never called), and the two paths now agree.
1295
1322
  */
1296
1323
  override fun onBackPressed() {
1297
1324
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && isInPictureInPictureMode) {
1298
1325
  // Finish exits PiP and returns the user to MainActivity (the
1299
- // parent of PlayerActivity in the task stack). This matches the
1300
- // V11 behaviour bit-for-bit.
1326
+ // parent of PlayerActivity in the task stack).
1301
1327
  Log.i(TAG, "onBackPressed: in PiP, finishing PlayerActivity")
1302
1328
  finish()
1303
1329
  return
1304
1330
  }
1305
- super.onBackPressed()
1331
+
1332
+ // Not PiP: leaving means CLOSING. Stop the engine unconditionally —
1333
+ // if the service is already gone its own stop callback is not around
1334
+ // to do it, and leaving media running with no way to stop it is the
1335
+ // worse of the two failures.
1336
+ val ptr = PlaybackHost.handle()
1337
+ if (ptr != 0L) {
1338
+ try {
1339
+ MPVLib.nativeStop(ptr)
1340
+ Log.i(TAG, "onBackPressed: stopped mpv (ptr=$ptr)")
1341
+ } catch (e: Throwable) {
1342
+ Log.w(TAG, "onBackPressed: nativeStop threw ${e.message}")
1343
+ }
1344
+ } else {
1345
+ Log.w(TAG, "onBackPressed: no engine handle; nothing to stop")
1346
+ }
1347
+
1348
+ if (MediaPlaybackService.isRunning()) {
1349
+ try {
1350
+ // Plain startService: the service is already foreground, so there
1351
+ // is no startForeground deadline to meet.
1352
+ startService(
1353
+ android.content.Intent(this, MediaPlaybackService::class.java).apply {
1354
+ action = MediaPlaybackService.ACTION_STOP
1355
+ },
1356
+ )
1357
+ Log.i(TAG, "onBackPressed: delivered ACTION_STOP to MediaPlaybackService")
1358
+ } catch (e: Throwable) {
1359
+ Log.e(TAG, "onBackPressed: could not deliver ACTION_STOP", e)
1360
+ }
1361
+ }
1362
+
1363
+ finish()
1306
1364
  }
1307
1365
 
1308
1366
  // ── PiP helpers (Phase 9) ──────────────────────────────────────────
@@ -15,6 +15,7 @@ import com.facebook.react.bridge.ReadableArray
15
15
  import com.facebook.react.bridge.ReadableMap
16
16
  import com.facebook.react.bridge.ReactApplicationContext
17
17
  import com.facebook.react.bridge.ReactMethod
18
+ import com.facebook.react.bridge.UiThreadUtil
18
19
  import com.facebook.react.module.annotations.ReactModule
19
20
  import com.facebook.react.modules.core.DeviceEventManagerModule
20
21
  import com.facebook.fbreact.specs.NativeMpvPlayerSpec
@@ -2121,6 +2122,67 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2121
2122
  override fun isAudioPlaybackServiceRunning(): Boolean =
2122
2123
  com.simba.player.MediaPlaybackService.isRunning()
2123
2124
 
2125
+ // ── V21: single-Activity surface control ────────────────────────────
2126
+ //
2127
+ // These take a Promise rather than being `isBlockingSynchronousMethod`
2128
+ // because view mutation is main-thread-only while a blocking sync method
2129
+ // runs on the module queue. The Promise carries the result back so JS can
2130
+ // distinguish "the surface moved" from "there was no surface to move",
2131
+ // and disable a control rather than render one that quietly does nothing.
2132
+
2133
+ /**
2134
+ * Resize the video surface to an absolute rect inside its container.
2135
+ *
2136
+ * Resolves `false` — never throws — when no surface is mounted, the call
2137
+ * arrives off the main thread, or the extents are non-positive. A caller
2138
+ * that gets `false` must not treat the video as presented.
2139
+ */
2140
+ @ReactMethod
2141
+ override fun setVideoBounds(
2142
+ x: Double,
2143
+ y: Double,
2144
+ width: Double,
2145
+ height: Double,
2146
+ promise: Promise,
2147
+ ) {
2148
+ UiThreadUtil.runOnUiThread {
2149
+ promise.resolve(
2150
+ PlayerSurface.setBounds(x.toInt(), y.toInt(), width.toInt(), height.toInt()),
2151
+ )
2152
+ }
2153
+ }
2154
+
2155
+ /** Expand the video surface to fill its container. Resolves `false` if it did not. */
2156
+ @ReactMethod
2157
+ override fun fillVideoBounds(promise: Promise) {
2158
+ UiThreadUtil.runOnUiThread {
2159
+ promise.resolve(PlayerSurface.fillBounds())
2160
+ }
2161
+ }
2162
+
2163
+ /**
2164
+ * Show or hide the video surface.
2165
+ *
2166
+ * Hiding is the correct state for audio-only playback: mpv keeps running
2167
+ * with no render target, which is exactly what an audio session needs.
2168
+ */
2169
+ @ReactMethod
2170
+ override fun setSurfaceVisible(visible: Boolean, promise: Promise) {
2171
+ UiThreadUtil.runOnUiThread {
2172
+ promise.resolve(PlayerSurface.setVisible(visible))
2173
+ }
2174
+ }
2175
+
2176
+ /**
2177
+ * Whether a video surface is currently mounted and usable.
2178
+ *
2179
+ * Lets a control decide its own affordance instead of assuming a surface
2180
+ * exists because the user is on a video screen.
2181
+ */
2182
+ @ReactMethod(isBlockingSynchronousMethod = true)
2183
+ @Override
2184
+ override fun isSurfaceMounted(): Boolean = PlayerSurface.current() != null
2185
+
2124
2186
  /**
2125
2187
  * `ReadableMap` reads that tolerate absent keys.
2126
2188
  *
@@ -2,9 +2,11 @@ package com.simba.player.mpv
2
2
 
3
3
  import android.content.Context
4
4
  import android.util.Log
5
+ import android.view.Gravity
5
6
  import android.view.SurfaceHolder
6
7
  import android.view.SurfaceView
7
- import android.view.ViewGroup
8
+ import android.view.View
9
+ import android.widget.FrameLayout
8
10
 
9
11
  /**
10
12
  * SurfaceView-backed video renderer that hands an Android Surface to libmpv
@@ -71,9 +73,9 @@ class MpvRenderView(context: Context) : SurfaceView(context),
71
73
 
72
74
  init {
73
75
  holder.addCallback(this)
74
- layoutParams = ViewGroup.LayoutParams(
75
- ViewGroup.LayoutParams.MATCH_PARENT,
76
- ViewGroup.LayoutParams.MATCH_PARENT
76
+ layoutParams = FrameLayout.LayoutParams(
77
+ FrameLayout.LayoutParams.MATCH_PARENT,
78
+ FrameLayout.LayoutParams.MATCH_PARENT
77
79
  )
78
80
  // Default z-order (BELOW the activity window) is intentional and
79
81
  // required for PiP. Do NOT call setZOrderOnTop or setZOrderMediaOverlay.
@@ -81,7 +83,65 @@ class MpvRenderView(context: Context) : SurfaceView(context),
81
83
  isClickable = false
82
84
  }
83
85
 
84
- // ── SurfaceHolder.Callback ─────────────────────────────────────────────
86
+ // ── Bounds (V21) ──────────────────────────────────────────────────────
87
+ //
88
+ // V21 moves the player into the consumer app's single Activity, where
89
+ // the same MpvRenderView must render both fullscreen and as the
90
+ // in-app mini player's live picture.
91
+ //
92
+ // These mutate `LayoutParams` and nothing else. That distinction is
93
+ // the whole point: `removeView`/`addView` would destroy and recreate
94
+ // the Surface, forcing mpv to re-attach and flashing black, whereas a
95
+ // LayoutParams change re-lays-out the existing SurfaceView in place.
96
+ // Because the surface composites BELOW the window, shrinking it to a
97
+ // small rect leaves the React tree drawing normally everywhere else.
98
+ //
99
+ // This is the same mechanism the audio mini bar already relies on.
100
+
101
+ /**
102
+ * Place the surface at an absolute rect, in pixels, inside the host
103
+ * container. Used by the in-app mini player.
104
+ *
105
+ * Refuses non-positive extents rather than clamping: a zero-sized
106
+ * SurfaceView is an invalid target for libmpv, and silently substituting
107
+ * a default here would hide a real layout bug behind a plausible-looking
108
+ * black frame.
109
+ */
110
+ fun setVideoBounds(x: Int, y: Int, width: Int, height: Int) {
111
+ if (width <= 0 || height <= 0) {
112
+ Log.w(TAG, "setVideoBounds refused ${width}x$height at ($x,$y): extents must be > 0")
113
+ return
114
+ }
115
+ val lp = frameParams()
116
+ lp.width = width
117
+ lp.height = height
118
+ lp.gravity = Gravity.TOP or Gravity.START
119
+ lp.leftMargin = x
120
+ lp.topMargin = y
121
+ layoutParams = lp
122
+ Log.i(TAG, "setVideoBounds -> ${width}x$height at ($x,$y)")
123
+ }
124
+
125
+ /** Expand the surface to fill the host container. */
126
+ fun fillBounds() {
127
+ val lp = frameParams()
128
+ lp.width = FrameLayout.LayoutParams.MATCH_PARENT
129
+ lp.height = FrameLayout.LayoutParams.MATCH_PARENT
130
+ lp.gravity = Gravity.TOP or Gravity.START
131
+ lp.leftMargin = 0
132
+ lp.topMargin = 0
133
+ layoutParams = lp
134
+ Log.i(TAG, "fillBounds -> MATCH_PARENT")
135
+ }
136
+
137
+ private fun frameParams(): FrameLayout.LayoutParams =
138
+ (layoutParams as? FrameLayout.LayoutParams)
139
+ ?: FrameLayout.LayoutParams(
140
+ FrameLayout.LayoutParams.MATCH_PARENT,
141
+ FrameLayout.LayoutParams.MATCH_PARENT,
142
+ )
143
+
144
+ // ── Surface attachment ─────────────────────────────────────────────────
85
145
 
86
146
  override fun surfaceCreated(holder: SurfaceHolder) {
87
147
  Log.d(TAG, "surfaceCreated")
@@ -100,7 +160,7 @@ class MpvRenderView(context: Context) : SurfaceView(context),
100
160
  detachSurfaceLocked()
101
161
  }
102
162
 
103
- // ── Surface attachment ─────────────────────────────────────────────────
163
+ // ── Public API ─────────────────────────────────────────────────────────
104
164
 
105
165
  /**
106
166
  * Call when the native mpv handle is available.
@@ -110,34 +170,75 @@ class MpvRenderView(context: Context) : SurfaceView(context),
110
170
  // New handle — any previously attached surface must be rebound
111
171
  // (mpv's wid still points at the previous handle's surface).
112
172
  attachedSurface = null
113
- if (holder.surface != null && holder.surface.isValid) {
114
- attachSurfaceLocked(holder.surface)
115
- }
173
+ ensureSurfaceAttached("setNativePtr")
174
+ }
175
+
176
+ /**
177
+ * Show or hide the surface.
178
+ *
179
+ * [View.GONE] for audio-only playback: mpv keeps running audio with no
180
+ * render target, which is the correct configuration.
181
+ *
182
+ * Flipping back to [View.VISIBLE] re-evaluates the surface binding, so a
183
+ * GONE → VISIBLE transition (audio mini player → video mini player) does
184
+ * not need the caller to know anything about Surface lifetimes.
185
+ */
186
+ fun setSurfaceVisible(visible: Boolean) {
187
+ val target = if (visible) View.VISIBLE else View.GONE
188
+ if (visibility == target) return
189
+ Log.i(TAG, "setSurfaceVisible(visible=$visible)")
190
+ visibility = target
191
+ if (visible) ensureSurfaceAttached("setSurfaceVisible")
192
+ }
193
+
194
+ /**
195
+ * Re-attempt the mpv ↔ Surface binding if it is not currently established.
196
+ *
197
+ * The binding has three independent preconditions — a live mpv handle, a
198
+ * valid Surface, and this view being attached to a window — and any of
199
+ * them can become true after any other. Hooking the two lifecycle
200
+ * callbacks that can flip them means callers never have to re-assert
201
+ * the binding by hand.
202
+ */
203
+ fun ensureSurfaceAttached(reason: String) {
204
+ if (attachedSurface != null) return
205
+ if (nativePtr == 0L) return
206
+ if (!isAttachedToWindow) return
207
+ val surface = holder.surface ?: return
208
+ if (!surface.isValid) return
209
+ Log.i(TAG, "ensureSurfaceAttached($reason): binding surface to mpv")
210
+ attachSurfaceLocked(surface)
211
+ }
212
+
213
+ override fun onAttachedToWindow() {
214
+ super.onAttachedToWindow()
215
+ ensureSurfaceAttached("onAttachedToWindow")
216
+ }
217
+
218
+ override fun onVisibilityChanged(changedView: View, visibility: Int) {
219
+ super.onVisibilityChanged(changedView, visibility)
220
+ if (visibility == View.VISIBLE) ensureSurfaceAttached("onVisibilityChanged")
116
221
  }
117
222
 
118
223
  private fun attachSurfaceLocked(surface: android.view.Surface?) {
119
- // Phase 33 defensive guards (added to satisfy Phase 33.5 unit
120
- // test). The original code already guarded `nativePtr == 0L`
121
- // and `!surface.isValid`, but a null `surface` would NPE on
122
- // the `isValid` deref. In practice the public call sites
123
- // (`setNativePtr` + `surfaceCreated`) already check for null,
124
- // but a future refactor could forget — guard here too.
224
+ // Defensive guards. Each precondition can be false independently and
225
+ // legitimately — there is no error to report, only a binding that is
226
+ // not yet possible. `ensureSurfaceAttached` re-runs once the missing
227
+ // precondition becomes true.
125
228
  if (nativePtr == 0L) return
126
229
  if (surface == null) return
127
230
  if (!surface.isValid) return
128
- // Phase 12.2.1: defensive guard for audio mode (View.GONE). When
129
- // the view is set to GONE in PlayerActivity (Phase 12.1.1), it
130
- // can still receive surfaceCreated (the holder is registered
131
- // and the Surface IS created), but the view has not been
132
- // attached to a window. Trying to drive an mpv render target
133
- // that has no window is a no-op at best and a crash on some
134
- // OEMs. Returning here is safe — when the view later becomes
135
- // visible / window-attached (e.g. user expands from PiP into a
136
- // full audio UI in a future phase), the holder will fire
137
- // surfaceChanged and we'll re-evaluate via setNativePtr's
138
- // re-attach path.
231
+ // A SurfaceView that is not attached to a window has no Surface
232
+ // Flinger layer to composite, so handing it to mpv produces a render
233
+ // target that can never be seen.
234
+ //
235
+ // Note this is NOT the same condition as `visibility == GONE`: a
236
+ // GONE view is still attached to its window. An earlier revision of
237
+ // this comment claimed they were equivalent and blamed audio mode,
238
+ // which is why audio→video had no reliable path back to a bound
239
+ // surface.
139
240
  if (!isAttachedToWindow) {
140
- Log.d(TAG, "attachSurfaceLocked: view not attached to window, skipping (likely audio mode / GONE)")
241
+ Log.d(TAG, "attachSurfaceLocked: not attached to a window, deferring")
141
242
  return
142
243
  }
143
244
  if (attachedSurface === surface) return // same Surface → no-op
@@ -0,0 +1,127 @@
1
+ package com.simba.player.mpv
2
+
3
+ import android.os.Handler
4
+ import android.os.Looper
5
+ import android.util.Log
6
+ import java.lang.ref.WeakReference
7
+
8
+ /**
9
+ * V21 — process-wide registry of the single [MpvRenderView].
10
+ *
11
+ * ## Why this file exists
12
+ *
13
+ * V21 collapses the two-Activity player into one, so exactly one
14
+ * `MpvRenderView` exists in the process for the whole app lifetime. The
15
+ * Activity that mounts it and the React Native module that JS talks to are
16
+ * different objects with different lifetimes and no direct reference to each
17
+ * other, so something has to publish the view between them.
18
+ *
19
+ * This is the same shape as `PlaybackHost`, which does it for the libmpv
20
+ * handle. The difference that matters is the reference type.
21
+ *
22
+ * ## Why a WeakReference, not a strong one
23
+ *
24
+ * `PlaybackHost` can hold its value strongly because it is a `Long`. This
25
+ * object holds a `View`, and a View retains its `Context` — which for a
26
+ * mounted render surface is the Activity. A strong field here would outlive
27
+ * `onDestroy` and leak the Activity, its window, and its whole view tree for
28
+ * as long as the process lives. That is the classic static-View leak, and it
29
+ * would be invisible in testing while steadily pinning memory in production.
30
+ *
31
+ * A `WeakReference` also gives the correct ownership story for free: the
32
+ * registry observes the surface, it does not own it. The Activity mounts it,
33
+ * and the Activity destroys it. [detach] exists so the Activity can say so
34
+ * explicitly rather than waiting for collection.
35
+ *
36
+ * ## Threading
37
+ *
38
+ * View mutation is main-thread only. Every public method here marshals to the
39
+ * main looper and reports success through a synchronous result when called
40
+ * from the main thread, so JS gets an honest "did this take effect" answer.
41
+ *
42
+ * ## No silent no-ops
43
+ *
44
+ * Each mutator returns `false` and logs when there is no surface to act on.
45
+ * Callers are expected to surface that to JS so a control whose handler could
46
+ * not run renders disabled rather than inert.
47
+ */
48
+ object PlayerSurface {
49
+
50
+ private const val TAG = "PlayerSurface"
51
+
52
+ private val mainHandler = Handler(Looper.getMainLooper())
53
+
54
+ private var viewRef: WeakReference<MpvRenderView> = WeakReference(null)
55
+
56
+ /** The live surface, or `null` when nothing is mounted. Never cache the result. */
57
+ fun current(): MpvRenderView? = viewRef.get()
58
+
59
+ /**
60
+ * Publish the process's surface. Called by the hosting Activity once the
61
+ * view is mounted and bound to a window.
62
+ */
63
+ fun attach(view: MpvRenderView) {
64
+ viewRef = WeakReference(view)
65
+ Log.i(TAG, "surface attached: ${System.identityHashCode(view)}")
66
+ }
67
+
68
+ /**
69
+ * Withdraw [view], but only if it is still the registered one.
70
+ *
71
+ * The identity check matters during a configuration change: the outgoing
72
+ * Activity's `onDestroy` can run after the incoming one has already
73
+ * mounted its replacement, and an unconditional clear would leave the new
74
+ * surface unregistered — with no error anywhere, since nothing failed.
75
+ */
76
+ fun detach(view: MpvRenderView) {
77
+ if (viewRef.get() !== view) {
78
+ Log.i(TAG, "detach ignored: ${System.identityHashCode(view)} is not the registered surface")
79
+ return
80
+ }
81
+ viewRef.clear()
82
+ Log.i(TAG, "surface detached")
83
+ }
84
+
85
+ /**
86
+ * Resize the surface to an absolute rect inside its container.
87
+ *
88
+ * @return `true` when the bounds were applied.
89
+ */
90
+ fun setBounds(x: Int, y: Int, width: Int, height: Int): Boolean =
91
+ withSurface("setBounds") { it.setVideoBounds(x, y, width, height) }
92
+
93
+ /** Expand the surface to fill its container. */
94
+ fun fillBounds(): Boolean = withSurface("fillBounds") { it.fillBounds() }
95
+
96
+ /** Show or hide the surface; hidden is the correct state for audio-only playback. */
97
+ fun setVisible(visible: Boolean): Boolean =
98
+ withSurface("setVisible") { it.setSurfaceVisible(visible) }
99
+
100
+ /**
101
+ * Run [block] against the surface on the main thread.
102
+ *
103
+ * Returns synchronously when already on the main thread so the caller
104
+ * (a React Native method running on the module queue) still gets a real
105
+ * answer; otherwise posts and reports `false`, because by the time the
106
+ * block runs the caller has long since returned and there is nobody left
107
+ * to tell.
108
+ */
109
+ private fun withSurface(op: String, block: (MpvRenderView) -> Unit): Boolean {
110
+ if (Looper.myLooper() == Looper.getMainLooper()) {
111
+ val view = viewRef.get()
112
+ if (view == null) {
113
+ Log.w(TAG, "$op refused: no surface is mounted")
114
+ return false
115
+ }
116
+ return try {
117
+ block(view)
118
+ true
119
+ } catch (t: Throwable) {
120
+ Log.e(TAG, "$op threw: ${t.message}", t)
121
+ false
122
+ }
123
+ }
124
+ Log.w(TAG, "$op refused: must be called from the main thread")
125
+ return false
126
+ }
127
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.13.1",
3
+ "version": "1.13.3",
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",
@@ -417,6 +417,32 @@ export interface MpvPlayerModuleBridge {
417
417
  stopPlayback(): void;
418
418
  /** Whether the foreground service currently holds a live session. */
419
419
  isAudioPlaybackServiceRunning(): boolean;
420
+
421
+ /**
422
+ * Resize the video surface to an absolute rect inside its container.
423
+ *
424
+ * V21 places the player in the consumer app's single Activity, where the
425
+ * one surface renders both fullscreen and the in-app mini player's live
426
+ * picture. This changes layout bounds only — it never reparents or
427
+ * remounts the view, so the Surface is not destroyed and mpv does not
428
+ * re-attach.
429
+ *
430
+ * Resolves `false` when there is no surface, when the call arrives off the
431
+ * main thread, or when the extents are non-positive. A caller that gets
432
+ * `false` must not present the video as shown.
433
+ */
434
+ setVideoBounds(
435
+ x: number,
436
+ y: number,
437
+ width: number,
438
+ height: number,
439
+ ): Promise<boolean>;
440
+ /** Expand the video surface to fill its container. Resolves `false` if it did not. */
441
+ fillVideoBounds(): Promise<boolean>;
442
+ /** Show or hide the video surface. Hidden is correct for audio-only playback. */
443
+ setSurfaceVisible(visible: boolean): Promise<boolean>;
444
+ /** Whether a video surface is currently mounted and usable. */
445
+ isSurfaceMounted(): boolean;
420
446
  /**
421
447
  * One-shot accessor for the launch params the most recent
422
448
  * `openPlayer` call handed to `PlayerActivity`. Returns `null`
@@ -688,6 +714,16 @@ const NOOP_BRIDGE: MpvPlayerModuleBridge = {
688
714
  },
689
715
  stopPlayback: () => {},
690
716
  isAudioPlaybackServiceRunning: () => false,
717
+ // V21: no surface exists in the fallback environment (jest / Storybook /
718
+ // web), so every surface mutator must report that it did nothing.
719
+ // Reporting `false` rather than resolving `true` is deliberate: a caller
720
+ // that treats a resolved `true` as "the video is on screen" would render
721
+ // chrome over a surface that was never mounted — a control that looks
722
+ // live and is not, which is the failure mode this module exists to avoid.
723
+ setVideoBounds: () => Promise.resolve(false),
724
+ fillVideoBounds: () => Promise.resolve(false),
725
+ setSurfaceVisible: () => Promise.resolve(false),
726
+ isSurfaceMounted: () => false,
691
727
  // V22.0.0 / 1.5.8 (D-035 fix #6): now matches the real
692
728
  // Promise<LaunchParams | null> runtime return type.
693
729
  getLaunchParams: () => Promise.resolve(null),
@@ -254,6 +254,52 @@ export interface Spec extends TurboModule {
254
254
  * honour. Synchronous: it reads a `@Volatile` flag the service owns.
255
255
  */
256
256
  isAudioPlaybackServiceRunning(): boolean;
257
+
258
+ /**
259
+ * Resize the video surface to an absolute rect inside its container, in
260
+ * device pixels.
261
+ *
262
+ * V21 moves the player into the consumer app's single Activity, where the
263
+ * same surface renders fullscreen and as the in-app mini player's live
264
+ * picture. This mutates the surface's layout bounds — it does NOT reparent
265
+ * or remount it, so the Surface is never destroyed and mpv never re-attaches.
266
+ *
267
+ * Resolves `false` rather than throwing when no surface is mounted, when the
268
+ * call arrives off the main thread, or when the extents are non-positive. A
269
+ * caller that gets `false` must not treat the video as presented: that is
270
+ * the whole reason this is a Promise instead of a fire-and-forget void.
271
+ */
272
+ setVideoBounds(
273
+ x: number,
274
+ y: number,
275
+ width: number,
276
+ height: number,
277
+ ): Promise<boolean>;
278
+
279
+ /**
280
+ * Expand the video surface to fill its container. Resolves `false` if it
281
+ * did not take effect.
282
+ */
283
+ fillVideoBounds(): Promise<boolean>;
284
+
285
+ /**
286
+ * Show or hide the video surface.
287
+ *
288
+ * Hidden is the correct state for audio-only playback: mpv keeps running
289
+ * with no render target. Showing it re-binds the surface, so an
290
+ * audio → video handoff does not need the caller to know anything about
291
+ * Surface lifetimes.
292
+ */
293
+ setSurfaceVisible(visible: boolean): Promise<boolean>;
294
+
295
+ /**
296
+ * Whether a video surface is currently mounted and usable.
297
+ *
298
+ * Lets a control decide its own affordance instead of assuming a surface
299
+ * exists because the user happens to be on a video screen. Synchronous: it
300
+ * reads a `WeakReference`.
301
+ */
302
+ isSurfaceMounted(): boolean;
257
303
  // Returns null when no launch is pending or after the first read.
258
304
  getLaunchParams(): Promise<{
259
305
  uri: string;
@@ -597,6 +597,58 @@ export function PlayerProvider({
597
597
  // the progress equality short-circuit correct under React's
598
598
  // batching.
599
599
  const unsubs: Array<() => void> = [];
600
+
601
+ // ── 2a-bis. Re-seed the EDGE-only level fields on file load ──────────
602
+ //
603
+ // `seekable` is a LEVEL value that mpv delivers only as an EDGE:
604
+ // MPV_EVENT_PROPERTY_CHANGE fires once, at the instant the flag flips
605
+ // false -> true. Two consequences:
606
+ //
607
+ // 1. A provider that mounts (or remounts, e.g. in a second React
608
+ // root) AFTER that flip never observes the event.
609
+ // 2. In the normal launch order the flag cannot have flipped yet at
610
+ // mount time either — the file has not been loaded. The mount-time
611
+ // seed therefore reads `false`, which is correct-but-useless, and
612
+ // the later edge is the only thing that can ever set it.
613
+ //
614
+ // Measured on device (Android 37): `onCacheState`, which changes
615
+ // continuously, reached JS 827 times while `onSeekable` arrived ZERO
616
+ // times across a cold start and an app restart — the edge was consumed
617
+ // natively and never surfaced to this subscriber.
618
+ //
619
+ // So re-read the level whenever a file loads. This is the correct place
620
+ // rather than in `applyPlayerEvent`, because that function is pure and
621
+ // has no bridge access, and rather than in the consumer, because the
622
+ // consumer has no way to know the flag is an edge.
623
+ //
624
+ // Do NOT "fix" this in the UI by treating `durationMs > 0` as proof of
625
+ // seekability: a live stream can report a duration and still have no
626
+ // seekable range, and that would light up a seek bar that cannot work.
627
+ const reseedEdgeLevels = (reason: string) => {
628
+ try {
629
+ const raw = bridge.getProperty('seekable');
630
+ // The bridge serialises MPV_FORMAT_FLAG to the JSON literals
631
+ // `true` / `false`. Anything else - "null" for an unavailable
632
+ // property, "" for the NOOP bridge - is not a value and must not be
633
+ // coerced to false, which would silently un-seek a playing file.
634
+ if (raw === 'true' || raw === 'false') {
635
+ const seekable = raw === 'true';
636
+ if (seekable !== progressRef.current.seekable) {
637
+ progressRef.current = { ...progressRef.current, seekable };
638
+ setProgress(progressRef.current);
639
+ }
640
+ }
641
+ } catch (e) {
642
+ // Best-effort: a bridge without `getProperty` (or no live mpv
643
+ // instance yet) leaves the field to the event stream.
644
+ // eslint-disable-next-line no-console
645
+ console.warn(
646
+ `[simba-player] seekable seed failed (${reason}):`,
647
+ e,
648
+ );
649
+ }
650
+ };
651
+
600
652
  for (const event of ALL_PLAYER_EVENTS) {
601
653
  const unsub = subscribePlayerEvent(
602
654
  event,
@@ -637,6 +689,14 @@ export function PlayerProvider({
637
689
  progressRef.current = nextProgress;
638
690
  return nextProgress;
639
691
  });
692
+
693
+ // A freshly loaded file is the moment `seekable` can first become
694
+ // true. Re-read the level so the seek bar is usable as soon as the
695
+ // media actually has a seekable range, rather than waiting for an
696
+ // edge this subscriber is not reliably delivered.
697
+ if (event === 'onFileLoaded') {
698
+ reseedEdgeLevels('onFileLoaded');
699
+ }
640
700
  },
641
701
  );
642
702
  unsubs.push(unsub);
@@ -667,46 +727,13 @@ export function PlayerProvider({
667
727
 
668
728
  // ── 2b. Re-read the LEVEL-only progress fields ───────────────────────
669
729
  //
670
- // `seekable` is a LEVEL value that mpv delivers only as an EDGE:
671
- // MPV_EVENT_PROPERTY_CHANGE is emitted once, at the instant the flag
672
- // flips from false to true. Any provider that mounts — or remounts,
673
- // e.g. in a second React root — after that flip never observes the
674
- // event, so the field stays at DEFAULT_PROGRESS forever and the
675
- // consumer's seek bar renders permanently disabled.
676
- //
677
- // Measured on device (Android 37): `onCacheState` — which changes
678
- // continuously — reached JS 827 times, while `onSeekable` arrived
679
- // ZERO times across both a cold start and an app restart, because by
680
- // then the flag had already settled and mpv will not repeat it.
681
- //
682
- // So read the level once at mount. The event keeps driving updates
683
- // afterwards; this only closes the gap for a provider that starts
684
- // mid-session. Without it the only correct usage pattern is
685
- // "subscribe strictly before loadFile", which no consumer can be
686
- // asked to guarantee across activities.
687
- try {
688
- const raw = bridge.getProperty('seekable');
689
- // The bridge serialises MPV_FORMAT_FLAG to the JSON literals
690
- // `true` / `false` (property.cpp, appendNode). Anything else -
691
- // "null" for an unavailable property, "" for the NOOP bridge -
692
- // is not a value, and must not be coerced to false.
693
- if (raw === 'true' || raw === 'false') {
694
- const seekable = raw === 'true';
695
- if (seekable !== progressRef.current.seekable) {
696
- const seeded: PlayerProgress = {
697
- ...progressRef.current,
698
- seekable,
699
- };
700
- progressRef.current = seeded;
701
- setProgress(seeded);
702
- }
703
- }
704
- } catch (e) {
705
- // Best-effort: a bridge without `getProperty` (or no live mpv
706
- // instance yet) leaves the field to the event stream.
707
- // eslint-disable-next-line no-console
708
- console.warn('[simba-player] seekable seed failed:', e);
709
- }
730
+ // See `reseedEdgeLevels` above for why `seekable` cannot be trusted to
731
+ // arrive as an event. Seeding here closes the gap for a provider that
732
+ // starts mid-session (the engine is process-global, so it can already be
733
+ // playing when a new React root mounts). The mount read alone is not
734
+ // sufficient in the normal launch order, which is why the same helper is
735
+ // also called on `onFileLoaded`.
736
+ reseedEdgeLevels('mount');
710
737
 
711
738
  // ── 2c. Seed the `mute` LEVEL too (same reasoning as `seekable`) ───
712
739
  //
@@ -995,3 +995,196 @@ describe('commands.loadFile applies the launch title (v1.9.3)', () => {
995
995
  );
996
996
  });
997
997
  });
998
+
999
+ // ── V21: seekable re-seed on file load ──────────────────────────────────────
1000
+
1001
+ describe('seekable re-seed on file load', () => {
1002
+ it('re-reads seekable when a file loads, because mpv only emits it as an edge', async () => {
1003
+ clearBridgeMocks();
1004
+ const getProperty = NativeModules.MpvPlayerModule
1005
+ .getProperty as jest.Mock;
1006
+
1007
+ // At mount nothing is loaded yet, so mpv legitimately reports false.
1008
+ // This is the ordinary launch order — the seed at mount alone can
1009
+ // therefore never be the thing that makes a seek bar usable.
1010
+ getProperty.mockImplementation((name: string) =>
1011
+ name === 'seekable' ? 'false' : 'null',
1012
+ );
1013
+
1014
+ const capture = captureSubscribes();
1015
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
1016
+ <PlayerProvider>{children}</PlayerProvider>
1017
+ );
1018
+
1019
+ const { result, unmount } = await renderHook(() => usePlayerProgress(), {
1020
+ wrapper,
1021
+ });
1022
+
1023
+ expect(result.current.seekable).toBe(false);
1024
+
1025
+ // The file is loaded now and mpv has flipped the flag. Measured on
1026
+ // device, the PROPERTY_CHANGE edge for `seekable` reached JS zero
1027
+ // times, so the provider has to re-read the level itself.
1028
+ getProperty.mockImplementation((name: string) =>
1029
+ name === 'seekable' ? 'true' : 'null',
1030
+ );
1031
+
1032
+ await act(async () => {
1033
+ for (const handler of capture.handlers.get('onFileLoaded') ?? []) {
1034
+ handler({ file: { uri: 'file:///a.mp4', title: 'A', duration: 3600 } });
1035
+ }
1036
+ });
1037
+
1038
+ // The seek bar must become usable. This is the assertion that fails
1039
+ // with the pre-fix provider, where `seekable` stayed at
1040
+ // DEFAULT_PROGRESS and the bar rendered permanently disabled.
1041
+ expect(result.current.seekable).toBe(true);
1042
+
1043
+ capture.restore();
1044
+ await unmount();
1045
+ });
1046
+
1047
+ it('does not treat a reported duration as proof of seekability', async () => {
1048
+ // The tempting app-side "fix" was `state.seekable || state.durationMs > 0`.
1049
+ // A live stream can report a duration and still have no seekable range;
1050
+ // inferring seekability from duration lights up a seek bar that cannot
1051
+ // work, which is the same "control that looks live and is not" class
1052
+ // this refactor is removing elsewhere.
1053
+ clearBridgeMocks();
1054
+ const getProperty = NativeModules.MpvPlayerModule
1055
+ .getProperty as jest.Mock;
1056
+ // A live stream: duration known, seekable still false, and no flip.
1057
+ getProperty.mockImplementation((name: string) =>
1058
+ name === 'seekable' ? 'false' : 'null',
1059
+ );
1060
+
1061
+ const capture = captureSubscribes();
1062
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
1063
+ <PlayerProvider>{children}</PlayerProvider>
1064
+ );
1065
+
1066
+ const { result, unmount } = await renderHook(() => usePlayerProgress(), {
1067
+ wrapper,
1068
+ });
1069
+
1070
+ await act(async () => {
1071
+ for (const handler of capture.handlers.get('onFileLoaded') ?? []) {
1072
+ handler({ file: { uri: 'live/hls', title: 'Live', duration: 0 } });
1073
+ }
1074
+ });
1075
+
1076
+ expect(result.current.seekable).toBe(false);
1077
+
1078
+ capture.restore();
1079
+ await unmount();
1080
+ });
1081
+ });
1082
+
1083
+ // ── V21: single-Activity surface control ────────────────────────────────────
1084
+
1085
+ describe('V21 surface control (setVideoBounds family)', () => {
1086
+ beforeEach(() => {
1087
+ clearBridgeMocks();
1088
+ });
1089
+
1090
+ it('exposes the surface commands on the command surface', async () => {
1091
+ const { result } = await renderHook(() => usePlayer());
1092
+ const c = result.current.commands;
1093
+ expect(typeof c.setVideoBounds).toBe('function');
1094
+ expect(typeof c.fillVideoBounds).toBe('function');
1095
+ expect(typeof c.setSurfaceVisible).toBe('function');
1096
+ expect(typeof c.isSurfaceMounted).toBe('function');
1097
+ });
1098
+
1099
+ it('forwards the rect verbatim to the bridge', async () => {
1100
+ // The whole design rests on these exact numbers reaching native: the
1101
+ // surface is placed by mutating its layout bounds, so a rounded,
1102
+ // clamped, or reordered argument would put the picture in the wrong
1103
+ // rect with no error anywhere.
1104
+ const setVideoBounds = NativeModules.MpvPlayerModule
1105
+ .setVideoBounds as jest.Mock;
1106
+ setVideoBounds.mockResolvedValue(true);
1107
+
1108
+ const { result } = await renderHook(() => usePlayer());
1109
+ await act(async () => {
1110
+ await result.current.commands.setVideoBounds(12, 34, 56, 78);
1111
+ });
1112
+
1113
+ expect(setVideoBounds).toHaveBeenCalledWith(12, 34, 56, 78);
1114
+ });
1115
+
1116
+ it('propagates a false result so callers can refuse to present video', async () => {
1117
+ // This is the reason these return a Promise<boolean> instead of
1118
+ // fire-and-forget: `false` means "there was no surface to move".
1119
+ // A caller that cannot see that would render chrome over a video
1120
+ // that was never shown - a control that looks live and is not.
1121
+ const setVideoBounds = NativeModules.MpvPlayerModule
1122
+ .setVideoBounds as jest.Mock;
1123
+ setVideoBounds.mockResolvedValue(false);
1124
+
1125
+ const { result } = await renderHook(() => usePlayer());
1126
+ let applied: boolean | undefined;
1127
+ await act(async () => {
1128
+ applied = await result.current.commands.setVideoBounds(0, 0, 10, 10);
1129
+ });
1130
+
1131
+ expect(applied).toBe(false);
1132
+ });
1133
+
1134
+ it('reports isSurfaceMounted from the bridge rather than assuming true', async () => {
1135
+ const isSurfaceMounted = NativeModules.MpvPlayerModule
1136
+ .isSurfaceMounted as jest.Mock;
1137
+ isSurfaceMounted.mockReturnValue(false);
1138
+
1139
+ const { result } = await renderHook(() => usePlayer());
1140
+ expect(result.current.commands.isSurfaceMounted()).toBe(false);
1141
+
1142
+ isSurfaceMounted.mockReturnValue(true);
1143
+ expect(result.current.commands.isSurfaceMounted()).toBe(true);
1144
+ });
1145
+
1146
+ it('forwards the visibility flag, including the hide direction', async () => {
1147
+ const setSurfaceVisible = NativeModules.MpvPlayerModule
1148
+ .setSurfaceVisible as jest.Mock;
1149
+ setSurfaceVisible.mockResolvedValue(true);
1150
+
1151
+ const { result } = await renderHook(() => usePlayer());
1152
+ await act(async () => {
1153
+ await result.current.commands.setSurfaceVisible(false);
1154
+ });
1155
+ expect(setSurfaceVisible).toHaveBeenCalledWith(false);
1156
+
1157
+ setSurfaceVisible.mockClear();
1158
+ await act(async () => {
1159
+ await result.current.commands.setSurfaceVisible(true);
1160
+ });
1161
+ expect(setSurfaceVisible).toHaveBeenCalledWith(true);
1162
+ });
1163
+ });
1164
+
1165
+ describe('NOOP fallback honesty (V21)', () => {
1166
+ const original = NativeModules.MpvPlayerModule;
1167
+
1168
+ afterEach(() => {
1169
+ NativeModules.MpvPlayerModule = original;
1170
+ });
1171
+
1172
+ it('reports that no surface exists instead of claiming success', async () => {
1173
+ // With no native module present, `getMpvPlayerModule()` hands back the
1174
+ // NOOP bridge. Every surface mutator must report failure there.
1175
+ //
1176
+ // If any of these returned success, a consumer would light up
1177
+ // mini-player chrome over a surface that was never mounted: a control
1178
+ // that looks live and is not, which is exactly the class of bug this
1179
+ // module's fallback exists to prevent.
1180
+ (NativeModules as { MpvPlayerModule?: unknown }).MpvPlayerModule =
1181
+ undefined;
1182
+
1183
+ const bridge = BridgeModule.getMpvPlayerModule();
1184
+
1185
+ expect(bridge.isSurfaceMounted()).toBe(false);
1186
+ await expect(bridge.fillVideoBounds()).resolves.toBe(false);
1187
+ await expect(bridge.setSurfaceVisible(true)).resolves.toBe(false);
1188
+ await expect(bridge.setVideoBounds(0, 0, 10, 10)).resolves.toBe(false);
1189
+ });
1190
+ });
@@ -305,6 +305,33 @@ export interface PlayerCommands {
305
305
  */
306
306
  getScreenBrightness(): number;
307
307
 
308
+ /**
309
+ * V21 — place the video surface at an absolute rect (device pixels).
310
+ *
311
+ * Layout bounds only. Never reparents or remounts the view, so the Surface
312
+ * is not destroyed and mpv does not re-attach — which is what makes an
313
+ * in-app mini player possible without a black flash.
314
+ *
315
+ * Resolves `false` when nothing took effect. Callers must treat `false` as
316
+ * "the surface is not where I asked for it" rather than proceeding as if
317
+ * the video were on screen.
318
+ */
319
+ setVideoBounds(
320
+ x: number,
321
+ y: number,
322
+ width: number,
323
+ height: number,
324
+ ): Promise<boolean>;
325
+ /** Expand the video surface to fill its container. Resolves `false` if it did not. */
326
+ fillVideoBounds(): Promise<boolean>;
327
+ /**
328
+ * Show or hide the video surface. Hidden is the correct state for
329
+ * audio-only playback — mpv keeps running with no render target.
330
+ */
331
+ setSurfaceVisible(visible: boolean): Promise<boolean>;
332
+ /** Whether a video surface is mounted and usable right now. */
333
+ isSurfaceMounted(): boolean;
334
+
308
335
  /**
309
336
  * Toggle an mpv audio filter. Backed by `--af-add` / `--af-remove`.
310
337
  * Examples: `setAudioFilter('scaletempo2=max-speed=32.0', true)` enables
@@ -698,6 +725,23 @@ function buildCommands(): PlayerCommands {
698
725
  dlog('commands.getScreenBrightness()');
699
726
  return getMpvPlayerModule().getScreenBrightness();
700
727
  },
728
+ // V21 single-Activity surface control
729
+ setVideoBounds: (x, y, width, height) => {
730
+ dlog('commands.setVideoBounds(', x, y, width, height, ')');
731
+ return getMpvPlayerModule().setVideoBounds(x, y, width, height);
732
+ },
733
+ fillVideoBounds: () => {
734
+ dlog('commands.fillVideoBounds()');
735
+ return getMpvPlayerModule().fillVideoBounds();
736
+ },
737
+ setSurfaceVisible: (visible) => {
738
+ dlog('commands.setSurfaceVisible(', visible, ')');
739
+ return getMpvPlayerModule().setSurfaceVisible(visible);
740
+ },
741
+ isSurfaceMounted: () => {
742
+ dlog('commands.isSurfaceMounted()');
743
+ return getMpvPlayerModule().isSurfaceMounted();
744
+ },
701
745
  setAudioFilter: (filter: string, enabled: boolean) => {
702
746
  dlog('commands.setAudioFilter(', filter, ',', enabled, ')');
703
747
  getMpvPlayerModule().setAudioFilter(filter, enabled);