@simba-dev/react-native-media-player 1.13.8 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/README.md +26 -24
  2. package/android/src/main/java/com/simba/player/MediaPlaybackService.kt +20 -17
  3. package/android/src/main/java/com/simba/player/PlayerPackage.kt +21 -6
  4. package/android/src/main/java/com/simba/player/mpv/MpvBridgeModule.kt +18 -307
  5. package/android/src/main/java/com/simba/player/mpv/MpvRenderView.kt +100 -0
  6. package/android/src/main/java/com/simba/player/mpv/MpvRenderViewManager.kt +116 -31
  7. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleTest.kt +0 -20
  8. package/package.json +2 -2
  9. package/src/bridge/MpvPlayerModule.ts +36 -83
  10. package/src/bridge/NativeMpvPlayer.ts +15 -52
  11. package/src/bridge/loadAndPlay.ts +65 -0
  12. package/src/components/PlayerRoot.tsx +9 -13
  13. package/src/components/SimbaVideo.tsx +121 -0
  14. package/src/components/__tests__/SimbaVideo.test.tsx +164 -0
  15. package/src/hooks/__tests__/useLaunchPlayback.test.tsx +44 -64
  16. package/src/hooks/useLaunchPlayback.ts +7 -11
  17. package/src/hooks/usePlayerActivity.ts +51 -60
  18. package/src/index.ts +11 -11
  19. package/src/specs/SimbaVideoViewNativeComponent.ts +84 -0
  20. package/src/types/__tests__/player.test.tsx +49 -17
  21. package/src/types/player.ts +28 -31
  22. package/android/src/main/java/com/simba/player/IMpvConfigProvider.kt +0 -36
  23. package/android/src/main/java/com/simba/player/IPipModeChangeEmitter.kt +0 -31
  24. package/android/src/main/java/com/simba/player/PlayerActivity.kt +0 -1626
  25. package/src/hooks/SimbaPlayerRoot.tsx +0 -128
  26. package/src/hooks/useIsPlayerActivity.ts +0 -61
  27. package/src/hooks/useLaunchParams.tsx +0 -126
@@ -19,8 +19,6 @@ import com.facebook.react.bridge.UiThreadUtil
19
19
  import com.facebook.react.module.annotations.ReactModule
20
20
  import com.facebook.react.modules.core.DeviceEventManagerModule
21
21
  import com.facebook.fbreact.specs.NativeMpvPlayerSpec
22
- import com.simba.player.IMpvConfigProvider
23
- import com.simba.player.IPipModeChangeEmitter
24
22
  import com.simba.player.PlaybackHost
25
23
  import org.json.JSONArray
26
24
  import org.json.JSONObject
@@ -33,9 +31,7 @@ import org.json.JSONObject
33
31
  */
34
32
  @ReactModule(name = MpvBridgeModule.NAME)
35
33
  class MpvBridgeModule(reactContext: ReactApplicationContext) :
