@simba-dev/react-native-media-player 3.0.5 → 3.2.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,10 +1,12 @@
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
10
12
  import java.util.concurrent.ExecutorService
@@ -19,8 +21,10 @@ import com.facebook.react.bridge.ReactMethod
19
21
  import com.facebook.react.bridge.UiThreadUtil
20
22
  import com.facebook.react.module.annotations.ReactModule
21
23
  import com.facebook.react.modules.core.DeviceEventManagerModule
24
+ import com.facebook.react.uimanager.util.ReactFindViewUtil
22
25
  import com.facebook.fbreact.specs.NativeMpvPlayerSpec
23
26
  import com.simba.player.PlaybackHost
27
+ import com.simba.player.PipNativeEntry
24
28
  import org.json.JSONArray
25
29
  import org.json.JSONObject
26
30
 
@@ -68,6 +72,14 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
68
72
  // re-encoding a near-duplicate JPEG on every scroll/re-render.
69
73
  private const val FRAME_POSITION_BUCKET_MS = 30_000L
70
74
 
75
+ // The PiP notification's fallbacks — ONE owner each.
76
+ //
77
+ // The JS path used to inline these two strings, and the native
78
+ // HOME path needs the same two facts for the same one
79
+ // notification. Two owners would be two chances to disagree.
80
+ private const val DEFAULT_PIP_TITLE = "Simba Player"
81
+ private const val DEFAULT_PIP_PROGRESS = "0 %"
82
+
71
83
  // v1.10.0 — hot-path property tracing.
72
84
  //
73
85
  // `time-pos` is mpv's per-frame property, so tracing every property
@@ -132,10 +144,11 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
132
144
  /**
133
145
  * The same policy, mirrored where the COMPANION can read it.
134
146
  *
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.
147
+ * `notifyUserLeaveHint(activity)` is a companion function: it is
148
+ * called from the consumer's Activity, which has no reference to
149
+ * this module instance, so it cannot read the instance field
150
+ * above. The instance writes this mirror when it applies the
151
+ * policy.
139
152
  *
140
153
  * The same pattern `debugLoggingEnabled` uses.
141
154
  */
@@ -143,6 +156,32 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
143
156
  var pipAutoEnterForCompanion: Boolean = false
144
157
  private set
145
158
 
159
+ /**
160
+ * The consumer's chrome `nativeID`, or `null`.
161
+ *
162
+ * Read from `pip.chromeNativeId` in the resolved config. The
163
+ * literal belongs to the CONSUMER: the library stores it and uses
164
+ * it, and never hardcodes one of its own.
165
+ *
166
+ * `null` means "this consumer has no chrome of its own". That is
167
+ * a real answer and not a missing value — the native HOME path
168
+ * then enters PiP without hiding anything.
169
+ */
170
+ @Volatile
171
+ var pipChromeNativeIdForCompanion: String? = null
172
+ private set
173
+
174
+ /**
175
+ * The chrome view the native HOME path hid, so it can be brought
176
+ * back when PiP ends.
177
+ *
178
+ * It is a `View`, so it is held here and nulled out on restore: a
179
+ * stale reference would keep a detached view — and through it the
180
+ * Activity — alive for the rest of the process.
181
+ */
182
+ @Volatile
183
+ private var pipHiddenChromeView: View? = null
184
+
146
185
  /**
147
186
  * Phase 21: recursive JSONObject → Kotlin Map converter. Used
148
187
  * by [setConfig] so the stored config can be consumed
@@ -181,6 +220,14 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
181
220
  */
