@simba-dev/react-native-media-player 3.1.0 → 3.3.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.
@@ -1,12 +1,15 @@
1
1
  package com.simba.player.mpv
2
2
 
3
+ import android.app.Activity
3
4
  import android.content.Intent
4
5
  import android.graphics.Bitmap
5
6
  import android.graphics.Rect
6
7
  import android.media.MediaMetadataRetriever
7
8
  import android.util.Log
9
+ import android.view.View
8
10
  import java.io.File
9
11
  import java.io.FileOutputStream
12
+ import java.lang.ref.WeakReference
10
13
  import java.util.concurrent.ExecutorService
11
14
  import java.util.concurrent.Executors
12
15
  import java.util.concurrent.RejectedExecutionException
@@ -19,8 +22,11 @@ import com.facebook.react.bridge.ReactMethod
19
22
  import com.facebook.react.bridge.UiThreadUtil
20
23
  import com.facebook.react.module.annotations.ReactModule
21
24
  import com.facebook.react.modules.core.DeviceEventManagerModule
25
+ import com.facebook.react.uimanager.util.ReactFindViewUtil
22
26
  import com.facebook.fbreact.specs.NativeMpvPlayerSpec
23
27
  import com.simba.player.PlaybackHost
28
+ import com.simba.player.PipManager
29
+ import com.simba.player.PipNativeEntry
24
30
  import org.json.JSONArray
25
31
  import org.json.JSONObject
26
32
 
@@ -68,6 +74,14 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
68
74
  // re-encoding a near-duplicate JPEG on every scroll/re-render.
69
75
  private const val FRAME_POSITION_BUCKET_MS = 30_000L
70
76
 
77
+ // The PiP notification's fallbacks — ONE owner each.
78
+ //
79
+ // The JS path used to inline these two strings, and the native
80
+ // HOME path needs the same two facts for the same one
81
+ // notification. Two owners would be two chances to disagree.
82
+ private const val DEFAULT_PIP_TITLE = "Simba Player"
83
+ private const val DEFAULT_PIP_PROGRESS = "0 %"
84
+
71
85
  // v1.10.0 — hot-path property tracing.
72
86
  //
73
87
  // `time-pos` is mpv's per-frame property, so tracing every property
@@ -132,10 +146,11 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
132
146
  /**
133
147
  * The same policy, mirrored where the COMPANION can read it.
134
148
  *
135
- * `notifyUserLeaveHint()` is a companion function: it is called
136
- * from the consumer's Activity, which has no reference to this
137
- * module instance, so it cannot read the instance field above.
138
- * The instance writes this mirror when it applies the policy.
149
+ * `notifyUserLeaveHint(activity)` is a companion function: it is
150
+ * called from the consumer's Activity, which has no reference to
151
+ * this module instance, so it cannot read the instance field
152
+ * above. The instance writes this mirror when it applies the
153
+ * policy.
139
154
  *
140
155
  * The same pattern `debugLoggingEnabled` uses.
141
156
  */
@@ -143,6 +158,47 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
143
158
  var pipAutoEnterForCompanion: Boolean = false
144
159
  private set
145
160
 
161
+ /**
162
+ * The consumer's chrome `nativeID`, or `null`.
163
+ *
164
+ * Read from `pip.chromeNativeId` in the resolved config. The
165
+ * literal belongs to the CONSUMER: the library stores it and uses
166
+ * it, and never hardcodes one of its own.
167
+ *
168
+ * `null` means "this consumer has no chrome of its own". That is
169
+ * a real answer and not a missing value — the native HOME path
170
+ * then enters PiP without hiding anything.
171
+ */
172
+ @Volatile
173
+ var pipChromeNativeIdForCompanion: String? = null
174
+ private set
175
+
176
+ /**
177
+ * The chrome view the native HOME path hid, so it can be brought
178
+ * back when PiP ends.
179
+ *
180
+ * It is a `View`, so it is held here and nulled out on restore: a
181
+ * stale reference would keep a detached view — and through it the
182
+ * Activity — alive for the rest of the process.
183
+ */
184
+ @Volatile
185
+ private var pipHiddenChromeView: View? = null
186
+
187
+ /**
188
+ * The Activity that asked for the PiP window.
189
+ *
190
+ * The mode-changed callback needs the Activity's window (to find
191
+ * the consumer's chrome) and its resources (for the display
192
+ * density), and it is called while the Activity is PAUSED - so
193
+ * the Activity that asked for the window is remembered here
194
+ * rather than looked up at that moment.
195
+ *
196
+ * Held WEAKLY: a strong reference would pin the Activity, its
197
+ * window and its whole view tree for the rest of the process.
198
+ */
199
+ @Volatile
200
+ private var pipActivityRef: WeakReference<Activity>? = null
201
+
146
202
  /**
147
203
  * Phase 21: recursive JSONObject → Kotlin Map converter. Used
148
204
  * by [setConfig] so the stored config can be consumed
@@ -178,9 +234,96 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
178
234
  * (well before any PiP lifecycle event can fire) to emit the event.
179
235
  * Mirrors the companion sendEvent pattern from
180
236
  * https://yor-dev.com/react-native-picture-in-picture-native-in-android/
237
+ *
238
+ * ## The chrome is hidden HERE, and not where the window is asked for
239
+ *
240
+ * `Activity.onUserLeaveHint()` is called as part of the Activity's
241
+ * PAUSE transaction. There is NO frame between the hide and the
242
+ * pause, so a `visibility = View.GONE` applied there never reaches
243
+ * the pixels: the PiP window is built from the window's LAST
244
+ * RENDERED BUFFER, and that buffer still holds the chrome.
245
+ * Measured on emulator-5554 (API 37) on 2026-11-03: the native
246
+ * hide ran ~40 ms before the OS was asked for the window, and the
247
+ * PiP window still showed the app's full expanded chrome, scaled
248
+ * down, with dead buttons.
249
+ *
250
+ * By the time this callback runs, the platform HAS entered PiP and
251
+ * the Activity's window IS the PiP window - so the hide is painted.
252
+ *
253
+ * ## Two mechanisms keep the app's chrome out of the PiP window,
254
+ * and this callback is the SECOND of them
255
+ *
256
+ * 1. **The crop (primary).** The platform CROPS the app's window to
257
+ * the rect in `PictureInPictureParams.setSourceRectHint(...)`
258
+ * and scales that crop into the PiP window. The library
259
+ * commits that hint EARLY — `Activity.setPictureInPictureParams
260
+ * (...)` — and keeps it current, and the hint is the region of
261
+ * the window the VIDEO occupies. So the chrome around the video
262
+ * is cropped away by the platform itself. (Google's own
263
+ * `androidx.core-pip` does exactly this: it tracks the player
264
+ * view's bounds and feeds them as the source rect.)
265
+ * 2. **The hide (second line of defence, and this callback).** The
266
+ * chrome the app draws OVER the video — the big pause button,
267
+ * the scrub row — is INSIDE the crop, so the crop cannot remove
268
+ * it. It is removed here.
269
+ *
270
+ * ## Why the hide happens HERE and not where the window is asked for
271
+ *
272
+ * `Activity.onUserLeaveHint()` is called as part of the Activity's
273
+ * PAUSE transaction. There is NO frame between the hide and the
274
+ * pause, so a `visibility = View.GONE` applied there never reaches
275
+ * the pixels: the PiP window is built from the window's LAST
276
+ * RENDERED BUFFER, and that buffer still holds the chrome.
277
+ * Measured on emulator-5554 (API 37) on 2026-11-03: the native
278
+ * hide ran ~40 ms before the OS was asked for the window, and the
279
+ * PiP window still showed the app's full expanded chrome, scaled
280
+ * down, with dead buttons.
281
+ *
282
+ * By the time this callback runs, the platform HAS entered PiP and
283
+ * the Activity's window IS the PiP window — and the platform's own
284
+ * documentation says the activity is in a "paused, but rendering"
285
+ * state there, so an invalidation made now IS drawn.
286
+ *
287
+ * @param newConfig the platform's new configuration. It is logged
288
+ * (it carries the PiP WINDOW's size in dp) and the work is
289
+ * done by the single-argument form, which every API level
290
+ * can call.
291
+ */
292
+ fun onPictureInPictureModeChanged(
293
+ isInPictureInPictureMode: Boolean,
294
+ newConfig: android.content.res.Configuration,
295
+ ) {
296
+ Log.i(
297
+ TAG,
298
+ "companion.onPictureInPictureModeChanged: isInPip=$isInPictureInPictureMode " +
299
+ "pipWindowDp=${newConfig.screenWidthDp}x${newConfig.screenHeightDp} " +
300
+ "instance=${instance != null}",
301
+ )
302
+ onPictureInPictureModeChanged(isInPictureInPictureMode)
303
+ }
304
+
305
+ /**
306
+ * The single-argument form of [onPictureInPictureModeChanged] —
307
+ * the one every API level can call.
308
+ *
309
+ * The platform's own `Activity.onPictureInPictureModeChanged(
310
+ * Boolean)` is the API 24-25 callback, and it is also what the
311
+ * consumer's Activity calls.
181
312
  */