36
- NativeMpvPlayerSpec(reactContext),
37
- IMpvConfigProvider,
38
- IPipModeChangeEmitter {
34
+ NativeMpvPlayerSpec(reactContext) {
39
35
 
40
36
  companion object {
41
37
  const val NAME = "MpvPlayerModule"
@@ -83,30 +79,6 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
83
79
  // the branch away in release entirely.
84
80
  private const val TRACE_PROPERTY_EVENTS = false
85
81
 
86
- // V22.0.0 / 1.5.10 (D-034): activity-aware launchParams guard.
87
- //
88
- // Background: `lastLaunchParams` (declared further down) is the
89
- // canonical handoff from `openPlayer(...)` to the next
90
- // `PlayerActivity` mount. The previous architecture had
91
- // `useLaunchParams()` consume it from BOTH MainActivity's React
92
- // tree and PlayerActivity's React tree - both activities mount
93
- // the same JS App and both wrap in `<SimbaPlayerRoot>` which
94
- // calls the hook on mount. Result on cold start: stale
95
- // lastLaunchParams from a prior `openPlayer` call got consumed
96
- // by MainActivity's tree, and `<PlayerRoot />` got rendered over
97
- // the Home screen (the V22 user regression).
98
- //
99
- // The fix: PlayerActivity's `onCreate` sets this flag to
100
- // `true` and `onDestroy` resets to `false`. `useLaunchParams()`
101
- // consults it via the synchronous `isCurrentActivityPlayer()`
102
- // bridge method and returns `null` (without touching
103
- // lastLaunchParams) when we are in any non-PlayerActivity host.
104
- // The flag is process-wide (companion object), so React tree
105
- // boundaries don't matter.
106
- @Volatile
107
- @JvmStatic
108
- var currentActivityIsPlayer: Boolean = false
109
-
110
82
  // Holds the ReactApplicationContext from RN init time so non-module
111
83
  // call sites (e.g. MainActivity.onPictureInPictureModeChanged) can
112
84
  // emit DeviceEventManagerModule events. Bridgeless RN: MainActivity's
@@ -126,73 +98,22 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
126
98
  var debugLoggingEnabled: Boolean = false
127
99
  private set
128
100
 
129
- /**
130
- * Phase 13: snapshot of the launch params the most recent
131
- * [openPlayer] call handed to `PlayerActivity`. Populated
132
- * before `startActivity` and consumed (cleared) by the next
133
- * [getLaunchParams] call. PlayerActivity's JS calls
134
- * `getLaunchParams()` on mount to rebuild its PlaybackContext
135
- * state — the launched activity's React context is fresh and
136
- * has no MainActivity PlaybackContext state to inherit.
137
- */
138
- @Volatile
139
- private var lastLaunchParams: LaunchParams? = null
140
-
141
- /**
142
- * D-039: PlayerActivity is the source of truth for launch
143
- * params read from its Intent extras, but the JS tree inside
144
- * the launched activity reads them back via [getLaunchParams]
145
- * which inspects [lastLaunchParams]. Without this push, any
146
- * PlayerActivity launch that bypasses [openPlayer] (deep link,
147
- * app shortcut, `am start`, ADB) leaves JS `getLaunchParams()`
148
- * returning null and `<PlayerRoot />` renders the empty
149
- * fallback. Populated from [com.simba.player.PlayerActivity.onCreate]
150
- * immediately after the `launchUri` / `launchTitle` /
151
- * `launchType` / `launchStartPositionMs` lazy vals are first
152
- * touched. No-op if `uri` is blank — MainActivity (which has
153
- * no player intent extras) won't accidentally clobber a real
154
- * launch in flight.
155
- */
156
- @JvmStatic
157
- fun setLaunchParamsFromIntent(
158
- uri: String,
159
- title: String,
160
- type: String,
161
- startPositionMs: Long,
162
- ) {
163
- if (uri.isBlank()) return
164
- lastLaunchParams = LaunchParams(uri, title, type, startPositionMs)
165
- Log.i(
166
- TAG,
167
- "[PlaybackTrace][Bridge][setLaunchParamsFromIntent] populated from Intent extras uri='$uri' type='$type' startMs=$startPositionMs",
168
- )
169
- }
170
-
171
- /**
172
- * Phase 13.3: simple value class for the launch params
173
- * cached for [getLaunchParams]. Mirrors the four intent
174
- * extras that PlayerActivity reads from its own `by lazy {}`
175
- * `launchUri` / `launchTitle` / `launchType` /
176
- * `launchStartPositionMs` properties.
177
- */
178
- data class LaunchParams(
179
- val uri: String,
180
- val title: String,
181
- val type: String,
182
- val startPositionMs: Long,
183
- )
184
-
185
101
  /**
186
102
  * Phase 21: cached PlayerConfig pushed by `<PlayerProvider
187
103
  * config={...}>` via `setConfig(configJson)`. Stored as a
188
- * Kotlin Map so module code (PlayerActivity) can read
189
- * individual keys without re-parsing JSON. `@Volatile` because
190
- * the push happens on the React Native JS thread while the
191
- * read happens on the Android main thread.
104
+ * Kotlin Map so individual keys can be read without re-parsing
105
+ * JSON. `@Volatile` because the push happens on the React Native
106
+ * JS thread while a read happens on the Android main thread.
192
107
  *
193
- * `null` when no Provider has wrapped the consumer app's
194
- * root — PlayerActivity logs that case explicitly so the
195
- * build verification can confirm the wire is live.
108
+ * `null` when no Provider has wrapped the consumer app's root.
109
+ *
110
+ * V21 F5: this cache no longer has a reader. Its only consumer
111
+ * was `IMpvConfigProvider.getCurrentConfig()`, called from
112
+ * `PlayerActivity`, which is deleted along with both
113
+ * module-side cast interfaces it existed to serve. `setConfig`
114
+ * itself stays — it is live public API every `<PlayerProvider>`
115
+ * calls — so the value is written and currently unread. Decide
116
+ * what reads it before adding another writer.
196
117
  */
197
118
  @Volatile
198
119
  private var currentConfig: Map<String, Any?>? = null
@@ -268,18 +189,6 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
268
189
  }
269
190
  }
270
191
 
271
- // ── IPipModeChangeEmitter (Phase 10) ────────────────────────────────
272
- // Phase 10: PlayerActivity (in the module) cannot call
273
- // `MpvBridgeModule.onPictureInPictureModeChanged` directly because
274
- // of the Gradle module boundary. It looks us up via the React Native
275
- // bridge (`getNativeModule("MpvPlayerModule") as? IPipModeChangeEmitter`)
276
- // and calls this method. We delegate to the companion method so the
277
- // single source of truth for PiP mode-change events stays in the
278
- // companion (the JS event name + payload contract is defined there).
279
- override fun emitPictureInPictureModeChanged(isInPictureInPictureMode: Boolean) {
280
- onPictureInPictureModeChanged(isInPictureInPictureMode)
281
- }
282
-
283
192
  init {
284
193
  // Capture the ReactApplicationContext for the companion sendEvent path.
285
194
  // Phase 36: clear the static reference when the module is destroyed so
@@ -1621,27 +1530,6 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1621
1530
  return if (nativePtr != 0L) MPVLib.nativeGetMuted(nativePtr) else false
1622
1531
  }
1623
1532
 
1624
- // V22.0.0 / 1.5.10 (D-034): activity-aware launchParams guard.
1625
- //
1626
- // Returns true while PlayerActivity is the foreground React host,
1627
- // false otherwise (MainActivity foreground, no React host, or
1628
- // about to attach). Mirrors the static
1629
- // `MpvBridgeModule.currentActivityIsPlayer` which PlayerActivity
1630
- // toggles in onCreate/onDestroy.
1631
- //
1632
- // Why a static companion flag rather than `getCurrentActivity()
1633
- // is PlayerActivity`: in `newArchEnabled=true` bridgeless mode,
1634
- // `getCurrentActivity()` can return null mid-attach (RN hasn't
1635
- // finished initializing), and the JS render path needs an
1636
- // authoritative answer the instant MainActivity's React tree
1637
- // mounts. The static flag set in `Activity.onCreate` (before
1638
- // React even renders) is always authoritative.
1639
- @ReactMethod(isBlockingSynchronousMethod = true)
1640
- @Override
1641
- override fun isCurrentActivityPlayer(): Boolean {
1642
- return currentActivityIsPlayer
1643
- }
1644
-
1645
1533
  // ── Lifecycle ──────────────────────────────────────────────────────────
1646
1534
 
1647
1535
  private fun prepareMpvCaBundle(): String {
@@ -1833,132 +1721,6 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1833
1721
  super.onCatalystInstanceDestroy()
1834
1722
  }
1835
1723
 
1836
- // ── PlayerActivity Launch (V12 Phase 3 + Phase 11) ─────────────────────
1837
- // Hands off to the dedicated `com.simba.player.PlayerActivity` (which
1838
- // lives in the `@simba/react-native-media-player` library module and
1839
- // therefore cannot be referenced directly from this app-side class —
1840
- // we go through the fully-qualified name on the Intent target).
1841
- //
1842
- // The `type` extra is the key new piece in Phase 11: it tells
1843
- // PlayerActivity which rendering path to take. `"video"` mounts the
1844
- // SurfaceView; `"audio"` will hide it (Phase 12) and surface an
1845
- // audio-only UI (Phase 13). PlayerActivity.EXTRA_* / TYPE_* constants
1846
- // are mirrored into the intent extras here so PlayerActivity can read
1847
- // them back in `onCreate` via its `by lazy {}` launch params.
1848
- //
1849
- // Reject codes (matched by the TS Spec's `E_*` contract in
1850
- // NativeMpvPlayer.ts):
1851
- // • E_INVALID_TYPE — `type` is neither "video" nor "audio"
1852
- // • E_AUDIO_REQUIRES_SERVICE — `type` IS "audio". V20 Phase C
1853
- // narrowed this method to video only. Audio is no longer forced
1854
- // into a window it has nothing to draw in; it goes through
1855
- // [startAudioPlayback], which starts the media service with no
1856
- // Activity at all. Rejecting rather than quietly still opening an
1857
- // Activity is deliberate: a stale JS bundle sending "audio" here
1858
- // gets a named, greppable failure instead of a full-screen blank
1859
- // player with no notification and no media keys.
1860
- // • E_NO_ACTIVITY — no current activity (RN bridge down)
1861
- // • E_ACTIVITY_NOT_FOUND — PlayerActivity not declared in manifest
1862
- // • E_SECURITY — manifest restriction refused the launch
1863
- // • E_OPEN_PLAYER_FAILED — anything else (e.g. flag mismatch)
1864
- @ReactMethod
1865
- @Override
1866
- override fun openPlayer(
1867
- uri: String,
1868
- title: String,
1869
- type: String,
1870
- startPositionMs: Double,
1871
- promise: Promise,
1872
- ) {
1873
- // V20 Phase C: audio no longer belongs here. See the docblock.
1874
- if (type == com.simba.player.PlayerActivity.TYPE_AUDIO) {
1875
- Log.w(TAG, "[PlaybackTrace][Bridge][openPlayer] type='audio' is no longer a window launch, rejecting E_AUDIO_REQUIRES_SERVICE")
1876
- promise.reject(
1877
- "E_AUDIO_REQUIRES_SERVICE",
1878
- "openPlayer is video-only as of 1.13.0; audio must use startAudioPlayback() so it does not need a window",
1879
- )
1880
- return
1881
- }
1882
- // 3.3: validate `type` — defensive against the JS layer ever
1883
- // passing a typo (the TS Spec already types it as the union
1884
- // `'video' | 'audio'`, but a stale bundle could skip the check).
1885
- if (type != com.simba.player.PlayerActivity.TYPE_VIDEO) {
1886
- Log.w(TAG, "[PlaybackTrace][Bridge][openPlayer] invalid type='$type', rejecting with E_INVALID_TYPE")
1887
- promise.reject("E_INVALID_TYPE", "type must be 'video', got '$type'")
1888
- return
1889
- }
1890
- // 3.4: require a current activity. In bridgeless RN this is null
1891
- // before the first activity attaches, after the last activity
1892
- // detaches, or in headless contexts. Without an activity we
1893
- // cannot launch PlayerActivity.
1894
- val activity = getCurrentActivity() ?: run {
1895
- Log.w(TAG, "[PlaybackTrace][Bridge][openPlayer] no current activity, rejecting with E_NO_ACTIVITY")
1896
- promise.reject("E_NO_ACTIVITY", "no current activity available to launch PlayerActivity")
1897
- return
1898
- }
1899
- // 3.5: build the intent. Title falls back to the URI when blank
1900
- // so the notification / lock-screen widget always has a display
1901
- // string.
1902
- //
1903
- // No intent flags are set, deliberately. An earlier version of this
1904
- // comment said "we use FLAG_ACTIVITY_NEW_TASK because we are
1905
- // launching from a non-Activity context ... the flag is harmless".
1906
- // Both halves were wrong: we launch from `activity`, and the flag is
1907
- // NOT harmless — it starts the target in a new task, which breaks
1908
- // the `singleTask` reuse that keeps a second `openPlayer` from
1909
- // stacking a duplicate player window, and leaves the video in a task
1910
- // the user's back gesture does not return from.
1911
- //
1912
- // If this ever does need to launch without an Activity, the flag
1913
- // belongs there — and the task-affinity consequences need dealing
1914
- // with, not waving through as "harmless".
1915
- val resolvedTitle = title.takeIf { it.isNotBlank() } ?: uri
1916
- val intent = android.content.Intent(
1917
- activity,
1918
- com.simba.player.PlayerActivity::class.java,
1919
- ).apply {
1920
- putExtra(com.simba.player.PlayerActivity.EXTRA_URI, uri)
1921
- putExtra(com.simba.player.PlayerActivity.EXTRA_TITLE, resolvedTitle)
1922
- putExtra(com.simba.player.PlayerActivity.EXTRA_TYPE, type)
1923
- putExtra(
1924
- com.simba.player.PlayerActivity.EXTRA_START_POSITION_MS,
1925
- startPositionMs.toLong(),
1926
- )
1927
- }
1928
- // 3.6: launch + 3.7: catch the three documented failure modes
1929
- // plus a generic catch-all. The order matters: ActivityNotFound
1930
- // and SecurityException are subclasses of each other on some
1931
- // OEMs, so we check the more specific one first.
1932
- try {
1933
- // Phase 13: cache the resolved launch params in the
1934
- // companion so the JS layer inside the launched
1935
- // PlayerActivity can read them back via
1936
- // [getLaunchParams] on mount (the launched activity's
1937
- // JS context is fresh — it doesn't have the
1938
- // PlaybackContext state from MainActivity, so we
1939
- // have to ship the params through the bridge).
1940
- lastLaunchParams = LaunchParams(uri, resolvedTitle, type, startPositionMs.toLong())
1941
- activity.startActivity(intent)
1942
- Log.i(
1943
- TAG,
1944
- "[PlaybackTrace][Bridge][openPlayer] launched PlayerActivity uri='$uri' type='$type' startMs=${startPositionMs.toLong()}",
1945
- )
1946
- promise.resolve(true)
1947
- } catch (e: android.content.ActivityNotFoundException) {
1948
- Log.w(TAG, "[PlaybackTrace][Bridge][openPlayer] PlayerActivity not found: ${e.message}")
1949
- emitErrorEvent("E_ACTIVITY_NOT_FOUND", "PlayerActivity is not declared in the manifest", e)
1950
- promise.reject("E_ACTIVITY_NOT_FOUND", "PlayerActivity is not declared in the manifest", e)
1951
- } catch (e: SecurityException) {
1952
- Log.w(TAG, "[PlaybackTrace][Bridge][openPlayer] security refusal: ${e.message}")
1953
- emitErrorEvent("E_SECURITY", "Manifest restriction refused PlayerActivity launch", e)
1954
- promise.reject("E_SECURITY", "Manifest restriction refused PlayerActivity launch", e)
1955
- } catch (e: Throwable) {
1956
- Log.e(TAG, "[PlaybackTrace][Bridge][openPlayer] launch failed", e)
1957
- emitErrorEvent("E_OPEN_PLAYER_FAILED", e.message ?: "openPlayer failed", e)
1958
- promise.reject("E_OPEN_PLAYER_FAILED", e.message ?: "openPlayer failed", e)
1959
- }
1960
- }
1961
-
1962
1724
  // ── Audio playback without an Activity (V20 Phase C) ────────────────────
1963
1725
  // The primitive that makes the mini player possible.
1964
1726
  //
@@ -2242,59 +2004,15 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2242
2004
  }
