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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/README.md +26 -24
  2. package/android/src/main/java/com/simba/player/MediaPlaybackService.kt +20 -17
  3. package/android/src/main/java/com/simba/player/PlayerPackage.kt +21 -6
  4. package/android/src/main/java/com/simba/player/mpv/MpvBridgeModule.kt +18 -307
  5. package/android/src/main/java/com/simba/player/mpv/MpvRenderView.kt +100 -0
  6. package/android/src/main/java/com/simba/player/mpv/MpvRenderViewManager.kt +116 -31
  7. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleTest.kt +0 -20
  8. package/package.json +2 -2
  9. package/src/bridge/MpvPlayerModule.ts +36 -83
  10. package/src/bridge/NativeMpvPlayer.ts +15 -52
  11. package/src/bridge/loadAndPlay.ts +65 -0
  12. package/src/components/PlayerRoot.tsx +9 -13
  13. package/src/components/SimbaVideo.tsx +121 -0
  14. package/src/components/__tests__/SimbaVideo.test.tsx +164 -0
  15. package/src/hooks/__tests__/useLaunchPlayback.test.tsx +44 -64
  16. package/src/hooks/useLaunchPlayback.ts +7 -11
  17. package/src/hooks/usePlayerActivity.ts +51 -60
  18. package/src/index.ts +11 -11
  19. package/src/specs/SimbaVideoViewNativeComponent.ts +84 -0
  20. package/src/types/__tests__/player.test.tsx +49 -17
  21. package/src/types/player.ts +28 -31
  22. package/android/src/main/java/com/simba/player/IMpvConfigProvider.kt +0 -36
  23. package/android/src/main/java/com/simba/player/IPipModeChangeEmitter.kt +0 -31
  24. package/android/src/main/java/com/simba/player/PlayerActivity.kt +0 -1626
  25. package/src/hooks/SimbaPlayerRoot.tsx +0 -128
  26. package/src/hooks/useIsPlayerActivity.ts +0 -61
  27. package/src/hooks/useLaunchParams.tsx +0 -126