182
313
  fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean) {
183
314
  Log.i(TAG, "companion.onPictureInPictureModeChanged: isInPip=$isInPictureInPictureMode instance=${instance != null}")
315
+ // The chrome comes back when PiP ends — and it comes back EVEN
316
+ // IF the React instance is gone: the view is a native one, and
317
+ // the app is showing it (or not showing it) either way. So the
318
+ // restore happens BEFORE the instance check below.
319
+ //
320
+ // The hide is native view work too, and it happens for the same
321
+ // reason: it is what the PiP window paints.
322
+ if (isInPictureInPictureMode) {
323
+ hideConsumerChrome()
324
+ } else {
325
+ restoreConsumerChrome()
326
+ }
184
327
  val ctx = instance ?: run {
185
328
  Log.w(TAG, "onPictureInPictureModeChanged: module instance not initialized yet")
186
329
  return
@@ -214,49 +357,544 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
214
357
  }
215
358
 
216
359
  /**
217
- * Called from the consumer's `Activity.onUserLeaveHint()` - the
218
- * user is leaving the app (home, recents, app switcher).
360
+ * The Activity the PiP window belongs to: the one that asked for
361
+ * it, or - when the platform entered PiP on its own - the Activity
362
+ * React Native currently has.
363
+ */
364
+ private fun pipActivity(): Activity? =
365
+ pipActivityRef?.get() ?: instance?.currentActivity
366
+
367
+ /**
368
+ * Remember the Activity that asked for the PiP window.
369
+ *
370
+ * Held WEAKLY: a strong reference would pin the Activity, its
371
+ * window and its whole view tree for the rest of the process.
372
+ */
373
+ private fun rememberPipActivity(activity: Activity) {
374
+ pipActivityRef = WeakReference(activity)
375
+ }
376
+
377
+ /**
378
+ * The ONE owner of "where the consumer's chrome is".
379
+ *
380
+ * The literal belongs to the CONSUMER: the library stores it and
381
+ * uses it, and never hardcodes one of its own.
382
+ *
383
+ * `ReactFindViewUtil` is React Native's own lookup: it walks the
384
+ * native View tree for the tag RN sets for the `nativeID` prop
385
+ * (`BaseViewManager.setNativeId`), which Fabric calls through the
386
+ * same setter.
387
+ *
388
+ * @return the chrome view, or `null` when the consumer has no
389
+ * chrome id or when no view carries it.
390
+ */
391
+ private fun findConsumerChromeView(root: View?): View? {
392
+ val chromeNativeId = pipChromeNativeIdForCompanion ?: return null
393
+ return root?.let { ReactFindViewUtil.findView(it, chromeNativeId) }
394
+ }
395
+
396
+ /**
397
+ * Hide the consumer's chrome, so the PiP window paints the
398
+ * picture and nothing else.
399
+ *
400
+ * A `null` view is NOT a failure. It means the chrome is ALREADY
401
+ * gone: the consumer's own BUTTON path unmounts the chrome in
402
+ * React before it asks for the window, and React's unmount
403
+ * removes the view from the tree. So there is nothing left to
404
+ * hide, the PiP entry continues, and nothing is refused.
405
+ */
406
+ private fun hideConsumerChrome() {
407
+ val chromeNativeId = pipChromeNativeIdForCompanion
408
+ if (chromeNativeId == null) {
409
+ // This consumer has no chrome of its own: the library
410
+ // ships none of its own, and there is nothing to hide.
411
+ return
412
+ }
413
+ val chromeView = findConsumerChromeView(pipActivity()?.window?.decorView)
414
+ if (chromeView == null) {
415
+ Log.i(
416
+ TAG,
417
+ "companion.hideConsumerChrome: no view carries the chrome nativeID " +
418
+ "'$chromeNativeId'; it is already hidden",
419
+ )
420
+ return
421
+ }
422
+ chromeView.visibility = View.GONE
423
+ pipHiddenChromeView = chromeView
424
+ Log.i(
425
+ TAG,
426
+ "companion.hideConsumerChrome: hid the chrome view with nativeID " +
427
+ "'$chromeNativeId'",
428
+ )
429
+ }
430
+
431
+ /**
432
+ * The HOME path: enter Picture-in-Picture NATIVELY, from the
433
+ * consumer's `Activity.onUserLeaveHint()` — the moment the user
434
+ * is leaving the app (home, recents, app switcher).
435
+ *
436
+ * ## Why NATIVE, and why HERE
219
437
  *
220
- * The consumer needs this because the PiP ENTRY has to be in the
221
- * consumer's hands, not the platform's: an Activity in PiP does
222
- * not redraw, so a consumer that draws its own chrome over the
223
- * picture has to remove that chrome BEFORE the window is frozen.
224
- * The platform's own auto-enter switch cannot give it that
225
- * chance - see `PipManager.buildPipParams` for the measurement.
438
+ * `onUserLeaveHint()` is the ONLY pre-pause hook Android offers.
226
439
  *
227
- * So the library's job is to say WHEN, and the consumer decides
228
- * whether to act: it removes its chrome, lets the frame that drew
229
- * it go by, and then asks the OS for the window itself.
440
+ * And by the time this runs, React Native has ALREADY frozen, in
441
+ * TWO ways: `FabricUIManager.onHostPause()` removes the DISPATCH_UI
442
+ * frame callback, so mount items are never applied to native views,
443
+ * and `JavaTimerManager.onHostPause()` freezes the timer registry,
444
+ * so `requestAnimationFrame` never fires. The JS runtime itself
445
+ * keeps running. Measured on emulator-5554 (API 37) on 2026-11-03:
446
+ * the JS handler ran immediately, the effect that would have
447
+ * driven the entry ran 5.7 s late, and the
448
+ * `requestAnimationFrame` never fired — so the chrome was still
449
+ * mounted when the OS took the window.
230
450
  *
231
- * The auto-enter policy is the consumer's own `pip.autoEnterOnLeave`
232
- * config, so this is a no-op when the consumer does not want
233
- * auto-enter.
451
+ * So the ENTRY happens HERE, in native code. The chrome is NOT
452
+ * hidden here: there is no frame between this hook and the pause,
453
+ * so a hide applied here never reaches the pixels. The chrome is
454
+ * hidden from `onPictureInPictureModeChanged(true)`, after the
455
+ * platform has entered PiP.
456
+ *
457
+ * ## What it refuses, and why
458
+ *
459
+ * - auto-enter off — that is the consumer's own policy
460
+ * (`pip.autoEnterOnLeave`), and the library honours it;
461
+ * - already in PiP — HOME pressed inside PiP must not re-enter;
462
+ * - no media loaded — a PiP window for a stopped session is a
463
+ * bug, and the facts are read from mpv, never from a JS flag.
464
+ *
465
+ * It refuses NOTHING about the chrome: a chrome id that no view
466
+ * carries means the chrome is already gone, and the entry goes on.
467
+ *
468
+ * @param activity the Activity that is leaving. It is the window
469
+ * the PiP entry applies to.
470
+ * @return `true` when the Activity entered Picture-in-Picture (or,
471
+ * on API 31+, when the platform's own auto-enter switch is
472
+ * armed and will enter it as soon as this returns), `false`
473
+ * when it did not.
234
474
  */
235
- fun notifyUserLeaveHint() {
475
+ fun notifyUserLeaveHint(activity: Activity): Boolean {
236
476
  Log.i(
237
477
  TAG,
238
478
  "companion.notifyUserLeaveHint: autoEnter=$pipAutoEnterForCompanion " +
239
- "instance=${instance != null}",
479
+ "chromeNativeId=${pipChromeNativeIdForCompanion ?: "(none)"}",
240
480
  )
481
+ // Platform precondition, not a policy: Picture-in-Picture
482
+ // itself needs API 24, and `isInPictureInPictureMode` does
483
+ // not exist below it.
484
+ if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) {
485
+ Log.w(TAG, "companion.notifyUserLeaveHint: refused: SDK < N")
486
+ return false
487
+ }
488
+ // 1. The consumer's policy comes first.
241
489
  if (!pipAutoEnterForCompanion) {
490
+ Log.i(TAG, "companion.notifyUserLeaveHint: auto-enter is off; not entering PiP")
491
+ return false
492
+ }
493
+ // 2. Already in PiP: HOME pressed inside PiP must not enter
494
+ // again — the OS would refuse it, and the refusal would
495
+ // be read as "PiP failed".
496
+ if (activity.isInPictureInPictureMode) {
497
+ Log.i(TAG, "companion.notifyUserLeaveHint: already in PiP; not entering again")
498
+ return false
499
+ }
500
+ // 3. No media loaded: a PiP window for a stopped session is
501
+ // a bug, not a feature.
502
+ if (!isMediaLoaded()) {
503
+ Log.i(TAG, "companion.notifyUserLeaveHint: no media loaded; not entering PiP")
504
+ return false
505
+ }
506
+ // 4. The chrome, when the consumer has one. The literal is
507
+ // the consumer's — the library never hardcodes one. The
508
+ // lookup here is a DIAGNOSTIC: the chrome is hidden from
509
+ // `onPictureInPictureModeChanged(true)`, because a hide
510
+ // applied now would never reach the pixels.
511
+ val chromeNativeId = pipChromeNativeIdForCompanion
512
+ if (chromeNativeId != null) {
513
+ val chromeView = findConsumerChromeView(activity.window?.decorView)
242
514
  Log.i(
243
515
  TAG,
244
- "companion.notifyUserLeaveHint: auto-enter is off; not telling the consumer",
516
+ "companion.notifyUserLeaveHint: the chrome view with nativeID " +
517
+ "'$chromeNativeId' is " +
518
+ if (chromeView == null) "not mounted (already hidden)" else "mounted",
245
519
  )
246
- return
247
520
  }
248
- val ctx = instance ?: run {
249
- Log.w(TAG, "notifyUserLeaveHint: module instance not initialized yet")
250
- return
521
+ rememberPipActivity(activity)
522
+ // 5. Commit the params BEFORE the window is asked for.
523
+ //
524
+ // The platform builds the PiP window from the LAST
525
+ // COMMITTED params, and the source rect hint in them is
526
+ // the rect it CROPS the app's window to. Params handed
527
+ // over only at the entry moment never crop anything, so
528
+ // the PiP window shows the whole window — the app's chrome
529
+ // included — scaled down.
530
+ commitPipParams(activity)
531
+ // 6. On API 31+ the PLATFORM enters PiP by itself, from the
532
+ // auto-enter switch in the committed params. ATMS refuses
533
+ // an explicit `enterPictureInPictureMode()` while
534
+ // auto-enter is enabled ("auto-enter should take in place
535
+ // instead"), so asking for the window here would be
536
+ // refused — and a refusal read as "PiP failed".
537
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
538
+ Log.i(
539
+ TAG,
540
+ "companion.notifyUserLeaveHint: auto-enter is armed; the platform enters PiP",
541
+ )
542
+ return true
251
543
  }
544
+ // 7. API 24-30: the explicit entry is the only way in.
545
+ val entered = enterPictureInPicture(activity)
546
+ if (!entered) {
547
+ Log.w(TAG, "companion.notifyUserLeaveHint: the OS refused the PiP entry")
548
+ return false
549
+ }
550
+ Log.i(TAG, "companion.notifyUserLeaveHint: entered PiP")
551
+ return true
552
+ }
553
+
554
+ /**
555
+ * Commit the CURRENT PiP params to the Activity.
556
+ *
557
+ * ## Why the params are committed EARLY
558
+ *
559
+ * The platform builds the PiP window from the LAST COMMITTED
560
+ * params — `Activity.setPictureInPictureParams(...)` — and the
561
+ * source rect hint among them is the rect it CROPS the app's
562
+ * window to. A hint handed over only at the entry moment never
563
+ * crops anything: the PiP window then shows the whole window,
564
+ * scaled down, with the app's chrome in it. Measured on
565
+ * emulator-5554 (API 37) on 2026-11-03: the PiP window showed the
566
+ * app's full expanded chrome, scaled down, with dead buttons.
567
+ *
568
+ * Google's own `androidx.core-pip` does exactly this — it tracks
569
+ * the player view's bounds and commits the params as they change.
570
+ *
571
+ * So the params are committed when the picture's geometry
572
+ * changes, when the video's aspect changes, and when the playback
573
+ * state changes (the action's icon is state-driven).
574
+ */
575
+ private fun commitPipParams(activity: Activity) {
576
+ // `setPictureInPictureParams` needs API 26. Below it the
577
+ // params only matter at the entry moment.
578
+ if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) return
579
+ val params = buildCurrentPipParams(activity)
252
580
  try {
253
- ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
254
- .emit("onUserLeaveHint", Arguments.createMap())
255
- Log.i(TAG, "companion.notifyUserLeaveHint: emit succeeded")
581
+ activity.setPictureInPictureParams(params)
582
+ Log.i(TAG, "companion.commitPipParams: committed the PiP params")
583
+ } catch (t: Throwable) {
584
+ Log.w(TAG, "companion.commitPipParams: setPictureInPictureParams threw", t)
585
+ }
586
+ }
587
+
588
+ /**
589
+ * Re-commit the PiP params, on the UI thread.
590
+ *
591
+ * The Activity's params have to be set on the UI thread, and the
592
+ * callers of this are not always on it (the bridge's commands run
593
+ * on the module queue).
594
+ */
595
+ fun onPlaybackStateChanged() {
596
+ UiThreadUtil.runOnUiThread {
597
+ val activity = instance?.currentActivity ?: return@runOnUiThread
598
+ commitPipParams(activity)
599
+ }
600
+ }
601
+
602
+ /**
603
+ * Re-commit the PiP params after the picture's geometry changed.
604
+ *
605
+ * The source rect hint is the region of the window the video
606
+ * occupies, so a moved or resized picture makes the committed
607
+ * hint stale. Called from the picture view's layout callback, on
608
+ * the UI thread.
609
+ */
610
+ fun onPictureBoundsChanged() {
611
+ val activity = instance?.currentActivity ?: return
612
+ commitPipParams(activity)
613
+ }
614
+
615
+ /**
616
+ * The params the platform should be building the PiP window from,
617
+ * right now.
618
+ *
619
+ * The ONE builder is `PipManager.buildPipParams`; this is the ONE
620
+ * place that gathers the facts it needs.
621
+ */
622
+ @androidx.annotation.RequiresApi(android.os.Build.VERSION_CODES.O)
623
+ private fun buildCurrentPipParams(
624
+ activity: Activity,
625
+ chapterTitle: String? = null,
626
+ progressPct: String? = null,
627
+ ): android.app.PictureInPictureParams {
628
+ // The rect of the window the VIDEO occupies. The platform crops
629
+ // the app's window to it, so it is what keeps the app's chrome
630
+ // out of the PiP window.
631
+ val frame = pipSourceRectInWindow()
632
+ // The PiP window's shape is the loaded video's shape, and it is
633
+ // taken from the SAME frame as the hint, so the two agree by
634
+ // construction.
635
+ val aspect = frame?.aspect ?: currentVideoAspect() ?: (16f / 9f)
636
+ val sourceRect = frame?.let { Rect(it.left, it.top, it.right, it.bottom) }
637
+ return PipManager.buildPipParams(
638
+ context = activity,
639
+ aspect = aspect,
640
+ sourceRectHint = sourceRect,
641
+ // The consumer's own title wins when it gave one; the rest
642
+ // is read from mpv, which is the same fact.
643
+ chapterTitle = chapterTitle ?: nativeTitle() ?: DEFAULT_PIP_TITLE,
644
+ progressPercentage = progressPct ?: nativeProgressPct() ?: DEFAULT_PIP_PROGRESS,
645
+ playing = isPlaying(),
646
+ // Auto-enter is armed ONLY while media is loaded: the
647
+ // platform would otherwise throw the user into a PiP
648
+ // window of a stopped session.
649
+ autoEnter = isMediaLoaded(),
650
+ )
651
+ }
652
+
653
+ /**
654
+ * Whether the engine is playing right now.
655
+ *
656
+ * Read from mpv's `playback-state` at the moment of use, never
657
+ * from a JS flag: the PiP action's icon has to be true even when
658
+ * the app is paused and no JS is running.
659
+ */
660
+ private fun isPlaying(): Boolean {
661
+ val ptr = PlaybackHost.handle()
662
+ if (ptr == 0L) return false
663
+ return try {
664
+ PipNativeEntry.isPlaying(MPVLib.nativeGetProperty(ptr, "playback-state"))
665
+ } catch (e: Exception) {
666
+ Log.w(TAG, "companion.isPlaying: reading playback-state failed", e)
667
+ false
668
+ }
669
+ }
670
+
671
+ /**
672
+ * The ONE owner of "how a PiP window is built".
673
+ *
674
+ * Both entry paths come through here:
675
+ * - the JS path — `enterPip(chapterTitle, progressPct)`, the
676
+ * consumer's own button;
677
+ * - the native path — `notifyUserLeaveHint(activity)`, the HOME
678
+ * button.
679
+ *
680
+ * One builder, one set of facts, one place where the OS's answer
681
+ * is read. A second, slightly different params builder is how
682
+ * those two paths would drift apart.
683
+ *
684
+ * @return the OS's own answer: `true` when the Activity entered
685
+ * Picture-in-Picture, `false` when it refused (or the
686
+ * call threw).
687
+ */
688
+ private fun enterPictureInPicture(
689
+ activity: Activity,
690
+ chapterTitle: String? = null,
691
+ progressPct: String? = null,
692
+ ): Boolean {
693
+ // `return try`, not a bare `try`. A `try`/`catch` in
694
+ // STATEMENT position is not this function's return value in
695
+ // Kotlin — not even as the last statement of a function with
696
+ // a non-`Unit` return type. Only an EXPRESSION `try` produces
697
+ // a value, and the branches inside it are the ones that carry
698
+ // the OS's answer.
699
+ return try {
700
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
701
+ // The ONE params builder: the same facts, the same
702
+ // rect, the same action — as the ones the library
703
+ // commits to the Activity outside the entry moment.
704
+ val pipParams = buildCurrentPipParams(activity, chapterTitle, progressPct)
705
+ // `enterPictureInPictureMode` ANSWERS whether the OS
706
+ // accepted the request, and the answer is the only
707
+ // authority on this.
708
+ activity.enterPictureInPictureMode(pipParams)
709
+ } else {
710
+ // API 24–25 support PiP but not PictureInPictureParams.
711
+ // The no-arg overload returns Unit, so those versions
712
+ // have no answer to relay; the PiP mode-change event is
713
+ // the only confirmation available there.
714
+ activity.enterPictureInPictureMode()
715
+ true
716
+ }
717
+ } catch (throwable: Throwable) {
718
+ // `enterPictureInPictureMode` can throw
719
+ // `IllegalArgumentException` (bad params),
720
+ // `RuntimeException` (OEM customisations), or
721
+ // `SecurityException` (PiP not permitted). We log the
722
+ // actual cause, and the `false` below tells the caller
723
+ // that PiP did NOT happen.
724
+ Log.w(TAG, "[PlaybackTrace][Bridge][enterPip:threw]", throwable)
725
+ false
726
+ }
727
+ }
728
+
729
+ /**
730
+ * Bring the hidden chrome back, and forget it.
731
+ *
732
+ * Called when PiP ends (`onPictureInPictureModeChanged(false)`).
733
+ */
734
+ private fun restoreConsumerChrome() {
735
+ val view = pipHiddenChromeView ?: return
736
+ pipHiddenChromeView = null
737
+ try {
738
+ view.visibility = View.VISIBLE
739
+ Log.i(TAG, "companion.restoreConsumerChrome: restored the chrome view")
740
+ } catch (e: Exception) {
741
+ Log.w(TAG, "companion.restoreConsumerChrome: restoring the chrome view failed", e)
742
+ }
743
+ }
744
+
745
+ /**
746
+ * Whether mpv currently has media loaded.
747
+ *
748
+ * Read live through [PlaybackHost] — never from a JS flag, which
749
+ * can be stale by the time the user presses HOME. The question
750
+ * is mpv's own `playback-state`: `idle` and `stopped` are its
751
+ * "no media" states, and everything else (`loading`, `play`,
752
+ * `pause`, `eof-reached`) means something is still loaded.
753
+ */
754
+ private fun isMediaLoaded(): Boolean {
755
+ val ptr = PlaybackHost.handle()
756
+ if (ptr == 0L) return false
757
+ return try {
758
+ val state = MPVLib.nativeGetProperty(ptr, "playback-state").trim().trim('"')
759
+ state.isNotEmpty() && state != "idle" && state != "stopped"
760
+ } catch (e: Exception) {
761
+ // The native lease guard refuses calls against a
762
+ // destroyed engine; that is a normal outcome, not a
763
+ // crash.
764
+ Log.w(TAG, "companion.notifyUserLeaveHint: reading playback-state failed", e)
765
+ false
766
+ }
767
+ }
768
+
769
+ /**
770
+ * The title for the PiP notification, read from mpv.
771
+ *
772
+ * mpv's `media-title` IS the title the consumer supplied: the
773
+ * library writes it as mpv's `force-media-title` BEFORE the load
774
+ * (mpv reads that option at load time), and mpv reports it back
775
+ * under `media-title`. Same fact, not a second one.
776
+ */
777
+ private fun nativeTitle(): String? {
778
+ val ptr = PlaybackHost.handle()
779
+ if (ptr == 0L) return null
780
+ return try {
781
+ PipNativeEntry.title(MPVLib.nativeGetProperty(ptr, "media-title"))
782
+ } catch (e: Exception) {
783
+ Log.w(TAG, "companion.notifyUserLeaveHint: reading media-title failed", e)
784
+ null
785
+ }
786
+ }
787
+
788
+ /**
789
+ * The progress percentage for the PiP notification, read from
790
+ * mpv: `time-pos` over `duration`, in the consumer's exact
791
+ * `"NN %"` format.
792
+ *
793
+ * mpv reports both in SECONDS; the consumer's format works in
794
+ * milliseconds, so the values are converted before they are
795
+ * divided. The ratio is the same either way, but the rounding
796
+ * is not, so the units are made to match before the fact is
797
+ * computed.
798
+ */
799
+ private fun nativeProgressPct(): String? {
800
+ val ptr = PlaybackHost.handle()
801
+ if (ptr == 0L) return null
802
+ return try {
803
+ val positionSec =
804
+ MPVLib.nativeGetProperty(ptr, "time-pos").trim().trim('"').toDoubleOrNull()
805
+ val durationSec =
806
+ MPVLib.nativeGetProperty(ptr, "duration").trim().trim('"').toDoubleOrNull()
807
+ if (positionSec == null || durationSec == null) return null
808
+ PipNativeEntry.progressPct(
809
+ Math.round(positionSec * 1000.0),
810
+ Math.round(durationSec * 1000.0),
811
+ )
812
+ } catch (e: Exception) {
813
+ Log.w(TAG, "companion.notifyUserLeaveHint: reading time-pos/duration failed", e)
814
+ null
815
+ }
816
+ }
817
+
818
+ /**
819
+ * Display aspect (width / height) of the loaded video, or `null`
820
+ * when it is not known.
821
+ *
822
+ * Reads the same `width` / `height` properties as
823
+ * [getVideoParams]. Null is the honest answer for "no file
824
+ * loaded" and for "audio only" — both are real, expected states
825
+ * rather than failures — and callers decide what a shape-less
826
+ * PiP window means for them.
827
+ */
828
+ private fun currentVideoAspect(): Float? {
829
+ val ptr = PlaybackHost.handle()
830
+ if (ptr == 0L) return null
831
+ return try {
832
+ val w = MPVLib.nativeGetProperty(ptr, "width").trim().trim('"').toDoubleOrNull()
833
+ val h = MPVLib.nativeGetProperty(ptr, "height").trim().trim('"').toDoubleOrNull()
834
+ if (w != null && h != null && w > 0.0 && h > 0.0) (w / h).toFloat() else null
256
835
  } catch (e: Exception) {
257
- Log.w(TAG, "notifyUserLeaveHint: emit threw", e)
836
+ // The native lease guard refuses reads against a destroyed engine.
837
+ Log.w(TAG, "[PlaybackTrace][Bridge][currentVideoAspect] ${e.message}")
838
+ null
258
839
  }
259
840
  }