2243
2005
  }
2244
2006
 
2245
- /**
2246
- * Phase 13.3: one-shot accessor for the launch params the most
2247
- * recent [openPlayer] call handed to `PlayerActivity`. PlayerActivity
2248
- * (a fresh React context) calls this on mount so its JS can rebuild
2249
- * a `PlaybackEntry` from the same intent extras that PlayerActivity's
2250
- * own `by lazy {}` `launchUri` / `launchTitle` / `launchType` /
2251
- * `launchStartPositionMs` properties read.
2252
- *
2253
- * Returns `null` when called from MainActivity (no recent
2254
- * `openPlayer` invocation) — the App.tsx effect that calls this
2255
- * is a no-op in that case, and the regular V11 inline-mount path
2256
- * runs.
2257
- *
2258
- * One-shot semantics: the params are cleared after the first
2259
- * read so a re-read in the same activity does not double-apply.
2260
- * A second invocation from a different activity (e.g. an
2261
- * expand-from-PiP path) would no-op on the cleared state, which
2262
- * is correct — that path uses MainActivity's PlaybackContext, not
2263
- * PlayerActivity's.
2264
- */
2265
- @ReactMethod
2266
- @Override
2267
- override fun getLaunchParams(promise: Promise) {
2268
- val params = lastLaunchParams
2269
- if (params == null) {
2270
- // No launch pending (or already consumed) — resolve with JS `null`
2271
- // so the consumer's `await bridge.getLaunchParams()` sees the same
2272
- // nullable shape the spec promised (`Promise<LaunchParams | null>`).
2273
- promise.resolve(null)
2274
- return
2275
- }
2276
- // Clear immediately — we want the next call (in the same
2277
- // activity or any other) to see null. The first read is the
2278
- // only meaningful one.
2279
- lastLaunchParams = null
2280
- val map = Arguments.createMap()
2281
- map.putString("uri", params.uri)
2282
- map.putString("title", params.title)
2283
- map.putString("type", params.type)
2284
- map.putDouble("startPositionMs", params.startPositionMs.toDouble())
2285
- Log.i(TAG, "[PlaybackTrace][Bridge][getLaunchParams] returning uri='${params.uri}' type='${params.type}'")
2286
- promise.resolve(map)
2287
- }
2288
-
2289
2007
  // ── PlayerConfig (Phase 21) ──────────────────────────────────────────────
