@simba-dev/react-native-media-player 1.10.0 → 1.12.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.
@@ -142,13 +142,27 @@ class PlayerActivity : ReactActivity() {
142
142
 
143
143
  private var mpvRenderView: MpvRenderView? = null
144
144
 
145
- // ── Native pointer cache (Phase 9) ────────────────────────────────
146
- // The libmpv native pointer, captured whenever wireNativePtr
147
- // successfully resolves it via the RN bridge. Used by Phase 9's
148
- // getVideoAspect() to query `video-params/aspect` for PiP sizing.
149
- // Zero means "mpv not yet initialised by JS"; Phase 9 falls back
150
- // to the 16:9 default in that case.
151
- private var lastNativePtr: Long = 0L
145
+ // ── Engine handle (V20 Phase A) ─────────────────────────────────────
146
+ // V20 removed `PlaybackHost.handle()`, the cached copy of the libmpv handle.
147
+ // The copy could never be invalidated: MpvBridgeModule.destroy() zeroed
148
+ // only its own field, so after a destroy/re-create the Activity held a
149
+ // pointer that no longer matched the process global `g_mpv` and every
150
+ // call below was refused by the native lease guard. The symptom was a
151
+ // control surface that was present, wired and permanently inert.
152
+ //
153
+ // The handle now lives in exactly one place — `PlaybackHost` — and is
154
+ // read at the point of use via `PlaybackHost.handle()`. This listener
155
+ // exists only so the render view is wired when mpv becomes available;
156
+ // it replaces a 300ms × 200-attempt polling loop.
157
+ private val onEngineAvailable: (Long) -> Unit = engineAvailable@{ ptr ->
158
+ val view = mpvRenderView ?: return@engineAvailable
159
+ Log.i(TAG, "engine available ptr=$ptr, calling MpvRenderView.setNativePtr")
160
+ view.setNativePtr(ptr)
161
+ // The session's first metadata read happens now that mpv is wired,
162
+ // so the lock-screen widget shows the file's real tags rather than
163
+ // just the launch title.
164
+ setMediaSessionMetadata()
165
+ }
152
166
 
153
167
  // ── PiP action receiver (Phase 10) ────────────────────────────────
154
168
  // `PipActionReceiver` listens for the 3 PiP overlay intents
@@ -282,19 +296,20 @@ class PlayerActivity : ReactActivity() {
282
296
  return prefs.getBoolean(KEY_AUDIO_BG_PLAYBACK, true)
283
297
  }
284
298
 
285
- // ── MediaSession (Phase 15) ─────────────────────────────────────────
286
- // Basic MediaSession so the audio PiP gets system media controls
287
- // (lock-screen widget, Bluetooth pause/play, Android Auto, etc.).
288
- // The session is created in onCreate and released in onDestroy;
289
- // the callback translates play/pause into MPVLib calls.
299
+ // ── MediaSession (V20 Phase B) ───────────────────────────────────────
300
+ // This Activity no longer holds a MediaSessionCompat.
301
+ //
302
+ // It used to: the session was created in onCreate and released in
303
+ // onDestroy, which meant the lock-screen widget, the notification and
304
+ // the Bluetooth/Auto transport controls all died the moment this window
305
+ // closed — "hide the player" and "shut the player down" were the same
306
+ // verb, and a mini player could not exist.
290
307
  //
291
- // This is intentionally minimal — no notification, no metadata
292
- // (the title is set on the PiP params in buildCurrentPipParams).
293
- // A future phase can layer in the full MediaStyle notification
294
- // + MediaMetadata (artwork, duration, position) on top of this
295
- // same session.
296
- private var mediaSession: android.support.v4.media.session.MediaSessionCompat? = null
297
- private var mediaSessionCallback: android.support.v4.media.session.MediaSessionCompat.Callback? = null
308
+ // The session now belongs to `MediaPlaybackService`, per Media3's
309
+ // guidance to contain Player and MediaSession inside a separate
310
+ // Service. This Activity pushes state and metadata to it through
311
+ // `MediaPlaybackService.publishState` / `publishMetadata`, and the
312
+ // service's own callback issues the transport commands.
298
313
 
299
314
  // ── Progress update timer (Phase 17) ─────────────────────────────────
300
315
  // 1Hz periodic runnable that queries mpv's `time-pos` property
@@ -483,31 +498,22 @@ class PlayerActivity : ReactActivity() {
483
498
  Log.i(TAG, "MpvRenderView hidden for audio mode (visibility=GONE)")
484
499
  }
485
500
 
486
- // ── Phase 7: Wire the libmpv native pointer into MpvRenderView ────
487
- // The mpv handle is owned by `MpvBridgeModule` (in the consumer app's
488
- // `com.simba.player.mpv` package). The module can't see that class
489
- // directly, so we resolve it through the RN bridge:
490
- // 1. Resolve the ReactApplicationContext via the ReactApplication
491
- // interface (works for both bridgeless `reactHost` and legacy
492
- // `reactInstanceManager`).
493
- // 2. Look up the bridge module by its registered name
494
- // (`MpvPlayerModule`).
495
- // 3. Cast to the module-side `IMpvNativePtrProvider` interface
496
- // (MpvBridgeModule implements it).
497
- // 4. Call `fetchNativePtr()` and pass to `mpvRenderView.setNativePtr`.
501
+ // ── Wire the libmpv handle into MpvRenderView (V20 Phase A) ─────────
502
+ // V20 replaced a polling loop with a listener.
503
+ //
504
+ // Before: the Activity asked the RN bridge for the handle via
505
+ // `getNativeModule("MpvPlayerModule")`, cast to
506
+ // `IMpvNativePtrProvider`, and retried every 300ms up to 200 times
507
+ // (~60s) because a cold React start can take 30+s. That existed to
508
+ // work around a Gradle module boundary that Phase 6 already removed,
509
+ // and it cached the result in `PlaybackHost.handle()`, which could never be
510
+ // invalidated.
498
511
  //
499
- // Defer via `Handler(Looper.getMainLooper()).post { ... }` so the
500
- // lookup runs AFTER super.onCreate has installed the React tree,
501
- // AFTER the activity is fully resumed (RN may still be initialising
502
- // its bridge at this point), and AFTER the SurfaceView's first
503
- // surfaceCreated callback has fired (so the view's internal holder
504
- // is ready for an attachSurfaceLocked call). 50ms is enough on
505
- // every device we have tested (Pixel 4a through S23); if mpv is
506
- // still 0 here, a follow-up Handler.postDelayed retries every
507
- // 200ms until non-zero (capped at 5 attempts to avoid an infinite
508
- // spin if RN never initialises).
509
- val h = Handler(Looper.getMainLooper())
510
- h.post { wireNativePtr(retryCount = 0) }
512
+ // Now: `PlaybackHost` owns the handle and notifies when it appears.
513
+ // `whenAvailable` invokes the listener immediately if the handle is
514
+ // already present, so a late-mounting Activity converges with no
515
+ // polling, no interface cast and no cached copy.
516
+ PlaybackHost.whenAvailable(onEngineAvailable)
511
517
 
512
518
  // ── Phase 10: Register PiP action receiver ────────────────────────
513
519
  // Listens for the 3 PiP overlay intents and forwards them to JS via
@@ -525,13 +531,10 @@ class PlayerActivity : ReactActivity() {
525
531
  registerReceiver(receiver, PipManager.intentFilter())
526
532
  }
527
533
  Log.i(TAG, "onCreate: PipActionReceiver registered")
528
- // Phase 15.3: create the basic MediaSession. The session is
529
- // active for the lifetime of the activity and is released in
530
- // onDestroy. We create it last (after the receiver is
531
- // registered) so the system has both the broadcast channel
532
- // and the media-button channel available for the same
533
- // launch.
534
- createMediaSession()
534
+ // V20 Phase B: the MediaSession is no longer created here.
535
+ // Starting the service is what brings the session up — the service
536
+ // creates it in its own onCreate and releases it in its own
537
+ // onDestroy, so it outlives this window.
535
538
  // Phase 16.6: start the MediaPlaybackService as a foreground
536
539
  // service so the persistent media-style notification appears
537
540
  // in the system shade. Android 8+ requires
@@ -550,90 +553,11 @@ class PlayerActivity : ReactActivity() {
550
553
  loadAndLogPlayerConfig()
551
554
  }
552
555
 
553
- /**
554
- * Phase 7: Resolve the libmpv native pointer from the JS-side
555
- * `MpvBridgeModule` via the React Native bridge and hand it to
556
- * `MpvRenderView.setNativePtr(...)`. Retries on the main thread if
557
- * the pointer is still 0 (mpv not yet initialised by JS).
558
- */
559
- private fun wireNativePtr(retryCount: Int) {
560
- val view = mpvRenderView ?: run {
561
- Log.w(TAG, "wireNativePtr: MpvRenderView gone, aborting")
562
- return
563
- }
564
- val reactContext: ReactApplicationContext? = resolveReactApplicationContext()
565
- if (reactContext == null) {
566
- Log.w(TAG, "wireNativePtr: ReactApplicationContext null (retryCount=$retryCount)")
567
- maybeRetry(retryCount)
568
- return
569
- }
570
- val nativeModule: NativeModule? = try {
571
- reactContext.getNativeModule("MpvPlayerModule")
572
- } catch (e: Exception) {
573
- Log.w(TAG, "wireNativePtr: getNativeModule threw ${e.message}", e)
574
- null
575
- }
576
- if (nativeModule !is IMpvNativePtrProvider) {
577
- Log.w(
578
- TAG,
579
- "wireNativePtr: 'MpvPlayerModule' not registered yet or doesn't implement IMpvNativePtrProvider " +
580
- "(got ${nativeModule?.javaClass?.simpleName ?: "null"}, retryCount=$retryCount)",
581
- )
582
- maybeRetry(retryCount)
583
- return
584
- }
585
- val ptr = nativeModule.fetchNativePtr()
586
- if (ptr == 0L) {
587
- Log.i(TAG, "wireNativePtr: MpvBridgeModule not yet initialised by JS (retryCount=$retryCount)")
588
- maybeRetry(retryCount)
589
- return
590
- }
591
- // Phase 9: cache the native pointer so subsequent PiP param
592
- // updates can query mpv's `video-params/aspect` without
593
- // re-resolving the bridge module.
594
- lastNativePtr = ptr
595
- Log.i(TAG, "wireNativePtr: ptr=$ptr, calling MpvRenderView.setNativePtr")
596
- view.setNativePtr(ptr)
597
- // Phase 19.4: refresh the MediaSession metadata now that the
598
- // mpv handle is wired up. The first call (in
599
- // createMediaSession) was just the launch title; this one
600
- // queries mpv's `media-title` / `metadata/by-key/artist` /
601
- // `metadata/by-key/album` and updates the lock-screen
602
- // widget with the actual file tags. A future phase can
603
- // also re-run this from an observer hook (Phase 22
604
- // territory) to catch later metadata refreshes.
605
- setMediaSessionMetadata()
606
- }
607
-
608
- /**
609
- * Phase 7 helper: schedule another `wireNativePtr` attempt on the main
610
- * thread. D-040: bump the retry budget from 5×200ms (1.2s, the V22
611
- * baseline) to 200×300ms (60s) so a cold start of PlayerActivity's
612
- * React tree — which can take 30+ seconds before the ReactApplication
613
- * Context is ready — still succeeds. Without this, a direct
614
- * `am start` / deep link / app-shortcut launch (where MainActivity is
615
- * NOT warming React first) leaves MpvRenderView's nativePtr at 0 and
616
- * the video stays black even though mpv initialised. After 200
617
- * attempts we log + give up — a hung RN init is the only path that
618
- * exhausts the budget and that scenario surfaces separately as the
619
- * JS bundle failing to mount.
620
- */
621
- private fun maybeRetry(retryCount: Int) {
622
- if (retryCount >= 200) {
623
- Log.e(TAG, "wireNativePtr: giving up after ${retryCount + 1} attempts (~60s)")
624
- return
625
- }
626
- Handler(Looper.getMainLooper()).postDelayed(
627
- { wireNativePtr(retryCount + 1) },
628
- 300L,
629
- )
630
- }
631
-
632
556
  /**
633
557
  * Phase 21 helper: resolve the module-side [IMpvConfigProvider] via
634
558
  * the React Native bridge and log the active PlayerConfig keys.
635
559
  *
636
- * Mirrors the wireNativePtr retry pattern in spirit (resolve
560
+ * Mirrors the engine-availability pattern in spirit (resolve
637
561
  * context → lookup → cast) but runs once — a missed config read
638
562
  * is just a missing log line, not a playback failure. The
639
563
  * lookup runs synchronously because the Provider push happens
@@ -706,169 +630,16 @@ class PlayerActivity : ReactActivity() {
706
630
  // `module.getCurrentConfig()` directly each time.
707
631
  }
708
632
 
709
- // ── MediaSession (Phase 15.3 + Phase 18) ──────────────────────────────
710
- // Creates the MediaSessionCompat that translates ALL system
711
- // transport requests (lock-screen widget, Bluetooth, Android
712
- // Auto, headset button, MediaPlaybackService's notification
713
- // actions) into MPVLib calls. The session is released in
714
- // onDestroy via [releaseMediaSession].
715
- //
716
- // Phase 15.3 created a "basic" session with onPlay / onPause
717
- // only. Phase 18 expands the callback to cover the full
718
- // transport set: play, pause, stop, skip-to-next, skip-to-prev,
719
- // seek-to, play-from-media-id, play-from-search. The
720
- // session's `PlaybackStateCompat` advertises the matching
721
- // ACTION_* flags so the system UI renders the right buttons
722
- // and seek bar.
633
+ // ── MediaSession (V20 Phase B) ──────────────────────────────────────
634
+ // The session itself belongs to MediaPlaybackService now — see that
635
+ // class header for why. What remains here is the Activity's side of
636
+ // the conversation: this Activity knows when playback state changed
637
+ // because of *its own* lifecycle decisions (an audio-focus loss, a PiP
638
+ // transition, a resume) and publishes them.
723
639
  //
724
- // The session activity (PendingIntent) is set so the system
725
- // can bring PlayerActivity to the foreground when the user
726
- // taps the lock-screen widget. Without a session activity,
727
- // the system has no way to know which activity owns the
728
- // session and would default to launching the app's main
729
- // launcher intent (which could be wrong if the user launched
730
- // PlayerActivity from a deep link).
731
- private fun createMediaSession() {
732
- val callback = object : android.support.v4.media.session.MediaSessionCompat.Callback() {
733
- override fun onPlay() {
734
- Log.i(TAG, "MediaSession.onPlay")
735
- val ptr = lastNativePtr
736
- if (ptr != 0L) {
737
- try {
738
- MPVLib.nativePlay(ptr)
739
- updateMediaSessionState(playing = true)
740
- } catch (e: Exception) {
741
- Log.w(TAG, "MediaSession.onPlay: nativePlay threw ${e.message}", e)
742
- }
743
- }
744
- }
745
-
746
- override fun onPause() {
747
- Log.i(TAG, "MediaSession.onPause")
748
- val ptr = lastNativePtr
749
- if (ptr != 0L) {
750
- try {
751
- MPVLib.nativePause(ptr)
752
- updateMediaSessionState(playing = false)
753
- } catch (e: Exception) {
754
- Log.w(TAG, "MediaSession.onPause: nativePause threw ${e.message}", e)
755
- }
756
- }
757
- }
758
-
759
- override fun onStop() {
760
- // Phase 18.3.3: stop mpv (clears the file + resets the
761
- // engine state). The session stays active so a
762
- // subsequent onPlay can re-load — the activity's
763
- // closePlayer() path is what deactivates + releases
764
- // the session.
765
- Log.i(TAG, "MediaSession.onStop")
766
- val ptr = lastNativePtr
767
- if (ptr != 0L) {
768
- try {
769
- MPVLib.nativeStop(ptr)
770
- updateMediaSessionState(playing = false, state = android.support.v4.media.session.PlaybackStateCompat.STATE_STOPPED)
771
- } catch (e: Exception) {
772
- Log.w(TAG, "MediaSession.onStop: nativeStop threw ${e.message}", e)
773
- }
774
- }
775
- }
776
-
777
- override fun onSkipToNext() {
778
- Log.i(TAG, "MediaSession.onSkipToNext")
779
- val ptr = lastNativePtr
780
- if (ptr != 0L) {
781
- try {
782
- MPVLib.nativePlaylistNext(ptr)
783
- // The playlist will fire a new file-load; we don't
784
- // know the new position yet, so just refresh the
785
- // state with the new playing flag.
786
- updateMediaSessionState(playing = true)
787
- } catch (e: Exception) {
788
- Log.w(TAG, "MediaSession.onSkipToNext: nativePlaylistNext threw ${e.message}", e)
789
- }
790
- }
791
- }
792
-
793
- override fun onSkipToPrevious() {
794
- Log.i(TAG, "MediaSession.onSkipToPrevious")
795
- val ptr = lastNativePtr
796
- if (ptr != 0L) {
797
- try {
798
- MPVLib.nativePlaylistPrev(ptr)
799
- updateMediaSessionState(playing = true)
800
- } catch (e: Exception) {
801
- Log.w(TAG, "MediaSession.onSkipToPrevious: nativePlaylistPrev threw ${e.message}", e)
802
- }
803
- }
804
- }
805
-
806
- override fun onSeekTo(pos: Long) {
807
- // Phase 18.3.6: seek to absolute position (ms). mpv's
808
- // `nativeSeek` takes seconds (Double), so divide by
809
- // 1000. The progress update timer (Phase 17) will
810
- // pick up the new position on its next tick and ship
811
- // it to MediaPlaybackService.
812
- Log.i(TAG, "MediaSession.onSeekTo($pos)")
813
- val ptr = lastNativePtr
814
- if (ptr != 0L && pos >= 0L) {
815
- try {
816
- MPVLib.nativeSeek(ptr, pos.toDouble() / 1000.0)
817
- } catch (e: Exception) {
818
- Log.w(TAG, "MediaSession.onSeekTo: nativeSeek threw ${e.message}", e)
819
- }
820
- }
821
- }
822
- }
823
- mediaSessionCallback = callback
824
- val session = android.support.v4.media.session.MediaSessionCompat(this, TAG)
825
- session.setFlags(
826
- android.support.v4.media.session.MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or
827
- android.support.v4.media.session.MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS,
828
- )
829
- session.setCallback(callback)
830
- // Phase 18.4: set the session activity — a PendingIntent
831
- // that the system can fire to bring PlayerActivity back to
832
- // the foreground on lock-screen interactions. Without
833
- // this, the system defaults to the app's launcher
834
- // intent, which might be wrong (e.g. user launched the
835
- // player from a deep link to a different activity).
836
- val sessionActivityIntent = android.content.Intent(this, PlayerActivity::class.java).apply {
837
- flags = android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP or
838
- android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
839
- }
840
- val sessionActivityPendingIntent = android.app.PendingIntent.getActivity(
841
- this,
842
- 0,
843
- sessionActivityIntent,
844
- android.app.PendingIntent.FLAG_UPDATE_CURRENT or android.app.PendingIntent.FLAG_IMMUTABLE,
845
- )
846
- session.setSessionActivity(sessionActivityPendingIntent)
847
- session.isActive = true
848
- mediaSession = session
849
- // Phase 19.4: initial metadata set with the launch title.
850
- // At this point the file hasn't loaded yet so mpv's
851
- // `media-title` is empty — the fallback chain in
852
- // setMediaSessionMetadata picks up `launchTitle`. Once
853
- // `wireNativePtr` succeeds, [wireNativePtr] re-queries mpv
854
- // and refreshes the metadata with the actual tags.
855
- setMediaSessionMetadata()
856
- Log.i(TAG, "MediaSession created (active=true, callback set, sessionActivity set)")
857
- }
858
-
859
- // Update PlaybackState with the current playing flag + state +
860
- // position. Called from the session callback (after the
861
- // MPVLib call) and from onResume so the lock-screen reflects
862
- // the current state when the activity comes back to the
863
- // foreground.
864
- //
865
- // Phase 18.6: the action set is now the full transport set
866
- // (PLAY, PAUSE, STOP, SKIP_NEXT, SKIP_PREV, SEEK_TO,
867
- // PLAY_PAUSE) so the system UI can render every control the
868
- // spec calls for. The state defaults to STATE_PLAYING /
869
- // STATE_PAUSED based on the `playing` flag; callers can
870
- // override with `state = STATE_STOPPED` etc. for finer
871
- // transitions.
640
+ // The transport commands themselves arrive through the service's
641
+ // callback, which reads the engine via PlaybackHost at the moment of
642
+ // use — so a command can no longer be issued against a stale handle.
872
643
  private fun updateMediaSessionState(
873
644
  playing: Boolean,
874
645
  state: Int = if (playing) {
@@ -877,41 +648,7 @@ class PlayerActivity : ReactActivity() {
877
648
  android.support.v4.media.session.PlaybackStateCompat.STATE_PAUSED
878
649
  },
879
650
  ) {
880
- val session = mediaSession ?: return
881
- val stateBuilder = android.support.v4.media.session.PlaybackStateCompat.Builder()
882
- // Full transport set — the system UI can render any of
883
- // these controls based on what it decides to show
884
- // (lock-screen widget shows 5, Bluetooth shows 2-3, etc.).
885
- stateBuilder.setActions(
886
- android.support.v4.media.session.PlaybackStateCompat.ACTION_PLAY or
887
- android.support.v4.media.session.PlaybackStateCompat.ACTION_PAUSE or
888
- android.support.v4.media.session.PlaybackStateCompat.ACTION_PLAY_PAUSE or
889
- android.support.v4.media.session.PlaybackStateCompat.ACTION_STOP or
890
- android.support.v4.media.session.PlaybackStateCompat.ACTION_SKIP_TO_NEXT or
891
- android.support.v4.media.session.PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or
892
- android.support.v4.media.session.PlaybackStateCompat.ACTION_SEEK_TO,
893
- )
894
- // Phase 18.6.2: include the current position so the
895
- // system UI can show the seek-bar at the right place
896
- // even before the first progress update tick lands.
897
- val positionMs = getPlaybackPositionMs()
898
- stateBuilder.setState(state, positionMs, 1.0f)
899
- session.setPlaybackState(stateBuilder.build())
900
- }
901
-
902
- // Release the session and null the field so a re-create picks up
903
- // a fresh instance. Called from onDestroy.
904
- private fun releaseMediaSession() {
905
- val session = mediaSession ?: return
906
- try {
907
- session.isActive = false
908
- session.release()
909
- Log.i(TAG, "MediaSession released")
910
- } catch (e: Exception) {
911
- Log.w(TAG, "releaseMediaSession: session.release threw ${e.message}", e)
912
- }
913
- mediaSession = null
914
- mediaSessionCallback = null
651
+ MediaPlaybackService.publishState(playing, state)
915
652
  }
916
653
 
917
654
  // ── Headset / Bluetooth disconnect (Phase 20) ───────────────────────
@@ -1063,7 +800,7 @@ class PlayerActivity : ReactActivity() {
1063
800
  }
1064
801
 
1065
802
  private fun pauseOnAudioFocusLoss(reason: String) {
1066
- val ptr = lastNativePtr
803
+ val ptr = PlaybackHost.handle()
1067
804
  if (ptr != 0L) {
1068
805
  try {
1069
806
  MPVLib.nativePause(ptr)
@@ -1076,7 +813,7 @@ class PlayerActivity : ReactActivity() {
1076
813
  }
1077
814
 
1078
815
  private fun duckVolume() {
1079
- val ptr = lastNativePtr
816
+ val ptr = PlaybackHost.handle()
1080
817
  if (ptr == 0L) return
1081
818
  try {
1082
819
  val currentVolume = MPVLib.nativeGetVolume(ptr).toFloat()
@@ -1092,7 +829,7 @@ class PlayerActivity : ReactActivity() {
1092
829
  }
1093
830
 
1094
831
  private fun restoreVolume() {
1095
- val ptr = lastNativePtr
832
+ val ptr = PlaybackHost.handle()
1096
833
  if (ptr == 0L || preDuckVolume < 0f) return
1097
834
  try {
1098
835
  MPVLib.nativeSetVolume(ptr, preDuckVolume.toDouble())
@@ -1109,7 +846,7 @@ class PlayerActivity : ReactActivity() {
1109
846
  // notification in sync via the existing updateMediaSessionState
1110
847
  // helper).
1111
848
  private fun pauseOnHeadsetDisconnect() {
1112
- val ptr = lastNativePtr
849
+ val ptr = PlaybackHost.handle()
1113
850
  if (ptr != 0L) {
1114
851
  try {
1115
852
  MPVLib.nativePause(ptr)
@@ -1141,14 +878,9 @@ class PlayerActivity : ReactActivity() {
1141
878
  intent.putExtra(MediaPlaybackService.EXTRA_POSITION_MS, launchStartPositionMs)
1142
879
  intent.putExtra(MediaPlaybackService.EXTRA_DURATION_MS, 0L)
1143
880
  intent.putExtra(MediaPlaybackService.EXTRA_IS_PLAYING, true)
1144
- // Phase 16.3: pass the session token so the service's
1145
- // MediaStyle notification can wire to the activity's
1146
- // MediaSessionCompat (Phase 15). The token is a
1147
- // Parcelable so it survives the Intent extra marshalling.
1148
- val session = mediaSession
1149
- if (session != null) {
1150
- intent.putExtra(MediaPlaybackService.EXTRA_SESSION_TOKEN, session.sessionToken)
1151
- }
881
+ // V20 Phase B: no session token is passed any more. The service owns
882
+ // the session and publishes its own token to the MediaStyle
883
+ // notification, so there is nothing for this Activity to hand over.
1152
884
  return intent
1153
885
  }
1154
886
 
@@ -1165,20 +897,15 @@ class PlayerActivity : ReactActivity() {
1165
897
  }
1166
898
  }
1167
899
 
1168
- // Phase 16.7: stop the service. We send a graceful ACTION_STOP
1169
- // intent so the service can run its own stopForeground +
1170
- // stopSelf sequence (the MediaStyle notification cleans up
1171
- // cleanly that way; calling stopService from outside can
1172
- // leave a stale foreground notification on some OEM skins).
1173
- private fun stopMediaPlaybackService() {
1174
- try {
1175
- val intent = buildMediaPlaybackServiceIntent(MediaPlaybackService.ACTION_STOP)
1176
- startService(intent)
1177
- Log.i(TAG, "MediaPlaybackService stop requested")
1178
- } catch (e: Exception) {
1179
- Log.w(TAG, "stopMediaPlaybackService: ${e.message}", e)
1180
- }
1181
- }
900
+ // V20 Phase B deleted `stopMediaPlaybackService` here.
901
+ //
902
+ // It existed so this Activity could wind the service down in
903
+ // `onDestroy`. Now it doesn't: the service owns its own lifetime, and
904
+ // the paths that genuinely mean "stop playing" — the notification's
905
+ // Stop and cancel buttons, and the session's own stop callback — are
906
+ // handled by the service itself. An Activity tearing itself down is
907
+ // no longer a statement about whether playback should continue, which
908
+ // is the whole point of the change.
1182
909
 
1183
910
  // Phase 17.2 / 17.4: ship the current position + duration to
1184
911
  // MediaPlaybackService so its notification's progress bar stays
@@ -1268,15 +995,16 @@ class PlayerActivity : ReactActivity() {
1268
995
  Log.w(TAG, "onResume: setPictureInPictureParams threw ${e.message}", e)
1269
996
  }
1270
997
  }
1271
- // Phase 15.3: refresh the MediaSession state on resume. The
1272
- // session is created once in onCreate, but the playback state
1273
- // (playing / paused) can change while the activity is
1274
- // backgrounded (e.g. the user hit the PiP play/pause button).
1275
- // We don't have a direct read of mpv's playing flag without
1276
- // an observer hook, so we conservatively default to
1277
- // `playing = true` on resume — the next MPVLib event from JS
1278
- // (or the next session callback) will correct it.
1279
- if (mediaSession != null) {
998
+ // Refresh the session state on resume. Playback state can change
999
+ // while this window is in the background (the user may have used the
1000
+ // notification, the lock-screen widget or a Bluetooth control), and
1001
+ // the service cannot see *this* Activity resume, so we re-publish.
1002
+ //
1003
+ // `playing = true` is a deliberate default, not a reading: mpv's
1004
+ // pause flag is not observable from here without an observer hook,
1005
+ // and the next session callback or MPVLib event corrects it. What
1006
+ // matters is that the session is not left advertising a stale state.
1007
+ if (MediaPlaybackService.isRunning()) {
1280
1008
  updateMediaSessionState(playing = true)
1281
1009
  }
1282
1010
  // Phase 17.4: start the 1Hz progress update runnable. This
@@ -1325,7 +1053,7 @@ class PlayerActivity : ReactActivity() {
1325
1053
  // React Native module registry and cast to the module-side
1326
1054
  // `IPipModeChangeEmitter` contract.
1327
1055
  //
1328
- // Resolution mirrors wireNativePtr (Phase 7): resolve
1056
+ // Resolution follows the same resolve-then-lookup shape: resolve
1329
1057
  // ReactApplicationContext via (application as? ReactApplication)
1330
1058
  // ?.reactHost.currentReactContext, then getNativeModule("MpvPlayerModule")
1331
1059
  // cast to IPipModeChangeEmitter. The lookup runs on the main
@@ -1340,11 +1068,11 @@ class PlayerActivity : ReactActivity() {
1340
1068
  // surface from mpv, but it doesn't re-attach when a new surface
1341
1069
  // arrives. We trigger a re-attach here so the player resumes
1342
1070
  // rendering immediately after PiP exit.
1343
- if (!isInPictureInPictureMode && lastNativePtr != 0L) {
1071
+ if (!isInPictureInPictureMode && PlaybackHost.handle() != 0L) {
1344
1072
  mpvRenderView?.let { view ->
1345
1073
  Log.i(TAG, "onPictureInPictureModeChanged (exit): re-attaching surface to mpv")
1346
1074
  try {
1347
- view.setNativePtr(lastNativePtr)
1075
+ view.setNativePtr(PlaybackHost.handle())
1348
1076
  } catch (e: Exception) {
1349
1077
  Log.w(TAG, "onPictureInPictureModeChanged: setNativePtr threw ${e.message}", e)
1350
1078
  }
@@ -1359,7 +1087,7 @@ class PlayerActivity : ReactActivity() {
1359
1087
  /**
1360
1088
  * Phase 10 helper: resolve [IPipModeChangeEmitter] via the React
1361
1089
  * Native bridge and emit the PiP mode-change event. Mirrors the
1362
- * wireNativePtr retry pattern in spirit (resolve context →
1090
+ * engine-availability pattern in spirit (resolve context →
1363
1091
  * lookup → cast) but only runs once per PiP transition — there's no
1364
1092
  * retry because a missed event is a single-frame UI glitch, not a
1365
1093
  * playback failure.
@@ -1468,7 +1196,7 @@ class PlayerActivity : ReactActivity() {
1468
1196
  // Phase 38: abandon audio focus on pause so other apps can resume
1469
1197
  // audio. We re-request on the next onResume.
1470
1198
  abandonAudioFocus()
1471
- if (!pipEntryInFlight && lastNativePtr != 0L) {
1199
+ if (!pipEntryInFlight && PlaybackHost.handle() != 0L) {
1472
1200
  // Quick path: the defer flag isn't set, so we know
1473
1201
  // immediately this is a real pause (user pressed back,
1474
1202
  // locked the screen, opened another activity). Run the
@@ -1480,8 +1208,9 @@ class PlayerActivity : ReactActivity() {
1480
1208
  )
1481
1209
  } else {
1482
1210
  try {
1483
- MPVLib.nativePause(lastNativePtr)
1484
- Log.i(TAG, "onPause: paused mpv synchronously (lastNativePtr=$lastNativePtr)")
1211
+ val ptr = PlaybackHost.handle()
1212
+ MPVLib.nativePause(ptr)
1213
+ Log.i(TAG, "onPause: paused mpv synchronously (ptr=$ptr)")
1485
1214
  } catch (e: Exception) {
1486
1215
  Log.w(TAG, "onPause: nativePause threw ${e.message}", e)
1487
1216
  }
@@ -1508,7 +1237,7 @@ class PlayerActivity : ReactActivity() {
1508
1237
  }
1509
1238
  if (activity.isInPictureInPictureMode) {
1510
1239
  Log.i(TAG, "onPause (deferred 200ms): entered PiP, mpv continues playing")
1511
- } else if (activity.lastNativePtr != 0L) {
1240
+ } else if (PlaybackHost.handle() != 0L) {
1512
1241
  if (activity.shouldKeepPlayingInBackground()) {
1513
1242
  Log.i(
1514
1243
  TAG,
@@ -1516,7 +1245,7 @@ class PlayerActivity : ReactActivity() {
1516
1245
  )
1517
1246
  } else {
1518
1247
  try {
1519
- MPVLib.nativePause(activity.lastNativePtr)
1248
+ MPVLib.nativePause(PlaybackHost.handle())
1520
1249
  Log.i(TAG, "onPause (deferred 200ms): NOT in PiP, paused mpv")
1521
1250
  } catch (e: Exception) {
1522
1251
  Log.w(TAG, "onPause (deferred): nativePause threw ${e.message}", e)
@@ -1639,11 +1368,11 @@ class PlayerActivity : ReactActivity() {
1639
1368
  // `video-params/aspect` property. Falls back to 16:9 (the most
1640
1369
  // common modern aspect) when mpv hasn't loaded any video yet.
1641
1370
  private fun getVideoAspect(): Float {
1642
- if (lastNativePtr == 0L) {
1371
+ if (PlaybackHost.handle() == 0L) {
1643
1372
  return 16f / 9f
1644
1373
  }
1645
1374
  return try {
1646
- val raw = MPVLib.nativeGetProperty(lastNativePtr, "video-params/aspect")
1375
+ val raw = MPVLib.nativeGetProperty(PlaybackHost.handle(), "video-params/aspect")
1647
1376
  val parsed = raw.trim().toFloatOrNull()
1648
1377
  if (parsed != null && parsed.isFinite() && parsed > 0f) {
1649
1378
  parsed.coerceIn(0.42f, 2.38f)
@@ -1666,9 +1395,9 @@ class PlayerActivity : ReactActivity() {
1666
1395
  // pattern [getVideoAspect] uses for the video-params/aspect
1667
1396
  // property.
1668
1397
  private fun getPlaybackPositionMs(): Long {
1669
- if (lastNativePtr == 0L) return 0L
1398
+ if (PlaybackHost.handle() == 0L) return 0L
1670
1399
  return try {
1671
- val raw = MPVLib.nativeGetProperty(lastNativePtr, "time-pos")
1400
+ val raw = MPVLib.nativeGetProperty(PlaybackHost.handle(), "time-pos")
1672
1401
  val parsed = raw.trim().toDoubleOrNull()
1673
1402
  if (parsed != null && parsed.isFinite() && parsed >= 0.0) {
1674
1403
  (parsed * 1000.0).toLong()
@@ -1684,9 +1413,9 @@ class PlayerActivity : ReactActivity() {
1684
1413
  // property. Returns ms, or 0L when not yet known (mpv sets
1685
1414
  // `duration` once the file is parsed).
1686
1415
  private fun getPlaybackDurationMs(): Long {
1687
- if (lastNativePtr == 0L) return 0L
1416
+ if (PlaybackHost.handle() == 0L) return 0L
1688
1417
  return try {
1689
- val raw = MPVLib.nativeGetProperty(lastNativePtr, "duration")
1418
+ val raw = MPVLib.nativeGetProperty(PlaybackHost.handle(), "duration")
1690
1419
  val parsed = raw.trim().toDoubleOrNull()
1691
1420
  if (parsed != null && parsed.isFinite() && parsed > 0.0) {
1692
1421
  (parsed * 1000.0).toLong()
@@ -1708,76 +1437,57 @@ class PlayerActivity : ReactActivity() {
1708
1437
  // for the first artist in the tag list, which on multi-artist
1709
1438
  // files can be a featured artist rather than the main one).
1710
1439
  private fun getMediaTitle(): String {
1711
- if (lastNativePtr == 0L) return ""
1440
+ if (PlaybackHost.handle() == 0L) return ""
1712
1441
  return try {
1713
- MPVLib.nativeGetProperty(lastNativePtr, "media-title").trim()
1442
+ MPVLib.nativeGetProperty(PlaybackHost.handle(), "media-title").trim()
1714
1443
  } catch (_: Exception) {
1715
1444
  ""
1716
1445
  }
1717
1446
  }
1718
1447
 
1719
1448
  private fun getMediaArtist(): String {
1720
- if (lastNativePtr == 0L) return ""
1449
+ if (PlaybackHost.handle() == 0L) return ""
1721
1450
  return try {
1722
- MPVLib.nativeGetProperty(lastNativePtr, "metadata/by-key/artist").trim()
1451
+ MPVLib.nativeGetProperty(PlaybackHost.handle(), "metadata/by-key/artist").trim()
1723
1452
  } catch (_: Exception) {
1724
1453
  ""
1725
1454
  }
1726
1455
  }
1727
1456
 
1728
1457
  private fun getMediaAlbum(): String {
1729
- if (lastNativePtr == 0L) return ""
1458
+ if (PlaybackHost.handle() == 0L) return ""
1730
1459
  return try {
1731
- MPVLib.nativeGetProperty(lastNativePtr, "metadata/by-key/album").trim()
1460
+ MPVLib.nativeGetProperty(PlaybackHost.handle(), "metadata/by-key/album").trim()
1732
1461
  } catch (_: Exception) {
1733
1462
  ""
1734
1463
  }
1735
1464
  }
1736
1465
 
1737
- // Phase 19.2 + 19.4: build a MediaMetadataCompat from the
1738
- // current values and set it on the MediaSession. Called from
1739
- // createMediaSession (initial set with launch title) and from
1740
- // the post-wireNativePtr refresh (so the metadata reflects the
1741
- // actual mpv tags once the file is loaded).
1466
+ // V20 Phase B: the session lives on the service, so this publishes
1467
+ // to it rather than writing a session directly.
1742
1468
  //
1743
- // Title fallback chain: mpv `media-title` → launch title →
1744
- // "Simba Player" (last resort so the lock-screen widget never
1745
- // shows blank). Artist / album stay empty when not tagged —
1746
- // the lock-screen widget collapses to title-only in that case
1747
- // (matches how Spotify / YouTube Music render un-tagged files).
1469
+ // Called once from `PlaybackHost.whenAvailable` (mpv exists by then, so
1470
+ // the real tags are readable) and once more whenever the engine reports
1471
+ // a new file.
1748
1472
  //
1749
- // The metadata is set on the session (not the notification
1750
- // directly) so the system media controls (lock-screen widget,
1751
- // Android Auto, Bluetooth) all pick up the same values. The
1752
- // notification's own title/subtitle are still set in
1753
- // MediaPlaybackService.buildNotification (Phase 16), so the
1754
- // notification UI also reflects the metadata — the values
1755
- // just arrive through two paths.
1473
+ // Title fallback chain: mpv `media-title` → launch title → "Simba
1474
+ // Player", so the lock-screen widget never shows blank. Artist and
1475
+ // album stay empty when the file is untagged, and the system collapses
1476
+ // the widget to title-only — which is how Spotify and YouTube Music
1477
+ // render untagged files.
1756
1478
  private fun setMediaSessionMetadata() {
1757
- val session = mediaSession ?: return
1758
1479
  val title = getMediaTitle().ifBlank { launchTitle.ifBlank { "Simba Player" } }
1759
1480
  val artist = getMediaArtist()
1760
1481
  val album = getMediaAlbum()
1761
- val duration = getPlaybackDurationMs()
1762
- val builder = android.support.v4.media.MediaMetadataCompat.Builder()
1763
- .putString(android.support.v4.media.MediaMetadataCompat.METADATA_KEY_TITLE, title)
1764
- .putString(android.support.v4.media.MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, title)
1765
- .putString(android.support.v4.media.MediaMetadataCompat.METADATA_KEY_ARTIST, artist)
1766
- .putString(android.support.v4.media.MediaMetadataCompat.METADATA_KEY_ALBUM, album)
1767
- .putString(android.support.v4.media.MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, buildDisplaySubtitle(artist, album))
1768
- .putString(android.support.v4.media.MediaMetadataCompat.METADATA_KEY_MEDIA_URI, launchUri)
1769
- if (duration > 0L) {
1770
- builder.putLong(android.support.v4.media.MediaMetadataCompat.METADATA_KEY_DURATION, duration)
1771
- }
1772
- try {
1773
- session.setMetadata(builder.build())
1774
- Log.i(
1775
- TAG,
1776
- "MediaSession metadata set: title='$title' artist='$artist' album='$album' duration=$duration",
1777
- )
1778
- } catch (e: Exception) {
1779
- Log.w(TAG, "setMediaSessionMetadata: session.setMetadata threw ${e.message}", e)
1780
- }
1482
+ Log.i(TAG, "MediaSession metadata: title='$title' artist='$artist' album='$album'")
1483
+ MediaPlaybackService.publishMetadata(
1484
+ title = title,
1485
+ artist = artist,
1486
+ album = album,
1487
+ artworkPath = "",
1488
+ mediaUri = launchUri,
1489
+ displaySubtitle = buildDisplaySubtitle(artist, album),
1490
+ )
1781
1491
  }
1782
1492
 
1783
1493
  // Phase 19.2 helper: build the `"Artist • Album"` display
@@ -1793,6 +1503,11 @@ class PlayerActivity : ReactActivity() {
1793
1503
  }
1794
1504
 
1795
1505
  override fun onDestroy() {
1506
+ // V20 Phase A: stop listening for engine availability FIRST. The
1507
+ // listener closes over `this`, so leaving it registered would keep
1508
+ // this destroyed Activity reachable from a process-scoped object and
1509
+ // re-run `setMediaSessionMetadata()` against a dead view hierarchy.
1510
+ PlaybackHost.cancelWhenAvailable(onEngineAvailable)
1796
1511
  // Step 6.6.1: cleanup the SurfaceView (detach Surface from mpv
1797
1512
  // and zero the native pointer so any late native callback becomes
1798
1513
  // a no-op).
@@ -1827,22 +1542,18 @@ class PlayerActivity : ReactActivity() {
1827
1542
  // Phase 38: abandon audio focus as part of the teardown sequence
1828
1543
  // (matches onPause; idempotent if already abandoned).
1829
1544
  abandonAudioFocus()
1830
- // Phase 16.7: stop the MediaPlaybackService. We send a
1831
- // ACTION_STOP intent so the service runs its own teardown
1832
- // (removes the foreground state, then calls stopSelf) instead
1833
- // of relying on stopService to yank it. The teardown order
1834
- // matters: we stop the service BEFORE releasing the
1835
- // MediaSession because the service holds a token reference;
1836
- // if the token becomes invalid before the service drops it,
1837
- // the notification's MediaStyle.setMediaSession(token) call
1838
- // in the next build will log a warning.
1839
- stopMediaPlaybackService()
1840
- // Phase 15.3: release the MediaSession before the activity is
1841
- // torn down. Order doesn't matter much for MediaSession
1842
- // (release is idempotent), but we do it before the receiver
1843
- // unregister so the lock-screen widget disappears as part of
1844
- // the same shutdown.
1845
- releaseMediaSession()
1545
+ // V20 Phase B: this Activity no longer stops the service or
1546
+ // releases the session on its way out.
1547
+ //
1548
+ // It used to. That is precisely why the notification and the
1549
+ // lock-screen widget vanished the moment the player window closed,
1550
+ // and why "hide the player" and "shut the player down" were the same
1551
+ // verb. Both now belong to the service's own lifecycle: the service
1552
+ // stops itself, and releases its session in its own `onDestroy`.
1553
+ //
1554
+ // What *is* still correct to stop here is everything scoped to this
1555
+ // window — the broadcast receiver, the audio focus request, the
1556
+ // render view — because those die with the window by design.
1846
1557
  // Phase 10: unregister the PiP action broadcast receiver. Must
1847
1558
  // happen BEFORE the super call so the receiver is gone before
1848
1559
  // the activity is fully torn down (otherwise Android logs a
@@ -1863,4 +1574,4 @@ class PlayerActivity : ReactActivity() {
1863
1574
  super.onDestroy()
1864
1575
  Log.i(TAG, "onDestroy: tearing down PlayerActivity")
1865
1576
  }
1866
- }
1577
+ }