841
+
842
+ /**
843
+ * The rect of the window the video actually occupies, or `null`
844
+ * when there is no such rect.
845
+ *
846
+ * ## What the rect is, and what the platform does with it
847
+ *
848
+ * Android's `setSourceRectHint` wants the region of the window where
849
+ * the video is. The platform CROPS the app's window to that rect and
850
+ * scales the crop into the PiP window — which is what keeps the
851
+ * app's chrome out of the PiP window, because the chrome around the
852
+ * video is outside the crop.
853
+ *
854
+ * It is **not** the picture view's box. The picture fills its lane
855
+ * (`StyleSheet.absoluteFill`), so the view's rect is the whole window,
856
+ * and hinting that would crop the whole window into the PiP window —
857
+ * the app's chrome included, scaled down. The rect has to be the
858
+ * video's FRAME inside the view: the largest rect of the video's own
859
+ * shape that fits inside it, or the whole view when the picture is
860
+ * filling it.
861
+ *
862
+ * ## Where the numbers come from
863
+ *
864
+ * - the view's rect — `MpvRenderView.cachedWindowBounds`, published by
865
+ * the UI thread on layout, because `getLocationInWindow()` is a
866
+ * UI-thread API and this code runs on the bridge thread.
867
+ * - the video's shape — `currentVideoAspect()`, the same `width` /
868
+ * `height` properties `getVideoParams` reads.
869
+ * - the fill — `MpvRenderView.currentFillsView`, whether the picture
870
+ * mpv is rendering with right now FILLS its view (`cover`, `stretch`)
871
+ * or FITS inside it (`contain`, the default).
872
+ *
873
+ * ## Why every step can answer `null`
874
+ *
875
+ * `null` is the honest answer when there is no video rect to point at:
876
+ * no live picture, no layout yet, or no video dimensions. It degrades to
877
+ * the platform's no-hint behaviour, which costs a black transition but
878
+ * never a distorted one.
879
+ *
880
+ * The reader this replaces (`PlayerSurface.boundsInWindow`) answered
881
+ * `null` **unconditionally** — it read a registry the V22 architecture
882
+ * has no writer for — so PiP entry always grew out of a black
883
+ * rectangle. That was the bug.
884
+ */
885
+ private fun pipSourceRectInWindow(): PictureFrame? {
886
+ val view = MpvRenderViewRegistry.current() ?: return null
887
+ val bounds = view.cachedWindowBounds ?: return null
888
+ val aspect = currentVideoAspect() ?: return null
889
+ return PipSourceRect.frameInWindow(
890
+ bounds.left,
891
+ bounds.top,
892
+ bounds.width,
893
+ bounds.height,
894
+ aspect,
895
+ view.currentFillsView,
896
+ )
897
+ }
260
898
  }