2290
2008
  //
2291
2009
  // Phase 21: `<PlayerProvider config={...}>` calls this with the
2292
2010
  // JSON-serialised PlayerConfig. We parse + cache as a Kotlin Map
2293
- // so module code (PlayerActivity) can read individual keys
2294
- // without re-parsing JSON. PlayerActivity looks the cached
2295
- // config up via the module-side [IMpvConfigProvider] interface
2296
- // (mirrors the IMpvNativePtrProvider / IPipModeChangeEmitter
2297
- // pattern from Phases 7 + 10).
2011
+ // so individual keys can be read without re-parsing JSON.
2012
+ //
2013
+ // V21 F5: nothing reads that cache any more (its only reader,
2014
+ // `IMpvConfigProvider`, went with `PlayerActivity`). The setter
2015
+ // stays because `<PlayerProvider>` calls it on every mount.
2298
2016
  //
2299
2017
  // Idempotent: re-calling with the same JSON is safe (just
2300
2018
  // overwrites the cache). The TS-side `PlayerProvider` only
@@ -2334,13 +2052,6 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2334
2052
  }
2335
2053
  }
2336
2054
 
2337
- // IMpvConfigProvider (Phase 21): module-side accessor used by
2338
- // PlayerActivity to read the active PlayerConfig without
2339
- // crossing the Gradle boundary. Returns the Kotlin Map cached
2340
- // by [setConfig], or null when no Provider has wrapped the
2341
- // consumer app's root.
2342
- override fun getCurrentConfig(): Map<String, Any?>? = currentConfig
2343
-
2344
2055
  // ── Picture-in-Picture ─────────────────────────────────────────────────
