@simba-dev/react-native-media-player 2.1.0 → 3.0.1

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.
@@ -2,6 +2,7 @@ package com.simba.player.mpv
2
2
 
3
3
  import android.content.Intent
4
4
  import android.graphics.Bitmap
5
+ import android.graphics.Rect
5
6
  import android.media.MediaMetadataRetriever
6
7
  import android.util.Log
7
8
  import java.io.File
@@ -2323,6 +2324,60 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2323
2324
  }
2324
2325
  }
2325
2326
 
2327
+ /**
2328
+ * The rect of the window the video actually occupies, or `null` when
2329
+ * there is no such rect.
2330
+ *
2331
+ * ## What the rect is
2332
+ *
2333
+ * Android's `setSourceRectHint` wants the region of the window where the
2334
+ * video is, so PiP entry animates the real frame into the PiP window
2335
+ * instead of growing out of a black rectangle.
2336
+ *
2337
+ * It is **not** the picture view's box. The picture fills its lane
2338
+ * (`StyleSheet.absoluteFill`), so the view's rect is the whole window,
2339
+ * and hinting that would make the PiP window take the window's shape —
2340
+ * portrait on a phone — with the video arriving tiny and letterboxed
2341
+ * inside it. The rect has to be the video's FRAME inside the view: the
2342
+ * largest rect of the video's own shape that fits inside it, or the
2343
+ * whole view when the picture is filling it.
2344
+ *
2345
+ * ## Where the numbers come from
2346
+ *
2347
+ * - the view's rect — `MpvRenderView.cachedWindowBounds`, published by
2348
+ * the UI thread on layout, because `getLocationInWindow()` is a
2349
+ * UI-thread API and this code runs on the bridge thread.
2350
+ * - the video's shape — `currentVideoAspect()`, the same `width` /
2351
+ * `height` properties `getVideoParams` reads.
2352
+ * - the zoom — `MpvRenderView.currentVideoZoom`, the `video-zoom` mpv
2353
+ * is rendering with right now.
2354
+ *
2355
+ * ## Why every step can answer `null`
2356
+ *
2357
+ * `null` is the honest answer when there is no video rect to point at:
2358
+ * no live picture, no layout yet, or no video dimensions. It degrades to
2359
+ * the platform's no-hint behaviour, which costs a black transition but
2360
+ * never a distorted one.
2361
+ *
2362
+ * The reader this replaces (`PlayerSurface.boundsInWindow`) answered
2363
+ * `null` **unconditionally** — it read a registry the V22 architecture
2364
+ * has no writer for — so PiP entry always grew out of a black
2365
+ * rectangle. That was the bug.
2366
+ */
2367
+ private fun pipSourceRectInWindow(): PictureFrame? {
2368
+ val view = MpvRenderViewRegistry.current() ?: return null
2369
+ val bounds = view.cachedWindowBounds ?: return null
2370
+ val aspect = currentVideoAspect() ?: return null
2371
+ return PipSourceRect.frameInWindow(
2372
+ bounds.left,
2373
+ bounds.top,
2374
+ bounds.width,
2375
+ bounds.height,
2376
+ aspect,
2377
+ view.currentVideoZoom,
2378
+ )
2379
+ }
2380
+
2326
2381
  /**
2327
2382
  * Push the PiP params the SYSTEM will use onto the Activity.
2328
2383
  *
@@ -2361,11 +2416,23 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2361
2416
  )
2362
2417
  return
2363
2418
  }
2364
- val aspect = currentVideoAspect() ?: (16f / 9f)
2419
+ // The window's shape and the source rect hint are taken from the
2420
+ // SAME frame, so they can never disagree. The system scales the
2421
+ // hinted region to the window non-proportionally when the two
2422
+ // shapes differ, and the video visibly arrives stretched.
2423
+ //
2424
+ // The frame's shape is the video's own shape whenever the
2425
+ // picture is rendered with `contain`, which is the app's
2426
+ // default: the frame inside the view IS the video, letterboxed
2427
+ // into the view's own shape. So the window's shape does not
2428
+ // change here — only the hint does, from `null` (a black
2429
+ // rectangle) to a real rect that points at the picture.
2430
+ val frame = pipSourceRectInWindow()
2431
+ val aspect = frame?.aspect ?: (currentVideoAspect() ?: (16f / 9f))
2365
2432
  val params = com.simba.player.PipManager.buildPipParams(
2366
2433
  context = activity,
2367
2434
  aspect = aspect,
2368
- sourceRectHint = PlayerSurface.boundsInWindow(),
2435
+ sourceRectHint = frame?.let { Rect(it.left, it.top, it.right, it.bottom) },
2369
2436
  autoEnter = true,
2370
2437
  )
2371
2438
  activity.runOnUiThread {
@@ -2432,30 +2499,43 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2432
2499
  //
2433
2500
  // Read from the same `width` / `height` properties `getVideoParams`
2434
2501
  // already reads, rather than adding a second, parallel way to ask
2435
- // mpv about dimensions.
2436
- val aspect = currentVideoAspect()
2437
- if (aspect == null) {
2502
+ // mpv about dimensions. The frame below is where the shape is
2503
+ // actually taken from when there is one; this is the fallback.
2504
+ val videoAspect = currentVideoAspect()
2505
+ if (videoAspect == null) {
2438
2506
  Log.w(
2439
2507
  TAG,
2440
2508
  "[PlaybackTrace][Bridge][enterPip] no video dimensions loaded " +
2441
2509
  "(no file, or audio-only); PiP window will use 16:9",
2442
2510
  )
2443
2511
  }
2444
- // Source rect hint: where the video actually is right now, in window
2445
- // coordinates. This is what makes PiP entry animate the real frame into
2446
- // the window instead of growing out of a black rectangle.
2512
+ // Source rect hint: the region of the window where the video
2513
+ // actually is, so PiP entry animates the real frame into the PiP
2514
+ // window instead of growing out of a black rectangle.
2515
+ //
2516
+ // It is NOT the picture view's box. The picture fills its lane, so
2517
+ // the view's rect is the whole window, and hinting that would make
2518
+ // the PiP window take the window's shape - portrait on a phone -
2519
+ // with the video arriving tiny and letterboxed inside it. It is the
2520
+ // video's FRAME inside the view: the largest rect of the video's own
2521
+ // shape that fits inside it, or the whole view when the picture is
2522
+ // filling it.
2447
2523
  //
2448
- // The hint's shape has to match the aspect ratio above, or the system
2449
- // scales the frame non-proportionally to fit and the video visibly
2450
- // arrives stretched. Both come from the same place -- the surface is
2451
- // sized with the video's own shape by `setVideoBounds` / `fillBounds`,
2452
- // and `boundsInWindow()` reports that same surface -- so they agree by
2453
- // construction instead of being kept in sync by hand.
2524
+ // The hint's shape has to match the aspect ratio below, or the
2525
+ // system scales the frame non-proportionally to fit and the video
2526
+ // visibly arrives stretched. So the aspect is taken FROM THE SAME
2527
+ // FRAME: the two agree by construction instead of being kept in
2528
+ // sync by hand.
2454
2529
  //
2455
- // Null when the surface is hidden or zero-sized: no video rect to
2456
- // animate from. That degrades to the no-hint behaviour, which costs a
2457
- // black transition but never a distorted one.
2458
- val sourceRect = PlayerSurface.boundsInWindow()
2530
+ // Null when there is no video rect to point at - no live picture, no
2531
+ // layout yet, or no video dimensions. That degrades to the no-hint
2532
+ // behaviour, which costs a black transition but never a distorted
2533
+ // one.
2534
+ val frame = pipSourceRectInWindow()
2535
+ val sourceRect = frame?.let { Rect(it.left, it.top, it.right, it.bottom) }
2536
+ // The PiP window's shape. Taken from the frame when there is one, so
2537
+ // it matches the hint exactly; the video's own aspect otherwise.
2538
+ val aspect = frame?.aspect ?: videoAspect ?: (16f / 9f)
2459
2539
  // `return try`, not a bare `try`. A `try`/`catch` in STATEMENT
2460
2540
  // position is not this function's return value in Kotlin — not
2461
2541
  // even as the last statement of a function with a non-`Unit`
@@ -2467,7 +2547,7 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2467
2547
  if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
2468
2548
  val pipParams = com.simba.player.PipManager.buildPipParams(
2469
2549
  context = activity,
2470
- aspect = aspect ?: (16f / 9f),
2550
+ aspect = aspect,
2471
2551
  sourceRectHint = sourceRect,
2472
2552
  chapterTitle = title,
2473
2553
  progressPercentage = pct,
@@ -90,8 +90,52 @@ class MpvRenderView(context: Context) : SurfaceView(context),
90
90
  /** @see MpvRenderViewManager.setVolume */