261
899
 
262
900
  init {
@@ -360,13 +998,13 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
360
998
  "surfaceAttached" -> "onSurfaceAttached"
361
999
  else -> event
362
1000
  }
363
- // The video's dimensions just changed. Nothing has to be
364
- // refreshed here any more: the params the platform reads are
365
- // the ones the CONSUMER's entry carries, and the consumer
366
- // builds them at the moment it asks for the window - by then
367
- // it knows the video's current shape. (The platform's own
368
- // auto-enter switch, which used to read params stashed on the
369
- // activity, is gone: see `PipManager.buildPipParams`.)
1001
+ // The video's dimensions just changed, so the committed PiP
1002
+ // params are stale: they carry the video's aspect and the rect
1003
+ // it occupies in the window, and the platform builds the PiP
1004
+ // window from the LAST COMMITTED params.
1005
+ if (event == "fileLoaded") {
1006
+ onPlaybackStateChanged()
1007
+ }
370
1008
  try {
371
1009
  val payload = JsonUtil.jsonStringToReactMap(jsonPayload)
372
1010
  eventEmitter.emit(jsEvent, payload)
@@ -808,6 +1446,9 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
808
1446
  Log.i(TAG, "[PlaybackTrace][Bridge][play] ptr=$nativePtr")
809
1447
  MPVLib.nativePlay(nativePtr)
810
1448
  Log.i(TAG, "[PlaybackTrace][Bridge][play] nativePlay returned")
1449
+ // The PiP action's icon is state-driven, so the committed params
1450
+ // have to follow the playback state.
1451
+ onPlaybackStateChanged()
811
1452
  }