182
221
  fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean) {
183
222
  Log.i(TAG, "companion.onPictureInPictureModeChanged: isInPip=$isInPictureInPictureMode instance=${instance != null}")
223
+ // The chrome the native HOME path hid comes back when PiP
224
+ // ends — and it comes back EVEN IF the React instance is
225
+ // gone: the view is a native one, and the app is showing it
226
+ // (or not showing it) either way. So the restore happens
227
+ // BEFORE the instance check below.
228
+ if (!isInPictureInPictureMode) {
229
+ restoreConsumerChrome()
230
+ }
184
231
  val ctx = instance ?: run {
185
232
  Log.w(TAG, "onPictureInPictureModeChanged: module instance not initialized yet")
186
233
  return
@@ -214,49 +261,390 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
214
261
  }
215
262
 
216
263
  /**
217
- * Called from the consumer's `Activity.onUserLeaveHint()` - the
218
- * user is leaving the app (home, recents, app switcher).
264
+ * The HOME path: enter Picture-in-Picture NATIVELY, from the
265
+ * consumer's `Activity.onUserLeaveHint()` — the moment the user
266
+ * is leaving the app (home, recents, app switcher).
267
+ *
268
+ * ## Why NATIVE, and why HERE
269
+ *
270
+ * `onUserLeaveHint()` is the ONLY pre-pause hook Android offers.
271
+ * `onPictureInPictureModeChanged(true)` arrives AFTER `onPause`,
272
+ * which is too late to change what the window holds.
273
+ *
274
+ * And by the time this runs, React Native has already paused the
275
+ * React scheduler with the Activity: a React commit cannot land
276
+ * and there is no frame clock. Measured on emulator-5554 (API 37)
277
+ * on 2026-11-03: the JS handler ran immediately, the effect that
278
+ * would have driven the entry ran 5.7 s late, and the
279
+ * `requestAnimationFrame` never fired — so the chrome was still
280
+ * mounted when the OS took the window.
219
281
  *
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.
282
+ * So the entry happens HERE, in native code, and the chrome is
283
+ * hidden with a native View-system mutation
284
+ * (`visibility = View.GONE`), which takes effect without a React
285
+ * commit and without a frame clock.
226
286
  *
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.
287
+ * ## The order, and why it is not negotiable
230
288
  *
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.
289
+ * An Activity in Picture-in-Picture is "paused, but rendering"
290
+ * (AOSP) — the WINDOW keeps rendering; what stops is REACT. So
291
+ * the PiP window keeps whatever the Activity's window held at
292
+ * the moment of the transition: the chrome has to be GONE before
293
+ * the entry, and the PiP params are built AFTER the hide.
294
+ *
295
+ * ## What it refuses, and why
296
+ *
297
+ * - auto-enter off — that is the consumer's own policy
298
+ * (`pip.autoEnterOnLeave`), and the library honours it;
299
+ * - already in PiP — HOME pressed inside PiP must not re-enter;
300
+ * - no media loaded — a PiP window for a stopped session is a
301
+ * bug, and the facts are read from mpv, never from a JS flag;
302
+ * - a configured chrome id that no view carries — entering PiP
303
+ * with the chrome still mounted paints the app's dead chrome
304
+ * into the PiP window, which is the defect this path exists
305
+ * to fix.
306
+ *
307
+ * @param activity the Activity that is leaving. It is the window
308
+ * the PiP entry applies to, and the root the chrome view
309
+ * is searched under.
310
+ * @return the OS's own answer: `true` when the Activity entered
311
+ * Picture-in-Picture, `false` when it did not.
234
312
  */
235
- fun notifyUserLeaveHint() {
313
+ fun notifyUserLeaveHint(activity: Activity): Boolean {
236
314
  Log.i(
237
315
  TAG,
238
316
  "companion.notifyUserLeaveHint: autoEnter=$pipAutoEnterForCompanion " +
239
- "instance=${instance != null}",
317
+ "chromeNativeId=${pipChromeNativeIdForCompanion ?: "(none)"}",
240
318
  )
319
+ // Platform precondition, not a policy: Picture-in-Picture
320
+ // itself needs API 24, and `isInPictureInPictureMode` does
321
+ // not exist below it.
322
+ if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) {
323
+ Log.w(TAG, "companion.notifyUserLeaveHint: refused: SDK < N")
324
+ return false
325
+ }
326
+ // 1. The consumer's policy comes first.
241
327
  if (!pipAutoEnterForCompanion) {
328
+ Log.i(TAG, "companion.notifyUserLeaveHint: auto-enter is off; not entering PiP")
329
+ return false
330
+ }
331
+ // 2. Already in PiP: HOME pressed inside PiP must not enter
332
+ // again — the OS would refuse it, and the refusal would
333
+ // be read as "PiP failed".
334
+ if (activity.isInPictureInPictureMode) {
335
+ Log.i(TAG, "companion.notifyUserLeaveHint: already in PiP; not entering again")
336
+ return false
337
+ }
338
+ // 3. No media loaded: a PiP window for a stopped session is
339
+ // a bug, not a feature.
340
+ if (!isMediaLoaded()) {
341
+ Log.i(TAG, "companion.notifyUserLeaveHint: no media loaded; not entering PiP")
342
+ return false
343
+ }
344
+ // 4. The chrome, when the consumer has one. The literal is
345
+ // the consumer's — the library never hardcodes one.
346
+ val chromeNativeId = pipChromeNativeIdForCompanion
347
+ if (chromeNativeId != null) {
348
+ val root = activity.window?.decorView
349
+ // `ReactFindViewUtil` is React Native's own lookup: it
350
+ // walks the native View tree for the tag RN sets for the
351
+ // `nativeID` prop (`BaseViewManager.setNativeId`), which
352
+ // Fabric calls through the same setter.
353
+ val chromeView = root?.let { ReactFindViewUtil.findView(it, chromeNativeId) }
354
+ if (chromeView == null) {
355
+ // The chrome cannot be hidden, so entering PiP would
356
+ // paint the app's dead chrome into the PiP window.
357
+ // Refuse instead.
358
+ Log.w(
359
+ TAG,
360
+ "companion.notifyUserLeaveHint: no view carries the chrome nativeID " +
361
+ "'$chromeNativeId'; refusing the PiP entry",
362
+ )
363
+ return false
364
+ }
365
+ // 5. Hide it natively. A View-system mutation, so it
366
+ // lands without a React commit and without a frame
367
+ // clock.
368
+ chromeView.visibility = View.GONE
369
+ pipHiddenChromeView = chromeView
242
370
  Log.i(
243
371
  TAG,
244
- "companion.notifyUserLeaveHint: auto-enter is off; not telling the consumer",
372
+ "companion.notifyUserLeaveHint: hid the chrome view with nativeID " +
373
+ "'$chromeNativeId'",
245
374
  )
246
- return
247
375
  }
248
- val ctx = instance ?: run {
249
- Log.w(TAG, "notifyUserLeaveHint: module instance not initialized yet")
250
- return
376
+ // 6. Build the params and ask the OS for the window. The
377
+ // params are built AFTER the hide, on purpose: the PiP
378
+ // window keeps what the window held at the transition.
379
+ val entered = enterPictureInPicture(
380
+ activity = activity,
381
+ chapterTitle = nativeTitle() ?: DEFAULT_PIP_TITLE,
382
+ progressPct = nativeProgressPct() ?: DEFAULT_PIP_PROGRESS,
383
+ )
384
+ // 7. A refused entry must not leave the consumer with an
385
+ // invisible chrome.
386
+ if (!entered) {
387
+ Log.w(TAG, "companion.notifyUserLeaveHint: the OS refused the PiP entry")
388
+ restoreConsumerChrome()
389
+ return false
251
390
  }
391
+ Log.i(TAG, "companion.notifyUserLeaveHint: entered PiP")
392
+ return true
393
+ }
394
+
395
+ /**
396
+ * The ONE owner of "how a PiP window is built".
397
+ *
398
+ * Both entry paths come through here:
399
+ * - the JS path — `enterPip(chapterTitle, progressPct)`, the
400
+ * consumer's own button;
401
+ * - the native path — `notifyUserLeaveHint(activity)`, the HOME
402
+ * button.
403
+ *
404
+ * One builder, one set of facts, one place where the OS's answer
405
+ * is read. A second, slightly different params builder is how
406
+ * those two paths would drift apart.
407
+ *
408
+ * @return the OS's own answer: `true` when the Activity entered
409
+ * Picture-in-Picture, `false` when it refused (or the
410
+ * call threw).
411
+ */
412
+ private fun enterPictureInPicture(
413
+ activity: Activity,
414
+ chapterTitle: String,
415
+ progressPct: String,
416
+ ): Boolean {
417
+ // The PiP window's shape is the loaded video's shape.
418
+ val videoAspect = currentVideoAspect()
419
+ if (videoAspect == null) {
420
+ Log.w(
421
+ TAG,
422
+ "[PlaybackTrace][Bridge][enterPip] no video dimensions loaded " +
423
+ "(no file, or audio-only); PiP window will use 16:9",
424
+ )
425
+ }
426
+ // Source rect hint: the region of the window where the video
427
+ // actually is, so PiP entry animates the real frame into the
428
+ // PiP window instead of growing out of a black rectangle.
429
+ //
430
+ // The hint's shape has to match the aspect ratio below, or
431
+ // the system scales the frame non-proportionally to fit and
432
+ // the video visibly arrives stretched. So the aspect is
433
+ // taken FROM THE SAME FRAME: the two agree by construction
434
+ // instead of being kept in sync by hand.
435
+ val frame = pipSourceRectInWindow()
436
+ val sourceRect = frame?.let { Rect(it.left, it.top, it.right, it.bottom) }
437
+ // The PiP window's shape. Taken from the frame when there is
438
+ // one, so it matches the hint exactly; the video's own aspect
439
+ // otherwise.
440
+ val aspect = frame?.aspect ?: videoAspect ?: (16f / 9f)
441
+ // `return try`, not a bare `try`. A `try`/`catch` in
442
+ // STATEMENT position is not this function's return value in
443
+ // Kotlin — not even as the last statement of a function with
444
+ // a non-`Unit` return type. Only an EXPRESSION `try` produces
445
+ // a value, and the branches inside it are the ones that carry
446
+ // the OS's answer.
447
+ return try {
448
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
449
+ val pipParams = com.simba.player.PipManager.buildPipParams(
450
+ context = activity,
451
+ aspect = aspect,
452
+ sourceRectHint = sourceRect,
453
+ chapterTitle = chapterTitle,
454
+ progressPercentage = progressPct,
455
+ )
456
+ // `enterPictureInPictureMode` ANSWERS whether the OS
457
+ // accepted the request, and the answer is the only
458
+ // authority on this.
459
+ activity.enterPictureInPictureMode(pipParams)
460
+ } else {
461
+ // API 24–25 support PiP but not PictureInPictureParams.
462
+ // The no-arg overload returns Unit, so those versions
463
+ // have no answer to relay; the PiP mode-change event is
464
+ // the only confirmation available there.
465
+ activity.enterPictureInPictureMode()
466
+ true
467
+ }
468
+ } catch (throwable: Throwable) {
469
+ // `enterPictureInPictureMode` can throw
470
+ // `IllegalArgumentException` (bad params),
471
+ // `RuntimeException` (OEM customisations), or
472
+ // `SecurityException` (PiP not permitted). We log the
473
+ // actual cause, and the `false` below tells the caller
474
+ // that PiP did NOT happen.
475
+ Log.w(TAG, "[PlaybackTrace][Bridge][enterPip:threw]", throwable)
476
+ false
477
+ }
478
+ }
479
+
480
+ /**
481
+ * Bring the hidden chrome back, and forget it.
482
+ *
483
+ * Called when the OS refuses the entry, and when PiP ends
484
+ * (`onPictureInPictureModeChanged(false)`).
485
+ */
486
+ private fun restoreConsumerChrome() {
487
+ val view = pipHiddenChromeView ?: return
488
+ pipHiddenChromeView = null
252
489
  try {
253
- ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
254
- .emit("onUserLeaveHint", Arguments.createMap())
255
- Log.i(TAG, "companion.notifyUserLeaveHint: emit succeeded")
490
+ view.visibility = View.VISIBLE
491
+ Log.i(TAG, "companion.restoreConsumerChrome: restored the chrome view")
492
+ } catch (e: Exception) {
493
+ Log.w(TAG, "companion.restoreConsumerChrome: restoring the chrome view failed", e)
494
+ }
495
+ }
496
+
497
+ /**
498
+ * Whether mpv currently has media loaded.
499
+ *
500
+ * Read live through [PlaybackHost] — never from a JS flag, which
501
+ * can be stale by the time the user presses HOME. The question
502
+ * is mpv's own `playback-state`: `idle` and `stopped` are its
503
+ * "no media" states, and everything else (`loading`, `play`,
504
+ * `pause`, `eof-reached`) means something is still loaded.
505
+ */
506
+ private fun isMediaLoaded(): Boolean {
507
+ val ptr = PlaybackHost.handle()
508
+ if (ptr == 0L) return false
509
+ return try {
510
+ val state = MPVLib.nativeGetProperty(ptr, "playback-state").trim().trim('"')
511
+ state.isNotEmpty() && state != "idle" && state != "stopped"
512
+ } catch (e: Exception) {
513
+ // The native lease guard refuses calls against a
514
+ // destroyed engine; that is a normal outcome, not a
515
+ // crash.
516
+ Log.w(TAG, "companion.notifyUserLeaveHint: reading playback-state failed", e)
517
+ false
518
+ }
519
+ }
520
+
521
+ /**
522
+ * The title for the PiP notification, read from mpv.
523
+ *
524
+ * mpv's `media-title` IS the title the consumer supplied: the
525
+ * library writes it as mpv's `force-media-title` BEFORE the load
526
+ * (mpv reads that option at load time), and mpv reports it back
527
+ * under `media-title`. Same fact, not a second one.
528
+ */
529
+ private fun nativeTitle(): String? {
530
+ val ptr = PlaybackHost.handle()
531
+ if (ptr == 0L) return null
532
+ return try {
533
+ PipNativeEntry.title(MPVLib.nativeGetProperty(ptr, "media-title"))
534
+ } catch (e: Exception) {
535
+ Log.w(TAG, "companion.notifyUserLeaveHint: reading media-title failed", e)
536
+ null
537
+ }
538
+ }
539
+
540
+ /**
541
+ * The progress percentage for the PiP notification, read from
542
+ * mpv: `time-pos` over `duration`, in the consumer's exact
543
+ * `"NN %"` format.
544
+ *
545
+ * mpv reports both in SECONDS; the consumer's format works in
546
+ * milliseconds, so the values are converted before they are
547
+ * divided. The ratio is the same either way, but the rounding
548
+ * is not, so the units are made to match before the fact is
549
+ * computed.
550
+ */
551
+ private fun nativeProgressPct(): String? {
552
+ val ptr = PlaybackHost.handle()
553
+ if (ptr == 0L) return null
554
+ return try {
555
+ val positionSec =
556
+ MPVLib.nativeGetProperty(ptr, "time-pos").trim().trim('"').toDoubleOrNull()
557
+ val durationSec =
558
+ MPVLib.nativeGetProperty(ptr, "duration").trim().trim('"').toDoubleOrNull()
559
+ if (positionSec == null || durationSec == null) return null
560
+ PipNativeEntry.progressPct(
561
+ Math.round(positionSec * 1000.0),
562
+ Math.round(durationSec * 1000.0),
563
+ )
564
+ } catch (e: Exception) {
565
+ Log.w(TAG, "companion.notifyUserLeaveHint: reading time-pos/duration failed", e)
566
+ null
567
+ }
568
+ }
569
+
570
+ /**
571
+ * Display aspect (width / height) of the loaded video, or `null`
572
+ * when it is not known.
573
+ *
574
+ * Reads the same `width` / `height` properties as
575
+ * [getVideoParams]. Null is the honest answer for "no file
576
+ * loaded" and for "audio only" — both are real, expected states
577
+ * rather than failures — and callers decide what a shape-less
578
+ * PiP window means for them.
579
+ */
580
+ private fun currentVideoAspect(): Float? {
581
+ val ptr = PlaybackHost.handle()
582
+ if (ptr == 0L) return null
583
+ return try {
584
+ val w = MPVLib.nativeGetProperty(ptr, "width").trim().trim('"').toDoubleOrNull()
585
+ val h = MPVLib.nativeGetProperty(ptr, "height").trim().trim('"').toDoubleOrNull()
586
+ if (w != null && h != null && w > 0.0 && h > 0.0) (w / h).toFloat() else null
256
587
  } catch (e: Exception) {
257
- Log.w(TAG, "notifyUserLeaveHint: emit threw", e)
588
+ // The native lease guard refuses reads against a destroyed engine.
589
+ Log.w(TAG, "[PlaybackTrace][Bridge][currentVideoAspect] ${e.message}")
590
+ null
258
591
  }
259
592
  }
593
+
594
+ /**
595
+ * The rect of the window the video actually occupies, or `null`
596
+ * when there is no such rect.
597
+ *
598
+ * ## What the rect is
599
+ *
600
+ * Android's `setSourceRectHint` wants the region of the window where the
601
+ * video is, so PiP entry animates the real frame into the PiP window
602
+ * instead of growing out of a black rectangle.
603
+ *
604
+ * It is **not** the picture view's box. The picture fills its lane
605
+ * (`StyleSheet.absoluteFill`), so the view's rect is the whole window,
606
+ * and hinting that would make the PiP window take the window's shape —
607
+ * portrait on a phone — with the video arriving tiny and letterboxed
608
+ * inside it. The rect has to be the video's FRAME inside the view: the
609
+ * largest rect of the video's own shape that fits inside it, or the
610
+ * whole view when the picture is filling it.
611
+ *
612
+ * ## Where the numbers come from
613
+ *
614
+ * - the view's rect — `MpvRenderView.cachedWindowBounds`, published by
615
+ * the UI thread on layout, because `getLocationInWindow()` is a
616
+ * UI-thread API and this code runs on the bridge thread.
617
+ * - the video's shape — `currentVideoAspect()`, the same `width` /
618
+ * `height` properties `getVideoParams` reads.
619
+ * - the fill — `MpvRenderView.currentFillsView`, whether the picture
620
+ * mpv is rendering with right now FILLS its view (`cover`, `stretch`)
621
+ * or FITS inside it (`contain`, the default).
622
+ *
623
+ * ## Why every step can answer `null`
624
+ *
625
+ * `null` is the honest answer when there is no video rect to point at:
626
+ * no live picture, no layout yet, or no video dimensions. It degrades to
627
+ * the platform's no-hint behaviour, which costs a black transition but
628
+ * never a distorted one.
629
+ *
630
+ * The reader this replaces (`PlayerSurface.boundsInWindow`) answered
631
+ * `null` **unconditionally** — it read a registry the V22 architecture
632
+ * has no writer for — so PiP entry always grew out of a black
633
+ * rectangle. That was the bug.
634
+ */
635
+ private fun pipSourceRectInWindow(): PictureFrame? {
636
+ val view = MpvRenderViewRegistry.current() ?: return null
637
+ val bounds = view.cachedWindowBounds ?: return null
638
+ val aspect = currentVideoAspect() ?: return null
639
+ return PipSourceRect.frameInWindow(
640
+ bounds.left,
641
+ bounds.top,
642
+ bounds.width,
643
+ bounds.height,
644
+ aspect,
645
+ view.currentFillsView,
646
+ )
647
+ }
260
648
  }