91
91
  var pendingVolume: Float = 100f
92
92
 
93
- /** mpv `video-zoom`: `0` fit · `1` fill/crop · `2` fill ignoring aspect. */
94
- private var pendingVideoZoom: String? = "0"
93
+ /**
94
+ * The zoom mode, as it is carried to mpv's `video-zoom` property:
95
+ * `0` contain · `1` cover · `2` stretch.
96
+ *
97
+ * The MODE names are this codebase's (see `SimbaVideo.tsx`); the numbers
98
+ * are what the engine is asked for.
99
+ */
100
+ private var pendingVideoZoom: String? = PipSourceRect.ZOOM_FIT
101
+
102
+ /**
103
+ * The view's rect in **window** coordinates, as of the last layout pass.
104
+ *
105
+ * This is the geometry the PiP source-rect hint is built from. It is
106
+ * cached rather than read on demand because
107
+ * `View.getLocationInWindow()` is a UI-thread API and the PiP code that
108
+ * needs the rect runs on the bridge thread — so the UI thread publishes
109
+ * it here and the bridge thread reads it.
110
+ *
111
+ * A plain field would not do. The writer is the UI thread and the reader
112
+ * is the bridge thread, and without `@Volatile` the reader could see a
113
+ * stale rect — or a half-written one — with nothing in the logs to say
114
+ * so. `@Volatile` makes the publication safe.
115
+ *
116
+ * `null` means "no rect to point at": the view has not been laid out
117
+ * yet, or it has no area. The caller degrades to the platform's no-hint
118
+ * behaviour rather than pointing at a region that does not exist.
119
+ */
120
+ @Volatile
121
+ var cachedWindowBounds: PictureFrame? = null
122
+ private set
123
+
124
+ /**
125
+ * The `video-zoom` mpv is rendering with **right now**.
126
+ *
127
+ * Not the pending one. A `resizeMode` that arrives before the mpv handle
128
+ * exists is recorded and applied later, so publishing the pending value
129
+ * would let the PiP source rect be computed against a zoom the engine
130
+ * has never rendered with — a rect describing a letterboxed picture when
131
+ * the picture is actually stretched.
132
+ *
133
+ * `0` (contain) until a zoom is applied, because that is the app's
134
+ * default `resizeMode` and the mode this module starts in.
135
+ */
136
+ @Volatile
137
+ var currentVideoZoom: String = PipSourceRect.ZOOM_FIT
138
+ private set
95
139
 
96
140
  fun nativePtrHandle(): Long = nativePtr
97
141
 
@@ -111,6 +155,50 @@ class MpvRenderView(context: Context) : SurfaceView(context),
111
155
  isClickable = false
112
156
  }
113
157
 