812
1453
 
813
1454
  @ReactMethod
@@ -817,6 +1458,9 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
817
1458
  Log.i(TAG, "[PlaybackTrace][Bridge][pause] ptr=$nativePtr")
818
1459
  MPVLib.nativePause(nativePtr)
819
1460
  Log.i(TAG, "[PlaybackTrace][Bridge][pause] nativePause returned")
1461
+ // The PiP action's icon is state-driven, so the committed params
1462
+ // have to follow the playback state.
1463
+ onPlaybackStateChanged()
820
1464
  }
821
1465
 
822
1466
  @ReactMethod
@@ -825,6 +1469,10 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
825
1469
  ensurePtr()
826
1470
  Log.i(TAG, "[PlaybackTrace][Bridge][stop] ptr=$nativePtr")
827
1471
  MPVLib.nativeStop(nativePtr)
1472
+ // A stopped session has no media, so the auto-enter switch has to
1473
+ // be disarmed: the platform must not throw the user into a PiP
1474
+ // window of a stopped session.
1475
+ onPlaybackStateChanged()
828
1476
  }
829
1477
 
830
1478
  @ReactMethod
@@ -832,6 +1480,9 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
832
1480
  override fun togglePlayPause() {
833
1481
  ensurePtr()
834
1482
  MPVLib.nativeTogglePlayPause(nativePtr)
1483
+ // The PiP action's icon is state-driven, so the committed params
1484
+ // have to follow the playback state.
1485
+ onPlaybackStateChanged()
835
1486
  }