2345
2056
 
2346
2057
  /**
@@ -68,6 +68,33 @@ class MpvRenderView(context: Context) : SurfaceView(context),
68
68
  // transitions, so this is normally a no-op after first attach.
69
69
  private var attachedSurface: android.view.Surface? = null
70
70
 
71
+ // ── Props held until a handle exists ─────────────────────────────────
72
+ //
73
+ // React Native sets props as soon as the view is created, which can be
74
+ // before `MpvBridgeModule.initPlayer()` has produced a handle. Writing
75
+ // these straight into mpv at that moment would either throw or be dropped
76
+ // by an uninitialised instance, and the prop would then never take effect
77
+ // — a view that renders before the engine and silently ignores
78
+ // `paused`/`volume` afterwards.
79
+ //
80
+ // So props are recorded here unconditionally and pushed into mpv on the
81
+ // next line that has a handle: either `setNativePtr` or any setter
82
+ // arriving after the handle exists. Both paths re-apply the full set, so
83
+ // ordering between prop arrival and handle arrival stops mattering.
84
+ /** @see MpvRenderViewManager.setPaused */
85
+ var pendingPaused: Boolean = false
86
+
87
+ /** @see MpvRenderViewManager.setMuted */
88
+ var pendingMuted: Boolean = false
89
+
90
+ /** @see MpvRenderViewManager.setVolume */
91
+ var pendingVolume: Float = 100f
92
+
93
+ /** mpv `video-zoom`: `0` fit · `1` fill/crop · `2` fill ignoring aspect. */
94
+ private var pendingVideoZoom: String? = "0"
95
+
96
+ fun nativePtrHandle(): Long = nativePtr
97
+
71
98
  companion object {
72
99
  private const val TAG = "MpvRenderView"
73
100
  }