158
+ // ── Window geometry (the PiP source rect's raw material) ─────────────
159
+
160
+ /**
161
+ * Publish the view's rect in window coordinates.
162
+ *
163
+ * Always called from a layout callback, so it runs on the UI thread —
164
+ * which is the only thread allowed to ask a `View` where it is.
165
+ */
166
+ private fun refreshWindowBounds() {
167
+ // `getLocationInWindow()` answers (0, 0) for a view that is not
168
+ // attached to a window yet. That is a lie, and believing it would
169
+ // put the PiP hint in the top-left corner of the screen. No
170
+ // attachment, no rect.
171
+ if (!isAttachedToWindow || width <= 0 || height <= 0) {
172
+ cachedWindowBounds = null
173
+ return
174
+ }
175
+ val location = IntArray(2)
176
+ getLocationInWindow(location)
177
+ cachedWindowBounds = PictureFrame(
178
+ location[0],
179
+ location[1],
180
+ location[0] + width,
181
+ location[1] + height,
182
+ )
183
+ }
184
+
185
+ /**
186
+ * Refresh the cached window rect after every layout pass.
187
+ *
188
+ * `super.onLayout(...)` first: the view's own position is only final
189
+ * once the layout pass has run, so the rect is read afterwards.
190
+ */
191
+ override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
192
+ super.onLayout(changed, left, top, right, bottom)
193
+ refreshWindowBounds()
194
+ }
195
+
196
+ /** Refresh the cached window rect when the view's size changes. */
197
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
198
+ super.onSizeChanged(w, h, oldw, oldh)
199
+ refreshWindowBounds()
200
+ }
201
+
114
202
  // ── Bounds (V21) ──────────────────────────────────────────────────────
115
203
  //
116
204
  // V21 moves the player into the consumer app's single Activity, where
@@ -244,6 +332,11 @@ class MpvRenderView(context: Context) : SurfaceView(context),
244
332
  MPVLib.nativeSetVolume(nativePtr, pendingVolume.toDouble().coerceIn(0.0, 100.0))
245
333
  pendingVideoZoom?.let {
246
334
  MPVLib.setPropertyString(nativePtr, "video-zoom", it)
335
+ // The zoom that was held is applied NOW, so it is the one the
336
+ // engine renders with. Publishing it here is what keeps
337
+ // `currentVideoZoom` from describing a zoom that was never
338
+ // applied.
339
+ currentVideoZoom = it
247
340
  }
248
341
  }
249
342
 
@@ -258,6 +351,15 @@ class MpvRenderView(context: Context) : SurfaceView(context),
258
351
  pendingVideoZoom = zoom
259
352
  if (nativePtr == 0L) return
260
353
  MPVLib.setPropertyString(nativePtr, "video-zoom", zoom)
354
+ // Applied, so it is current. A zoom recorded WITHOUT a handle is
355
+ // not published here — it is published by `reapplyPendingProps`,
356
+ // at the moment it actually reaches the engine.
357
+ //
358
+ // A null zoom resets the engine's property, and the module's own
359
+ // default for a reset zoom is "0" (contain) — the same answer the
360
+ // pending field starts with, so the reader never sees a zoom that
361
+ // was never applied.
362
+ currentVideoZoom = zoom ?: PipSourceRect.ZOOM_FIT
261
363
  }
262
364
 
263
365
  /**
@@ -340,6 +442,18 @@ class MpvRenderView(context: Context) : SurfaceView(context),
340
442
  override fun onAttachedToWindow() {
341
443
  super.onAttachedToWindow()
342
444
  ensureSurfaceAttached("onAttachedToWindow")
445
+ // The view may have been laid out before it was attached, in which
446
+ // case the cached rect is missing; refresh it now that the window
447
+ // is there to be located in.
448
+ refreshWindowBounds()
449
+ }
450
+
451
+ override fun onDetachedFromWindow() {
452
+ // The cached rect describes a position in a window this view is no
453
+ // longer in. Leaving it published would point the PiP hint at
454
+ // somewhere the picture is not.
455
+ cachedWindowBounds = null
456
+ super.onDetachedFromWindow()
343
457
  }
344
458
 
345
459
  override fun onVisibilityChanged(changedView: View, visibility: Int) {
@@ -105,11 +105,30 @@ class MpvRenderViewManager : SimpleViewManager<MpvRenderView>() {
105
105
  * mpv's `video-zoom`, carried as a string because mpv properties are strings
106
106
  * and the spec declares this prop as `WithDefault<string, 'contain'>`.
107
107
  *
108
- * `0` fit / letterbox · `1` fill / crop · `2` fill, aspect ignored
108
+ * `0` unscaled · `1` twice the size · `2` four times the size
109
109
  *
110
110
  * Applied through [MpvRenderView] so a value that arrives before the handle
111
111
  * is held and re-applied on bind, instead of being silently lost against an
112
112
  * uninitialised mpv instance.
113
+ *
114
+ * ## What these numbers actually are
115
+ *
116
+ * mpv's `video-zoom` is **not** a fit / fill / stretch enum. It is a
117
+ * **log2 scale factor**: `0` is unscaled, `1` is twice the size, `2` is
118
+ * four times the size (mpv's manual, `--video-zoom`). So the three values
119
+ * are three magnified fits, and the mode names they carry in this codebase
120
+ * (`contain` / `cover` / `stretch`) do not describe what the engine renders:
121
+ *
122
+ * - `0` — a fit. The picture keeps its aspect and is letterboxed into the
123
+ * view. This one matches its name.
124
+ * - `1` — a **2x** magnification, cropped by the view. It is not a cover.
125
+ * - `2` — a **4x** magnification, cropped by the view. The aspect is
126
+ * **not** ignored, so it is not a stretch.
127
+ *
128
+ * The app asks for `cover` on its mini-player dock, so the dock is today a
129
+ * 2x magnified, cropped picture. The app's own bug tracker carries this as
130
+ * an open bug: the fix is mpv's `panscan` (`1.0` for cover) and
131
+ * `keepaspect` (`no` for stretch), not `video-zoom`.
113
132
  */