836
1487
 
837
1488
  @ReactMethod
@@ -2332,6 +2983,10 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2332
2983
  // was a documented public flag that nothing read, so pressing
2333
2984
  // home never entered PiP - the value was already here.
2334
2985
  applyPipAutoEnterOnLeave(parsed)
2986
+ // The chrome `nativeID` belongs to the consumer, and it is
2987
+ // applied on EVERY push - so a config that does not carry it
2988
+ // leaves the value at `null` instead of keeping a stale one.
2989
+ applyPipChromeNativeId(parsed)
2335
2990
  val keys = parsed?.keys?.sorted()?.joinToString(", ") ?: "(none)"
2336
2991
  Log.i(
2337
2992
  TAG,
@@ -2353,8 +3008,8 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2353
3008
  }
2354
3009
 
2355
3010
  /**
2356
- * Apply `pip.autoEnterOnLeave` — remember the policy, and tell the
2357
- * CONSUMER when the user leaves.
3011
+ * Apply `pip.autoEnterOnLeave` — remember the policy, so the
3012
+ * native HOME path knows whether to enter PiP at all.
2358
3013
  *
2359
3014
  * What this does NOT do any more: arm the platform's own switch
2360
3015
  * (`PictureInPictureParams.Builder.setAutoEnterEnabled`, API 31+).
@@ -2368,12 +3023,12 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2368
3023
  * down. Measured on device on 2026-11-03.
2369
3024
  * See `PipManager.buildPipParams` for the full account.
2370
3025
  *
2371
- * What it does now: the policy is remembered (so
2372
- * `notifyUserLeaveHint()` can decide whether to speak at all), and
2373
- * when the consumer's Activity reports that the user is leaving, the
2374
- * consumer is told through the `onUserLeaveHint` event. The consumer
2375
- * then removes its chrome, lets the frame that drew it go by, and
2376
- * asks the OS for the window itself.
3026
+ * What it does now: the policy is remembered, and the consumer's
3027
+ * Activity reports that the user is leaving by calling
3028
+ * `MpvBridgeModule.notifyUserLeaveHint(activity)`. The library then
3029
+ * hides the consumer's chrome NATIVELY and asks the OS for the window
3030
+ * itself - in that order, and inside `onUserLeaveHint()`, because by
3031
+ * then no React commit can land.
2377
3032
  *
2378
3033
  * The consumer's Activity must override `onUserLeaveHint()` and
2379
3034
  * declare `android:supportsPictureInPicture="true"`. Both are the
@@ -2387,14 +3042,14 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2387
3042
  try {
2388
3043
  val desired = PipAutoEnterPolicy.desiredAutoEnter(config) ?: return
2389
3044
  pipAutoEnter = desired
2390
- // The policy is remembered so `notifyUserLeaveHint()` knows
2391
- // whether to tell the consumer that it should enter PiP. The
2392
- // platform's OWN auto-enter switch is NOT armed: the system
2393
- // would transition the activity before the consumer could
2394
- // remove its chrome, and React cannot commit a frame while
2395
- // the Activity is paused - so the consumer's chrome would be
2396
- // still mounted in the PiP window, dead and scaled down. See
2397
- // `PipManager.buildPipParams` for the measurement.
3045
+ // The policy is remembered so `notifyUserLeaveHint(activity)`
3046
+ // knows whether to enter PiP at all. The platform's OWN
3047
+ // auto-enter switch is NOT armed: the system would transition
3048
+ // the activity before the chrome could be hidden, and React
3049
+ // cannot commit a frame while the Activity is paused - so the
3050
+ // chrome would be still mounted in the PiP window, dead and
3051
+ // scaled down. See `PipManager.buildPipParams` for the
3052
+ // measurement.
2398
3053
  pipAutoEnterForCompanion = desired
2399
3054
  } catch (t: Throwable) {
2400
3055
  // Never let this reject the `setConfig` promise: the config
@@ -2405,58 +3060,35 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2405
3060
  }
2406
3061
 
2407
3062
  /**
2408
- * The rect of the window the video actually occupies, or `null` when
2409
- * there is no such rect.
2410
- *
2411
- * ## What the rect is
2412
- *
2413
- * Android's `setSourceRectHint` wants the region of the window where the
2414
- * video is, so PiP entry animates the real frame into the PiP window
2415
- * instead of growing out of a black rectangle.
2416
- *
2417
- * It is **not** the picture view's box. The picture fills its lane
2418
- * (`StyleSheet.absoluteFill`), so the view's rect is the whole window,
2419
- * and hinting that would make the PiP window take the window's shape —
2420
- * portrait on a phone — with the video arriving tiny and letterboxed
2421
- * inside it. The rect has to be the video's FRAME inside the view: the
2422
- * largest rect of the video's own shape that fits inside it, or the
2423
- * whole view when the picture is filling it.
2424
- *
2425
- * ## Where the numbers come from
2426
- *
2427
- * - the view's rect — `MpvRenderView.cachedWindowBounds`, published by
2428
- * the UI thread on layout, because `getLocationInWindow()` is a
2429
- * UI-thread API and this code runs on the bridge thread.
2430
- * - the video's shape — `currentVideoAspect()`, the same `width` /
2431
- * `height` properties `getVideoParams` reads.
2432
- * - the fill — `MpvRenderView.currentFillsView`, whether the picture
2433
- * mpv is rendering with right now FILLS its view (`cover`, `stretch`)
2434
- * or FITS inside it (`contain`, the default).
2435
- *
2436
- * ## Why every step can answer `null`
2437
- *
2438
- * `null` is the honest answer when there is no video rect to point at:
2439
- * no live picture, no layout yet, or no video dimensions. It degrades to
2440
- * the platform's no-hint behaviour, which costs a black transition but
2441
- * never a distorted one.
2442
- *
2443
- * The reader this replaces (`PlayerSurface.boundsInWindow`) answered
2444
- * `null` **unconditionally** — it read a registry the V22 architecture
2445
- * has no writer for — so PiP entry always grew out of a black
2446
- * rectangle. That was the bug.
3063
+ * Apply `pip.chromeNativeId` — remember the consumer's chrome
3064
+ * `nativeID`.
3065
+ *
3066
+ * The literal belongs to the CONSUMER: the library stores it and uses
3067
+ * it, and never hardcodes one of its own. `null` means "this consumer
3068
+ * has no chrome of its own", which is a real answer and not a missing
3069
+ * value — the native HOME path then enters PiP without hiding
3070
+ * anything.
3071
+ *
3072
+ * Applied on EVERY config push, so a config that does not carry the
3073
+ * id leaves the value at `null` instead of keeping a stale one from
3074
+ * an earlier push.
3075
+ *
3076
+ * @param config the RESOLVED config map, as parsed by `setConfig`.
2447
3077
  */
