@simba-dev/react-native-media-player 1.11.0 → 1.13.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.
@@ -19,8 +19,8 @@ import com.facebook.react.module.annotations.ReactModule
19
19
  import com.facebook.react.modules.core.DeviceEventManagerModule
20
20
  import com.facebook.fbreact.specs.NativeMpvPlayerSpec
21
21
  import com.simba.player.IMpvConfigProvider
22
- import com.simba.player.IMpvNativePtrProvider
23
22
  import com.simba.player.IPipModeChangeEmitter
23
+ import com.simba.player.PlaybackHost
24
24
  import org.json.JSONArray
25
25
  import org.json.JSONObject
26
26
 
@@ -34,7 +34,6 @@ import org.json.JSONObject
34
34
  class MpvBridgeModule(reactContext: ReactApplicationContext) :
35
35
  NativeMpvPlayerSpec(reactContext),
36
36
  IMpvConfigProvider,
37
- IMpvNativePtrProvider,
38
37
  IPipModeChangeEmitter {
39
38
 
40
39
  companion object {
@@ -286,8 +285,24 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
286
285
 
287
286
  // ── State ──────────────────────────────────────────────────────────────
288
287
 
289
- /** Native mpv_handle* stored as Long (0 = uninitialized). */
290
- private var nativePtr: Long = 0
288
+ /**
289
+ * V20 Phase A: the libmpv handle, *delegated* to [PlaybackHost].
290
+ *
291
+ * This is deliberately a property, not a field. It holds no state of
292
+ * its own — [PlaybackHost] is the single owner, because the handle is
293
+ * a process-global in C++ (`g_mpv`) and a React Native TurboModule
294
+ * dies with its React context, which would leave the handle owned by
295
+ * something that is not alive when playback still needs it.
296
+ *
297
+ * Keeping the name means the ~30 existing read sites are unchanged;
298
+ * what changed is that a read can no longer return a stale copy,
299
+ * because there is no longer a copy to be stale.
300
+ */
301
+ private var nativePtr: Long
302
+ get() = PlaybackHost.handle()
303
+ set(value) {
304
+ if (value == 0L) PlaybackHost.clearHandle() else PlaybackHost.publishHandle(value)
305
+ }
291
306
 
292
307
  /** Event emitter for JS-side event listeners. */
293
308
  private val eventEmitter: DeviceEventManagerModule.RCTDeviceEventEmitter by lazy {
@@ -1817,7 +1832,15 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1817
1832
  //
1818
1833
  // Reject codes (matched by the TS Spec's `E_*` contract in
1819
1834
  // NativeMpvPlayer.ts):
1820
- // • E_INVALID_TYPE — `type` is not "video" or "audio"
1835
+ // • E_INVALID_TYPE — `type` is neither "video" nor "audio"
1836
+ // • E_AUDIO_REQUIRES_SERVICE — `type` IS "audio". V20 Phase C
1837
+ // narrowed this method to video only. Audio is no longer forced
1838
+ // into a window it has nothing to draw in; it goes through
1839
+ // [startAudioPlayback], which starts the media service with no
1840
+ // Activity at all. Rejecting rather than quietly still opening an
1841
+ // Activity is deliberate: a stale JS bundle sending "audio" here
1842
+ // gets a named, greppable failure instead of a full-screen blank
1843
+ // player with no notification and no media keys.
1821
1844
  // • E_NO_ACTIVITY — no current activity (RN bridge down)
1822
1845
  // • E_ACTIVITY_NOT_FOUND — PlayerActivity not declared in manifest
1823
1846
  // • E_SECURITY — manifest restriction refused the launch
@@ -1831,14 +1854,21 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1831
1854
  startPositionMs: Double,
1832
1855
  promise: Promise,
1833
1856
  ) {
1857
+ // V20 Phase C: audio no longer belongs here. See the docblock.
1858
+ if (type == com.simba.player.PlayerActivity.TYPE_AUDIO) {
1859
+ Log.w(TAG, "[PlaybackTrace][Bridge][openPlayer] type='audio' is no longer a window launch, rejecting E_AUDIO_REQUIRES_SERVICE")
1860
+ promise.reject(
1861
+ "E_AUDIO_REQUIRES_SERVICE",
1862
+ "openPlayer is video-only as of 1.13.0; audio must use startAudioPlayback() so it does not need a window",
1863
+ )
1864
+ return
1865
+ }
1834
1866
  // 3.3: validate `type` — defensive against the JS layer ever
1835
1867
  // passing a typo (the TS Spec already types it as the union
1836
1868
  // `'video' | 'audio'`, but a stale bundle could skip the check).
1837
- if (type != com.simba.player.PlayerActivity.TYPE_VIDEO &&
1838
- type != com.simba.player.PlayerActivity.TYPE_AUDIO
1839
- ) {
1869
+ if (type != com.simba.player.PlayerActivity.TYPE_VIDEO) {
1840
1870
  Log.w(TAG, "[PlaybackTrace][Bridge][openPlayer] invalid type='$type', rejecting with E_INVALID_TYPE")
1841
- promise.reject("E_INVALID_TYPE", "type must be 'video' or 'audio', got '$type'")
1871
+ promise.reject("E_INVALID_TYPE", "type must be 'video', got '$type'")
1842
1872
  return
1843
1873
  }
1844
1874
  // 3.4: require a current activity. In bridgeless RN this is null
@@ -1905,6 +1935,212 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1905
1935
  }
1906
1936
  }
1907
1937
 
1938
+ // ── Audio playback without an Activity (V20 Phase C) ────────────────────
1939
+ // The primitive that makes the mini player possible.
1940
+ //
1941
+ // Until now the only way to start `MediaPlaybackService` was
1942
+ // `PlayerActivity.onCreate`. So the media session, the notification
1943
+ // and media-key routing existed only while a window was open, and
1944
+ // audio was forced into a full-screen Activity purely to get the
1945
+ // service running. That is an Activity used as a launcher for
1946
+ // something it does not draw — audio has no surface, no PiP
1947
+ // requirement, and nothing to show in a window.
1948
+ //
1949
+ // So this method does, natively and in this order:
1950
+ //
1951
+ // 1. engine ensure a handle, load the file, seek, play
1952
+ // 2. service startForegroundService with the media metadata
1953
+ //
1954
+ // Engine first is the whole design. The service builds its
1955
+ // notification out of the engine's `duration` / `time-pos`, so
1956
+ // loading first means the notification is right on its first frame
1957
+ // rather than being visibly corrected a second later. Doing this as
1958
+ // two JS round-trips would leave a real gap where the file is
1959
+ // loaded and playing but nothing owns it: audio with no
1960
+ // notification, no media keys, and no session — which is exactly
1961
+ // the defect class this whole phase set out to remove.
1962
+ //
1963
+ // No Activity is required. `reactApplicationContext` outlives every
1964
+ // window, which is the same reason the engine itself is a
1965
+ // process-global rather than an Activity field.
1966
+
1967
+ @ReactMethod
1968
+ @Override
1969
+ override fun startAudioPlayback(options: ReadableMap?, promise: Promise) {
1970
+ val uri = optString(options, "uri").orEmpty()
1971
+ if (uri.isBlank()) {
1972
+ Log.w(TAG, "[PlaybackTrace][Bridge][startAudioPlayback] blank uri, rejecting E_INVALID_URI")
1973
+ promise.reject("E_INVALID_URI", "options.uri is required")
1974
+ return
1975
+ }
1976
+
1977
+ // `ensurePtr` throws; a Promise caller needs a named code, not a
1978
+ // bridge-level exception with no rejection. Create the engine if
1979
+ // JS has not already done so — a cold start can legitimately
1980
+ // reach audio before anything called `initPlayer()`.
1981
+ if (nativePtr == 0L && !initPlayer()) {
1982
+ Log.e(TAG, "[PlaybackTrace][Bridge][startAudioPlayback] no engine handle, rejecting E_ENGINE_UNAVAILABLE")
1983
+ promise.reject("E_ENGINE_UNAVAILABLE", "libmpv instance unavailable; initPlayer() returned false")
1984
+ return
1985
+ }
1986
+ val handle = nativePtr
1987
+ if (handle == 0L) {
1988
+ Log.e(TAG, "[PlaybackTrace][Bridge][startAudioPlayback] handle still zero after init, rejecting E_ENGINE_UNAVAILABLE")
1989
+ promise.reject("E_ENGINE_UNAVAILABLE", "libmpv instance unavailable; handle is zero")
1990
+ return
1991
+ }
1992
+
1993
+ val resolvedPath = normalizeMpvInput(resolveContentUri(uri))
1994
+ try {
1995
+ MPVLib.nativeLoadFile(handle, resolvedPath)
1996
+ } catch (e: Throwable) {
1997
+ Log.e(TAG, "[PlaybackTrace][Bridge][startAudioPlayback] nativeLoadFile failed for '$resolvedPath'", e)
1998
+ promise.reject("E_LOAD_FAILED", e.message ?: "mpv refused '$uri'", e)
1999
+ return
2000
+ }
2001
+
2002
+ // Seek is applied regardless of `autoPlay`: resuming a paused
2003
+ // episode at a bookmark is a real case, and it would be odd for
2004
+ // the position to depend on whether we happen to start playing.
2005
+ val startPositionMs = optDouble(options, "startPositionMs") ?: 0.0
2006
+ if (startPositionMs > 0.0) {
2007
+ try {
2008
+ MPVLib.nativeSeek(handle, startPositionMs / 1000.0)
2009
+ } catch (e: Throwable) {
2010
+ // A seek that cannot land is not fatal to playback —
2011
+ // the file is loaded and will play from the top. Say so
2012
+ // rather than dropping it.
2013
+ Log.w(TAG, "[PlaybackTrace][Bridge][startAudioPlayback] initial seek to ${startPositionMs.toLong()}ms failed: ${e.message}")
2014
+ }
2015
+ }
2016
+
2017
+ val autoPlay = optBoolean(options, "autoPlay") ?: true
2018
+ if (autoPlay) {
2019
+ try {
2020
+ MPVLib.nativePlay(handle)
2021
+ } catch (e: Throwable) {
2022
+ Log.e(TAG, "[PlaybackTrace][Bridge][startAudioPlayback] nativePlay failed", e)
2023
+ promise.reject("E_LOAD_FAILED", e.message ?: "mpv could not start playback", e)
2024
+ return
2025
+ }
2026
+ }
2027
+
2028
+ val title = optString(options, "title")?.takeIf { it.isNotBlank() } ?: uri
2029
+ val intent = android.content.Intent(
2030
+ reactApplicationContext,
2031
+ com.simba.player.MediaPlaybackService::class.java,
2032
+ ).apply {
2033
+ action = com.simba.player.MediaPlaybackService.ACTION_START
2034
+ putExtra(com.simba.player.MediaPlaybackService.EXTRA_TITLE, title)
2035
+ putExtra(com.simba.player.MediaPlaybackService.EXTRA_ARTIST, optString(options, "artist").orEmpty())
2036
+ putExtra(com.simba.player.MediaPlaybackService.EXTRA_ALBUM, optString(options, "album").orEmpty())
2037
+ putExtra(com.simba.player.MediaPlaybackService.EXTRA_ARTWORK_PATH, optString(options, "artworkPath").orEmpty())
2038
+ putExtra(com.simba.player.MediaPlaybackService.EXTRA_POSITION_MS, startPositionMs.toLong())
2039
+ putExtra(com.simba.player.MediaPlaybackService.EXTRA_DURATION_MS, 0L)
2040
+ putExtra(com.simba.player.MediaPlaybackService.EXTRA_IS_PLAYING, autoPlay)
2041
+ }
2042
+
2043
+ try {
2044
+ // startForegroundService, not startService: the service calls
2045
+ // startForeground in its onStartCommand, and Android 8+
2046
+ // throws ForegroundServiceDidNotStartInTimeException if it
2047
+ // was started as a background service instead.
2048
+ androidx.core.content.ContextCompat.startForegroundService(reactApplicationContext, intent)
2049
+ } catch (e: Throwable) {
2050
+ // Background-start restrictions, or a missing
2051
+ // FOREGROUND_SERVICE permission / service declaration.
2052
+ // Named loudly: this is the case where audio is loaded and
2053
+ // playing with no notification and no media keys, and a
2054
+ // silent failure here is how that gets shipped.
2055
+ Log.e(TAG, "[PlaybackTrace][Bridge][startAudioPlayback] startForegroundService failed", e)
2056
+ promise.reject("E_START_SERVICE_FAILED", e.message ?: "could not start MediaPlaybackService", e)
2057
+ return
2058
+ }
2059
+
2060
+ Log.i(
2061
+ TAG,
2062
+ "[PlaybackTrace][Bridge][startAudioPlayback] playing uri='$resolvedPath' title='$title' startMs=${startPositionMs.toLong()} autoPlay=$autoPlay",
2063
+ )
2064
+ promise.resolve(true)
2065
+ }
2066
+
2067
+ @ReactMethod
2068
+ @Override
2069
+ override fun stopAudioPlayback() {
2070
+ val context = reactApplicationContext
2071
+ val serviceUp = com.simba.player.MediaPlaybackService.isRunning()
2072
+ // Stop the engine unconditionally. If the service is already
2073
+ // gone, the session's own stop callback is not around to do it,
2074
+ // and leaving audio running with no way to stop it is the worse
2075
+ // failure of the two.
2076
+ if (nativePtr != 0L) {
2077
+ try {
2078
+ MPVLib.nativeStop(nativePtr)
2079
+ } catch (e: Throwable) {
2080
+ Log.w(TAG, "[PlaybackTrace][Bridge][stopAudioPlayback] nativeStop threw ${e.message}")
2081
+ }
2082
+ } else {
2083
+ Log.w(TAG, "[PlaybackTrace][Bridge][stopAudioPlayback] no engine handle; nothing to stop")
2084
+ }
2085
+
2086
+ if (!serviceUp) {
2087
+ Log.i(TAG, "[PlaybackTrace][Bridge][stopAudioPlayback] service not running; engine stopped, nothing to tear down")
2088
+ return
2089
+ }
2090
+ try {
2091
+ // Ordinary startService: the service is already foreground,
2092
+ // so there is no startForeground deadline to meet.
2093
+ context.startService(
2094
+ android.content.Intent(context, com.simba.player.MediaPlaybackService::class.java).apply {
2095
+ action = com.simba.player.MediaPlaybackService.ACTION_STOP
2096
+ },
2097
+ )
2098
+ } catch (e: Throwable) {
2099
+ Log.e(TAG, "[PlaybackTrace][Bridge][stopAudioPlayback] could not deliver ACTION_STOP", e)
2100
+ }
2101
+ }
2102
+
2103
+ @ReactMethod(isBlockingSynchronousMethod = true)
2104
+ @Override
2105
+ override fun isAudioPlaybackServiceRunning(): Boolean =
2106
+ com.simba.player.MediaPlaybackService.isRunning()
2107
+
2108
+ /**
2109
+ * `ReadableMap` reads that tolerate absent keys.
2110
+ *
2111
+ * A JS caller that writes `{uri, startPositionMs: undefined}` hands us
2112
+ * a key that *exists* and holds null, so `hasKey` alone would send
2113
+ * `getDouble` into a throw on the bridge thread. These treat
2114
+ * "absent" and "explicitly null" the same way, which is what the
2115
+ * TS optional-property contract already means to a caller.
2116
+ */
2117
+ private fun optString(options: ReadableMap?, key: String): String? {
2118
+ if (options == null || !options.hasKey(key) || options.isNull(key)) return null
2119
+ return try {
2120
+ options.getString(key)
2121
+ } catch (_: Throwable) {
2122
+ null
2123
+ }
2124
+ }
2125
+
2126
+ private fun optDouble(options: ReadableMap?, key: String): Double? {
2127
+ if (options == null || !options.hasKey(key) || options.isNull(key)) return null
2128
+ return try {
2129
+ options.getDouble(key)
2130
+ } catch (_: Throwable) {
2131
+ null
2132
+ }
2133
+ }
2134
+
2135
+ private fun optBoolean(options: ReadableMap?, key: String): Boolean? {
2136
+ if (options == null || !options.hasKey(key) || options.isNull(key)) return null
2137
+ return try {
2138
+ options.getBoolean(key)
2139
+ } catch (_: Throwable) {
2140
+ null
2141
+ }
2142
+ }
2143
+
1908
2144
  /**
1909
2145
  * Phase 13.3: one-shot accessor for the launch params the most
1910
2146
  * recent [openPlayer] call handed to `PlayerActivity`. PlayerActivity
@@ -2221,21 +2457,23 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2221
2457
  // ── Native Pointer (for MpvRenderView) ─────────────────────────────────
2222
2458
 
2223
2459
  /**
2224
- * Phase 7: module-side accessor (Long) used by `PlayerActivity` (which
2225
- * lives in the `@simba/react-native-media-player` module and therefore
2226
- * cannot reference `MpvBridgeModule` directly) to obtain the active
2227
- * libmpv handle without crossing the Gradle module boundary.
2460
+ * The JS-facing pointer accessor.
2228
2461
  *
2229
- * The JS-facing @ReactMethod below stays as-is to keep the public
2230
- * TurboModule API stable. The two methods share the same private
2231
- * `nativePtr` field, so they can never disagree.
2462
+ * V20 Phase A removed its `IMpvNativePtrProvider` sibling. That
2463
+ * interface existed so `PlayerActivity` could fetch the handle across
2464
+ * a Gradle module boundary — a boundary Phase 6 had already removed
2465
+ * (see `MPVLib`'s own header). `PlayerActivity` now reads
2466
+ * `PlaybackHost` directly and registers with `whenAvailable`, so the
2467
+ * interface had no remaining consumer and was deleted rather than
2468
+ * left in place as fiction.
2469
+ *
2470
+ * This method stays because it is part of the published TurboModule
2471
+ * spec and removing it would be a breaking change for consumers.
2232
2472
  */
2233
- override fun fetchNativePtr(): Long = nativePtr
2234
-
2235
2473
  @ReactMethod(isBlockingSynchronousMethod = true)
2236
2474
  @Override
2237
2475
  override fun getNativePtr(): Double {
2238
- return nativePtr.toDouble()
2476
+ return PlaybackHost.handle().toDouble()
2239
2477
  }
2240
2478
 
2241
2479
  // ── Helpers ────────────────────────────────────────────────────────────
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.11.0",
3
+ "version": "1.13.0",
4
4
  "description": "React Native video & audio player powered by libmpv — Picture-in-Picture, MediaSession, foreground service, and a customizable TypeScript UI. Built for Android. Designed as a drop-in replacement for react-native-video / react-native-track-player / expo-av. See CHANGELOG.md for per-version notes.",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -191,6 +191,7 @@ export interface CaptureFrameOptions {
191
191
  * - Filters + playlist
192
192
  * - State queries
193
193
  * - Activity launch (openPlayer/getLaunchParams)
194
+ * - Audio without an Activity (startAudioPlayback/stopAudioPlayback)
194
195
  * - Configuration (setConfig)
195
196
  * - PiP + screen
196
197
  * - Orientation + immersive
@@ -396,6 +397,26 @@ export interface MpvPlayerModuleBridge {
396
397
  type: 'video' | 'audio',
397
398
  startPositionMs: number,
398
399
  ): Promise<boolean>;
400
+ /**
401
+ * Start an AUDIO track in the foreground media service with no
402
+ * `PlayerActivity` and therefore no window and no surface. V20
403
+ * Phase C. See `NativeMpvPlayer.ts` for the full reject-code
404
+ * contract (`E_INVALID_URI`, `E_ENGINE_UNAVAILABLE`, `E_LOAD_FAILED`,
405
+ * `E_START_SERVICE_FAILED`).
406
+ */
407
+ startAudioPlayback(options: {
408
+ uri: string;
409
+ title?: string;
410
+ artist?: string;
411
+ album?: string;
412
+ artworkPath?: string;
413
+ startPositionMs?: number;
414
+ autoPlay?: boolean;
415
+ }): Promise<boolean>;
416
+ /** Stop playback and tear the foreground service down. */
417
+ stopAudioPlayback(): void;
418
+ /** Whether the foreground service currently holds a live session. */
419
+ isAudioPlaybackServiceRunning(): boolean;
399
420
  /**
400
421
  * One-shot accessor for the launch params the most recent
401
422
  * `openPlayer` call handed to `PlayerActivity`. Returns `null`
@@ -647,6 +668,26 @@ const NOOP_BRIDGE: MpvPlayerModuleBridge = {
647
668
  void _startPositionMs;
648
669
  return Promise.resolve(false);
649
670
  },
671
+ // Audio playback without an Activity (V20 Phase C).
672
+ //
673
+ // Resolves `false` for the same reason `openPlayer` does: the fallback
674
+ // bridge is what jest and web previews get, and it has no engine and
675
+ // no service. `false` is falsy and assertable; a throw would take down
676
+ // a screen that only wanted to know the launch did not happen.
677
+ startAudioPlayback: (_options: {
678
+ uri: string;
679
+ title?: string;
680
+ artist?: string;
681
+ album?: string;
682
+ artworkPath?: string;
683
+ startPositionMs?: number;
684
+ autoPlay?: boolean;
685
+ }) => {
686
+ void _options;
687
+ return Promise.resolve(false);
688
+ },
689
+ stopAudioPlayback: () => {},
690
+ isAudioPlaybackServiceRunning: () => false,
650
691
  // V22.0.0 / 1.5.8 (D-035 fix #6): now matches the real
651
692
  // Promise<LaunchParams | null> runtime return type.
652
693
  getLaunchParams: () => Promise.resolve(null),
@@ -162,16 +162,90 @@ export interface Spec extends TurboModule {
162
162
  getDuration(): number;
163
163
  getPlaybackState(): string;
164
164
 
165
- // ── Activity launch (V12 Phase 3 / V13 Phase 52) ───────────────────────
166
- // Promise<boolean> — Kotlin @ReactMethod rejects with E_INVALID_TYPE /
167
- // E_NO_ACTIVITY / E_ACTIVITY_NOT_FOUND / E_SECURITY / E_OPEN_PLAYER_FAILED.
168
- // See `MpvBridgeModule.kt:1240-1320` for the launch implementation.
165
+ // ── Video window launch (V12 Phase 3 / V13 Phase 52 / V20 Phase C) ─────
166
+ // VIDEO ONLY as of 1.13.0.
167
+ //
168
+ // Promise<boolean> — Kotlin @ReactMethod rejects with
169
+ // • E_INVALID_TYPE — type is neither "video" nor "audio"
170
+ // • E_AUDIO_REQUIRES_SERVICE — type IS "audio". Audio no longer opens
171
+ // a window; it must go through `startAudioPlayback` below. Sending
172
+ // "audio" here rejects loudly rather than opening an Activity that
173
+ // has no surface and no notification.
174
+ // • E_NO_ACTIVITY / E_ACTIVITY_NOT_FOUND / E_SECURITY /
175
+ // E_OPEN_PLAYER_FAILED
169
176
  openPlayer(
170
177
  uri: string,
171
178
  title: string,
172
179
  type: string,
173
180
  startPositionMs: number,
174
181
  ): Promise<boolean>;
182
+
183
+ // ── Audio playback, no Activity (V20 Phase C) ──────────────────────────
184
+ /**
185
+ * Start an AUDIO track in the foreground media service, with no
186
+ * `PlayerActivity` and therefore no window and no surface.
187
+ *
188
+ * Why this exists: before V20, `MediaPlaybackService` could only be
189
+ * started from `PlayerActivity.onCreate`, so the session, the media
190
+ * notification and the media-key routing existed *only* while a window
191
+ * was open. Audio was forced into a full-screen Activity purely to get
192
+ * that service running — an Activity exists to draw, and audio has
193
+ * nothing to draw. `PlayerActivity` remains for video because PiP is
194
+ * per-Activity *window state* and cannot be attached to a React
195
+ * Navigation destination; nothing in the platform requires that of
196
+ * audio.
197
+ *
198
+ * Both steps happen natively, in this order, and the promise resolves
199
+ * only when both have run:
200
+ * 1. engine — ensure a handle exists, load the file, seek, play
201
+ * 2. service — `startForegroundService` with the media metadata
202
+ *
203
+ * Engine-first is deliberate. The service builds its notification from
204
+ * the engine's `duration` and `time-pos`, so loading first means the
205
+ * notification is correct on its first frame instead of being rebuilt
206
+ * once the position ticker catches up. Doing this as two JS round-trips
207
+ * would leave a window where the file is loaded but nothing owns
208
+ * playback — audio would play with no notification and no media keys.
209
+ *
210
+ * No Activity is required: this uses the React *application* context,
211
+ * which outlives every window.
212
+ *
213
+ * Reject codes:
214
+ * • E_INVALID_URI — `uri` blank
215
+ * • E_ENGINE_UNAVAILABLE — no libmpv handle and one could not be made
216
+ * • E_LOAD_FAILED — mpv refused the file
217
+ * • E_START_SERVICE_FAILED — the OS refused the foreground start
218
+ * (background-start restrictions, missing FOREGROUND_SERVICE)
219
+ */
220
+ startAudioPlayback(options: {
221
+ uri: string;
222
+ title?: string;
223
+ artist?: string;
224
+ album?: string;
225
+ /** Local path, `file://`, or an `http(s)` URL. Blank falls back to
226
+ * the app's drawable icon, as the notification always has. */
227
+ artworkPath?: string;
228
+ startPositionMs?: number;
229
+ /** Default true. Seek is applied regardless of `autoPlay`. */
230
+ autoPlay?: boolean;
231
+ }): Promise<boolean>;
232
+
233
+ /**
234
+ * Stop playback and tear the foreground service down. This is the mini
235
+ * player's close (X) verb — distinct from *minimize*, which is a React
236
+ * state change and never reaches the native layer.
237
+ *
238
+ * Synchronous and idempotent: the service's own `ACTION_STOP` handler
239
+ * already tolerates being called when nothing is loaded.
240
+ */
241
+ stopAudioPlayback(): void;
242
+
243
+ /**
244
+ * Whether the foreground service currently holds a live session.
245
+ * For assertions and for UI that must not offer a control it cannot
246
+ * honour. Synchronous: it reads a `@Volatile` flag the service owns.
247
+ */
248
+ isAudioPlaybackServiceRunning(): boolean;
175
249
  // Returns null when no launch is pending or after the first read.
176
250
  getLaunchParams(): Promise<{
177
251
  uri: string;
@@ -16,10 +16,37 @@ export interface OpenPlayerOptions {
16
16
  uri: string;
17
17
  /** Display title for the notification / top bar. */
18
18
  title: string;
19
- /** `'video'` launches the full-screen activity; `'audio'` plays in the background. */
19
+ /**
20
+ * `'video'` opens `PlayerActivity`. `'audio'` does NOT — it starts the
21
+ * foreground media service and plays with no window at all.
22
+ *
23
+ * That fork lives here rather than at the call sites on purpose.
24
+ * Three separate entry points reach this hook (`openPlayer`,
25
+ * `useOpenWithResume`, `useOpenPlaylist`) and a consumer has no way to
26
+ * tell which one a given screen uses. Deciding "does audio need a
27
+ * window?" at each of those would mean three places to keep in sync,
28
+ * and the one forgotten would open a blank full-screen player for a
29
+ * track with no surface.
30
+ */
20
31
  type: 'video' | 'audio';
21
32
  /** Resume position in milliseconds. 0 (or omitted) starts from the beginning. */
22
33
  startPositionMs?: number;
34
+ /**
35
+ * Optional artwork for the media notification's large icon — a local
36
+ * path, `file://`, or an `http(s)` URL.
37
+ *
38
+ * Audio only: `PlayerActivity` shows the video frame itself, so it has
39
+ * nothing to be handed. Consumed by `startAudioPlayback`; ignored on
40
+ * the video path, which is why passing it unconditionally is safe.
41
+ */
42
+ artworkPath?: string;
43
+ /**
44
+ * Optional artist / album lines for the notification subtitle.
45
+ * Audio only, for the same reason as `artworkPath`. Both are optional:
46
+ * an untagged file shows a title and nothing else.
47
+ */
48
+ artist?: string;
49
+ album?: string;
23
50
  }
24
51
 
25
52
  /**
@@ -94,11 +121,31 @@ export function usePlayerActivity(): UsePlayerActivityResult {
94
121
  () => ({
95
122
  openPlayer: (opts) => {
96
123
  const bridge = getMpvPlayerModule();
124
+ const startPositionMs = opts.startPositionMs ?? 0;
125
+
126
+ // Audio never opens a window. See `OpenPlayerOptions.type`.
127
+ if (opts.type === 'audio') {
128
+ return bridge.startAudioPlayback({
129
+ uri: opts.uri,
130
+ title: opts.title,
131
+ startPositionMs,
132
+ // A launch means "play this". The only reason not to would
133
+ // be an explicit pause request, and the way to ask for one
134
+ // is `commands.pause()` after the fact — not a launch that
135
+ // silently does nothing, which is what `autoPlay: false`
136
+ // here would look like to every existing caller.
137
+ autoPlay: true,
138
+ ...(opts.artworkPath ? {artworkPath: opts.artworkPath} : {}),
139
+ ...(opts.artist ? {artist: opts.artist} : {}),
140
+ ...(opts.album ? {album: opts.album} : {}),
141
+ });
142
+ }
143
+
97
144
  return bridge.openPlayer(
98
145
  opts.uri,
99
146
  opts.title,
100
147
  opts.type,
101
- opts.startPositionMs ?? 0,
148
+ startPositionMs,
102
149
  );
103
150
  },
104
151
  getLaunchParams: () => {
@@ -1,30 +0,0 @@
1
- package com.simba.player
2
-
3
- /**
4
- * Module-side contract that lets non-RN consumers (e.g. `PlayerActivity`)
5
- * fetch the active libmpv native pointer without crossing the Gradle
6
- * module boundary into the consumer app's bridge code.
7
- *
8
- * Why this exists:
9
- * - `MpvBridgeModule` lives in the consumer app at
10
- * `com.simba.player.mpv.MpvBridgeModule`. The module cannot import
11
- * it directly (Gradle does not let a library depend on its consumer).
12
- * - But `PlayerActivity` (which lives in the module) needs to call
13
- * `mpvRenderView.setNativePtr(ptr)` so the SurfaceView can attach
14
- * to mpv's `wid`. That ptr is owned by `MpvBridgeModule`.
15
- * - Solution: `MpvBridgeModule` implements this interface; module
16
- * code looks it up via `reactContext.getNativeModule("MpvPlayerModule")`
17
- * and casts to `IMpvNativePtrProvider`. The cast is safe because
18
- * we control both sides of the boundary.
19
- *
20
- * Phase 7 deliverable. The bridge-side ReactMethod `getNativePtr(): Double`
21
- * remains unchanged (keeps the JS-facing API stable) — this interface is
22
- * the native-only accessor used by the module's own activity code.
23
- */
24
- interface IMpvNativePtrProvider {
25
- /**
26
- * @return the active libmpv handle as a `Long`, or `0L` if mpv has
27
- * not been initialized yet (or has been destroyed).
28
- */
29
- fun fetchNativePtr(): Long
30
- }