@simba-dev/react-native-media-player 1.12.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.
@@ -10,7 +10,9 @@ import android.content.Intent
10
10
  import android.graphics.Bitmap
11
11
  import android.graphics.BitmapFactory
12
12
  import android.os.Build
13
+ import android.os.Handler
13
14
  import android.os.IBinder
15
+ import android.os.Looper
14
16
  import android.support.v4.media.MediaMetadataCompat
15
17
  import android.support.v4.media.session.MediaSessionCompat
16
18
  import android.support.v4.media.session.PlaybackStateCompat
@@ -62,23 +64,26 @@ import java.net.URL
62
64
  * same shape: `MainActivity` + `PlayerActivity` + `PlaybackService`, with
63
65
  * the service owning the player and session.
64
66
  *
65
- * ## Why the notification buttons now work
67
+ * ## Why the notification has no hand-added buttons
66
68
  *
67
- * The previous handlers were:
69
+ * V20 Phase B replaced these handlers, which did nothing:
68
70
  *
69
71
  * ```
70
- * ACTION_SKIP_NEXT -> Log.d(TAG, "… (MediaSession is the source of truth)")
71
- * ACTION_SKIP_PREV -> Log.d(TAG, "… (MediaSession is the source of truth)")
72
+ * ACTION_SKIP_NEXT -> Log.d(TAG, "... (MediaSession is the source of truth)")
73
+ * ACTION_SKIP_PREV -> Log.d(TAG, "... (MediaSession is the source of truth)")
72
74
  * ```
73
75
  *
74
- * and a play/pause handler that flipped a cached boolean and rebuilt the
75
- * notification without touching the engine. Two visible buttons and one
76
- * visible transport control that did nothing. There was no ordering in
77
- * which those were correct — the MediaStyle may or may not have routed
78
- * the tap to the session instead, which is exactly the ambiguity that
79
- * makes a control untrustworthy. Now every button maps to a real
80
- * command, and [PlaybackStateCompat.ACTION_SEEK_TO] is advertised so the
81
- * notification's progress bar is actually seekable.
76
+ * with real commands - but *also* kept our own action buttons on top of a
77
+ * session-backed MediaStyle. Device verification showed both sets rendering at
78
+ * once: two play-looking buttons and no way to tell which one was live. That
79
+ * is the "control that may or may not be the real one" ambiguity the whole
80
+ * change set out to remove, reintroduced by the fix.
81
+ *
82
+ * The buttons are gone. A MediaStyle carrying a session token renders the
83
+ * transport controls from the session advertised actions and routes taps to
84
+ * the session callback, which issues the real command - so the session alone
85
+ * is the single path. ACTION_SEEK_TO is advertised, which is what makes the
86
+ * progress bar seekable rather than decorative.
82
87
  */