2448
- private fun pipSourceRectInWindow(): PictureFrame? {
2449
- val view = MpvRenderViewRegistry.current() ?: return null
2450
- val bounds = view.cachedWindowBounds ?: return null
2451
- val aspect = currentVideoAspect() ?: return null
2452
- return PipSourceRect.frameInWindow(
2453
- bounds.left,
2454
- bounds.top,
2455
- bounds.width,
2456
- bounds.height,
2457
- aspect,
2458
- view.currentFillsView,
2459
- )
3078
+ private fun applyPipChromeNativeId(config: Map<String, Any?>?) {
3079
+ try {
3080
+ pipChromeNativeIdForCompanion = PipNativeEntry.chromeNativeId(config)
3081
+ Log.i(
3082
+ TAG,
3083
+ "[PlaybackTrace][Bridge][pip] chrome nativeID = " +
3084
+ (pipChromeNativeIdForCompanion ?: "(none)"),
3085
+ )
3086
+ } catch (t: Throwable) {
3087
+ // Never let this reject the `setConfig` promise: the config
3088
+ // itself was stored fine, and a rejected promise would tell
3089
+ // the consumer its WHOLE configuration failed.
3090
+ Log.w(TAG, "[PlaybackTrace][Bridge][pip] applying the chrome nativeID failed", t)
3091
+ }
2460
3092
  }
2461
3093
 
2462
3094
  // ── Picture-in-Picture ─────────────────────────────────────────────────
@@ -2500,130 +3132,25 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2500
3132
  // has always claimed, so both zero-arg and two-arg calls are
2501
3133
  // legal. The defaults below keep the PiP notification useful
2502
3134
  // rather than blank.
2503
- val title = chapterTitle?.takeIf { it.isNotBlank() } ?: "Simba Player"
2504
- val pct = progressPct?.takeIf { it.isNotBlank() } ?: "0 %"
2505
- // The PiP window's shape is the loaded video's shape. This used to
2506
- // take the `16f / 9f` default from buildPipParams, so every PiP
2507
- // window was 16:9 no matter what was playing -- a 4:3 archive or a
2508
- // 2.35:1 scope film was letterboxed into the wrong window, and the
2509
- // mismatch was baked in at entry so the system animated to a shape
2510
- // that did not match the picture inside it.
2511
- //
2512
- // Read from the same `width` / `height` properties `getVideoParams`
2513
- // already reads, rather than adding a second, parallel way to ask
2514
- // mpv about dimensions. The frame below is where the shape is
2515
- // actually taken from when there is one; this is the fallback.
2516
- val videoAspect = currentVideoAspect()
2517
- if (videoAspect == null) {
2518
- Log.w(
2519
- TAG,
2520
- "[PlaybackTrace][Bridge][enterPip] no video dimensions loaded " +
2521
- "(no file, or audio-only); PiP window will use 16:9",
2522
- )
2523
- }
2524
- // Source rect hint: the region of the window where the video
2525
- // actually is, so PiP entry animates the real frame into the PiP
2526
- // window instead of growing out of a black rectangle.
2527
- //
2528
- // It is NOT the picture view's box. The picture fills its lane, so
2529
- // the view's rect is the whole window, and hinting that would make
2530
- // the PiP window take the window's shape - portrait on a phone -
2531
- // with the video arriving tiny and letterboxed inside it. It is the
2532
- // video's FRAME inside the view: the largest rect of the video's own
2533
- // shape that fits inside it, or the whole view when the picture is
2534
- // filling it.
2535
- //
2536
- // The hint's shape has to match the aspect ratio below, or the
2537
- // system scales the frame non-proportionally to fit and the video
2538
- // visibly arrives stretched. So the aspect is taken FROM THE SAME
2539
- // FRAME: the two agree by construction instead of being kept in
2540
- // sync by hand.
2541
- //
2542
- // Null when there is no video rect to point at - no live picture, no
2543
- // layout yet, or no video dimensions. That degrades to the no-hint
2544
- // behaviour, which costs a black transition but never a distorted
2545
- // one.
2546
- val frame = pipSourceRectInWindow()
2547
- val sourceRect = frame?.let { Rect(it.left, it.top, it.right, it.bottom) }
2548
- // The PiP window's shape. Taken from the frame when there is one, so
2549
- // it matches the hint exactly; the video's own aspect otherwise.
2550
- val aspect = frame?.aspect ?: videoAspect ?: (16f / 9f)
2551
- // `return try`, not a bare `try`. A `try`/`catch` in STATEMENT
2552
- // position is not this function's return value in Kotlin — not
2553
- // even as the last statement of a function with a non-`Unit`
2554
- // return type. The compiler says "Missing return statement",
2555
- // which is precisely what it said the first time round. Only an
2556
- // EXPRESSION `try` produces a value, and the branches inside it
2557
- // are the ones that carry the OS's answer.
2558
- return try {
2559
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
2560
- val pipParams = com.simba.player.PipManager.buildPipParams(
2561
- context = activity,
2562
- aspect = aspect,
2563
- sourceRectHint = sourceRect,
2564
- chapterTitle = title,
2565
- progressPercentage = pct,
2566
- )
2567
- // `enterPictureInPictureMode` ANSWERS whether the OS
2568
- // accepted the request, and the answer was being
2569
- // discarded. It is the only authority on this: the app
2570
- // hides its chrome when PiP is up, so "we think it worked"
2571
- // is not good enough.
2572
- activity.enterPictureInPictureMode(pipParams)
2573
- } else {
2574
- // API 24–25 support PiP but not PictureInPictureParams.
2575
- // The no-arg overload returns Unit, so those versions
2576
- // have no answer to relay; the PiP mode-change event is
2577
- // the only confirmation available there.
2578
- activity.enterPictureInPictureMode()
2579
- true
2580
- }
2581
- } catch (throwable: Throwable) {
2582
- // P1: the previous `catch (_: IllegalStateException)` was
2583
- // too narrow. `enterPictureInPictureMode` can also throw
2584
- // `IllegalArgumentException` (bad params), `RuntimeException`
2585
- // (OEM customisations), or `SecurityException` (PiP not
2586
- // permitted). We log the actual cause, and the `false` below
2587
- // tells the JS side that PiP did NOT happen.
2588
- //
2589
- // (This block used to say a "5 s recovery timer in
2590
- // `VideoPipAdapter`" would take over. There is no
2591
- // `VideoPipAdapter` in this repository — it was removed with
2592
- // the V12 single-activity architecture — so nothing was
2593
- // taking over, and a refused request simply stranded the app
2594
- // with no chrome. The `false` return is the recovery.)
2595
- Log.w(TAG, "[PlaybackTrace][Bridge][enterPip:threw]", throwable)
2596
- false
2597
- }
3135
+ val title = chapterTitle?.takeIf { it.isNotBlank() } ?: DEFAULT_PIP_TITLE
3136
+ val pct = progressPct?.takeIf { it.isNotBlank() } ?: DEFAULT_PIP_PROGRESS
3137
+ // The Activity is remembered, because the PiP mode-changed callback
3138
+ // needs its window (to find the consumer's chrome) and it arrives
3139
+ // while the Activity is paused.
3140
+ rememberPipActivity(activity)
3141
+ // The params are committed BEFORE the window is requested, so the
3142
+ // platform has the source rect hint it crops the app's window to.
3143
+ commitPipParams(activity)
3144
+ // The params are built and the window is requested by the
3145
+ // companion's ONE builder - the same one the native HOME path
3146
+ // uses - so the two paths cannot drift apart.
3147
+ return enterPictureInPicture(activity, title, pct)
2598
3148
  }