114
133
  @ReactProp(name = "resizeMode")
115
134
  fun setResizeMode(view: MpvRenderView, resizeMode: String?) {
@@ -0,0 +1,214 @@
1
+ package com.simba.player.mpv
2
+
3
+ /**
4
+ * A rectangle in **window** coordinates.
5
+ *
6
+ * `left` / `top` are the rect's origin in window space; `right` / `bottom`
7
+ * are its far edge, which is the exclusive convention `android.graphics.Rect`
8
+ * uses, so the conversion is a straight copy with no off-by-one to argue about.
9
+ *
10
+ * ## Why this exists
11
+ *
12
+ * Android's `setSourceRectHint` wants the region of the window where the
13
+ * video actually is, so PiP entry animates the real frame into the PiP
14
+ * window instead of growing out of a black rectangle.
15
+ *
16
+ * That region is **not** the picture view's box. The app's picture fills its
17
+ * lane (`StyleSheet.absoluteFill`), so the view's rect is the whole window,
18
+ * and handing the view's box to the system would tell it to make the PiP
19
+ * window the shape of the window — portrait on a phone — with the video
20
+ * arriving tiny and letterboxed inside it.
21
+ *
22
+ * So the rect has to be the video's FRAME inside the view: the largest rect
23
+ * of the video's own shape that fits inside the view (letterbox / pillarbox
24
+ * bars around it), or the whole view when the picture is filling it.
25
+ *
26
+ * ## Why the arithmetic is pure
27
+ *
28
+ * There is no Android framework type in this file's arithmetic on purpose.
29
+ * The module's Robolectric tests are `@Ignore`d because they cannot run
30
+ * offline, so a decision that lived behind an Android type would ship
31
+ * untested. Keeping the decision here means the unit test is plain JUnit and
32
+ * actually EXECUTES.
33
+ *
34
+ * The Android-side half — where the picture view is and how big it is — lives
35
+ * in `MpvRenderView`; the question "what rect of that view does the video
36
+ * occupy" lives here. One owner per fact.
37
+ */
38
+ data class PictureFrame(val left: Int, val top: Int, val right: Int, val bottom: Int) {
39
+
40
+ /** The rect's width. Never negative for a frame this module builds. */
41
+ val width: Int get() = right - left
42
+
43
+ /** The rect's height. Never negative for a frame this module builds. */
44
+ val height: Int get() = bottom - top
45
+
46
+ /**
47
+ * The rect's shape, as width / height.
48
+ *
49
+ * `0` when the rect has no height — the honest answer for a degenerate
50
+ * rect, and the reason callers must not divide by this themselves.
51
+ */
52
+ val aspect: Float get() = if (height > 0) width.toFloat() / height.toFloat() else 0f
53
+ }
54
+
55
+ /**
56
+ * The PiP source-rect arithmetic.
57
+ *
58
+ * ## What this decides
59
+ *
60
+ * Given the picture view's rect in window coordinates, the video's own aspect
61
+ * ratio, and the zoom the picture is rendered with, answer: **which rect of
62
+ * the window is the video?**
63
+ *
64
+ * ## The zoom modes
65
+ *
66
+ * `videoZoom` is the zoom the picture is being rendered with, which this
67
+ * codebase carries as a numeric string (`contain` → "0", `cover` → "1",
68
+ * `stretch` → "2"; see `SimbaVideo.tsx` and `MpvRenderViewManager.setResizeMode`).
69
+ *
70
+ * ## What those numbers are in mpv — and why this file does not care
71
+ *
72
+ * mpv's `video-zoom` is a log2 **scale factor**, not a fit / fill / stretch
73
+ * enum: `0` is unscaled, `1` is twice the size, `2` is four times the size.
74
+ * So the app's `cover` renders as a 2x magnified, cropped picture and its
75
+ * `stretch` as a 4x magnified one. (That is an open bug in the app's tracker;
76
+ * the fix is mpv's `panscan` / `keepaspect`.)
77
+ *
78
+ * The arithmetic here does not change, because it asks a question about the
79
+ * VISIBLE REGION rather than about the engine's internals: a picture that is
80
+ * magnified still covers every pixel of the view it is drawn in, so the
81
+ * region of the window the video occupies is the whole view either way. The
82
+ * only mode whose visible region is smaller than the view is the one that
83
+ * leaves bars around the picture — the unscaled fit.
84
+ *
85
+ * - **"0" — contain.** The picture is FITTED into the view, so the visible
86
+ * video is the LARGEST rect of the video's shape that FITS INSIDE the
87
+ * view, centred. Bars sit above/below (wider video) or left/right
88
+ * (narrower video).
89
+ * - **"1" — cover.** The picture FILLS the view, so everything the user can
90
+ * see is the view itself. The frame IS the view rect.
91
+ * - **"2" — stretch.** The picture FILLS the view too, so again the frame
92
+ * IS the view rect.
93
+ *
94
+ * The two filling modes answer the same rect, and that is not a
95
+ * coincidence: a picture that fills the view covers every pixel of it, so
96
+ * the region of the window the video occupies IS the view — whatever the
97
+ * engine does with the shape behind it.
98
+ *
99
+ * Anything else — an unrecognised mode, a blank string — is treated as
100
+ * contain. The app's default `resizeMode` is `contain`, so contain is the
101
+ * mode the video is actually rendering with in the common case, and it is
102
+ * the mode that keeps the frame's shape equal to the video's shape.
103
+ *
104
+ * ## Why the guards return `null`
105
+ *
106
+ * A source rect that describes nothing is worse than no source rect at all:
107
+ * the system would animate the PiP window out of a region that does not
108
+ * contain the video. `null` degrades to the platform's no-hint behaviour,
109
+ * which costs a black transition but never a distorted one.
110
+ */
111
+ object PipSourceRect {
112
+
113
+ /** The "contain" mode: the picture is fitted inside the view. */
114
+ const val ZOOM_FIT = "0"
115
+
116
+ /** The "cover" mode: the picture fills the view. */
117
+ const val ZOOM_FILL = "1"
118
+
119
+ /** The "stretch" mode: the picture fills the view. */
120
+ const val ZOOM_STRETCH = "2"
121
+
122
+ /**
123
+ * The window rect the video occupies, or `null` when there is no such
124
+ * rect to point at.
125
+ *
126
+ * @param viewLeft The picture view's left edge, in window coordinates.
127
+ * @param viewTop The picture view's top edge, in window coordinates.
128
+ * @param viewWidth The picture view's width, in pixels.
129
+ * @param viewHeight The picture view's height, in pixels.
130
+ * @param videoAspect The video's own width / height.
131
+ * @param videoZoom The zoom mode the picture is rendered with, as a
132
+ * numeric string ("0" contain · "1" cover · "2" stretch).
133
+ */
134
+ fun frameInWindow(
135
+ viewLeft: Int,
136
+ viewTop: Int,
137
+ viewWidth: Int,
138
+ viewHeight: Int,
139
+ videoAspect: Float,
140
+ videoZoom: String,
141
+ ): PictureFrame? {
142
+ // A view with no area has no video in it.
143
+ if (viewWidth <= 0 || viewHeight <= 0) return null
144
+
145
+ // NaN and infinity are not shapes. `NaN <= 0f` is false, so the
146
+ // finiteness check has to come first or a NaN aspect would sail
147
+ // through into the arithmetic below.
148
+ if (!videoAspect.isFinite() || videoAspect <= 0f) return null
149
+
150
+ return when (videoZoom.trim()) {
151
+ // Cover and stretch both fill the view, so in both cases the
152
+ // visible picture IS the view's rect.
153
+ ZOOM_FILL, ZOOM_STRETCH -> PictureFrame(
154
+ viewLeft,
155
+ viewTop,
156
+ viewLeft + viewWidth,
157
+ viewTop + viewHeight,
158
+ )
159
+
160
+ // Contain, and anything this code does not recognise.
161
+ else -> fitFrame(viewLeft, viewTop, viewWidth, viewHeight, videoAspect)
162
+ }
163
+ }
164
+
165
+ /**
166
+ * The largest rect of the video's shape that fits inside the view,
167
+ * centred in it.
168
+ *
169
+ * Two cases, and they are not interchangeable:
170
+ *
171
+ * - The video is WIDER than the view → the frame is the view's full
172
+ * width and a proportionally shorter height, centred vertically.
173
+ * Letterbox bars above and below.
174
+ * - The video is NARROWER than the view → the frame is the view's full
175
+ * height and a proportionally narrower width, centred horizontally.
176
+ * Pillarbox bars left and right.
177
+ */
178
+ private fun fitFrame(
179
+ viewLeft: Int,
180
+ viewTop: Int,
181
+ viewWidth: Int,
182
+ viewHeight: Int,
183
+ videoAspect: Float,
184
+ ): PictureFrame? {
185
+ val viewAspect = viewWidth.toFloat() / viewHeight.toFloat()
186
+
187
+ val fittedWidth: Int
188
+ val fittedHeight: Int
189
+ if (videoAspect > viewAspect) {
190
+ fittedWidth = viewWidth
191
+ fittedHeight = Math.round(viewWidth / videoAspect)
192
+ } else {
193
+ fittedHeight = viewHeight
194
+ fittedWidth = Math.round(viewHeight * videoAspect)
195
+ }
196
+
197
+ // A fit that rounds away to nothing has no rect to point at.
198
+ if (fittedWidth <= 0 || fittedHeight <= 0) return null
199
+
200
+ // Float rounding can push the fitted edge a pixel past the view's
201
+ // edge. The frame has to stay INSIDE the picture, or the hint would
202
+ // describe a region that is not on screen.
203
+ val width = fittedWidth.coerceAtMost(viewWidth)
204
+ val height = fittedHeight.coerceAtMost(viewHeight)
205
+ if (width <= 0 || height <= 0) return null
206
+
207
+ // Integer division centres the frame: the odd leftover pixel stays
208
+ // on the far side, which is the same choice the platform's own
209
+ // letterboxing makes and one pixel nobody can see.
210
+ val left = viewLeft + (viewWidth - width) / 2
211
+ val top = viewTop + (viewHeight - height) / 2
212
+ return PictureFrame(left, top, left + width, top + height)
213
+ }
214
+ }
@@ -1,7 +1,6 @@
1
1
  package com.simba.player.mpv
2
2
 
3
3
  import android.app.Activity
4
- import android.graphics.Rect
5
4
  import android.os.Looper
6
5
  import android.util.Log
7
6
  import android.view.View
@@ -40,12 +39,14 @@ import java.lang.ref.WeakReference
40
39
  * they are left with no writer, and reviving one would put the hazard back
41
40
  * in reach.
42
41
  *
43
- * [boundsInWindow] is the PiP source-rect hint. It reads [viewRef] too, so
44
- * it answers `null` and PiP entry has no rect to animate from. Fixing that
45
- * is a separate piece of work: the old rect was sized by [setBounds] /
46
- * [fillBounds], so it matched the video's own shape by construction, and the
47
- * Yoga-sized picture does not carry that guarantee. See the app's master
48
- * plan, bug `B-036`.
42
+ * The PiP source-rect hint does NOT live here. It used to be
43
+ * [boundsInWindow], which read [viewRef] — and [viewRef] has no writer in
44
+ * this architecture, so it answered `null` forever and PiP entry grew out of
45
+ * a black rectangle. The hint is built from the LIVE picture view instead
46
+ * (`MpvRenderViewRegistry`), because the picture's real on-screen bounds are
47
+ * the only thing that can say where the video is; and it is the video's FRAME
48
+ * inside that view, not the view's box. See `MpvBridgeModule`'s
49
+ * `pipSourceRectInWindow`.
49
50
  *
50
51
  * ## Why this file exists
51
52
  *
@@ -226,46 +227,6 @@ object PlayerSurface {
226
227
  fun setVisible(visible: Boolean): Boolean =
227
228
  withSurface("setVisible") { it.setSurfaceVisible(visible) }
228
229
 
229
- /**
230
- * The surface's current rect in window coordinates, or `null` when it has
231
- * no on-screen area.
232
- *
233
- * This is the `setSourceRectHint` Android wants at PiP entry. With it the
234
- * system animates the real video frame into the PiP window; without it the
235
- * window grows out of a black rectangle.
236
- *
237
- * The hint must describe a rect of the *same shape* as the PiP aspect
238
- * ratio, or the system scales the frame non-proportionally to fit and the
239
- * video visibly arrives stretched or squashed. Because this rect is the
240
- * surface itself and the surface is sized by [setBounds] / [fillBounds]
241
- * with the video's own shape, the two agree by construction rather than by
242
- * being kept in sync by hand.
243
- *
244
- * `null` is the honest answer while the surface is `GONE` or zero-sized --
245
- * there is no video rect to animate from, and returning a zero rect would
246
- * ask the system to animate from nothing. Null degrades to the no-hint
247
- * behaviour, which costs a black transition but never a distorted one.
248
- */
249
- @JvmStatic
250
- fun boundsInWindow(): Rect? {
251
- if (Looper.myLooper() != Looper.getMainLooper()) {
252
- Log.e(TAG, "boundsInWindow refused: must be called from the main thread")
253
- return null
254
- }
255
- val view = viewRef.get() ?: return null
256
- if (view.visibility != View.VISIBLE || view.width <= 0 || view.height <= 0) {
257
- return null
258
- }
259
- val location = IntArray(2)
260
- view.getLocationInWindow(location)
261
- return Rect(
262
- location[0],
263
- location[1],
264
- location[0] + view.width,
265
- location[1] + view.height,
266
- )
267
- }
268
-
269
230
  /**
270
231
  * Run [block] against the surface on the main thread.
271
232
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "2.1.0",
3
+ "version": "3.0.1",
4
4
  "description": "React Native video & audio player powered by libmpv — Picture-in-Picture, MediaSession, foreground service, and a customizable TypeScript UI. Built for Android. Designed as a drop-in replacement for react-native-video / react-native-track-player / expo-av. See CHANGELOG.md for per-version notes.",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -50,7 +50,7 @@ const PlayerConfigContext = createContext<ResolvedPlayerConfig | null>(null);
50
50
  * Returns the React tree to render as the player's chrome.
51
51
  *
52
52
  * Why a function (not a component): the parent decides WHEN to call
53
- * it (typically inside a `PlayerRoot` component), which lets us
53
+ * it (typically in the consumer's own tree), which lets us
54
54
  * wrap the result in error boundaries / suspense fallbacks in a
55
55
  * future phase without changing the consumer's API.
56
56
  */
@@ -114,8 +114,8 @@ export function useTheme(): PlayerTheme {
114
114
  * that wants controls renders them and passes them here.
115
115
  *
116
116
  * Returns `null` (not throws) when used outside a provider, because
117
- * `<PlayerRoot>` needs to render without chrome in that case. The
118
- * other hooks (`usePlayerConfig` / `useTheme`) throw because they
117
+ * a consumer's own root needs to render without chrome in that case.
118
+ * The other hooks (`usePlayerConfig` / `useTheme`) throw because they
119
119
  * have no useful fallback value.
120
120
  *
121
121
  * @example
@@ -479,8 +479,8 @@ export interface PlayerProviderProps {
479
479
  * The `renderControls` slot is intentionally NOT pushed to the native
480
480
  * side — it's a JS-only concept (a function reference can't be
481
481
  * serialised to JSON). Consumer apps wrap their PlayerActivity's JS
482
- * tree with `<PlayerProvider renderControls={...}>` and the
483
- * `<PlayerRoot>` component reads it via `useRenderControls()`.
482
+ * tree with `<PlayerProvider renderControls={...}>` and their own
483
+ * component reads it via `useRenderControls()`.
484
484
  *
485
485
  * V13 Phase 51: in addition to config + renderControls, the provider
486
486
  * now holds the live player state. The state is updated by:
@@ -12,6 +12,21 @@ export interface SimbaVideoProps extends NativeSimbaVideoViewProps {
12
12
  * How the picture fills this view. Maps onto mpv's `video-zoom`
13
13
  * (0 / 1 / 2) rather than being reimplemented.
14
14
  *
15
+ * ## The mapping is currently WRONG for `cover` and `stretch`
16
+ *
17
+ * mpv's `video-zoom` is a log2 **scale factor**, not a fit / fill / stretch
18
+ * enum: `0` is unscaled, `1` is twice the size, `2` is four times the size.
19
+ * So `cover` renders as a 2x magnified, cropped picture and `stretch` as a
20
+ * 4x magnified one — neither is what its name says, and the aspect is never
21
+ * ignored.
22
+ *
23
+ * `contain` is correct: `0` is unscaled, so the picture keeps its aspect
24
+ * and is letterboxed into the view.
25
+ *
26
+ * The fix is mpv's `panscan` (`1.0` for cover) and `keepaspect` (`no` for
27
+ * stretch), which is a change in the native half. Until that lands, treat
28
+ * `cover` and `stretch` as "a magnified fit", not as a cover and a stretch.
29
+ *
15
30
  * @default 'contain'
16
31
  */
17
32
  resizeMode?: SimbaVideoResizeMode;
package/src/index.ts CHANGED
@@ -41,9 +41,26 @@
41
41
  * the surface and the consumer's controls, and **nothing else** when
42
42
  * `renderControls` is absent.
43
43
  *
44
- * This is a **breaking** change, hence the major version. `<PlayerRoot>`
45
- * without `renderControls` renders no controls after 2.0.0, where it
46
- * rendered `DefaultControls` before.
44
+ * This is a **breaking** change, hence the major version.
45
+ *
46
+ * ## v3.0.0 — the vestigial root and surface are gone
47
+ *
48
+ * `<PlayerRoot>` and `<PlayerSurface>` are **removed**. They were the
49
+ * JS-side remainder of an arrangement that ended in 2.0.0: a native
50
+ * `SurfaceView` pinned to the Activity root, with a transparent React box
51
+ * standing in for it so a controls overlay had a rectangle to anchor to.
52
+ *
53
+ * The picture is `<SimbaVideo>` now — a Fabric component in the
54
+ * consumer's own tree, with React Native owning its layout, its z-order
55
+ * and its lifecycle — so there is no surface for a placeholder to
56
+ * reserve. Neither component had an importer: in this package and in its
57
+ * host app, the only reference to either was its own export.
58
+ *
59
+ * A consumer that used `<PlayerRoot>` for its **launch** — the one job it
60
+ * still had — loses nothing: `useLaunchPlayback` is still exported, and
61
+ * it is still the once-per-payload load. A consumer that used it for the
62
+ * **overlay** composes the same thing from a `View` and its own
63
+ * `renderControls`.
47
64
  */
48
65
 
49
66
  export {
@@ -55,16 +72,12 @@ export {
55
72
  type RenderControlsFn,
56
73
  } from './components/PlayerProvider';
57
74
 
58
- export { PlayerRoot } from './components/PlayerRoot';
59
-
60
75
  export {
61
76
  SimbaVideo,
62
77
  type SimbaVideoProps,
63
78
  type SimbaVideoResizeMode,
64
79
  } from './components/SimbaVideo';
65
80
 
66
- export { PlayerSurface, type PlayerSurfaceProps } from './components/PlayerSurface';
67
-
68
81
  export {
69
82
  type AudioConfig,
70
83
  type DebugConfig,
@@ -142,11 +155,11 @@ export {
142
155
  DEFAULT_FRAME_QUALITY,
143
156
  type CaptureFrameOptions,
144
157
  } from './hooks/useResumeThumbnail';
145
- // V21 F5 — the load half of `<PlayerRoot>`, and the in-window launch
146
- // primitive. Video no longer starts an Activity, so a consumer that
147
- // wants to play media into its own already-mounted surface drives it
148
- // from here: pass the payload, and `useLaunchPlayback` loads it exactly
149
- // once. See its docstring for the once-per-payload contract.
158
+ // V21 F5 — the in-window launch primitive. Video no longer starts an
159
+ // Activity, so a consumer that wants to play media into its own
160
+ // already-mounted surface drives it from here: pass the payload, and
161
+ // `useLaunchPlayback` loads it exactly once. See its docstring for the
162
+ // once-per-payload contract.
150
163
  export {useLaunchPlayback} from './hooks/useLaunchPlayback';
151
164
 
152
165
  export {
@@ -1,124 +0,0 @@
1
- import React from 'react';
2
- import { StyleSheet, View } from 'react-native';
3
- import { useRenderControls } from './PlayerProvider';
4
- import { useLaunchPlayback } from '../hooks/useLaunchPlayback';
5
- import type { LaunchParams } from '../bridge/MpvPlayerModule';
6
- import { PlayerSurface } from './PlayerSurface';
7
-
8
- /**
9
- * The player's root: the surface, and the consumer's controls over it.
10
- *
11
- * ## v2.0.0 — the library draws no chrome
12
- *
13
- * Before 2.0.0 this component fell back to `<DefaultControls>` — the
14
- * 564-line control bundle the library used to ship — whenever the
15
- * consumer did not pass `renderControls`. That fallback is **gone**.
16
- * The library renders **no chrome of its own**: the consumer's
17
- * `renderControls` output, or nothing at all.
18
- *
19
- * The overlay is mounted only when there is something to put in it, so
20
- * a consumer that drives the player itself (the usual case — render
21
- * `<SimbaVideo />` in your own tree) gets no phantom container over
22
- * the surface.
23
- *
24
- * V21 F5: `launchParams` is now an explicit prop with no implicit
25
- * fallback. It used to fall back to `useLaunchParams()`, which read a
26
- * one-shot native queue that only a second Activity ever filled — so the
27
- * fallback could not fire, and keeping it would have been a branch that
28
- * looked live and was not. Pass the payload in, or drive loading
29
- * yourself with the exported `useLaunchPlayback`.
30
- *
31
- * Renders the full player UI in two layers:
32
- * 1. **`<PlayerSurface />`** (Phase 25): the JS-side placeholder
33
- * for the native SurfaceView that mpv draws into. Fills the
34
- * available space via `flex: 1`.
35
- * 2. **Controls overlay** (Phase 23 + 24): the consumer's custom
36
- * controls, via `renderControls`. Absolutely positioned over the
37
- * surface so the video fills the screen and the controls layer on
38
- * top.
39
- *
40
- * Wiring example for a consumer:
41
- *
42
- * @example
43
- * ```tsx
44
- * function App() {
45
- * return (
46
- * <PlayerProvider
47
- * config={{ theme: { accent: '#FFD700' } }}
48
- * renderControls={() => <MyCustomControls />}
49
- * >
50
- * <PlayerRoot />
51
- * </PlayerProvider>
52
- * );
53
- * }
54
- * ```
55
- *
56
- * Design notes
57
- * ------------
58
- * - The controls overlay uses `position: 'absolute'` + the four
59
- * insets (`top / left / right / bottom: 0`) so it stretches over
60
- * the surface without affecting its layout. The surface owns the
61
- * flex layout for the tree; the controls float on top.
62
- * - When `renderControls` is provided, we render its output
63
- * wrapped in the same absolutely-positioned overlay container,
64
- * so custom controls don't need to handle their own
65
- * positioning — they Just Work over the surface.
66
- */
67
- /**
68
- * V22.0.0 / 1.5.8 (D-035 fix #5): optional `launchParams` prop.
69
- *
70
- * `<SimbaPlayerRoot>` already calls `useLaunchParams()` once at the
71
- * activity boundary. If we also called it here, the second read would
72
- * hit an empty one-shot queue (the first read consumed it) and we'd
73
- * fall through to the `null` branch — leaving the screen with no
74
- * media loaded. Letting the parent pass `launchParams` down as a
75
- * prop means the player root always sees the resolved payload.
76
- *
77
- * Direct consumers that mount `<PlayerRoot />` without
78
- * `<SimbaPlayerRoot>` (rare; legacy V11/V12 patterns) keep working:
79
- * when `launchParams` is left `undefined` we fall back to the hook,
80
- * which reads the queue exactly once and returns `null` on
81
- * subsequent mounts.
82
- */
83
- export interface PlayerRootProps {
84
- launchParams?: LaunchParams | null;
85
- }
86
-
87
- export function PlayerRoot({
88
- launchParams,
89
- }: PlayerRootProps = {}): React.ReactElement {
90
- const renderControls = useRenderControls();
91
-
92
- // V22.0.0 / 1.5.8 (D-035 fix #3 + #5 + #7): feed the launch URI to
93
- // mpv exactly once per `(uri, startPositionMs)` payload, NOT once
94
- // per render. `useLaunchPlayback` owns that contract.
95
- // The effect is keyed on the URI + start position, so it fires once
96
- // when the payload resolves to a real URI, then never again until
97
- // the URI actually changes.
98
- useLaunchPlayback(launchParams);
99
-
100
- // The library draws no chrome. Whatever the consumer supplied is
101
- // what appears over the surface; if the consumer supplied nothing,
102
- // there is nothing to draw.
103
- const controls = renderControls != null ? renderControls() : null;
104
-
105
- return (
106
- <View style={styles.root}>
107
- <PlayerSurface />
108
- {controls != null ? <View style={styles.overlay}>{controls}</View> : null}
109
- </View>
110
- );
111
- }
112
-
113
- const styles = StyleSheet.create({
114
- root: {
115
- flex: 1,
116
- },
117
- overlay: {
118
- position: 'absolute',
119
- top: 0,
120
- left: 0,
121
- right: 0,
122
- bottom: 0,
123
- },
124
- });
@@ -1,62 +0,0 @@
1
- import React from 'react';
2
- import { StyleSheet, View } from 'react-native';
3
-
4
- export interface PlayerSurfaceProps {
5
- /**
6
- * Background color for the placeholder. Defaults to `'transparent'`,
7
- * so whatever is behind it shows through to the user.
8
- *
9
- * **v2.0.0:** the native SurfaceView this placeholder used to stand
10
- * in for is gone — the picture is `<SimbaVideo />`, in the React
11
- * tree. A non-transparent value therefore paints a backdrop *over*
12
- * the picture wherever the placeholder sits in front of it.
13
- */
14
- backgroundColor?: string;
15
- }
16
-
17
- /**
18
- * A transparent, full-size **layout placeholder**.
19
- *
20
- * ## v2.0.0 — what this is, and is not
21
- *
22
- * This component used to stand in for the native SurfaceView that mpv
23
- * drew into. Back then the surface was a **sibling** of the React
24
- * root — pinned to `android.R.id.content` by the library's own
25
- * `PlayerActivity` — and this box reserved the screen rectangle the
26
- * controls overlay was positioned against.
27
- *
28
- * **That arrangement is gone.** The picture is now `<SimbaVideo />`:
29
- * a Fabric component (`SimbaVideoView`) inside the React tree, with
30
- * React Native owning its layout, its z-order and its lifecycle.
31
- * Neither the library nor a host app mounts a surface at the activity
32
- * root any more — a host app's Activity says so in as many words.
33
- *
34
- * What is left is a transparent `flex: 1` box: a full-size rectangle
35
- * for a controls overlay to anchor to. `<PlayerRoot>` renders it.
36
- *
37
- * Whether this component and `<PlayerRoot>` should exist at all is an
38
- * open question — see `B-035` in the app's master plan. Until that is
39
- * decided they stay: a published package cannot quietly drop a public
40
- * export.
41
- */
42
- export function PlayerSurface({
43
- backgroundColor = 'transparent',
44
- }: PlayerSurfaceProps): React.ReactElement {
45
- return (
46
- <View
47
- style={[styles.surface, { backgroundColor }]}
48
- accessibilityElementsHidden
49
- importantForAccessibility="no-hide-descendants"
50
- // Collapses any accessibility tree contribution from this
51
- // placeholder; the SurfaceView on the native side is already
52
- // hidden from a11y (Phase 4 sets `importantForAccessibility`
53
- // to `no` on the MpvRenderView).
54
- />
55
- );
56
- }
57
-
58
- const styles = StyleSheet.create({
59
- surface: {
60
- flex: 1,
61
- },
62
- });