261
649
 
262
650
  init {
@@ -2332,6 +2720,10 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2332
2720
  // was a documented public flag that nothing read, so pressing
2333
2721
  // home never entered PiP - the value was already here.
2334
2722
  applyPipAutoEnterOnLeave(parsed)
2723
+ // The chrome `nativeID` belongs to the consumer, and it is
2724
+ // applied on EVERY push - so a config that does not carry it
2725
+ // leaves the value at `null` instead of keeping a stale one.
2726
+ applyPipChromeNativeId(parsed)
2335
2727
  val keys = parsed?.keys?.sorted()?.joinToString(", ") ?: "(none)"
2336
2728
  Log.i(
2337
2729
  TAG,
@@ -2353,24 +2745,27 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2353
2745
  }
2354
2746
 
2355
2747
  /**
2356
- * Apply `pip.autoEnterOnLeave` — remember the policy, and tell the
2357
- * CONSUMER when the user leaves.
2748
+ * Apply `pip.autoEnterOnLeave` — remember the policy, so the
2749
+ * native HOME path knows whether to enter PiP at all.
2358
2750
  *
2359
2751
  * What this does NOT do any more: arm the platform's own switch
2360
2752
  * (`PictureInPictureParams.Builder.setAutoEnterEnabled`, API 31+).
2361
2753
  * The platform's switch makes the SYSTEM transition the activity into
2362
- * PiP without the consumer being able to do anything first, and an
2363
- * Activity in PiP does not redraw — so a consumer that draws its own
2364
- * chrome over the picture had that chrome frozen into the PiP
2365
- * window, dead and scaled down. Measured on device on 2026-11-03.
2754
+ * PiP without the consumer being able to do anything first. The
2755
+ * Activity in PiP is "paused, but rendering" - what stops is REACT:
2756
+ * its scheduler is paused with the Activity, so no commit lands and
2757
+ * no frame is produced. So a consumer that draws its own chrome over
2758
+ * the picture still had that chrome mounted when the PiP window was
2759
+ * created, and with no frame coming it stayed there: dead and scaled
2760
+ * down. Measured on device on 2026-11-03.
2366
2761
  * See `PipManager.buildPipParams` for the full account.
2367
2762
  *
2368
- * What it does now: the policy is remembered (so
2369
- * `notifyUserLeaveHint()` can decide whether to speak at all), and
2370
- * when the consumer's Activity reports that the user is leaving, the
2371
- * consumer is told through the `onUserLeaveHint` event. The consumer
2372
- * then removes its chrome, lets the frame that drew it go by, and
2373
- * asks the OS for the window itself.
2763
+ * What it does now: the policy is remembered, and the consumer's
2764
+ * Activity reports that the user is leaving by calling
2765
+ * `MpvBridgeModule.notifyUserLeaveHint(activity)`. The library then
2766
+ * hides the consumer's chrome NATIVELY and asks the OS for the window
2767
+ * itself - in that order, and inside `onUserLeaveHint()`, because by
2768
+ * then no React commit can land.
2374
2769
  *
2375
2770
  * The consumer's Activity must override `onUserLeaveHint()` and
2376
2771
  * declare `android:supportsPictureInPicture="true"`. Both are the
@@ -2384,14 +2779,14 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2384
2779
  try {
2385
2780
  val desired = PipAutoEnterPolicy.desiredAutoEnter(config) ?: return
2386
2781
  pipAutoEnter = desired
2387
- // The policy is remembered so `notifyUserLeaveHint()` knows
2388
- // whether to tell the consumer that it should enter PiP. The
2389
- // platform's OWN auto-enter switch is NOT armed: the system
2390
- // would transition the activity without the consumer being
2391
- // able to remove its chrome first, and an Activity in PiP
2392
- // does not redraw - so the consumer's chrome would be frozen
2393
- // into the PiP window as a dead layer. See
2394
- // `PipManager.buildPipParams` for the measurement.
2782
+ // The policy is remembered so `notifyUserLeaveHint(activity)`
2783
+ // knows whether to enter PiP at all. The platform's OWN
2784
+ // auto-enter switch is NOT armed: the system would transition
2785
+ // the activity before the chrome could be hidden, and React
2786
+ // cannot commit a frame while the Activity is paused - so the
2787
+ // chrome would be still mounted in the PiP window, dead and
2788
+ // scaled down. See `PipManager.buildPipParams` for the
2789
+ // measurement.
2395
2790
  pipAutoEnterForCompanion = desired
2396
2791
  } catch (t: Throwable) {
2397
2792
  // Never let this reject the `setConfig` promise: the config
@@ -2402,58 +2797,35 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2402
2797
  }
2403
2798
 
2404
2799
  /**
2405
- * The rect of the window the video actually occupies, or `null` when
2406
- * there is no such rect.
2407
- *
2408
- * ## What the rect is
2409
- *
2410
- * Android's `setSourceRectHint` wants the region of the window where the
2411
- * video is, so PiP entry animates the real frame into the PiP window
2412
- * instead of growing out of a black rectangle.
2413
- *
2414
- * It is **not** the picture view's box. The picture fills its lane
2415
- * (`StyleSheet.absoluteFill`), so the view's rect is the whole window,
2416
- * and hinting that would make the PiP window take the window's shape —
2417
- * portrait on a phone — with the video arriving tiny and letterboxed
2418
- * inside it. The rect has to be the video's FRAME inside the view: the
2419
- * largest rect of the video's own shape that fits inside it, or the
2420
- * whole view when the picture is filling it.
2421
- *
2422
- * ## Where the numbers come from
2423
- *
2424
- * - the view's rect — `MpvRenderView.cachedWindowBounds`, published by
2425
- * the UI thread on layout, because `getLocationInWindow()` is a
2426
- * UI-thread API and this code runs on the bridge thread.
2427
- * - the video's shape — `currentVideoAspect()`, the same `width` /
2428
- * `height` properties `getVideoParams` reads.
2429
- * - the fill — `MpvRenderView.currentFillsView`, whether the picture
2430
- * mpv is rendering with right now FILLS its view (`cover`, `stretch`)
2431
- * or FITS inside it (`contain`, the default).
2432
- *
2433
- * ## Why every step can answer `null`
2434
- *
2435
- * `null` is the honest answer when there is no video rect to point at:
2436
- * no live picture, no layout yet, or no video dimensions. It degrades to
2437
- * the platform's no-hint behaviour, which costs a black transition but
2438
- * never a distorted one.
2439
- *
2440
- * The reader this replaces (`PlayerSurface.boundsInWindow`) answered
2441
- * `null` **unconditionally** — it read a registry the V22 architecture
2442
- * has no writer for — so PiP entry always grew out of a black
2443
- * rectangle. That was the bug.
2800
+ * Apply `pip.chromeNativeId` — remember the consumer's chrome
2801
+ * `nativeID`.
2802
+ *
2803
+ * The literal belongs to the CONSUMER: the library stores it and uses
2804
+ * it, and never hardcodes one of its own. `null` means "this consumer
2805
+ * has no chrome of its own", which is a real answer and not a missing
2806
+ * value — the native HOME path then enters PiP without hiding
2807
+ * anything.
2808
+ *
2809
+ * Applied on EVERY config push, so a config that does not carry the
2810
+ * id leaves the value at `null` instead of keeping a stale one from
2811
+ * an earlier push.
2812
+ *
2813
+ * @param config the RESOLVED config map, as parsed by `setConfig`.
2444
2814
  */
2445
- private fun pipSourceRectInWindow(): PictureFrame? {
2446
- val view = MpvRenderViewRegistry.current() ?: return null
2447
- val bounds = view.cachedWindowBounds ?: return null
2448
- val aspect = currentVideoAspect() ?: return null
2449
- return PipSourceRect.frameInWindow(
2450
- bounds.left,
2451
- bounds.top,
2452
- bounds.width,
2453
- bounds.height,
2454
- aspect,
2455
- view.currentFillsView,
2456
- )
2815
+ private fun applyPipChromeNativeId(config: Map<String, Any?>?) {
2816
+ try {
2817
+ pipChromeNativeIdForCompanion = PipNativeEntry.chromeNativeId(config)
2818
+ Log.i(
2819
+ TAG,
2820
+ "[PlaybackTrace][Bridge][pip] chrome nativeID = " +
2821
+ (pipChromeNativeIdForCompanion ?: "(none)"),
2822
+ )
2823
+ } catch (t: Throwable) {
2824
+ // Never let this reject the `setConfig` promise: the config
2825
+ // itself was stored fine, and a rejected promise would tell
2826
+ // the consumer its WHOLE configuration failed.
2827
+ Log.w(TAG, "[PlaybackTrace][Bridge][pip] applying the chrome nativeID failed", t)
2828
+ }
2457
2829
  }
2458
2830
 
2459
2831
  // ── Picture-in-Picture ─────────────────────────────────────────────────
@@ -2497,130 +2869,18 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2497
2869
  // has always claimed, so both zero-arg and two-arg calls are
2498
2870
  // legal. The defaults below keep the PiP notification useful
2499
2871
  // rather than blank.
2500
- val title = chapterTitle?.takeIf { it.isNotBlank() } ?: "Simba Player"
2501
- val pct = progressPct?.takeIf { it.isNotBlank() } ?: "0 %"
2502
- // The PiP window's shape is the loaded video's shape. This used to
2503
- // take the `16f / 9f` default from buildPipParams, so every PiP
2504
- // window was 16:9 no matter what was playing -- a 4:3 archive or a
2505
- // 2.35:1 scope film was letterboxed into the wrong window, and the
2506
- // mismatch was baked in at entry so the system animated to a shape
2507
- // that did not match the picture inside it.
2508
- //
2509
- // Read from the same `width` / `height` properties `getVideoParams`
2510
- // already reads, rather than adding a second, parallel way to ask
2511
- // mpv about dimensions. The frame below is where the shape is
2512
- // actually taken from when there is one; this is the fallback.
2513
- val videoAspect = currentVideoAspect()
2514
- if (videoAspect == null) {
2515
- Log.w(
2516
- TAG,
2517
- "[PlaybackTrace][Bridge][enterPip] no video dimensions loaded " +
2518
- "(no file, or audio-only); PiP window will use 16:9",
2519
- )
2520
- }
2521
- // Source rect hint: the region of the window where the video
2522
- // actually is, so PiP entry animates the real frame into the PiP
2523
- // window instead of growing out of a black rectangle.
2524
- //
2525
- // It is NOT the picture view's box. The picture fills its lane, so
2526
- // the view's rect is the whole window, and hinting that would make
2527
- // the PiP window take the window's shape - portrait on a phone -
2528
- // with the video arriving tiny and letterboxed inside it. It is the
2529
- // video's FRAME inside the view: the largest rect of the video's own
2530
- // shape that fits inside it, or the whole view when the picture is
2531
- // filling it.
2532
- //
2533
- // The hint's shape has to match the aspect ratio below, or the
2534
- // system scales the frame non-proportionally to fit and the video
2535
- // visibly arrives stretched. So the aspect is taken FROM THE SAME
2536
- // FRAME: the two agree by construction instead of being kept in
2537
- // sync by hand.
2538
- //
2539
- // Null when there is no video rect to point at - no live picture, no
2540
- // layout yet, or no video dimensions. That degrades to the no-hint
2541
- // behaviour, which costs a black transition but never a distorted
2542
- // one.
2543
- val frame = pipSourceRectInWindow()
2544
- val sourceRect = frame?.let { Rect(it.left, it.top, it.right, it.bottom) }
2545
- // The PiP window's shape. Taken from the frame when there is one, so
2546
- // it matches the hint exactly; the video's own aspect otherwise.
2547
- val aspect = frame?.aspect ?: videoAspect ?: (16f / 9f)
2548
- // `return try`, not a bare `try`. A `try`/`catch` in STATEMENT
2549
- // position is not this function's return value in Kotlin — not
2550
- // even as the last statement of a function with a non-`Unit`
2551
- // return type. The compiler says "Missing return statement",
2552
- // which is precisely what it said the first time round. Only an
2553
- // EXPRESSION `try` produces a value, and the branches inside it
2554
- // are the ones that carry the OS's answer.
2555
- return try {
2556
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
2557
- val pipParams = com.simba.player.PipManager.buildPipParams(
2558
- context = activity,
2559
- aspect = aspect,
2560
- sourceRectHint = sourceRect,
2561
- chapterTitle = title,
2562
- progressPercentage = pct,
2563
- )
2564
- // `enterPictureInPictureMode` ANSWERS whether the OS
2565
- // accepted the request, and the answer was being
2566
- // discarded. It is the only authority on this: the app
2567
- // hides its chrome when PiP is up, so "we think it worked"
2568
- // is not good enough.
2569
- activity.enterPictureInPictureMode(pipParams)
2570
- } else {
2571
- // API 24–25 support PiP but not PictureInPictureParams.
2572
- // The no-arg overload returns Unit, so those versions
2573
- // have no answer to relay; the PiP mode-change event is
2574
- // the only confirmation available there.
2575
- activity.enterPictureInPictureMode()
2576
- true
2577
- }
2578
- } catch (throwable: Throwable) {
2579
- // P1: the previous `catch (_: IllegalStateException)` was
2580
- // too narrow. `enterPictureInPictureMode` can also throw
2581
- // `IllegalArgumentException` (bad params), `RuntimeException`
2582
- // (OEM customisations), or `SecurityException` (PiP not
2583
- // permitted). We log the actual cause, and the `false` below
2584
- // tells the JS side that PiP did NOT happen.
2585
- //
2586
- // (This block used to say a "5 s recovery timer in
2587
- // `VideoPipAdapter`" would take over. There is no
2588
- // `VideoPipAdapter` in this repository — it was removed with
2589
- // the V12 single-activity architecture — so nothing was
2590
- // taking over, and a refused request simply stranded the app
2591
- // with no chrome. The `false` return is the recovery.)
2592
- Log.w(TAG, "[PlaybackTrace][Bridge][enterPip:threw]", throwable)
2593
- false
2594
- }
2872
+ val title = chapterTitle?.takeIf { it.isNotBlank() } ?: DEFAULT_PIP_TITLE
2873
+ val pct = progressPct?.takeIf { it.isNotBlank() } ?: DEFAULT_PIP_PROGRESS
2874
+ // The params are built and the window is requested by the
2875
+ // companion's ONE builder - the same one the native HOME path
2876
+ // uses - so the two paths cannot drift apart.
2877
+ return enterPictureInPicture(activity, title, pct)
2595
2878
  }