@@ -1,1626 +0,0 @@
1
- package com.simba.player
2
-
3
- import android.app.PictureInPictureParams
4
- import android.content.Context
5
- import android.content.pm.PackageManager
6
- import android.content.res.Configuration
7
- import android.graphics.Color
8
- import android.graphics.Rect
9
- import android.graphics.drawable.ColorDrawable
10
- import android.os.Build
11
- import android.os.Bundle
12
- import android.os.Handler
13
- import android.os.Looper
14
- import android.util.Log
15
- import android.view.View
16
- import android.view.ViewGroup
17
- import android.widget.FrameLayout
18
- import com.facebook.react.ReactActivity
19
- import com.facebook.react.ReactActivityDelegate
20
- import com.facebook.react.ReactApplication
21
- import com.facebook.react.ReactRootView
22
- import com.facebook.react.bridge.NativeModule
23
- import com.facebook.react.bridge.ReactApplicationContext
24
- import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
25
- import com.facebook.react.defaults.DefaultReactActivityDelegate
26
- import com.simba.player.mpv.MPVLib
27
- import com.simba.player.mpv.MpvRenderView
28
- import com.simba.player.mpv.PlayerSurface
29
-
30
- /**
31
- * Dedicated ReactActivity that hosts the SIMBA video/audio player.
32
- *
33
- * Replaces the V11 pattern of mounting the player inside [MainActivity]'s
34
- * React tree, which caused a Picture-in-Picture black-screen bug because
35
- * the SurfaceView was nested inside RN's view tree and an opaque shell
36
- * background covered the surface during PiP re-layout (see mpvKt /
37
- * heritage mpv-android for the proven pattern: SurfaceView at the
38
- * activity root with default z-order).
39
- *
40
- * Mirrors [com.simba.player.MainActivity] so React Native infra is
41
- * inherited identically (same main component, same React host, same
42
- * fabric setting). The activity is free-orientation by design — the JS
43
- * layer (MpvBridgeModule.setOrientation) is the only authority on
44
- * orientation during playback (V11 T8.2).
45
- *
46
- * Phase 6: MpvRenderView (SurfaceView) is added at index 0 of the
47
- * activity content root, BENEATH the ReactRootView that super.onCreate
48
- * installs at index 1. This is the proven PiP-friendly layout (mpvKt /
49
- * BaseMPVView): the SurfaceView is on a SurfaceFlinger layer that PiP
50
- * captures correctly even when paused, and the React UI floats on top
51
- * via transparent background (handled separately in Phase 8).
52
- */
53
- class PlayerActivity : ReactActivity() {
54
-
55
- companion object {
56
- private const val TAG = "PlayerActivity"
57
-
58
- /**
59
- * Component name used for the React root inside this activity.
60
- * Reuses the app's existing `SimbaPlayer` root so we don't have to
61
- * maintain a second JS entry point in Phase 1. A dedicated
62
- * `SimbaPlayerScreen` entry point is a Q1 decision tracked in the
63
- * V12 tracker.
64
- */
65
- const val MAIN_COMPONENT_NAME = "SimbaPlayer"
66
-
67
- /**
68
- * 1.8.0 — launch-option (initial prop) key that tells the consumer's
69
- * root component it is running in the player activity. Set to `true`
70
- * here and `false` in the consumer's `MainActivity`; both values are
71
- * read on the JS side, per React root.
72
- */
73
- const val EXTRA_IS_PLAYER_ACTIVITY = "isPlayerActivity"
74
-
75
- // ── Intent extras (Phase 3) ─────────────────────────────────────
76
- // Set by MpvBridgeModule.openPlayer(uri, title, type, startPositionMs)
77
- // when launching this activity. Phase 4 will read these back and log
78
- // them; Phase 11+ will use them to drive playback.
79
- const val EXTRA_URI = "com.simba.player.EXTRA_URI"
80
- const val EXTRA_TITLE = "com.simba.player.EXTRA_TITLE"
81
- const val EXTRA_TYPE = "com.simba.player.EXTRA_TYPE"
82
- const val EXTRA_START_POSITION_MS = "com.simba.player.EXTRA_START_POSITION_MS"
83
-
84
- /** Allowed values for [EXTRA_TYPE]. */
85
- const val TYPE_VIDEO = "video"
86
- const val TYPE_AUDIO = "audio"
87
-
88
- // ── Phase 14.2: audio-background-playback setting ─────────────────
89
- // SharedPreferences file + key. The default (`true`) means
90
- // audio files keep playing when the user backgrounds the
91
- // activity; flipping to `false` makes audio behave like video
92
- // (pause on background). A future Wave 5 settings screen can
93
- // expose a toggle that writes this key.
94
- private const val PREFS_NAME = "simba_player_prefs"
95
- private const val KEY_AUDIO_BG_PLAYBACK = "audio_background_playback"
96
-
97
- // ── Phase 17: progress update interval ─────────────────────────────
98
- // 1Hz is the right cadence for a media notification's progress
99
- // bar — sub-second updates would burn battery for no
100
- // perceptible benefit, sub-2-second updates would feel
101
- // jumpy on long-form content (audiobooks / podcasts).
102
- const val PROGRESS_UPDATE_INTERVAL_MS = 1000L
103
-
104
- // ── Phase 22: default theme color values ────────────────────────────
105
- // Mirror of `DEFAULT_THEME` in `src/types/config.ts`. Used as the
106
- // log fallback when the PlayerConfig's theme section is missing
107
- // or a specific color key is absent. Must stay in sync with the
108
- // TS side — a divergence would mean the native side logs a
109
- // different color than DefaultControls renders.
110
- private const val DEFAULT_THEME_ACCENT = "#FFD700"
111
- private const val DEFAULT_THEME_BACKGROUND = "#121216"
112
- private const val DEFAULT_THEME_TEXT = "#FFFFFF"
113
- }
114
-
115
- // ── Launch parameters (Phase 4) ───────────────────────────────────
116
- // Pulled from the intent extras set by MpvBridgeModule.openPlayer(...).
117
- // Stored as private vals (immutable for the activity lifetime) via
118
- // `by lazy {}` so they're computed on first read after the framework
119
- // has populated `intent` — `intent` is null before Activity.attach(),
120
- // so eager initialisation would NPE.
121
-
122
- private val launchUri: String by lazy {
123
- intent?.getStringExtra(EXTRA_URI) ?: ""
124
- }
125
-
126
- private val launchTitle: String by lazy {
127
- intent?.getStringExtra(EXTRA_TITLE)?.takeIf { it.isNotBlank() } ?: launchUri
128
- }
129
-
130
- private val launchType: String by lazy {
131
- intent?.getStringExtra(EXTRA_TYPE)?.takeIf { it == TYPE_VIDEO || it == TYPE_AUDIO } ?: TYPE_VIDEO
132
- }
133
-
134
- private val launchStartPositionMs: Long by lazy {
135
- intent?.getLongExtra(EXTRA_START_POSITION_MS, 0L) ?: 0L
136
- }
137
-
138
- // ── Player surface (Phase 6) ──────────────────────────────────────
139
- // MpvRenderView (SurfaceView) mounted at index 0 of the activity
140
- // content root, beneath the ReactRootView. Phase 7 will wire the
141
- // mpv native pointer into this view. Reference is nulled in
142
- // onDestroy after cleanup + removal.
143
-
144
- private var mpvRenderView: MpvRenderView? = null
145
-
146
- // ── Engine handle (V20 Phase A) ─────────────────────────────────────
147
- // V20 removed `PlaybackHost.handle()`, the cached copy of the libmpv handle.
148
- // The copy could never be invalidated: MpvBridgeModule.destroy() zeroed
149
- // only its own field, so after a destroy/re-create the Activity held a
150
- // pointer that no longer matched the process global `g_mpv` and every
151
- // call below was refused by the native lease guard. The symptom was a
152
- // control surface that was present, wired and permanently inert.
153
- //
154
- // The handle now lives in exactly one place — `PlaybackHost` — and is
155
- // read at the point of use via `PlaybackHost.handle()`. This listener
156
- // exists only so the render view is wired when mpv becomes available;
157
- // it replaces a 300ms × 200-attempt polling loop.
158
- private val onEngineAvailable: (Long) -> Unit = engineAvailable@{ ptr ->
159
- val view = mpvRenderView ?: return@engineAvailable
160
- Log.i(TAG, "engine available ptr=$ptr, calling MpvRenderView.setNativePtr")
161
- view.setNativePtr(ptr)
162
- // The session's first metadata read happens now that mpv is wired,
163
- // so the lock-screen widget shows the file's real tags rather than
164
- // just the launch title.
165
- setMediaSessionMetadata()
166
- }
167
-
168
- // ── PiP action receiver (Phase 10) ────────────────────────────────
169
- // `PipActionReceiver` listens for the 3 PiP overlay intents
170
- // (play/pause, expand, close) and forwards them to JS via
171
- // `DeviceEventManagerModule.emit`. Registered in `onCreate` and
172
- // unregistered in `onDestroy`. PlayerActivity owns its own instance
173
- // — MainActivity has its own for the inline-mount V11 path; the
174
- // broadcast is delivered to all matching dynamic receivers, so the
175
- // two activities co-exist without conflict when both are in memory
176
- // (only one is foreground at a time).
177
- private var pipReceiver: PipActionReceiver? = null
178
-
179
- // ── PiP mode-change defer flag (Phase 10) ─────────────────────────
180
- // Set to `true` in `onUserLeaveHint` when we initiate PiP entry.
181
- // Read in `onPause`'s deferred check so we don't pause mpv while the
182
- // PiP transition is still in flight (which would kill playback
183
- // during the PiP entry animation, causing a black PiP window for
184
- // ~200ms — same root cause as the V11 bug).
185
- private var pipEntryInFlight: Boolean = false
186
-
187
- // ── Phase 38: audio focus (spec §38.4) ──────────────────────────────
188
- // Listener that pauses mpv when the system grants audio focus to
189
- // another app (e.g., an incoming phone call, navigation prompt,
190
- // voice assistant). AudioFocusRequest is API 26+; older devices use
191
- // the deprecated requestAudioFocus(listener, streamType, durationHint)
192
- // overload. We register on resume (when playback starts) and
193
- // abandon on pause (when the activity backgrounds). On focus loss
194
- // with AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK we lower mpv's volume
195
- // instead of pausing (the "duck" convention from Spotify et al.);
196
- // on AUDIOFOCUS_LOSS or AUDIOFOCUS_LOSS_TRANSIENT we pause.
197
- private var audioFocusListener: android.media.AudioManager.OnAudioFocusChangeListener? = null
198
- private var audioFocusRequest: android.media.AudioFocusRequest? = null
199
- private var hasAudioFocus: Boolean = false
200
- // Pre-duck volume (so we can restore after AUDIOFOCUS_GAIN)
201
- private var preDuckVolume: Float = -1f
202
-
203
- // Forward audio focus changes to JS via the DeviceEventManagerModule
204
- // so the JS layer can update UI (e.g., show "Paused — phone call"
205
- // overlay). Mirrors the `onPipModeChanged` pattern from Phase 10.
206
- private fun emitAudioFocusChange(focusChange: Int) {
207
- Handler(Looper.getMainLooper()).post {
208
- val reactContext = resolveReactApplicationContext() ?: run {
209
- Log.w(TAG, "emitAudioFocusChange: ReactApplicationContext null, dropping event")
210
- return@post
211
- }
212
- val module: NativeModule? = try {
213
- reactContext.getNativeModule("MpvPlayerModule")
214
- } catch (e: Exception) {
215
- Log.w(TAG, "emitAudioFocusChange: getNativeModule threw ${e.message}", e)
216
- null
217
- }
218
- if (module !is com.simba.player.IMpvConfigProvider) {
219
- // IMpvConfigProvider is a stand-in interface — we'll define a
220
- // dedicated IAudioFocusEmitter if Phase 38.4 expansion requires it.
221
- // For now, log + skip the JS emit (audio focus handling still
222
- // works locally — only the JS-side UI notification is missing).
223
- Log.d(TAG, "emitAudioFocusChange: no IMpvConfigProvider, skipping JS emit (focusChange=$focusChange)")
224
- return@post
225
- }
226
- // We don't actually need the config — just access the module-side
227
- // emit path. Future phases can add a dedicated IAudioFocusEmitter.
228
- Log.d(TAG, "emitAudioFocusChange: focusChange=$focusChange (local handling only)")
229
- }
230
- }
231
-
232
- // ── Phase 40: ComponentCallbacks2 listener (Phase 38.7 + 39.0) ──────────
233
- // Forwards OS memory-pressure events to MpvBridgeModule.onTrimMemory()
234
- // which reduces mpv's cache-secs accordingly. Registered in onCreate
235
- // (activity-scoped) so the listener is automatically scoped to the
236
- // activity lifecycle.
237
- //
238
- // We hold a strong reference to the listener as a field so the
239
- // garbage collector can't reclaim it while it's registered. The
240
- // matching unregisterComponentCallbacks happens in onDestroy.
241
- private val trimMemoryListener = object : android.content.ComponentCallbacks2 {
242
- override fun onTrimMemory(level: Int) {
243
- Log.i(TAG, "trimMemoryListener.onTrimMemory: level=$level")
244
- forwardTrimMemoryToBridge(level)
245
- }
246
-
247
- override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
248
- // No-op — we don't care about config changes for memory management.
249
- }
250
-
251
- override fun onLowMemory() {
252
- // Deprecated in API 34 but still called. Equivalent to
253
- // onTrimMemory(TRIM_MEMORY_COMPLETE).
254
- Log.w(TAG, "trimMemoryListener.onLowMemory (deprecated path)")
255
- forwardTrimMemoryToBridge(android.content.ComponentCallbacks2.TRIM_MEMORY_COMPLETE)
256
- }
257
-
258
- private fun forwardTrimMemoryToBridge(level: Int) {
259
- try {
260
- val reactContext = resolveReactApplicationContext() ?: return
261
- val module = reactContext.getNativeModule("MpvPlayerModule") ?: return
262
- // The module instance exposes `onTrimMemory(Int)` as a public
263
- // method (Phase 39) so we can call it directly via reflection.
264
- val method = module.javaClass.getMethod("onTrimMemory", Int::class.javaPrimitiveType)
265
- method.invoke(module, level)
266
- } catch (e: NoSuchMethodException) {
267
- Log.w(TAG, "trimMemoryListener: MpvBridgeModule.onTrimMemory(Int) not found", e)
268
- } catch (e: Exception) {
269
- Log.w(TAG, "trimMemoryListener: forward failed", e)
270
- }
271
- }
272
- }
273
-
274
- // ── Headset unplug receiver (Phase 20) ─────────────────────────────
275
- // BroadcastReceiver for `AudioManager.ACTION_AUDIO_BECOMING_NOISY`,
276
- // which the system fires when a wired headset / Bluetooth
277
- // headphones are unplugged (or the A2DP source disconnects).
278
- // On that event we pause mpv + update the MediaSession so the
279
- // user doesn't get audio blasting out of the phone speaker.
280
- // Registered in onResume, unregistered in onPause — the
281
- // receiver is only needed while the activity is foregrounded
282
- // (the foreground service + media session already cover the
283
- // background case, and the system will refire the broadcast
284
- // if the activity comes back to the foreground later).
285
- private var headsetReceiver: android.content.BroadcastReceiver? = null
286
-
287
- // ── Audio background playback (Phase 14) ───────────────────────────
288
- // When `true` (the default), audio files keep playing after the
289
- // user backgrounds the activity (recents / home / app switcher).
290
- // The setting is stored in a dedicated SharedPreferences file so it
291
- // can be flipped from a future settings screen without touching
292
- // the React Native bundle. Phase 14.2 sets the default + storage;
293
- // a Phase 22 / Wave 5 task can add a UI for it.
294
- private val audioBackgroundPlayback: Boolean
295
- get() {
296
- val prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
297
- return prefs.getBoolean(KEY_AUDIO_BG_PLAYBACK, true)
298
- }
299
-
300
- // ── MediaSession (V20 Phase B) ───────────────────────────────────────
301
- // This Activity no longer holds a MediaSessionCompat.
302
- //
303
- // It used to: the session was created in onCreate and released in
304
- // onDestroy, which meant the lock-screen widget, the notification and
305
- // the Bluetooth/Auto transport controls all died the moment this window
306
- // closed — "hide the player" and "shut the player down" were the same
307
- // verb, and a mini player could not exist.
308
- //
309
- // The session now belongs to `MediaPlaybackService`, per Media3's
310
- // guidance to contain Player and MediaSession inside a separate
311
- // Service. This Activity pushes state and metadata to it through
312
- // `MediaPlaybackService.publishState` / `publishMetadata`, and the
313
- // service's own callback issues the transport commands.
314
-
315
- // ── Progress update timer (Phase 17) ─────────────────────────────────
316
- // 1Hz periodic runnable that queries mpv's `time-pos` property
317
- // and ships the position to MediaPlaybackService via an
318
- // ACTION_UPDATE intent. Started in onResume, stopped in
319
- // onPause, cleared in onDestroy. The interval is 1000ms — fast
320
- // enough to keep the notification's progress bar looking
321
- // smooth, slow enough that mpv's `nativeGetProperty` is not
322
- // overwhelmed.
323
- private val progressUpdateHandler = Handler(Looper.getMainLooper())
324
- private val progressUpdateRunnable: Runnable = object : Runnable {
325
- override fun run() {
326
- updateMediaPlaybackServicePosition()
327
- progressUpdateHandler.postDelayed(this, PROGRESS_UPDATE_INTERVAL_MS)
328
- }
329
- }
330
- private var progressUpdatesRunning: Boolean = false
331
-
332
- // ── ReactActivity contract ────────────────────────────────────────
333
-
334
- override fun getMainComponentName(): String = MAIN_COMPONENT_NAME
335
-
336
- /**
337
- * 1.8.0 — hand this activity's React root a PER-TREE "this is the
338
- * player activity" fact, via the launch options (initial props).
339
- *
340
- * `MpvBridgeModule.currentActivityIsPlayer` is a process-wide
341
- * `@Volatile @JvmStatic` flag: while `PlayerActivity` is alive, EVERY
342
- * React root in the process reads `true` through
343
- * `isCurrentActivityPlayer()`, including the one hosted by the
344
- * consumer's `MainActivity`. That is the right answer for
345
- * `useLaunchParams()`'s "don't claim the payload outside the player
346
- * host" guard, but a consumer gating its OWN chrome on it would
347
- * mount that chrome in the background activity too — a full-bleed
348
- * overlay riding over every browsing screen.
349
- *
350
- * Launch options are per-ROOT, so this is the only channel that can
351
- * answer "is *this* tree the player tree" honestly. The consumer reads
352
- * the prop on its root component (`initialProps.isPlayerActivity`)
353
- * and publishes it through a React context. Documented on
354
- * `useIsPlayerActivity` in `src/hooks/`.
355
- */
356
- override fun createReactActivityDelegate(): ReactActivityDelegate =
357
- object : DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) {
358
- override fun getLaunchOptions(): Bundle = Bundle().apply {
359
- putBoolean(EXTRA_IS_PLAYER_ACTIVITY, true)
360
- }
361
- }
362
-
363
- // ── Lifecycle ─────────────────────────────────────────────────────
364
-
365
- override fun onCreate(savedInstanceState: Bundle?) {
366
- // Black window background BEFORE super so the brief window between
367
- // activity start and React's first paint is opaque black instead of
368
- // the default white. Eliminates the white flicker when launching
369
- // into a video.
370
- // V22.0.0 / 1.5.10 (D-034): mark this activity as "player host"
371
- // BEFORE RN mounts so `useLaunchParams()` (called from the
372
- // module's React tree on first commit) sees a true answer and
373
- // claims the most-recent `lastLaunchParams`. Without this, any
374
- // prior session's launchParams would already have been consumed
375
- // by MainActivity's React tree (which goes through the same
376
- // SimbaPlayerRoot) and SimbaPlayerRoot would render the
377
- // PlayerRoot-only fallback in MainActivity - the V22 user
378
- // regression on cold start.
379
- com.simba.player.mpv.MpvBridgeModule.currentActivityIsPlayer = true
380
- window.setBackgroundDrawable(ColorDrawable(Color.BLACK))
381
- super.onCreate(savedInstanceState)
382
- // D-042: Phase 8 "transparent React UI" wiring. The activity content
383
- // root is a FrameLayout (android.R.id.content) installed by
384
- // AppCompat, with `android:windowBackground` set by the inherited
385
- // AppCompat DayNight theme — by default an opaque color that hides
386
- // the SurfaceView at index 0. Even with the ReactRootView at
387
- // index 1, both the root frame AND the ReactRootView draw their
388
- // own backgrounds BEFORE the JSX tree paints, so mpv's decoded
389
- // frames never reach the screen unless we flip both to transparent
390
- // here. The window background we just set above (`Color.BLACK`) is
391
- // a brief pre-super fallback; the JSX tree paints a fully
392
- // styled dark UI on top once the bundle loads.
393
- val rootFrame = findViewById<ViewGroup>(android.R.id.content)
394
- rootFrame?.setBackgroundColor(Color.TRANSPARENT)
395
- // Find ReactRootView in the rootFrame and clear its background
396
- // too — RN installs its own default color (white in light mode,
397
- // gray in dark mode). Search recursively because the rootFrame
398
- // wraps a ReactSurfaceView / ReactRootView inside another FrameLayout
399
- // on bridgeless mode.
400
- rootFrame?.let { root ->
401
- for (i in 0 until root.childCount) {
402
- val child = root.getChildAt(i)
403
- if (child is ReactRootView || child.javaClass.name.contains("ReactSurfaceView")) {
404
- (child as? View)?.setBackgroundColor(Color.TRANSPARENT)
405
- } else if (child is ViewGroup) {
406
- for (j in 0 until child.childCount) {
407
- val grand = child.getChildAt(j)
408
- if (grand is ReactRootView || grand.javaClass.name.contains("ReactSurfaceView")) {
409
- (grand as? View)?.setBackgroundColor(Color.TRANSPARENT)
410
- }
411
- }
412
- }
413
- }
414
- }
415
- Log.i(
416
- TAG,
417
- "onCreate: component=${mainComponentName} savedInstanceState=$savedInstanceState",
418
- )
419
- // Touch the lazy launch params so we have one consistent log entry
420
- // showing all four extras (and any nulls) immediately after super.
421
- // Subsequent reads of these properties are zero-cost cached.
422
- Log.i(TAG, "launchUri=$launchUri")
423
- Log.i(TAG, "launchTitle=$launchTitle")
424
- Log.i(TAG, "launchType=$launchType")
425
- Log.i(TAG, "launchStartPositionMs=$launchStartPositionMs")
426
- Log.i(TAG, "PlayerActivity ready (uri='$launchUri', type='$launchType', startMs=$launchStartPositionMs)")
427
- // D-039: push the Intent extras into the bridge's launchParams holder so
428
- // JS `useLaunchParams()` / `bridge.getLaunchParams()` see the same params
429
- // regardless of whether this activity was launched via `bridge.openPlayer`
430
- // (which sets the holder in Kotlin before `startActivity`) or via Intent
431
- // (deep link / app shortcut / `am start` / ADB, which never touches the
432
- // bridge). Without this push, the launched React tree renders the empty
433
- // `<PlayerRoot />` fallback and the video stays black even though mpv is
434
- // initialised and the SurfaceView is mounted.
435
- com.simba.player.mpv.MpvBridgeModule.setLaunchParamsFromIntent(
436
- uri = launchUri,
437
- title = launchTitle,
438
- type = launchType,
439
- startPositionMs = launchStartPositionMs,
440
- )
441
- // Phase 40: register a ComponentCallbacks2 listener so the system
442
- // notifies us of memory-pressure events (Phase 38.7 + 39.0). When
443
- // the OS trims memory, we forward the level to MpvBridgeModule
444
- // which reduces mpv's cache-secs accordingly. Registered here
445
- // (activity-scoped) rather than application-scoped so we don't
446
- // leak the listener across activity restarts.
447
- applicationContext.registerComponentCallbacks(trimMemoryListener)
448
- // Phase 11.3: explicit audio-mode entry log so the V12 launch path
449
- // for audio files is grep-able in logcat. Phase 12 will hide the
450
- // MpvRenderView; Phase 13 will surface an audio-only UI; until then
451
- // this log is the primary signal that `type=audio` reached the
452
- // activity (the MpvRenderView still mounts in Phase 11 so we can
453
- // validate the intent contract first).
454
- if (launchType == TYPE_AUDIO) {
455
- Log.i(TAG, "Audio mode entered: MpvRenderView will be hidden in Phase 12; mpv engine will run without video output")
456
- }
457
-
458
- // ── Mount the render surface (V21) ─────────────────────────────────
459
- // This block used to create the MpvRenderView inline, size it
460
- // MATCH_PARENT, add it at index 0, and hide it only for audio. That
461
- // duplicated the one piece of knowledge the bridge also needs — "is
462
- // there a surface, and where is it" — inside an Activity, while
463
- // `PlayerSurface` (the registry the bridge reads) was never populated by
464
- // anyone. `isSurfaceMounted()` therefore answered `false` and all four
465
- // surface mutators refused, on a fully working video path.
466
- //
467
- // Mounting is now the library's job, through `PlayerSurface.mount`,
468
- // which is the single implementation of "create it, put it under the
469
- // React root, register it". The Activity supplies an Activity and
470
- // nothing else; `MainActivity` will do exactly the same after the
471
- // collapse.
472
- //
473
- // mount() deliberately leaves the view GONE at 0x0, so showing video is
474
- // always two explicit acts — give it size, then show it — and no host can
475
- // end up with an accidental full-bleed surface over its own UI.
476
- val renderView = PlayerSurface.mount(this)
477
- if (renderView == null) {
478
- // mount() has already logged the concrete reason. Carrying on with a
479
- // null view is safe (onEngineAvailable returns early, onDestroy is
480
- // null-safe) and it means audio still plays if only video cannot.
481
- Log.e(TAG, "no render surface mounted; this window cannot present video")
482
- } else {
483
- mpvRenderView = renderView
484
- if (launchType != TYPE_AUDIO) {
485
- PlayerSurface.fillBounds()
486
- PlayerSurface.setVisible(true)
487
- Log.i(TAG, "render surface sized to fill and shown for video")
488
- } else {
489
- Log.i(TAG, "render surface left hidden for audio mode")
490
- }
491
- }
492
-
493
- // ── Wire the libmpv handle into MpvRenderView (V20 Phase A) ─────────
494
- // V20 replaced a polling loop with a listener.
495
- //
496
- // Before: the Activity asked the RN bridge for the handle via
497
- // `getNativeModule("MpvPlayerModule")`, cast to
498
- // `IMpvNativePtrProvider`, and retried every 300ms up to 200 times
499
- // (~60s) because a cold React start can take 30+s. That existed to
500
- // work around a Gradle module boundary that Phase 6 already removed,
501
- // and it cached the result in `PlaybackHost.handle()`, which could never be
502
- // invalidated.
503
- //
504
- // Now: `PlaybackHost` owns the handle and notifies when it appears.
505
- // `whenAvailable` invokes the listener immediately if the handle is
506
- // already present, so a late-mounting Activity converges with no
507
- // polling, no interface cast and no cached copy.
508
- PlaybackHost.whenAvailable(onEngineAvailable)
509
-
510
- // ── Phase 10: Register PiP action receiver ────────────────────────
511
- // Listens for the 3 PiP overlay intents and forwards them to JS via
512
- // DeviceEventManagerModule.emit (see PipActionReceiver.onReceive).
513
- // API 33+ requires the RECEIVER_EXPORTED / RECEIVER_NOT_EXPORTED
514
- // flag at registration. The PendingIntents in PipManager.buildRemoteAction
515
- // target this class by name, so the broadcasts come from the system
516
- // process — that means RECEIVER_NOT_EXPORTED is the correct choice
517
- // (only the platform / our own process need to deliver to us).
518
- val receiver = PipActionReceiver()
519
- pipReceiver = receiver
520
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
521
- registerReceiver(receiver, PipManager.intentFilter(), Context.RECEIVER_NOT_EXPORTED)
522
- } else {
523
- registerReceiver(receiver, PipManager.intentFilter())
524
- }
525
- Log.i(TAG, "onCreate: PipActionReceiver registered")
526
- // V20 Phase B: the MediaSession is no longer created here.
527
- // Starting the service is what brings the session up — the service
528
- // creates it in its own onCreate and releases it in its own
529
- // onDestroy, so it outlives this window.
530
- // Phase 16.6: start the MediaPlaybackService as a foreground
531
- // service so the persistent media-style notification appears
532
- // in the system shade. Android 8+ requires
533
- // startForegroundService (rather than startService) when the
534
- // destination service will call startForeground; the service
535
- // must call startForeground within 5 seconds of
536
- // onStartCommand or the system will throw a
537
- // ForegroundServiceDidNotStartInTimeException.
538
- startMediaPlaybackService()
539
- // Phase 21.5: read the PlayerConfig pushed by
540
- // `<PlayerProvider config={...}>` via the module-side
541
- // `IMpvConfigProvider` interface and log the active keys.
542
- // Future phases (22-25) extend the lookup to read individual
543
- // fields (theme colors, pip toggles, audio background) and
544
- // apply them. Idempotent — a missing Provider just logs.
545
- loadAndLogPlayerConfig()
546
- }
547
-
548
- /**
549
- * Phase 21 helper: resolve the module-side [IMpvConfigProvider] via
550
- * the React Native bridge and log the active PlayerConfig keys.
551
- *
552
- * Mirrors the engine-availability pattern in spirit (resolve
553
- * context → lookup → cast) but runs once — a missed config read
554
- * is just a missing log line, not a playback failure. The
555
- * lookup runs synchronously because the Provider push happens
556
- * during the React root mount (very early in the activity's
557
- * lifetime, typically before `onCreate` finishes).
558
- *
559
- * Phase 22+ will read individual fields here (theme colors, pip
560
- * toggles, audio background, etc.) and apply them; for now we
561
- * just log keys to confirm the wire is live.
562
- */
563
- private fun loadAndLogPlayerConfig() {
564
- val reactContext: ReactApplicationContext? = resolveReactApplicationContext()
565
- if (reactContext == null) {
566
- Log.w(TAG, "loadAndLogPlayerConfig: ReactApplicationContext null, skipping")
567
- return
568
- }
569
- val module: NativeModule? = try {
570
- reactContext.getNativeModule("MpvPlayerModule")
571
- } catch (e: Exception) {
572
- Log.w(TAG, "loadAndLogPlayerConfig: getNativeModule threw ${e.message}", e)
573
- null
574
- }
575
- if (module !is IMpvConfigProvider) {
576
- Log.w(
577
- TAG,
578
- "loadAndLogPlayerConfig: 'MpvPlayerModule' not registered yet or doesn't implement IMpvConfigProvider " +
579
- "(got ${module?.javaClass?.simpleName ?: "null"})",
580
- )
581
- return
582
- }
583
- val config = module.getCurrentConfig()
584
- if (config == null) {
585
- Log.i(
586
- TAG,
587
- "loadAndLogPlayerConfig: no PlayerConfig set (consumer didn't wrap root in <PlayerProvider>)",
588
- )
589
- return
590
- }
591
- val keys = config.keys.sorted().joinToString(", ")
592
- Log.i(TAG, "loadAndLogPlayerConfig: active PlayerConfig keys=[$keys]")
593
- // Phase 22: drill into the theme section and log the active
594
- // color values so the build verification can confirm the
595
- // theme reaches the native side. Mirrors how Phase 22's
596
- // `DefaultControls.tsx` reads `useTheme()` on the JS side —
597
- // both ends see the same values (the Provider is the source
598
- // of truth, JS pushes to native in Phase 21's setConfig).
599
- val themeSection = config["theme"] as? Map<String, Any?>
600
- if (themeSection != null) {
601
- val accent = themeSection["accent"] as? String ?: DEFAULT_THEME_ACCENT
602
- val background = themeSection["background"] as? String ?: DEFAULT_THEME_BACKGROUND
603
- val text = themeSection["text"] as? String ?: DEFAULT_THEME_TEXT
604
- Log.i(
605
- TAG,
606
- "loadAndLogPlayerConfig: theme accent=$accent background=$background text=$text",
607
- )
608
- // Phase 22 future: pipe these into the MediaStyle
609
- // notification's color tokens (NotificationCompat.MediaStyle
610
- // does not accept arbitrary colors but the surrounding
611
- // NotificationCompat.Builder does — accent → setColor, etc.).
612
- // Deferred to a Phase 22 follow-up to avoid scope creep.
613
- } else {
614
- Log.i(TAG, "loadAndLogPlayerConfig: theme section absent (using default dark theme)")
615
- }
616
- // Phase 22+ will read additional sections here (pip.enabled,
617
- // audio.backgroundPlayback, subtitle.*, etc.) and apply them.
618
- // We deliberately do NOT cache the config on the activity —
619
- // the bridge is the source of truth, and a future phase that
620
- // flips config at runtime (settings screen) would invalidate a
621
- // cached copy. Future readers should call
622
- // `module.getCurrentConfig()` directly each time.
623
- }
624
-
625
- // ── MediaSession (V20 Phase B) ──────────────────────────────────────
626
- // The session itself belongs to MediaPlaybackService now — see that
627
- // class header for why. What remains here is the Activity's side of
628
- // the conversation: this Activity knows when playback state changed
629
- // because of *its own* lifecycle decisions (an audio-focus loss, a PiP
630
- // transition, a resume) and publishes them.
631
- //
632
- // The transport commands themselves arrive through the service's
633
- // callback, which reads the engine via PlaybackHost at the moment of
634
- // use — so a command can no longer be issued against a stale handle.
635
- private fun updateMediaSessionState(
636
- playing: Boolean,
637
- state: Int = if (playing) {
638
- android.support.v4.media.session.PlaybackStateCompat.STATE_PLAYING
639
- } else {
640
- android.support.v4.media.session.PlaybackStateCompat.STATE_PAUSED
641
- },
642
- ) {
643
- MediaPlaybackService.publishState(playing, state)
644
- }
645
-
646
- // ── Headset / Bluetooth disconnect (Phase 20) ───────────────────────
647
- // Register a BroadcastReceiver for
648
- // AudioManager.ACTION_AUDIO_BECOMING_NOISY. The system fires
649
- // this broadcast when a wired headset is unplugged, a
650
- // Bluetooth A2DP source disconnects, or the audio output
651
- // switches from headphones to the built-in speaker. Pausing
652
- // on the event prevents the user from getting audio blasting
653
- // out of the speaker (a common surprise when a user
654
- // disconnects their headphones mid-play).
655
- //
656
- // The receiver is only registered while the activity is
657
- // foregrounded — the foreground service (Phase 16) keeps the
658
- // media session alive in the background, and the system
659
- // re-fires the broadcast if the activity resumes. This also
660
- // means we don't accidentally double-pause when the audio-bg
661
- // path (Phase 14) keeps mpv playing in the background.
662
- private fun registerHeadsetReceiver() {
663
- if (headsetReceiver != null) return
664
- val receiver = object : android.content.BroadcastReceiver() {
665
- override fun onReceive(context: android.content.Context, intent: android.content.Intent) {
666
- if (intent.action == android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY) {
667
- Log.i(TAG, "ACTION_AUDIO_BECOMING_NOISY: pausing mpv (headphones unplugged)")
668
- pauseOnHeadsetDisconnect()
669
- }
670
- }
671
- }
672
- headsetReceiver = receiver
673
- // API 33+ requires the RECEIVER_EXPORTED / RECEIVER_NOT_EXPORTED
674
- // flag. ACTION_AUDIO_BECOMING_NOISY is a protected broadcast
675
- // sent by the system (not other apps), so
676
- // RECEIVER_NOT_EXPORTED is the correct choice.
677
- val filter = android.content.IntentFilter(android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)
678
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
679
- registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
680
- } else {
681
- registerReceiver(receiver, filter)
682
- }
683
- Log.i(TAG, "Headset receiver registered")
684
- }
685
-
686
- private fun unregisterHeadsetReceiver() {
687
- val receiver = headsetReceiver ?: return
688
- try {
689
- unregisterReceiver(receiver)
690
- Log.i(TAG, "Headset receiver unregistered")
691
- } catch (e: Exception) {
692
- Log.w(TAG, "unregisterHeadsetReceiver threw ${e.message}", e)
693
- }
694
- headsetReceiver = null
695
- }
696
-
697
- // ── Phase 38: audio focus request / abandon (spec §38.4) ────────────
698
- // Request audio focus on resume so the system knows we're playing.
699
- // On focus loss we either duck the volume (transient can-duck) or
700
- // pause mpv (transient / permanent loss). On focus gain we restore
701
- // volume + resume playback if the user has the "queue resume"
702
- // preference (Phase 14 audio-background-playback behaviour).
703
- //
704
- // The duck-on-can-duck convention is the same one Spotify / Apple
705
- // Music use for navigation prompts: lower the volume to 20% so the
706
- // user can hear the prompt, then restore when focus returns.
707
- private fun requestAudioFocus() {
708
- if (hasAudioFocus) return
709
- val audioManager = getSystemService(android.content.Context.AUDIO_SERVICE) as? android.media.AudioManager
710
- ?: run {
711
- Log.w(TAG, "requestAudioFocus: AudioManager unavailable")
712
- return
713
- }
714
- val listener = android.media.AudioManager.OnAudioFocusChangeListener { focusChange ->
715
- Log.i(TAG, "AudioFocus change: $focusChange")
716
- when (focusChange) {
717
- android.media.AudioManager.AUDIOFOCUS_GAIN -> {
718
- // Restore volume + resume if we paused for a transient loss
719
- if (preDuckVolume >= 0f) {
720
- restoreVolume()
721
- }
722
- // Phase 14 audio-bg: if the activity is still in PiP or the
723
- // audio-bg setting is on, resume playback. Conservative
724
- // default: don't auto-resume — let the user tap play.
725
- // (Auto-resume can be jarring after a phone call ends.)
726
- Log.i(TAG, "AudioFocus gained — playback ready for manual resume")
727
- }
728
- android.media.AudioManager.AUDIOFOCUS_LOSS -> {
729
- // Permanent loss (e.g., user switched to another audio app)
730
- pauseOnAudioFocusLoss("permanent")
731
- }
732
- android.media.AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
733
- // Transient loss (phone call, alarm, navigation)
734
- pauseOnAudioFocusLoss("transient")
735
- }
736
- android.media.AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
737
- // Can duck — lower volume to 20% (matches Spotify convention)
738
- duckVolume()
739
- }
740
- }
741
- emitAudioFocusChange(focusChange)
742
- }
743
- audioFocusListener = listener
744
- val result: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
745
- val playbackInfo = android.media.AudioAttributes.Builder()
746
- .setUsage(android.media.AudioAttributes.USAGE_MEDIA)
747
- .setContentType(android.media.AudioAttributes.CONTENT_TYPE_MOVIE)
748
- .build()
749
- val request = android.media.AudioFocusRequest.Builder(
750
- android.media.AudioManager.AUDIOFOCUS_GAIN
751
- )
752
- .setAudioAttributes(playbackInfo)
753
- .setAcceptsDelayedFocusGain(true)
754
- .setWillPauseWhenDucked(false) // we handle duck ourselves
755
- .setOnAudioFocusChangeListener(listener)
756
- .build()
757
- audioFocusRequest = request
758
- audioManager.requestAudioFocus(request)
759
- } else {
760
- @Suppress("DEPRECATION")
761
- audioManager.requestAudioFocus(
762
- listener,
763
- android.media.AudioManager.STREAM_MUSIC,
764
- android.media.AudioManager.AUDIOFOCUS_GAIN
765
- )
766
- }
767
- hasAudioFocus = (result == android.media.AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
768
- Log.i(TAG, "requestAudioFocus: result=$result hasFocus=$hasAudioFocus")
769
- }
770
-
771
- private fun abandonAudioFocus() {
772
- if (!hasAudioFocus) return
773
- val audioManager = getSystemService(android.content.Context.AUDIO_SERVICE) as? android.media.AudioManager
774
- ?: return
775
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
776
- audioFocusRequest?.let {
777
- audioManager.abandonAudioFocusRequest(it)
778
- }
779
- audioFocusRequest = null
780
- } else {
781
- @Suppress("DEPRECATION")
782
- audioFocusListener?.let {
783
- audioManager.abandonAudioFocus(it)
784
- }
785
- }
786
- audioFocusListener = null
787
- hasAudioFocus = false
788
- if (preDuckVolume >= 0f) {
789
- restoreVolume()
790
- }
791
- Log.i(TAG, "abandonAudioFocus: focus released")
792
- }
793
-
794
- private fun pauseOnAudioFocusLoss(reason: String) {
795
- val ptr = PlaybackHost.handle()
796
- if (ptr != 0L) {
797
- try {
798
- MPVLib.nativePause(ptr)
799
- Log.i(TAG, "pauseOnAudioFocusLoss ($reason): mpv paused")
800
- } catch (e: Exception) {
801
- Log.w(TAG, "pauseOnAudioFocusLoss: nativePause threw ${e.message}", e)
802
- }
803
- }
804
- updateMediaSessionState(playing = false)
805
- }
806
-
807
- private fun duckVolume() {
808
- val ptr = PlaybackHost.handle()
809
- if (ptr == 0L) return
810
- try {
811
- val currentVolume = MPVLib.nativeGetVolume(ptr).toFloat()
812
- if (preDuckVolume < 0f) {
813
- preDuckVolume = currentVolume
814
- }
815
- // Duck to 20% of current volume (Spotify convention)
816
- MPVLib.nativeSetVolume(ptr, (currentVolume * 0.2).toDouble())
817
- Log.i(TAG, "duckVolume: $currentVolume → ${currentVolume * 0.2}")
818
- } catch (e: Exception) {
819
- Log.w(TAG, "duckVolume: nativeGetVolume/SetVolume threw ${e.message}", e)
820
- }
821
- }
822
-
823
- private fun restoreVolume() {
824
- val ptr = PlaybackHost.handle()
825
- if (ptr == 0L || preDuckVolume < 0f) return
826
- try {
827
- MPVLib.nativeSetVolume(ptr, preDuckVolume.toDouble())
828
- Log.i(TAG, "restoreVolume: → $preDuckVolume")
829
- preDuckVolume = -1f
830
- } catch (e: Exception) {
831
- Log.w(TAG, "restoreVolume: nativeSetVolume threw ${e.message}", e)
832
- }
833
- }
834
-
835
- // Phase 20.2: pause mpv on headset disconnect. The pause
836
- // goes through the same code path as the MediaSession's
837
- // onPause() callback (which keeps the MediaSession state +
838
- // notification in sync via the existing updateMediaSessionState
839
- // helper).
840
- private fun pauseOnHeadsetDisconnect() {
841
- val ptr = PlaybackHost.handle()
842
- if (ptr != 0L) {
843
- try {
844
- MPVLib.nativePause(ptr)
845
- Log.i(TAG, "pauseOnHeadsetDisconnect: nativePause called (ptr=$ptr)")
846
- updateMediaSessionState(playing = false)
847
- } catch (e: Exception) {
848
- Log.w(TAG, "pauseOnHeadsetDisconnect: nativePause threw ${e.message}", e)
849
- }
850
- }
851
- }
852
-
853
- // ── MediaPlaybackService helpers (Phase 16) ─────────────────────────────
854
- // Build the start intent with the launch metadata + the
855
- // MediaSessionCompat token (created in Phase 15). The service
856
- // uses the token to wire its MediaStyle notification to the
857
- // same session the activity's playback controls drive.
858
- private fun buildMediaPlaybackServiceIntent(action: String): android.content.Intent {
859
- val intent = android.content.Intent(this, MediaPlaybackService::class.java)
860
- intent.action = action
861
- intent.putExtra(MediaPlaybackService.EXTRA_TITLE, launchTitle)
862
- // Phase 16: artist / album / artwork are not yet carried in
863
- // the launch params. We default artist + album to empty
864
- // strings (the service shows title only) and skip the
865
- // artwork path entirely. Phase 18 (W4) adds these extras to
866
- // the launch intent via the bridge.
867
- intent.putExtra(MediaPlaybackService.EXTRA_ARTIST, "")
868
- intent.putExtra(MediaPlaybackService.EXTRA_ALBUM, "")
869
- intent.putExtra(MediaPlaybackService.EXTRA_ARTWORK_PATH, "")
870
- intent.putExtra(MediaPlaybackService.EXTRA_POSITION_MS, launchStartPositionMs)
871
- intent.putExtra(MediaPlaybackService.EXTRA_DURATION_MS, 0L)
872
- intent.putExtra(MediaPlaybackService.EXTRA_IS_PLAYING, true)
873
- // V20 Phase B: no session token is passed any more. The service owns
874
- // the session and publishes its own token to the MediaStyle
875
- // notification, so there is nothing for this Activity to hand over.
876
- return intent
877
- }
878
-
879
- // Phase 16.6: start the foreground service. Uses
880
- // startForegroundService (Android 8+) because the service
881
- // will call startForeground within 5s.
882
- private fun startMediaPlaybackService() {
883
- try {
884
- val intent = buildMediaPlaybackServiceIntent(MediaPlaybackService.ACTION_START)
885
- androidx.core.content.ContextCompat.startForegroundService(this, intent)
886
- Log.i(TAG, "MediaPlaybackService start requested (foreground)")
887
- } catch (e: Exception) {
888
- Log.w(TAG, "startMediaPlaybackService: ${e.message}", e)
889
- }
890
- }
891
-
892
- // V20 Phase B deleted `stopMediaPlaybackService` here.
893
- //
894
- // It existed so this Activity could wind the service down in
895
- // `onDestroy`. Now it doesn't: the service owns its own lifetime, and
896
- // the paths that genuinely mean "stop playing" — the notification's
897
- // Stop and cancel buttons, and the session's own stop callback — are
898
- // handled by the service itself. An Activity tearing itself down is
899
- // no longer a statement about whether playback should continue, which
900
- // is the whole point of the change.
901
-
902
- // Phase 17.2 / 17.4: ship the current position + duration to
903
- // MediaPlaybackService so its notification's progress bar stays
904
- // in sync with the mpv state. Called both from the 1Hz
905
- // `progressUpdateRunnable` and on demand from onResume /
906
- // onPause.
907
- //
908
- // We use a non-foreground `startService` here (not
909
- // startForegroundService) because the service is already in
910
- // the foreground state — the system accepts ordinary service
911
- // starts for an already-foreground service without the 5s
912
- // startForeground deadline.
913
- private fun updateMediaPlaybackServicePosition() {
914
- try {
915
- val position = getPlaybackPositionMs()
916
- val duration = getPlaybackDurationMs()
917
- val intent = buildMediaPlaybackServiceIntent(MediaPlaybackService.ACTION_UPDATE)
918
- intent.putExtra(MediaPlaybackService.EXTRA_POSITION_MS, position)
919
- intent.putExtra(MediaPlaybackService.EXTRA_DURATION_MS, duration)
920
- startService(intent)
921
- } catch (e: Exception) {
922
- // Common when the service is no longer running (activity
923
- // was destroyed but the runnable fired once more). Silent
924
- // — the next onResume restarts the timer.
925
- Log.d(TAG, "updateMediaPlaybackServicePosition: ${e.message}")
926
- }
927
- }
928
-
929
- // Phase 17.4: start the 1Hz progress update runnable. Idempotent
930
- // — calling twice is a no-op (avoids double-firing if
931
- // onResume runs more than once without an intervening pause,
932
- // which can happen on some OEMs after a config change).
933
- private fun startProgressUpdates() {
934
- if (progressUpdatesRunning) return
935
- progressUpdatesRunning = true
936
- progressUpdateHandler.postDelayed(progressUpdateRunnable, PROGRESS_UPDATE_INTERVAL_MS)
937
- Log.i(TAG, "Progress updates started (interval=${PROGRESS_UPDATE_INTERVAL_MS}ms)")
938
- }
939
-
940
- // Phase 17.5: stop the 1Hz runnable + remove any pending
941
- // callback. Idempotent. Called from onPause and onDestroy.
942
- private fun stopProgressUpdates() {
943
- if (!progressUpdatesRunning) return
944
- progressUpdatesRunning = false
945
- progressUpdateHandler.removeCallbacks(progressUpdateRunnable)
946
- Log.i(TAG, "Progress updates stopped")
947
- }
948
-
949
- /**
950
- * Phase 7 helper: resolve the ReactApplicationContext via the
951
- * `ReactApplication` interface. The consumer app runs in bridgeless
952
- * mode (RN 0.76+), so we use `reactHost.currentReactContext` —
953
- * `reactNativeHost` has been removed from the interface in bridgeless
954
- * builds and is not available at the call site.
955
- */
956
- private fun resolveReactApplicationContext(): ReactApplicationContext? {
957
- val app = application as? ReactApplication ?: run {
958
- Log.w(TAG, "resolveReactApplicationContext: Application does not implement ReactApplication")
959
- return null
960
- }
961
- return try {
962
- app.reactHost?.currentReactContext as? ReactApplicationContext
963
- } catch (e: Exception) {
964
- Log.w(TAG, "resolveReactApplicationContext: reactHost access threw ${e.message}", e)
965
- null
966
- }
967
- }
968
-
969
- override fun onResume() {
970
- super.onResume()
971
- Log.i(TAG, "onResume: free-orientation (PlayerActivity does NOT pin)")
972
- // ── Phase 9: refresh PiP params ────────────────────────────────────
973
- // PiP params are tied to the activity, NOT to the PiP session —
974
- // the framework reads them when entering PiP. Setting them on
975
- // every resume guarantees they're current with the latest
976
- // surface size (e.g. orientation change) and aspect ratio (e.g.
977
- // user opened a different file).
978
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
979
- try {
980
- val params = buildCurrentPipParams()
981
- setPictureInPictureParams(params)
982
- Log.i(
983
- TAG,
984
- "onResume: setPictureInPictureParams called with aspect=${getVideoAspect()} bounds=$playerBounds",
985
- )
986
- } catch (e: Exception) {
987
- Log.w(TAG, "onResume: setPictureInPictureParams threw ${e.message}", e)
988
- }
989
- }
990
- // Refresh the session state on resume. Playback state can change
991
- // while this window is in the background (the user may have used the
992
- // notification, the lock-screen widget or a Bluetooth control), and
993
- // the service cannot see *this* Activity resume, so we re-publish.
994
- //
995
- // `playing = true` is a deliberate default, not a reading: mpv's
996
- // pause flag is not observable from here without an observer hook,
997
- // and the next session callback or MPVLib event corrects it. What
998
- // matters is that the session is not left advertising a stale state.
999
- if (MediaPlaybackService.isRunning()) {
1000
- updateMediaSessionState(playing = true)
1001
- }
1002
- // Phase 17.4: start the 1Hz progress update runnable. This
1003
- // keeps MediaPlaybackService's notification progress bar in
1004
- // sync with mpv's `time-pos` / `duration` properties. Runs
1005
- // only while the activity is in the foreground; onPause
1006
- // stops the runnable + sends a final ACTION_UPDATE so the
1007
- // notification reflects the pause moment.
1008
- startProgressUpdates()
1009
- // Phase 20.1: register the AudioManager.ACTION_AUDIO_BECOMING_NOISY
1010
- // receiver so we pause mpv when the user unplugs their
1011
- // headphones. Registered only while the activity is
1012
- // foregrounded (background audio playback doesn't need it —
1013
- // the system won't re-fire the broadcast when the service
1014
- // is in the foreground service state).
1015
- registerHeadsetReceiver()
1016
- // Phase 38: request audio focus so the system knows we're playing.
1017
- // On focus loss (phone call, navigation, alarm) we'll pause mpv or
1018
- // duck the volume — see requestAudioFocus() for the focus-change
1019
- // handling.
1020
- requestAudioFocus()
1021
- }
1022
-
1023
- override fun onPictureInPictureModeChanged(
1024
- isInPictureInPictureMode: Boolean,
1025
- newConfig: Configuration,
1026
- ) {
1027
- super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
1028
- Log.i(TAG, "onPictureInPictureModeChanged: isInPip=$isInPictureInPictureMode")
1029
- // Phase 9.5: re-set params on every PiP entry/exit so the new
1030
- // configuration (e.g. orientation change while in PiP) takes
1031
- // effect. The system calls this both on entry and exit, but
1032
- // setting params is a no-op when not in PiP mode.
1033
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
1034
- try {
1035
- setPictureInPictureParams(buildCurrentPipParams())
1036
- } catch (e: Exception) {
1037
- Log.w(TAG, "onPictureInPictureModeChanged: setPictureInPictureParams threw ${e.message}", e)
1038
- }
1039
- }
1040
- // Phase 10: forward to JS via the same MpvBridgeModule.companion
1041
- // emit path that V11's MainActivity used, so JS handlers
1042
- // listening for `onPipModeChanged` continue to fire. We can't
1043
- // call `MpvBridgeModule.onPictureInPictureModeChanged` directly
1044
- // (Gradle module boundary) so we look up the bridge via the
1045
- // React Native module registry and cast to the module-side
1046
- // `IPipModeChangeEmitter` contract.
1047
- //
1048
- // Resolution follows the same resolve-then-lookup shape: resolve
1049
- // ReactApplicationContext via (application as? ReactApplication)
1050
- // ?.reactHost.currentReactContext, then getNativeModule("MpvPlayerModule")
1051
- // cast to IPipModeChangeEmitter. The lookup runs on the main
1052
- // thread; missing context just logs a warning — the JS handler
1053
- // will be one missed event, the rest of PiP behaviour (params,
1054
- // RemoteActions) still works.
1055
- Handler(Looper.getMainLooper()).post { forwardPipModeToJs(isInPictureInPictureMode) }
1056
- // Phase 38 (spec §38.5: Surface lost during PiP → re-attach):
1057
- // when PiP exits, the SurfaceView's surface may have been torn down
1058
- // by the system (some OEMs destroy the surface during PiP to free
1059
- // GPU memory). MpvRenderView.surfaceDestroyed() detaches the
1060
- // surface from mpv, but it doesn't re-attach when a new surface
1061
- // arrives. We trigger a re-attach here so the player resumes
1062
- // rendering immediately after PiP exit.
1063
- if (!isInPictureInPictureMode && PlaybackHost.handle() != 0L) {
1064
- mpvRenderView?.let { view ->
1065
- Log.i(TAG, "onPictureInPictureModeChanged (exit): re-attaching surface to mpv")
1066
- try {
1067
- view.setNativePtr(PlaybackHost.handle())
1068
- } catch (e: Exception) {
1069
- Log.w(TAG, "onPictureInPictureModeChanged: setNativePtr threw ${e.message}", e)
1070
- }
1071
- }
1072
- }
1073
- // Phase 10.6: PiP transition completed; clear the entry-in-flight
1074
- // flag so the deferred onPause check knows it's safe to pause
1075
- // mpv if the activity is leaving for real (not via PiP).
1076
- pipEntryInFlight = false
1077
- }
1078
-
1079
- /**
1080
- * Phase 10 helper: resolve [IPipModeChangeEmitter] via the React
1081
- * Native bridge and emit the PiP mode-change event. Mirrors the
1082
- * engine-availability pattern in spirit (resolve context →
1083
- * lookup → cast) but only runs once per PiP transition — there's no
1084
- * retry because a missed event is a single-frame UI glitch, not a
1085
- * playback failure.
1086
- */
1087
- private fun forwardPipModeToJs(isInPictureInPictureMode: Boolean) {
1088
- val reactContext: ReactApplicationContext = resolveReactApplicationContext() ?: run {
1089
- Log.w(TAG, "forwardPipModeToJs: ReactApplicationContext null, dropping event")
1090
- return
1091
- }
1092
- val module: NativeModule? = try {
1093
- reactContext.getNativeModule("MpvPlayerModule")
1094
- } catch (e: Exception) {
1095
- Log.w(TAG, "forwardPipModeToJs: getNativeModule threw ${e.message}", e)
1096
- null
1097
- }
1098
- if (module !is IPipModeChangeEmitter) {
1099
- Log.w(
1100
- TAG,
1101
- "forwardPipModeToJs: 'MpvPlayerModule' not registered yet or doesn't implement IPipModeChangeEmitter " +
1102
- "(got ${module?.javaClass?.simpleName ?: "null"})",
1103
- )
1104
- return
1105
- }
1106
- module.emitPictureInPictureModeChanged(isInPictureInPictureMode)
1107
- }
1108
-
1109
- /**
1110
- * Phase 10.4: enter PiP when the user performs a "leave" gesture
1111
- * (home button, recent apps, swipe-down). This is the V11 pattern
1112
- * from `MainActivity` — V11's flow was auto-PiP on home press. V12
1113
- * keeps the same behaviour inside `PlayerActivity`.
1114
- *
1115
- * The PiP params (aspect, source rect, RemoteActions) were set in
1116
- * Phase 9's `onResume`; we call the no-arg `enterPictureInPictureMode()`
1117
- * overload so Android uses our pre-set params (the spec is explicit:
1118
- * "NO params, they're set via setPictureInPictureParams").
1119
- */
1120
- override fun onUserLeaveHint() {
1121
- super.onUserLeaveHint()
1122
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N &&
1123
- packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)
1124
- ) {
1125
- // Phase 10.6: set the defer flag BEFORE entering PiP so the
1126
- // imminent onPause knows the upcoming transition is PiP, not a
1127
- // real pause. Cleared in onPictureInPictureModeChanged once the
1128
- // transition completes.
1129
- pipEntryInFlight = true
1130
- try {
1131
- enterPictureInPictureMode()
1132
- Log.i(TAG, "onUserLeaveHint: entering PiP (pipEntryInFlight=true)")
1133
- } catch (e: Exception) {
1134
- // Enter failed (OEM quirk, system in lock-task mode, etc.) —
1135
- // clear the defer flag so the upcoming onPause behaves as a
1136
- // normal pause.
1137
- pipEntryInFlight = false
1138
- Log.w(TAG, "onUserLeaveHint: enterPictureInPictureMode threw ${e.message}", e)
1139
- }
1140
- } else {
1141
- Log.i(TAG, "onUserLeaveHint: PiP not supported, falling through to default")
1142
- }
1143
- }
1144
-
1145
- /**
1146
- * Phase 10.6 + Phase 14.1: when the activity is paused (typically
1147
- * because the user pressed home, opened recents, or switched to
1148
- * another app), decide whether to pause mpv. The decision tree:
1149
- *
1150
- * • If we're in PiP (or PiP entry is in flight that ends in
1151
- * PiP): do NOT pause. PiP keeps the activity visible in a
1152
- * small overlay; the user expects playback to continue.
1153
- * • If type=audio AND the user has the audioBackgroundPlayback
1154
- * setting enabled (default true): do NOT pause. Audio keeps
1155
- * playing in the background so the user can use other apps
1156
- * while listening. This mirrors how Spotify, Apple Music,
1157
- * etc. behave for audio.
1158
- * • Otherwise: pause mpv synchronously. This covers video
1159
- * backgrounds and the case where audio-background-playback
1160
- * is disabled.
1161
- *
1162
- * The framework sets `isInPictureInPictureMode` asynchronously
1163
- * during the PiP transition, so we can't check it synchronously
1164
- * here. Instead, defer the check by `200ms` (well past the time
1165
- * Android takes to enter PiP after `onUserLeaveHint`); if we're
1166
- * still not in PiP at that point, it's a real pause and we run
1167
- * the audio-vs-video decision.
1168
- *
1169
- * Mirrors the mpvKt pattern (their `BaseMPVView.onPause` does
1170
- * the same defer-then-check dance; we use the activity-level
1171
- * `isInPictureInPictureMode` rather than a view flag because
1172
- * the activity's flag is the source of truth).
1173
- */
1174
- override fun onPause() {
1175
- super.onPause()
1176
- // Phase 17.5: stop the 1Hz progress update runnable. The
1177
- // notification is now frozen at the last position. We send
1178
- // a final ACTION_UPDATE below the existing pause logic so
1179
- // the notification reflects the position at the moment the
1180
- // activity backgrounded (not the moment the runnable last
1181
- // fired, which can be up to 1s stale).
1182
- stopProgressUpdates()
1183
- // Phase 20.1: unregister the headset-disconnect receiver.
1184
- // Only needed while the activity is foregrounded; the
1185
- // foreground service keeps the media session alive in the
1186
- // background and would receive a re-broadcast on resume.
1187
- unregisterHeadsetReceiver()
1188
- // Phase 38: abandon audio focus on pause so other apps can resume
1189
- // audio. We re-request on the next onResume.
1190
- abandonAudioFocus()
1191
- if (!pipEntryInFlight && PlaybackHost.handle() != 0L) {
1192
- // Quick path: the defer flag isn't set, so we know
1193
- // immediately this is a real pause (user pressed back,
1194
- // locked the screen, opened another activity). Run the
1195
- // audio-vs-video decision now.
1196
- if (shouldKeepPlayingInBackground()) {
1197
- Log.i(
1198
- TAG,
1199
- "onPause: audio background playback ON, mpv continues (type='$launchType')",
1200
- )
1201
- } else {
1202
- try {
1203
- val ptr = PlaybackHost.handle()
1204
- MPVLib.nativePause(ptr)
1205
- Log.i(TAG, "onPause: paused mpv synchronously (ptr=$ptr)")
1206
- } catch (e: Exception) {
1207
- Log.w(TAG, "onPause: nativePause threw ${e.message}", e)
1208
- }
1209
- }
1210
- } else if (pipEntryInFlight) {
1211
- // Defer the decision: PiP transition is in flight. Re-check
1212
- // 200ms later — by then `isInPictureInPictureMode` will be
1213
- // true if Android took the PiP path, or false if the
1214
- // transition was cancelled. If we're not in PiP, fall
1215
- // through to the audio-vs-video decision.
1216
- //
1217
- // Phase 36 leak fix: capture `this` via WeakReference so the
1218
- // Handler's delayed Runnable doesn't pin the activity if it
1219
- // fires after onDestroy (e.g., the user finishes PlayerActivity
1220
- // mid-PiP-transition). Without the WeakReference, the lambda's
1221
- // implicit `this` capture keeps the activity alive for the
1222
- // full 200 ms delay window even after onDestroy nulled the
1223
- // important fields.
1224
- val activityRef = java.lang.ref.WeakReference(this)
1225
- Handler(Looper.getMainLooper()).postDelayed({
1226
- val activity = activityRef.get() ?: run {
1227
- Log.i(TAG, "onPause (deferred 200ms): activity gone, aborting")
1228
- return@postDelayed
1229
- }
1230
- if (activity.isInPictureInPictureMode) {
1231
- Log.i(TAG, "onPause (deferred 200ms): entered PiP, mpv continues playing")
1232
- } else if (PlaybackHost.handle() != 0L) {
1233
- if (activity.shouldKeepPlayingInBackground()) {
1234
- Log.i(
1235
- TAG,
1236
- "onPause (deferred 200ms): audio background playback ON, mpv continues (type='${activity.launchType}')",
1237
- )
1238
- } else {
1239
- try {
1240
- MPVLib.nativePause(PlaybackHost.handle())
1241
- Log.i(TAG, "onPause (deferred 200ms): NOT in PiP, paused mpv")
1242
- } catch (e: Exception) {
1243
- Log.w(TAG, "onPause (deferred): nativePause threw ${e.message}", e)
1244
- }
1245
- }
1246
- }
1247
- }, 200L)
1248
- }
1249
- // Phase 17.1: send a final ACTION_UPDATE so the
1250
- // notification's progress bar reflects the position at
1251
- // the moment of pause. Runs unconditionally — even when
1252
- // audio keeps playing in the background, the user
1253
- // benefits from seeing the position pin to the right
1254
- // value on the lock-screen widget. We defer the
1255
- // position query to the next looper tick so mpv has
1256
- // time to settle the last time-pos read after the
1257
- // pause itself.
1258
- Handler(Looper.getMainLooper()).postDelayed(
1259
- { updateMediaPlaybackServicePosition() },
1260
- 250L,
1261
- )
1262
- }
1263
-
1264
- /**
1265
- * Phase 14.1.2 / 14.1.3: shared decision helper used by both the
1266
- * quick and deferred `onPause` paths. Returns `true` when the
1267
- * current launch is audio AND the user has the
1268
- * `audioBackgroundPlayback` setting enabled. Returns `false`
1269
- * for video (which always pauses on background) and for audio
1270
- * when the setting is off.
1271
- */
1272
- private fun shouldKeepPlayingInBackground(): Boolean {
1273
- return launchType == TYPE_AUDIO && audioBackgroundPlayback
1274
- }
1275
-
1276
- /**
1277
- * Back-button behaviour.
1278
- *
1279
- * ## Why this does the teardown itself
1280
- *
1281
- * This used to be:
1282
- *
1283
- * ```kotlin
1284
- * if (isInPictureInPictureMode) { finish(); return }
1285
- * super.onBackPressed()
1286
- * ```
1287
- *
1288
- * which finishes the Activity **natively**. The event never reaches
1289
- * React Native, so a JS `BackHandler` cannot run — which left two back
1290
- * paths that disagreed:
1291
- *
1292
- * - the header chevron -> JS `exitPlayer()` -> stop the engine,
1293
- * release the foreground service, then finish;
1294
- * - the hardware key -> `super.onBackPressed()` -> finish only.
1295
- *
1296
- * Since the mpv engine is a process-global C++ handle that outlives any
1297
- * Activity, the second path closed the window while the media carried
1298
- * on: audio still audible, notification still posted, no window left to
1299
- * stop it. Verified on device — after the hardware key the media
1300
- * session was still `PLAYING` with zero `stopPlayback` / `nativeStop`
1301
- * lines in logcat, even with a JS BackHandler registered.
1302
- *
1303
- * ## Why natively rather than delegating to JS
1304
- *
1305
- * Delegating would make the player un-closable whenever the bundle is
1306
- * unhealthy — a JS crash would strand a playing session with no window
1307
- * and no working dismiss. The Activity already owns the engine through
1308
- * `PlaybackHost`, so the teardown here is both shorter and strictly
1309
- * more robust.
1310
- *
1311
- * The JS `BackHandler` in `VideoPlayer.tsx` is KEPT: it covers whatever
1312
- * does reach React (notably predictive back, where `onBackPressed` is
1313
- * never called), and the two paths now agree.
1314
- */
1315
- override fun onBackPressed() {
1316
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && isInPictureInPictureMode) {
1317
- // Finish exits PiP and returns the user to MainActivity (the
1318
- // parent of PlayerActivity in the task stack).
1319
- Log.i(TAG, "onBackPressed: in PiP, finishing PlayerActivity")
1320
- finish()
1321
- return
1322
- }
1323
-
1324
- // Not PiP: leaving means CLOSING. Stop the engine unconditionally —
1325
- // if the service is already gone its own stop callback is not around
1326
- // to do it, and leaving media running with no way to stop it is the
1327
- // worse of the two failures.
1328
- val ptr = PlaybackHost.handle()
1329
- if (ptr != 0L) {
1330
- try {
1331
- MPVLib.nativeStop(ptr)
1332
- Log.i(TAG, "onBackPressed: stopped mpv (ptr=$ptr)")
1333
- } catch (e: Throwable) {
1334
- Log.w(TAG, "onBackPressed: nativeStop threw ${e.message}")
1335
- }
1336
- } else {
1337
- Log.w(TAG, "onBackPressed: no engine handle; nothing to stop")
1338
- }
1339
-
1340
- if (MediaPlaybackService.isRunning()) {
1341
- try {
1342
- // Plain startService: the service is already foreground, so there
1343
- // is no startForeground deadline to meet.
1344
- startService(
1345
- android.content.Intent(this, MediaPlaybackService::class.java).apply {
1346
- action = MediaPlaybackService.ACTION_STOP
1347
- },
1348
- )
1349
- Log.i(TAG, "onBackPressed: delivered ACTION_STOP to MediaPlaybackService")
1350
- } catch (e: Throwable) {
1351
- Log.e(TAG, "onBackPressed: could not deliver ACTION_STOP", e)
1352
- }
1353
- }
1354
-
1355
- finish()
1356
- }
1357
-
1358
- // ── PiP helpers (Phase 9) ──────────────────────────────────────────
1359
- // Build the params that Android will use when entering PiP.
1360
- // Combines: aspect (from mpv or audio-square fallback), source
1361
- // rect (player bounds), actions (PipManager), title/subtitle
1362
- // (intent extras + position).
1363
- private fun buildCurrentPipParams(): PictureInPictureParams {
1364
- val bounds = playerBounds
1365
- // Phase 15.2: pick the PiP aspect ratio based on the launch
1366
- // type. For video, the natural aspect from mpv (`getVideoAspect()`)
1367
- // gives the same aspect as the in-app player. For audio, there
1368
- // is no meaningful video aspect — the MpvRenderView is GONE
1369
- // (Phase 12) — so we use a 1:1 square, which is the smallest
1370
- // PiP window Android allows and matches the user expectation
1371
- // for an audio overlay (Spotify / Apple Music / Audible all
1372
- // use small square or near-square PiP windows for audio). The
1373
- // `sourceRectHint` for audio is intentionally the full window
1374
- // (playerBounds falls back to the activity window when the
1375
- // GONE MpvRenderView has 0 size).
1376
- val aspect: Float = if (launchType == TYPE_AUDIO) {
1377
- 1f // 1:1 square — audio PiP convention
1378
- } else {
1379
- getVideoAspect()
1380
- }
1381
- // Phase 9.2.4 / 9.2.5: title and subtitle for Android 12+
1382
- // notification overlay. Title comes from the launch intent's
1383
- // EXTRA_TITLE (already cached in `launchTitle`); subtitle is
1384
- // the current playback position, but mpv's position is best
1385
- // queried via MPVLib — for now we leave subtitle null until
1386
- // Phase 10 wires the value through the bridge.
1387
- return PipManager.buildPipParams(
1388
- context = this,
1389
- aspect = aspect,
1390
- sourceRectHint = bounds,
1391
- chapterTitle = launchTitle,
1392
- progressPercentage = null,
1393
- )
1394
- }
1395
-
1396
- // Player bounds: the MpvRenderView's on-screen rectangle. Used
1397
- // as the source rect hint for the PiP entry animation. Falls
1398
- // back to the full activity window when MpvRenderView is not
1399
- // yet laid out (e.g. immediate resume after onCreate).
1400
- private val playerBounds: Rect
1401
- get() {
1402
- val view = mpvRenderView
1403
- if (view != null && view.width > 0 && view.height > 0) {
1404
- val location = IntArray(2)
1405
- view.getLocationInWindow(location)
1406
- return Rect(
1407
- location[0],
1408
- location[1],
1409
- location[0] + view.width,
1410
- location[1] + view.height,
1411
- )
1412
- }
1413
- // Fallback: full activity window.
1414
- return Rect(0, 0, window.decorView.width, window.decorView.height)
1415
- }
1416
-
1417
- // Read the current video's aspect ratio from mpv's
1418
- // `video-params/aspect` property. Falls back to 16:9 (the most
1419
- // common modern aspect) when mpv hasn't loaded any video yet.
1420
- private fun getVideoAspect(): Float {
1421
- if (PlaybackHost.handle() == 0L) {
1422
- return 16f / 9f
1423
- }
1424
- return try {
1425
- val raw = MPVLib.nativeGetProperty(PlaybackHost.handle(), "video-params/aspect")
1426
- val parsed = raw.trim().toFloatOrNull()
1427
- if (parsed != null && parsed.isFinite() && parsed > 0f) {
1428
- parsed.coerceIn(0.42f, 2.38f)
1429
- } else {
1430
- 16f / 9f
1431
- }
1432
- } catch (_: Exception) {
1433
- // mpv can throw if the property hasn't been set yet (no
1434
- // video loaded) or if the handle was destroyed mid-call.
1435
- 16f / 9f
1436
- }
1437
- }
1438
-
1439
- // Phase 17.1: read the current playback position from mpv's
1440
- // `time-pos` property (seconds, as a string). Returns the value
1441
- // in milliseconds, or 0L when mpv hasn't loaded anything yet
1442
- // (the property is empty / not set) or the handle is dead.
1443
- // `time-pos` is a double, but `nativeGetProperty` only returns
1444
- // a string — we parse and convert. The parse is the same
1445
- // pattern [getVideoAspect] uses for the video-params/aspect
1446
- // property.
1447
- private fun getPlaybackPositionMs(): Long {
1448
- if (PlaybackHost.handle() == 0L) return 0L
1449
- return try {
1450
- val raw = MPVLib.nativeGetProperty(PlaybackHost.handle(), "time-pos")
1451
- val parsed = raw.trim().toDoubleOrNull()
1452
- if (parsed != null && parsed.isFinite() && parsed >= 0.0) {
1453
- (parsed * 1000.0).toLong()
1454
- } else {
1455
- 0L
1456
- }
1457
- } catch (_: Exception) {
1458
- 0L
1459
- }
1460
- }
1461
-
1462
- // Phase 17.1: read the total duration from mpv's `duration`
1463
- // property. Returns ms, or 0L when not yet known (mpv sets
1464
- // `duration` once the file is parsed).
1465
- private fun getPlaybackDurationMs(): Long {
1466
- if (PlaybackHost.handle() == 0L) return 0L
1467
- return try {
1468
- val raw = MPVLib.nativeGetProperty(PlaybackHost.handle(), "duration")
1469
- val parsed = raw.trim().toDoubleOrNull()
1470
- if (parsed != null && parsed.isFinite() && parsed > 0.0) {
1471
- (parsed * 1000.0).toLong()
1472
- } else {
1473
- 0L
1474
- }
1475
- } catch (_: Exception) {
1476
- 0L
1477
- }
1478
- }
1479
-
1480
- // ── Media metadata (Phase 19) ──────────────────────────────────────
1481
- // Phase 19.1: query mpv for the loaded file's tagged metadata.
1482
- // All three helpers return "" when the property is missing or
1483
- // the handle is dead — callers fall back to the launch title
1484
- // (or just show title-only) when that happens. We use the
1485
- // `metadata/by-key/*` form because that's the reliable path
1486
- // in modern mpv (the older `metadata/artist` form only fires
1487
- // for the first artist in the tag list, which on multi-artist
1488
- // files can be a featured artist rather than the main one).
1489
- private fun getMediaTitle(): String {
1490
- if (PlaybackHost.handle() == 0L) return ""
1491
- return try {
1492
- MPVLib.nativeGetProperty(PlaybackHost.handle(), "media-title").trim()
1493
- } catch (_: Exception) {
1494
- ""
1495
- }
1496
- }
1497
-
1498
- private fun getMediaArtist(): String {
1499
- if (PlaybackHost.handle() == 0L) return ""
1500
- return try {
1501
- MPVLib.nativeGetProperty(PlaybackHost.handle(), "metadata/by-key/artist").trim()
1502
- } catch (_: Exception) {
1503
- ""
1504
- }
1505
- }
1506
-
1507
- private fun getMediaAlbum(): String {
1508
- if (PlaybackHost.handle() == 0L) return ""
1509
- return try {
1510
- MPVLib.nativeGetProperty(PlaybackHost.handle(), "metadata/by-key/album").trim()
1511
- } catch (_: Exception) {
1512
- ""
1513
- }
1514
- }
1515
-
1516
- // V20 Phase B: the session lives on the service, so this publishes
1517
- // to it rather than writing a session directly.
1518
- //
1519
- // Called once from `PlaybackHost.whenAvailable` (mpv exists by then, so
1520
- // the real tags are readable) and once more whenever the engine reports
1521
- // a new file.
1522
- //
1523
- // Title fallback chain: mpv `media-title` → launch title → "Simba
1524
- // Player", so the lock-screen widget never shows blank. Artist and
1525
- // album stay empty when the file is untagged, and the system collapses
1526
- // the widget to title-only — which is how Spotify and YouTube Music
1527
- // render untagged files.
1528
- private fun setMediaSessionMetadata() {
1529
- val title = getMediaTitle().ifBlank { launchTitle.ifBlank { "Simba Player" } }
1530
- val artist = getMediaArtist()
1531
- val album = getMediaAlbum()
1532
- Log.i(TAG, "MediaSession metadata: title='$title' artist='$artist' album='$album'")
1533
- MediaPlaybackService.publishMetadata(
1534
- title = title,
1535
- artist = artist,
1536
- album = album,
1537
- artworkPath = "",
1538
- mediaUri = launchUri,
1539
- displaySubtitle = buildDisplaySubtitle(artist, album),
1540
- )
1541
- }
1542
-
1543
- // Phase 19.2 helper: build the `"Artist • Album"` display
1544
- // string used for the notification subtitle. Returns the
1545
- // artist alone when album is blank, or null when both are
1546
- // blank (so the lock-screen widget can collapse to title-only).
1547
- private fun buildDisplaySubtitle(artist: String, album: String): String {
1548
- return when {
1549
- artist.isNotBlank() && album.isNotBlank() -> "$artist • $album"
1550
- artist.isNotBlank() -> artist
1551
- else -> ""
1552
- }
1553
- }
1554
-
1555
- override fun onDestroy() {
1556
- // V20 Phase A: stop listening for engine availability FIRST. The
1557
- // listener closes over `this`, so leaving it registered would keep
1558
- // this destroyed Activity reachable from a process-scoped object and
1559
- // re-run `setMediaSessionMetadata()` against a dead view hierarchy.
1560
- PlaybackHost.cancelWhenAvailable(onEngineAvailable)
1561
- // Step 6.6.1: cleanup the SurfaceView (detach Surface from mpv
1562
- // and zero the native pointer so any late native callback becomes
1563
- // a no-op).
1564
- mpvRenderView?.cleanup()
1565
- // Step 6.6.2: unmount through the library, which both removes the view
1566
- // from the content root and withdraws it from the registry in one
1567
- // identity-checked step. Removing it here without withdrawing it would
1568
- // leave `PlayerSurface` publishing a detached view, and the surface
1569
- // mutators would keep reporting success against a surface with no window.
1570
- mpvRenderView?.let { view -> PlayerSurface.unmount(view) }
1571
- // Step 6.6.3: null the reference.
1572
- mpvRenderView = null
1573
- Log.i(TAG, "onDestroy: MpvRenderView cleaned up and unmounted")
1574
- // V22.0.0 / 1.5.10 (D-034): clear the player-host flag. We set
1575
- // the flag in onCreate before RN mounts; we clear it here so
1576
- // the next time JS asks `isCurrentActivityPlayer()` it sees
1577
- // false. Without this, returning to MainActivity after the
1578
- // user finishes a video would leave the flag stuck at true
1579
- // and SimbaPlayerRoot in MainActivity would wrongly claim
1580
- // every future launchParams.
1581
- com.simba.player.mpv.MpvBridgeModule.currentActivityIsPlayer = false
1582
- // Phase 17.5: stop the progress update runnable. The
1583
- // service is about to stop (below), so the runnable would
1584
- // race with the service teardown on its next tick. Stop
1585
- // here first; the service stop in the next step cancels
1586
- // any final ACTION_UPDATE we might have queued.
1587
- stopProgressUpdates()
1588
- // Phase 40: unregister the ComponentCallbacks2 listener so the
1589
- // activity-scoped reference doesn't pin the listener past onDestroy.
1590
- applicationContext.unregisterComponentCallbacks(trimMemoryListener)
1591
- // Phase 38: abandon audio focus as part of the teardown sequence
1592
- // (matches onPause; idempotent if already abandoned).
1593
- abandonAudioFocus()
1594
- // V20 Phase B: this Activity no longer stops the service or
1595
- // releases the session on its way out.
1596
- //
1597
- // It used to. That is precisely why the notification and the
1598
- // lock-screen widget vanished the moment the player window closed,
1599
- // and why "hide the player" and "shut the player down" were the same
1600
- // verb. Both now belong to the service's own lifecycle: the service
1601
- // stops itself, and releases its session in its own `onDestroy`.
1602
- //
1603
- // What *is* still correct to stop here is everything scoped to this
1604
- // window — the broadcast receiver, the audio focus request, the
1605
- // render view — because those die with the window by design.
1606
- // Phase 10: unregister the PiP action broadcast receiver. Must
1607
- // happen BEFORE the super call so the receiver is gone before
1608
- // the activity is fully torn down (otherwise Android logs a
1609
- // `Receiver not registered` warning if the system fires a
1610
- // trailing broadcast during teardown).
1611
- pipReceiver?.let {
1612
- try {
1613
- unregisterReceiver(it)
1614
- Log.i(TAG, "onDestroy: PipActionReceiver unregistered")
1615
- } catch (e: Exception) {
1616
- Log.w(TAG, "onDestroy: unregisterReceiver threw ${e.message}", e)
1617
- }
1618
- }
1619
- pipReceiver = null
1620
- // Step 6.6.4: super last so React teardown happens after our
1621
- // surface cleanup (the React view tree uses the same content root
1622
- // we're modifying, so ordering matters).
1623
- super.onDestroy()
1624
- Log.i(TAG, "onDestroy: tearing down PlayerActivity")
1625
- }
1626
- }