83
88
  class MediaPlaybackService : Service() {
84
89
 
@@ -87,14 +92,28 @@ class MediaPlaybackService : Service() {
87
92
  const val CHANNEL_ID = "simba_player_media_playback"
88
93
  const val NOTIFICATION_ID = 1101
89
94
 
95
+ /**
96
+ * How often the service refreshes its own position cache, the
97
+ * session state and the notification. Matches the 1Hz the
98
+ * Activity-side ticker used to run at; the notification is the
99
+ * coarsest consumer of the three, so going finer would spend
100
+ * wake-ups on something no user can see move.
101
+ */
102
+ private const val TICK_INTERVAL_MS = 1000L
103
+
90
104
  // Intent actions
91
105
  const val ACTION_START = "com.simba.player.MEDIA_PLAYBACK_START"
92
106
  const val ACTION_UPDATE = "com.simba.player.MEDIA_PLAYBACK_UPDATE"
93
107
  const val ACTION_STOP = "com.simba.player.MEDIA_PLAYBACK_STOP"
94
- const val ACTION_PLAY_PAUSE = "com.simba.player.MEDIA_PLAYBACK_PLAY_PAUSE"
95
- const val ACTION_SKIP_NEXT = "com.simba.player.MEDIA_PLAYBACK_SKIP_NEXT"
96
- const val ACTION_SKIP_PREV = "com.simba.player.MEDIA_PLAYBACK_SKIP_PREV"
97
- const val ACTION_SEEK_TO = "com.simba.player.MEDIA_PLAYBACK_SEEK_TO"
108
+
109
+ // V20 Phase B originally added ACTION_PLAY_PAUSE / ACTION_SKIP_NEXT /
110
+ // ACTION_SKIP_PREV / ACTION_SEEK_TO so the notification's own
111
+ // action buttons had somewhere to land. Those buttons are gone -
112
+ // see buildNotification(). A MediaStyle carrying a session token
113
+ // renders the transport controls from the session's advertised
114
+ // actions and routes taps to the session callback, so these
115
+ // handlers were reachable from nowhere and were deleted rather
116
+ // than left in place as plausible-looking dead code.
98
117
 
99
118
  // Intent extras (kept in sync with PlayerActivity's
100
119
  // [buildMediaPlaybackServiceIntent] helper).
@@ -215,6 +234,75 @@ class MediaPlaybackService : Service() {
215
234
  private var currentDuration: Long = 0L
216
235
  private var isCurrentlyPlaying: Boolean = true
217
236
 
237
+ // ── Position ticker (V20 Phase C) ──────────────────────────────────────
238
+
239
+ /**
240
+ * This service owns its own 1Hz position ticker.
241
+ *
242
+ * It used to be driven by `PlayerActivity`'s
243
+ * `progressUpdateRunnable`, which only ran between that Activity's
244
+ * `onResume` and `onPause`. Once the window went away the tick stopped
245
+ * and `currentPosition` froze: the session's own state kept
246
+ * extrapolating via `speed = 1.0f`, so the system's lock-screen
247
+ * widget looked alive, while the notification's progress bar and this
248
+ * cache went stale. Two clocks disagreeing is worse than one frozen
249
+ * clock, because it reads as a bug in whichever one you are watching.
250
+ *
251
+ * It has to live here. With V20 Phase C, audio no longer opens an
252
+ * Activity at all, so there is frequently nothing left to drive a
253
+ * ticker that lived on an Activity — the notification would simply
254
+ * never move.
255
+ *
256
+ * Reads the engine directly each tick rather than trusting
257
+ * [isCurrentlyPlaying], so a track that ends underneath us (EOF) is
258
+ * noticed instead of being reported as playing forever.
259
+ */
260
+ private val tickerHandler = Handler(Looper.getMainLooper())
261
+ private var tickerRunning = false
262
+
263
+ private val positionTicker = object : Runnable {
264
+ override fun run() {
265
+ if (!tickerRunning) return
266
+ if (ptr() == 0L) {
267
+ // Engine torn down under us. Stop instead of spinning at
268
+ // 1Hz against a dead handle for as long as the service lives.
269
+ Log.w(TAG, "position ticker stopping: no engine handle")
270
+ tickerRunning = false
271
+ return
272
+ }
273
+ val idle = engineFlag("idle-active")
274
+ if (idle) {
275
+ // Nothing is loaded or the file reached its end. Publishing
276
+ // PLAYING here is how "the notification says it is playing
277
+ // and nothing is audible" happens.
278
+ Log.i(TAG, "position ticker: engine idle, publishing stopped state")
279
+ tickerRunning = false
280
+ publishPlaybackState(playing = false, state = PlaybackStateCompat.STATE_STOPPED)
281
+ notificationManager.notify(NOTIFICATION_ID, buildNotification())
282
+ return
283
+ }
284
+ val paused = engineFlag("pause")
285
+ isCurrentlyPlaying = !paused
286
+ publishPlaybackState(playing = !paused)
287
+ notificationManager.notify(NOTIFICATION_ID, buildNotification())
288
+ tickerHandler.postDelayed(this, TICK_INTERVAL_MS)
289
+ }
290
+ }
291
+
292
+ private fun startTicker() {
293
+ if (tickerRunning) return
294
+ tickerRunning = true
295
+ tickerHandler.postDelayed(positionTicker, TICK_INTERVAL_MS)
296
+ Log.i(TAG, "position ticker started (interval=${TICK_INTERVAL_MS}ms)")
297
+ }
298
+
299
+ private fun stopTicker(reason: String) {
300
+ if (!tickerRunning) return
301
+ tickerRunning = false
302
+ tickerHandler.removeCallbacks(positionTicker)
303
+ Log.i(TAG, "position ticker stopped ($reason)")
304
+ }
305
+
218
306
  // ── Lifecycle ──────────────────────────────────────────────────────────
219
307
 
220
308
  override fun onCreate() {
@@ -230,12 +318,6 @@ class MediaPlaybackService : Service() {
230
318
  when (intent?.action) {
231
319
  ACTION_UPDATE -> handleUpdate(intent)
232
320
  ACTION_STOP -> handleStop()
233
- // Every one of these now issues a real engine command. They
234
- // were previously a boolean flip and two log statements.
235
- ACTION_PLAY_PAUSE -> handlePlayPause()
236
- ACTION_SKIP_NEXT -> handleSkipNext()
237
- ACTION_SKIP_PREV -> handleSkipPrevious()
238
- ACTION_SEEK_TO -> handleSeekTo(intent)
239
321
  else -> handleStart(intent)
240
322
  }
241
323
  return START_REDELIVER_INTENT
@@ -247,6 +329,7 @@ class MediaPlaybackService : Service() {
247
329
  // Media3 puts player + session release in the *service's*
248
330
  // onDestroy. Doing it in an Activity's is what tied the session's
249
331
  // lifetime to a window.
332
+ stopTicker("service destroyed")
250
333
  releaseMediaSession()
251
334
  isRunning = false
252
335
  instance = null
@@ -269,26 +352,31 @@ class MediaPlaybackService : Service() {
269
352
  override fun onPlay() = command("onPlay") {
270
353
  MPVLib.nativePlay(ptr())
271
354
  publishPlaybackState(playing = true)
355
+ startTicker()
272
356
  }
273
357
 
274
358
  override fun onPause() = command("onPause") {
275
359
  MPVLib.nativePause(ptr())
276
360
  publishPlaybackState(playing = false)
361
+ stopTicker("paused")
277
362
  }
278
363
 
279
364
  override fun onStop() = command("onStop") {
280
365
  MPVLib.nativeStop(ptr())
281
366
  publishPlaybackState(playing = false, state = PlaybackStateCompat.STATE_STOPPED)
367
+ stopTicker("stopped")
282
368
  }
283
369
 
284
370
  override fun onSkipToNext() = command("onSkipToNext") {
285
371
  MPVLib.nativePlaylistNext(ptr())
286
372
  publishPlaybackState(playing = true)
373
+ startTicker()
287
374
  }
288
375
 
289
376
  override fun onSkipToPrevious() = command("onSkipToPrevious") {
290
377
  MPVLib.nativePlaylistPrev(ptr())
291
378
  publishPlaybackState(playing = true)
379
+ startTicker()
292
380
  }
293
381
 
294
382
  override fun onSeekTo(pos: Long) = command("onSeekTo($pos)") {
@@ -376,6 +464,16 @@ class MediaPlaybackService : Service() {
376
464
  }
377
465
  }
378
466
 
467
+ /**
468
+ * mpv renders boolean properties as the strings `"yes"` / `"no"`.
469
+ *
470
+ * Anything else — empty, `"null"`, a parse error — is reported as
471
+ * `false`, because "I could not read this" must not be mistaken for
472
+ * "this is true". A ticker's whole job is to be trustworthy.
473
+ */
474
+ private fun engineFlag(name: String): Boolean =
475
+ engineProperty(name).equals("yes", ignoreCase = true)
476
+
379
477
  /** Push the current transport state into the session. */
380
478
  private fun publishPlaybackState(
381
479
  playing: Boolean,
@@ -454,6 +552,10 @@ class MediaPlaybackService : Service() {
454
552
  isRunning = true
455
553
  applyMetadata(currentTitle, currentArtist, currentAlbum, currentArtworkPath, "", "")
456
554
  startForeground(NOTIFICATION_ID, buildNotification())
555
+ // Phase C: the engine has already been handed the file by the
556
+ // caller before this intent was built, so the ticker starts
557
+ // against a live engine rather than an empty one.
558
+ if (isCurrentlyPlaying) startTicker() else stopTicker("start without autoplay")
457
559
  Log.i(
458
560
  TAG,
459
561
  "Media playback started: title='$currentTitle' artist='$currentArtist' playing=$isCurrentlyPlaying",
@@ -474,6 +576,7 @@ class MediaPlaybackService : Service() {
474
576
  }
475
577
 
476
578
  private fun handleStop() {
579
+ stopTicker("stop command")
477
580
  command("notification-stop") {
478
581
  if (ptr() != 0L) MPVLib.nativeStop(ptr())
479
582
  }
@@ -482,72 +585,6 @@ class MediaPlaybackService : Service() {
482
585
  stopSelf()
483
586
  }
484
587
 
485
- private fun handlePlayPause() {
486
- val handle = ptr()
487
- if (handle == 0L) {
488
- Log.w(TAG, "ACTION_PLAY_PAUSE ignored: no engine handle")
489
- return
490
- }
491
- val playing = !isCurrentlyPlaying
492
- try {
493
- if (playing) MPVLib.nativePlay(handle) else MPVLib.nativePause(handle)
494
- } catch (e: Exception) {
495
- Log.w(TAG, "ACTION_PLAY_PAUSE: command threw ${e.message}", e)
496
- return
497
- }
498
- // State is published *after* the command, so the glyph reflects
499
- // what the engine was actually told to do — not what we hoped.
500
- publishPlaybackState(playing)
501
- notificationManager.notify(NOTIFICATION_ID, buildNotification())
502
- }
503
-
504
- private fun handleSkipNext() {
505
- if (ptr() == 0L) {
506
- Log.w(TAG, "ACTION_SKIP_NEXT ignored: no engine handle")
507
- return
508
- }
509
- try {
510
- MPVLib.nativePlaylistNext(ptr())
511
- } catch (e: Exception) {
512
- Log.w(TAG, "ACTION_SKIP_NEXT: ${e.message}", e)
513
- return
514
- }
515
- publishPlaybackState(playing = true)
516
- notificationManager.notify(NOTIFICATION_ID, buildNotification())
517
- }
518
-
519
- private fun handleSkipPrevious() {
520
- if (ptr() == 0L) {
521
- Log.w(TAG, "ACTION_SKIP_PREV ignored: no engine handle")
522
- return
523
- }
524
- try {
525
- MPVLib.nativePlaylistPrev(ptr())
526
- } catch (e: Exception) {
527
- Log.w(TAG, "ACTION_SKIP_PREV: ${e.message}", e)
528
- return
529
- }
530
- publishPlaybackState(playing = true)
531
- notificationManager.notify(NOTIFICATION_ID, buildNotification())
532
- }
533
-
534
- private fun handleSeekTo(intent: Intent) {
535
- val positionMs = intent.getLongExtra(EXTRA_POSITION_MS, -1L)
536
- val handle = ptr()
537
- if (handle == 0L || positionMs < 0L) {
538
- Log.w(TAG, "ACTION_SEEK_TO ignored (handle=$handle, pos=$positionMs)")
539
- return
540
- }
541
- try {
542
- MPVLib.nativeSeek(handle, positionMs.toDouble() / 1000.0)
543
- } catch (e: Exception) {
544
- Log.w(TAG, "ACTION_SEEK_TO: ${e.message}", e)
545
- return
546
- }
547
- publishPlaybackState(isCurrentlyPlaying)
548
- notificationManager.notify(NOTIFICATION_ID, buildNotification())
549
- }
550
-
551
588
  // ── Notification Channel (Android 8+) ──────────────────────────────────
552
589
 
553
590
  private fun createNotificationChannel() {
@@ -571,18 +608,16 @@ class MediaPlaybackService : Service() {
571
608
  // ── Notification Building ──────────────────────────────────────────────
572
609
 
573
610
  private fun buildNotification(): Notification {
574
- val playbackAction = if (isCurrentlyPlaying) {
575
- android.R.drawable.ic_media_pause
576
- } else {
577
- android.R.drawable.ic_media_play
578
- }
579
- val playbackContent = if (isCurrentlyPlaying) "Pause" else "Play"
580
-
581
- val subtitle: String? = when {
611
+ // Never null. `setContentText(null)` renders the literal string
612
+ // "null" in the MediaStyle subtitle when artist and album are both
613
+ // blank - which is every untagged file. An untagged item should
614
+ // show nothing, not the word "null".
615
+ val subtitle = when {
582
616
  currentArtist.isNotBlank() && currentAlbum.isNotBlank() ->
583
617
  "$currentArtist • $currentAlbum"
584
618
  currentArtist.isNotBlank() -> currentArtist
585
- else -> null
619
+ currentAlbum.isNotBlank() -> currentAlbum
620
+ else -> ""
586
621
  }
587
622
 
588
623
  val artwork: Bitmap? = loadArtworkBitmap(currentArtworkPath) ?: BitmapFactory.decodeResource(
@@ -605,6 +640,21 @@ class MediaPlaybackService : Service() {
605
640
 
606
641
  // MediaStyle points at *this service's own* session — no token
607
642
  // has to be handed in by an Activity any more.
643
+ //
644
+ // No manual actions are added here, deliberately.
645
+ //
646
+ // Once a MediaStyle carries a session token, the system renders
647
+ // the transport controls from `session.playbackState.actions` and
648
+ // routes taps to the session callback. Adding our own on top
649
+ // produced TWO overlapping control sets on device - two
650
+ // play-looking buttons and an ambiguous tap target - which is
651
+ // exactly the "control that may or may not be the real one"
652
+ // ambiguity this class was rewritten to remove.
653
+ //
654
+ // The session advertises PLAY / PAUSE / PLAY_PAUSE / STOP /
655
+ // SKIP_TO_NEXT / SKIP_TO_PREVIOUS / SEEK_TO, so every control we
656
+ // need is already rendered and already wired to a real command.
657
+ // Stop additionally gets the MediaStyle cancel button below.
608
658
  val session = mediaSession
609
659
  val mediaStyle = androidx.media.app.NotificationCompat.MediaStyle()
610
660
  .setShowActionsInCompactView(INDEX_PLAY, INDEX_NEXT, INDEX_PREV)
@@ -615,32 +665,10 @@ class MediaPlaybackService : Service() {
615
665
  }
616
666
  builder.setStyle(mediaStyle)
617
667
 
618
- // Action buttons
619
- builder.addAction(
620
- android.R.drawable.ic_media_previous,
621
- "Previous",
622
- buildActionIntent(this, ACTION_SKIP_PREV),
623
- )
624
- builder.addAction(playbackAction, playbackContent, buildActionIntent(this, ACTION_PLAY_PAUSE))
625
- builder.addAction(
626
- android.R.drawable.ic_media_next,
627
- "Next",
628
- buildActionIntent(this, ACTION_SKIP_NEXT),
629
- )
630
- builder.addAction(
631
- android.R.drawable.ic_menu_close_clear_cancel,
632
- "Stop",
633
- buildActionIntent(this, ACTION_STOP),
634
- )
635
-
636
668
  // Progress bar. Seekable now, because the session advertises
637
- // ACTION_SEEK_TO and ACTION_SEEK_TO dispatches a real command.
669
+ // ACTION_SEEK_TO - which is what makes the system render this
670
+ // seekable rather than as decoration.
638
671
  if (currentDuration > 0L) {
639
- builder.addAction(
640
- android.R.drawable.ic_media_play,
641
- "Seek",
642
- buildSeekIntent(currentPosition),
643
- )
644
672
  builder.setProgress(
645
673
  currentDuration.toInt(),
646
674
  currentPosition.toInt(),
@@ -651,19 +679,6 @@ class MediaPlaybackService : Service() {
651
679
  return builder.build()
652
680
  }
653
681
 
654
- private fun buildSeekIntent(positionMs: Long): PendingIntent {
655
- val intent = Intent(this, MediaPlaybackService::class.java).apply {
656
- action = ACTION_SEEK_TO
657
- putExtra(EXTRA_POSITION_MS, positionMs)
658
- }
659
- return PendingIntent.getService(
660
- this,
661
- (ACTION_SEEK_TO + positionMs).hashCode(),
662
- intent,
663
- PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
664
- )
665
- }
666
-
667
682
  // ── Artwork Loading ────────────────────────────────────────────────────
668
683
 
669
684
  private fun loadArtworkBitmap(path: String): Bitmap? {
@@ -689,4 +704,4 @@ class MediaPlaybackService : Service() {
689
704
  null
690
705
  }
691
706
  }
692
- }
707
+ }
@@ -1832,7 +1832,15 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1832
1832
  //
1833
1833
  // Reject codes (matched by the TS Spec's `E_*` contract in
1834
1834
  // NativeMpvPlayer.ts):
1835
- // • 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.
1836
1844
  // • E_NO_ACTIVITY — no current activity (RN bridge down)
1837
1845
  // • E_ACTIVITY_NOT_FOUND — PlayerActivity not declared in manifest
1838
1846
  // • E_SECURITY — manifest restriction refused the launch
@@ -1846,14 +1854,21 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1846
1854
  startPositionMs: Double,
1847
1855
  promise: Promise,
1848
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
+ }
1849
1866
  // 3.3: validate `type` — defensive against the JS layer ever
1850
1867
  // passing a typo (the TS Spec already types it as the union
1851
1868
  // `'video' | 'audio'`, but a stale bundle could skip the check).
1852
- if (type != com.simba.player.PlayerActivity.TYPE_VIDEO &&
1853
- type != com.simba.player.PlayerActivity.TYPE_AUDIO
1854
- ) {
1869
+ if (type != com.simba.player.PlayerActivity.TYPE_VIDEO) {
1855
1870
  Log.w(TAG, "[PlaybackTrace][Bridge][openPlayer] invalid type='$type', rejecting with E_INVALID_TYPE")
1856
- 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'")
1857
1872
  return
1858
1873
  }
1859
1874
  // 3.4: require a current activity. In bridgeless RN this is null
@@ -1920,6 +1935,212 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1920
1935
  }
1921
1936
  }
1922
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
+
1923
2144
  /**
1924
2145
  * Phase 13.3: one-shot accessor for the launch params the most
1925
2146
  * recent [openPlayer] call handed to `PlayerActivity`. PlayerActivity
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.12.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: () => {