2599
3149
 
2600
3150
  /**
2601
3151
  * Exit PiP mode by bringing the activity to the front.
2602
3152
  * Called from JS when user taps "Expand" in PiP RemoteActions.
2603
3153
  */
2604
- /**
2605
- * Display aspect (width / height) of the loaded video, or `null` when it
2606
- * is not known.
2607
- *
2608
- * Reads the same `width` / `height` properties as [getVideoParams]. Null
2609
- * is the honest answer for "no file loaded" and for "audio only" -- both
2610
- * are real, expected states rather than failures -- and callers decide
2611
- * what a shape-less PiP window means for them.
2612
- */
2613
- private fun currentVideoAspect(): Float? {
2614
- val ptr = nativePtr
2615
- if (ptr == 0L) return null
2616
- return try {
2617
- val w = MPVLib.nativeGetProperty(ptr, "width").trim().trim('"').toDoubleOrNull()
2618
- val h = MPVLib.nativeGetProperty(ptr, "height").trim().trim('"').toDoubleOrNull()
2619
- if (w != null && h != null && w > 0.0 && h > 0.0) (w / h).toFloat() else null
2620
- } catch (e: Exception) {
2621
- // The native lease guard refuses reads against a destroyed engine.
2622
- Log.w(TAG, "[PlaybackTrace][Bridge][currentVideoAspect] ${e.message}")
2623
- null
2624
- }
2625
- }
2626
-
2627
3154
  @ReactMethod
2628
3155
  @Override
2629
3156
  override fun exitPip() {