@@ -197,9 +224,82 @@ class MpvRenderView(context: Context) : SurfaceView(context),
197
224
  // New handle — any previously attached surface must be rebound
198
225
  // (mpv's wid still points at the previous handle's surface).
199
226
  attachedSurface = null
227
+ // Props that arrived before the handle existed were recorded, not
228
+ // applied. Push them now, or the view would render while silently
229
+ // ignoring `paused` / `volume` / `resizeMode`.
230
+ reapplyPendingProps()
200
231
  ensureSurfaceAttached("setNativePtr")
201
232
  }
202
233
 
234
+ /**
235
+ * Re-push every recorded prop into the now-current mpv instance.
236
+ *
237
+ * Safe to call on each prop change once a handle exists: these are
238
+ * idempotent property writes, not one-shot commands.
239
+ */
240
+ private fun reapplyPendingProps() {
241
+ if (nativePtr == 0L) return
242
+ if (pendingPaused) MPVLib.nativePause(nativePtr) else MPVLib.nativePlay(nativePtr)
243
+ MPVLib.nativeSetMuted(nativePtr, pendingMuted)
244
+ MPVLib.nativeSetVolume(nativePtr, pendingVolume.toDouble().coerceIn(0.0, 100.0))
245
+ pendingVideoZoom?.let {
246
+ MPVLib.setPropertyString(nativePtr, "video-zoom", it)
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Record and apply mpv's `video-zoom`.
252
+ *
253
+ * Routed through the pending field so a `resizeMode` prop that lands
254
+ * before the handle exists is not silently lost against an uninitialised
255
+ * instance.
256
+ */
257
+ fun applyVideoZoom(zoom: String?) {
258
+ pendingVideoZoom = zoom
259
+ if (nativePtr == 0L) return
260
+ MPVLib.setPropertyString(nativePtr, "video-zoom", zoom)
261
+ }
262
+
263
+ /**
264
+ * Release this view's surface binding without touching the engine.
265
+ *
266
+ * Called when React unmounts the view. The engine outlives the view by
267
+ * design — it belongs to `MpvBridgeModule` — so a React re-parent, theme
268
+ * change or memory-pressure remount must not interrupt playback. Only the
269
+ * surface↔mpv edge is released, and `ensureSurfaceAttached` re-establishes
270
+ * it on the next bind.
271
+ *
272
+ * Distinct from [cleanup], which additionally clears the handle and is
273
+ * reserved for the engine being destroyed.
274
+ */
275
+ fun detachSurfaceForViewDrop() {
276
+ detachSurfaceLocked()
277
+ }
278
+
279
+ /**
280
+ * React Native's layout pass can leave a `SurfaceView`'s Surface at a stale
281
+ * size, because Yoga and the Surface lifecycle are driven independently.
282
+ * `react-native-video` hits the same problem and fixes it the same way -
283
+ * see its `ExoPlayerView.requestLayout()`, which posts a second
284
+ * measure/layout so "the internal views receive the final size".
285
+ *
286
+ * Without this, `surfaceChanged` can report the previous geometry and mpv
287
+ * renders at the wrong size - or at 0x0 - which looks exactly like the
288
+ * black-video bug and produces no error anywhere.
289
+ */
290
+ private val layoutSync = Runnable {
291
+ measure(
292
+ MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
293
+ MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)
294
+ )
295
+ layout(left, top, right, bottom)
296
+ }
297
+
298
+ override fun requestLayout() {
299
+ super.requestLayout()
300
+ post(layoutSync)
301
+ }
302
+
203
303
  /**
204
304
  * Show or hide the surface.
205
305
  *
@@ -1,42 +1,127 @@
1
1
  package com.simba.player.mpv
2
2
 
3
- import android.view.View
4
- import com.facebook.react.bridge.ReadableArray
5
- import com.facebook.react.common.MapBuilder
6
- import com.facebook.react.uimanager.ThemedReactContext
3
+ import android.util.Log
4
+ import com.facebook.react.module.annotations.ReactModule
7
5
  import com.facebook.react.uimanager.SimpleViewManager
6
+ import com.facebook.react.uimanager.ThemedReactContext
8
7
  import com.facebook.react.uimanager.annotations.ReactProp
9
8
 
10
9
  /**
11
- * View Manager for the mpv rendering SurfaceView.
10
+ * Fabric-facing ViewManager for the mpv rendering SurfaceView.
11
+ *
12
+ * This is what makes the video picture an ordinary child of the React tree
13
+ * instead of a sibling of the React root. React Native then owns:
12
14
  *
13
- * This allows the mpv video output surface to be used as a React Native
14
- * component from JS, e.g.:
15
+ * - **layout.** The view gets a real Yoga measure/layout pass. The previous
16
+ * path mutated `LayoutParams` directly from Kotlin, which
17
+ * `react-native-video` documents as a hazard - see its `ExoPlayerView`
18
+ * `requestLayout()` override: "React Native (Yoga) can sometimes defer
19
+ * layout passes that are required by ... surface view".
20
+ * - **z-order.** The surface no longer sits behind an opaque React root, so
21
+ * no screen has to blank itself around the player.
22
+ * - **lifecycle.** Mount and unmount are the same events for the surface as
23
+ * for any other view.
15
24
  *
16
- * <MpvRenderView nativePtr={nativePtr} style={{flex: 1}} />
25
+ * The engine is deliberately *not* owned here. Playback control - `pause`,
26
+ * `volume`, `seek`, PiP - belongs to `MpvBridgeModule`, which gives it exactly
27
+ * one writer reachable from anywhere through `usePlayer().commands`. The
28
+ * props below exist so the declarative form `<SimbaVideo paused={...} />` is
29
+ * real rather than decorative; they write the same engine state those commands
30
+ * do, so an app may drive the engine from props, from commands, or from both.
17
31
  */
32
+ @ReactModule(name = MpvRenderViewManager.REACT_CLASS)
18
33
  class MpvRenderViewManager : SimpleViewManager<MpvRenderView>() {
19
34
 
20
- companion object {
21
- const val REACT_CLASS = "MpvRenderView"
22
- }
23
-
24
- override fun getName(): String = REACT_CLASS
25
-
26
- override fun createViewInstance(reactContext: ThemedReactContext): MpvRenderView {
27
- return MpvRenderView(reactContext)
28
- }
29
-
30
- /**
31
- * Pass the native mpv pointer to the view so it can attach the Surface.
32
- */
33
- @ReactProp(name = "nativePtr")
34
- fun setNativePtr(view: MpvRenderView, nativePtr: Double) {
35
- view.setNativePtr(nativePtr.toLong())
36
- }
37
-
38
- override fun onDropViewInstance(view: MpvRenderView) {
39
- super.onDropViewInstance(view)
40
- view.cleanup()
41
- }
42
- }
35
+ companion object {
36
+ /** Must match `codegenNativeComponent<NativeProps>('SimbaVideoView')`. */
37
+ const val REACT_CLASS = "SimbaVideoView"
38
+
39
+ private const val TAG = "MpvRenderViewManager"
40
+ }
41
+
42
+ override fun getName(): String = REACT_CLASS
43
+
44
+ override fun createViewInstance(reactContext: ThemedReactContext): MpvRenderView {
45
+ return MpvRenderView(reactContext)
46
+ }
47
+
48
+ /**
49
+ * Bind this surface to an mpv handle.
50
+ *
51
+ * Typed `Double` rather than `Int32`: mpv handles are 64-bit pointers, and
52
+ * an `Int32` prop would truncate them to 32 bits and hand mpv a pointer to
53
+ * nothing. Codegen maps the spec's `Double` to a Kotlin `double`.
54
+ */
55
+ @ReactProp(name = "nativePtr")
56
+ fun setNativePtr(view: MpvRenderView, nativePtr: Double) {
57
+ view.setNativePtr(nativePtr.toLong())
58
+ }
59
+
60
+ /**
61
+ * Declarative pause.
62
+ *
63
+ * Inert while no handle is bound rather than guessing: `setNativePtr` is what
64
+ * binds, and calling mpv with a zero handle throws. A view rendered before
65
+ * the engine exists therefore stays inert until the handle arrives, at which
66
+ * point [MpvRenderView.setNativePtr] rebinds and re-applies the pending
67
+ * props.
68
+ */
69
+ @ReactProp(name = "paused", defaultBoolean = false)
70
+ fun setPaused(view: MpvRenderView, paused: Boolean) {
71
+ view.pendingPaused = paused
72
+ val ptr = view.nativePtrHandle()
73
+ if (ptr == 0L) return
74
+ if (paused) MPVLib.nativePause(ptr) else MPVLib.nativePlay(ptr)
75
+ }
76
+
77
+ @ReactProp(name = "muted", defaultBoolean = false)
78
+ fun setMuted(view: MpvRenderView, muted: Boolean) {
79
+ view.pendingMuted = muted
80
+ val ptr = view.nativePtrHandle()
81
+ if (ptr == 0L) return
82
+ MPVLib.nativeSetMuted(ptr, muted)
83
+ }
84
+
85
+ /**
86
+ * Volume in mpv's native 0..100 range - the same range
87
+ * `PlayerCommands.setVolume` uses, so a value read from the engine is a value
88
+ * that can be handed straight back to it with no rescaling.
89
+ */
90
+ @ReactProp(name = "volume", defaultFloat = 100f)
91
+ fun setVolume(view: MpvRenderView, volume: Float) {
92
+ view.pendingVolume = volume
93
+ val ptr = view.nativePtrHandle()
94
+ if (ptr == 0L) return
95
+ MPVLib.nativeSetVolume(ptr, volume.toDouble().coerceIn(0.0, 100.0))
96
+ }
97
+
98
+ /**
99
+ * mpv's `video-zoom`, carried as a string because mpv properties are strings
100
+ * and the spec declares this prop as `WithDefault<string, 'contain'>`.
101
+ *
102
+ * `0` fit / letterbox · `1` fill / crop · `2` fill, aspect ignored
103
+ *
104
+ * Applied through [MpvRenderView] so a value that arrives before the handle
105
+ * is held and re-applied on bind, instead of being silently lost against an
106
+ * uninitialised mpv instance.
107
+ */
108
+ @ReactProp(name = "resizeMode")
109
+ fun setResizeMode(view: MpvRenderView, resizeMode: String?) {
110
+ view.applyVideoZoom(resizeMode)
111
+ }
112
+
113
+ /**
114
+ * Release this view's surface binding.
115
+ *
116
+ * Deliberately does **not** destroy the engine: the view never owned it. A
117
+ * React tree can unmount and remount this view freely - a re-parent, a theme
118
+ * change, memory pressure - and playback has to survive that, because the
119
+ * handle belongs to `MpvBridgeModule` and not to this view. Only the
120
+ * surface↔mpv binding is released here.
121
+ */
122
+ override fun onDropViewInstance(view: MpvRenderView) {
123
+ super.onDropViewInstance(view)
124
+ Log.i(TAG, "onDropViewInstance: releasing surface binding, engine untouched")
125
+ view.detachSurfaceForViewDrop()
126
+ }
127
+ }