2596
2879
 
2597
2880
  /**
2598
2881
  * Exit PiP mode by bringing the activity to the front.
2599
2882
  * Called from JS when user taps "Expand" in PiP RemoteActions.
2600
2883
  */
2601
- /**
2602
- * Display aspect (width / height) of the loaded video, or `null` when it
2603
- * is not known.
2604
- *
2605
- * Reads the same `width` / `height` properties as [getVideoParams]. Null
2606
- * is the honest answer for "no file loaded" and for "audio only" -- both
2607
- * are real, expected states rather than failures -- and callers decide
2608
- * what a shape-less PiP window means for them.
2609
- */
2610
- private fun currentVideoAspect(): Float? {
2611
- val ptr = nativePtr
2612
- if (ptr == 0L) return null
2613
- return try {
2614
- val w = MPVLib.nativeGetProperty(ptr, "width").trim().trim('"').toDoubleOrNull()
2615
- val h = MPVLib.nativeGetProperty(ptr, "height").trim().trim('"').toDoubleOrNull()
2616
- if (w != null && h != null && w > 0.0 && h > 0.0) (w / h).toFloat() else null
2617
- } catch (e: Exception) {
2618
- // The native lease guard refuses reads against a destroyed engine.
2619
- Log.w(TAG, "[PlaybackTrace][Bridge][currentVideoAspect] ${e.message}")
2620
- null
2621
- }
2622
- }
2623
-
2624
2884
  @ReactMethod
2625
2885
  @Override
2626
2886
  override fun exitPip() {