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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +317 -560
  2. package/android/src/main/cpp/main.cpp +117 -17
  3. package/android/src/main/java/com/simba/player/PipManager.kt +13 -0
  4. package/android/src/main/java/com/simba/player/mpv/MpvBridgeModule.kt +187 -8
  5. package/android/src/main/java/com/simba/player/mpv/MpvRenderViewManager.kt +11 -1
  6. package/android/src/main/java/com/simba/player/mpv/MpvRenderViewRegistry.kt +132 -0
  7. package/android/src/main/java/com/simba/player/mpv/PipAutoEnterPolicy.kt +54 -0
  8. package/android/src/main/java/com/simba/player/mpv/PlayerSurface.kt +41 -1
  9. package/package.json +11 -2
  10. package/src/bridge/MpvPlayerModule.ts +7 -1
  11. package/src/bridge/NativeMpvPlayer.ts +3 -3
  12. package/src/types/player.ts +7 -1
  13. package/android/src/test/java/com/simba/player/PipActionReceiverTest.kt +0 -123
  14. package/android/src/test/java/com/simba/player/PipManagerTest.kt +0 -281
  15. package/android/src/test/java/com/simba/player/TestApplication.kt +0 -26
  16. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleNullInstanceTest.kt +0 -117
  17. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleTest.kt +0 -212
  18. package/android/src/test/java/com/simba/player/mpv/MpvRenderViewTest.kt +0 -249
  19. package/scripts/override_react_methods.js +0 -184
  20. package/scripts/override_react_methods.py +0 -150
  21. package/src/bridge/__tests__/MpvPlayerModule.test.ts +0 -110
  22. package/src/bridge/__tests__/debugMode.test.ts +0 -138
  23. package/src/bridge/__tests__/errorContract.test.ts +0 -175
  24. package/src/bridge/__tests__/loadAndPlay.startPosition.test.tsx +0 -142
  25. package/src/components/__tests__/PlayerProvider.performance.test.tsx +0 -242
  26. package/src/components/__tests__/PlayerProvider.progressContext.test.tsx +0 -194
  27. package/src/components/__tests__/PlayerProvider.test.tsx +0 -558
  28. package/src/components/__tests__/PlayerRoot.test.tsx +0 -71
  29. package/src/components/__tests__/SimbaVideo.test.tsx +0 -164
  30. package/src/hooks/__tests__/resolveStreamType.test.ts +0 -159
  31. package/src/hooks/__tests__/useLaunchPlayback.test.tsx +0 -278
  32. package/src/hooks/__tests__/useResumeThumbnail.test.ts +0 -154
  33. package/src/stores/__tests__/playerQueueSelectionStore.test.ts +0 -73
  34. package/src/stores/__tests__/playerQueueStore.test.ts +0 -171
  35. package/src/types/__tests__/config.test.ts +0 -188
  36. package/src/types/__tests__/player.pipAnswer.test.tsx +0 -87
  37. package/src/types/__tests__/player.pipArity.test.tsx +0 -74
  38. package/src/types/__tests__/player.test.tsx +0 -1365
  39. package/src/types/__tests__/playerLoading.test.ts +0 -170
@@ -171,7 +171,88 @@ static JNIEnv *getEnv() {
171
171
  static void flushMpvCore(mpv_handle *mpv) {
172
172
  if (!mpv) return;
173
173
  const char *cmd[] = {"ignore", nullptr};
174
- mpv_command(mpv, cmd);
174
+ // FIRE-AND-FORGET BY DESIGN - not an oversight.
175
+ //
176
+ // `ignore` is a no-op command, so its return value carries no
177
+ // information about whether the flush worked: the whole point of
178
+ // this call is that it BLOCKS until mpv has drained its core
179
+ // queue. Reporting a failure here would be reporting an error we
180
+ // invented, so the result is deliberately not acted on.
181
+ //
182
+ // It is still CAPTURED, because the file-wide invariant is that no
183
+ // mpv_command() call in this file throws its return value away
184
+ // (see runMpvCommand below, and the guard test that pins it).
185
+ const int result = mpv_command(mpv, cmd);
186
+ (void)result;
187
+ }
188
+
189
+ // ── Helper: report a refused mpv command to JS ────────────────────────────
190
+ //
191
+ // mpv reports a command failure through the RETURN VALUE of
192
+ // mpv_command(): 0 is success, a negative value is one of mpv's own
193
+ // error codes (`include/mpv/client.h`, `mpv_error`) -
194
+ // MPV_ERROR_COMMAND (-12) for a command the core refuses,
195
+ // MPV_ERROR_LOADING_FAILED (-13) for a source it cannot open.
196
+ //
197
+ // Every command in this file used to THROW THAT VALUE AWAY. A refused
198
+ // seek was therefore indistinguishable from a completed one: the scrub
199
+ // bar stayed where it was, no error was raised anywhere, and the app
200
+ // believed the seek had worked. That is the silent lie B-007 is about.
201
+ //
202
+ // The failure now travels the EXISTING error path - the same
203
+ // MPVLib.onNativeError(code, recoverable, message, requestId) callback
204
+ // that event.cpp uses for mpv's own failures - so it lands on the same
205
+ // `onError` event, with the same `{code, codeName, nativeCode,
206
+ // recoverable, message}` payload, and the same stable contract the
207
+ // Kotlin bridge already maps (-12 -> "E_COMMAND_FAILED" -> 3016). No new
208
+ // event, no new channel, no new error shape.
209
+ //
210
+ // `recoverable = true` is the TRUTH here: a refused command does not
211
+ // end playback - mpv keeps playing whatever it was playing. The app
212
+ // renders a terminal error card only for `recoverable === false`, so
213
+ // the failure is REPORTED rather than hidden, and it never paints over
214
+ // a picture that is still moving.
215
+ static void reportCommandFailure(const char *command, int result, const char *detail) {
216
+ const char *reason = mpv_error_string(result);
217
+ LOGE("[PlaybackTrace][Native][command] '%s' failed: %s (code=%d)%s%s",
218
+ command, reason, result,
219
+ (detail && detail[0]) ? " - " : "", (detail && detail[0]) ? detail : "");
220
+ JNIEnv *env = getEnv();
221
+ if (!env || !g_cls_MPVLib || !g_mid_onError) return;
222
+ char message[192];
223
+ snprintf(message, sizeof(message), "mpv command '%s' failed: %s%s%s",
224
+ command, reason,
225
+ (detail && detail[0]) ? " - " : "", (detail && detail[0]) ? detail : "");
226
+ jstring jMessage = env->NewStringUTF(message);
227
+ jstring jRequestId = env->NewStringUTF("");
228
+ env->CallStaticVoidMethod(g_cls_MPVLib, g_mid_onError,
229
+ static_cast<jint>(result),
230
+ static_cast<jboolean>(true),
231
+ jMessage, jRequestId);
232
+ if (env->ExceptionCheck()) {
233
+ LOGE("onNativeError raised an exception; clearing it on the calling thread");
234
+ env->ExceptionClear();
235
+ }
236
+ if (jMessage) env->DeleteLocalRef(jMessage);
237
+ if (jRequestId) env->DeleteLocalRef(jRequestId);
238
+ }
239
+
240
+ // Runs an mpv command and REPORTS a refusal instead of swallowing it.
241
+ //
242
+ // Every mpv_command() call in this file goes through here (or captures
243
+ // its result inline), so "the command was refused" can never again be
244
+ // indistinguishable from "the command worked".
245
+ //
246
+ // Returns mpv's own return value so a caller that has to act on it can:
247
+ // nativeScreenshot hands JS a path, and a path to a file that was never
248
+ // written is a lie of the same family.
249
+ static int runMpvCommand(mpv_handle *mpv, const char **args,
250
+ const char *command, const char *detail) {
251
+ const int result = mpv_command(mpv, args);
252
+ if (result < 0) {
253
+ reportCommandFailure(command, result, detail);
254
+ }
255
+ return result;
175
256
  }
176
257
 
177
258
  // ── Lifecycle ─────────────────────────────────────────────────────────────
@@ -541,7 +622,7 @@ Java_com_simba_player_mpv_MPVLib_nativeStop(JNIEnv *env, jclass, jlong nativePtr
541
622
  if (!lease.valid()) return;
542
623
  mpv_handle *mpv = lease.get();
543
624
  const char *args[] = {"stop", nullptr};
544
- mpv_command(mpv, args);
625
+ runMpvCommand(mpv, args, "stop", nullptr);
545
626
  }
546
627
 
547
628
  extern "C" JNIEXPORT void JNICALL
@@ -564,7 +645,10 @@ Java_com_simba_player_mpv_MPVLib_nativeSeek(
564
645
  char cmd[64];
565
646
  snprintf(cmd, sizeof(cmd), "%.3f", position);
566
647
  const char *args[] = {"seek", cmd, "absolute", nullptr};
567
- mpv_command(mpv, args);
648
+ // B-007: the return value used to be thrown away here, so a seek
649
+ // mpv refused was indistinguishable from a seek that worked. The
650
+ // scrub bar simply did not move and nothing was reported.
651
+ runMpvCommand(mpv, args, "seek", cmd);
568
652
  }
569
653
 
570
654
  extern "C" JNIEXPORT void JNICALL
@@ -576,7 +660,12 @@ Java_com_simba_player_mpv_MPVLib_nativeSeekRelative(
576
660
  char cmd[64];
577
661
  snprintf(cmd, sizeof(cmd), "%.3f", seconds);
578
662
  const char *args[] = {"seek", cmd, "relative", nullptr};
579
- mpv_command(mpv, args);
663
+ // B-007: same defect as the absolute seek above - the refusal used
664
+ // to be discarded, so a relative skip that did not happen looked
665
+ // exactly like one that did.
666
+ char detail[64];
667
+ snprintf(detail, sizeof(detail), "relative %+.3f s", seconds);
668
+ runMpvCommand(mpv, args, "seek", detail);
580
669
  }
581
670
 
582
671
  extern "C" JNIEXPORT void JNICALL
@@ -587,10 +676,10 @@ Java_com_simba_player_mpv_MPVLib_nativeStepFrame(
587
676
  mpv_handle *mpv = lease.get();
588
677
  if (direction > 0) {
589
678
  const char *args[] = {"frame-step", nullptr};
590
- mpv_command(mpv, args);
679
+ runMpvCommand(mpv, args, "frame-step", nullptr);
591
680
  } else {
592
681
  const char *args[] = {"frame-back-step", nullptr};
593
- mpv_command(mpv, args);
682
+ runMpvCommand(mpv, args, "frame-back-step", nullptr);
594
683
  }
595
684
  }
596
685
 
@@ -602,8 +691,14 @@ Java_com_simba_player_mpv_MPVLib_nativeScreenshot(
602
691
  mpv_handle *mpv = lease.get();
603
692
  const char *path = env->GetStringUTFChars(outputPath, nullptr);
604
693
  const char *args[] = {"screenshot-to-file", path, nullptr};
605
- mpv_command(mpv, args);
694
+ const int result = runMpvCommand(mpv, args, "screenshot-to-file", path);
606
695
  env->ReleaseStringUTFChars(outputPath, path);
696
+ // A refused screenshot wrote NO file. Returning the path anyway
697
+ // would hand JS a path to a file that does not exist - the same
698
+ // silent lie this change removes everywhere else. The empty string
699
+ // is what this method already returns when the handle is not
700
+ // usable, and it is what the no-op JS bridge returns too.
701
+ if (result < 0) return env->NewStringUTF("");
607
702
  return outputPath;
608
703
  }
609
704
 
@@ -732,7 +827,9 @@ Java_com_simba_player_mpv_MPVLib_nativeLoadPlaylist(
732
827
  if (!lease.valid()) return;
733
828
  mpv_handle *mpv = lease.get();
734
829
  const char *clearArgs[] = {"playlist-clear", nullptr};
735
- mpv_command(mpv, clearArgs);
830
+ // B-007: the clear used to discard mpv's verdict, so a playlist
831
+ // that was NOT cleared looked exactly like one that was.
832
+ runMpvCommand(mpv, clearArgs, "playlist-clear", nullptr);
736
833
  jsize count = env->GetArrayLength(paths);
737
834
  for (jsize i = 0; i < count; i++) {
738
835
  jstring jpath = (jstring)env->GetObjectArrayElement(paths, i);
@@ -756,7 +853,7 @@ Java_com_simba_player_mpv_MPVLib_nativePlaylistNext(
756
853
  if (!lease.valid()) return;
757
854
  mpv_handle *mpv = lease.get();
758
855
  const char *args[] = {"playlist-next", nullptr};
759
- mpv_command(mpv, args);
856
+ runMpvCommand(mpv, args, "playlist-next", nullptr);
760
857
  }
761
858
 
762
859
  extern "C" JNIEXPORT void JNICALL
@@ -766,7 +863,7 @@ Java_com_simba_player_mpv_MPVLib_nativePlaylistPrev(
766
863
  if (!lease.valid()) return;
767
864
  mpv_handle *mpv = lease.get();
768
865
  const char *args[] = {"playlist-prev", nullptr};
769
- mpv_command(mpv, args);
866
+ runMpvCommand(mpv, args, "playlist-prev", nullptr);
770
867
  }
771
868
 
772
869
  extern "C" JNIEXPORT void JNICALL
@@ -778,7 +875,7 @@ Java_com_simba_player_mpv_MPVLib_nativePlaylistRemove(
778
875
  char cmd[32];
779
876
  snprintf(cmd, sizeof(cmd), "%d", index);
780
877
  const char *args[] = {"playlist-remove", cmd, nullptr};
781
- mpv_command(mpv, args);
878
+ runMpvCommand(mpv, args, "playlist-remove", cmd);
782
879
  }
783
880
 
784
881
  extern "C" JNIEXPORT void JNICALL
@@ -788,7 +885,7 @@ Java_com_simba_player_mpv_MPVLib_nativePlaylistShuffle(
788
885
  if (!lease.valid()) return;
789
886
  mpv_handle *mpv = lease.get();
790
887
  const char *args[] = {"playlist-shuffle", nullptr};
791
- mpv_command(mpv, args);
888
+ runMpvCommand(mpv, args, "playlist-shuffle", nullptr);
792
889
  }
793
890
 
794
891
  extern "C" JNIEXPORT void JNICALL
@@ -798,7 +895,10 @@ Java_com_simba_player_mpv_MPVLib_nativePlaylistClear(
798
895
  if (!lease.valid()) return;
799
896
  mpv_handle *mpv = lease.get();
800
897
  const char *clearArgs[] = {"playlist-clear", nullptr};
801
- mpv_command(mpv, clearArgs);
898
+ // B-007: the third command the register named. The verdict mpv
899
+ // returned was discarded, so a playlist that was NOT cleared was
900
+ // indistinguishable from one that was.
901
+ runMpvCommand(mpv, clearArgs, "playlist-clear", nullptr);
802
902
  }
803
903
 
804
904
  // `nativeSelectTrack()` was REMOVED — it carried no track type, and it
@@ -818,10 +918,10 @@ Java_com_simba_player_mpv_MPVLib_nativeSetVideoFilter(
818
918
  const char *utf = env->GetStringUTFChars(filter, nullptr);
819
919
  if (enable) {
820
920
  const char *cmd[] = {"vf", "add", utf, nullptr};
821
- mpv_command(mpv, cmd);
921
+ runMpvCommand(mpv, cmd, "vf add", utf);
822
922
  } else {
823
923
  const char *cmd[] = {"vf", "del", utf, nullptr};
824
- mpv_command(mpv, cmd);
924
+ runMpvCommand(mpv, cmd, "vf del", utf);
825
925
  }
826
926
  env->ReleaseStringUTFChars(filter, utf);
827
927
  }
@@ -836,10 +936,10 @@ Java_com_simba_player_mpv_MPVLib_nativeSetAudioFilter(
836
936
  const char *utf = env->GetStringUTFChars(filter, nullptr);
837
937
  if (enable) {
838
938
  const char *cmd[] = {"af", "add", utf, nullptr};
839
- mpv_command(mpv, cmd);
939
+ runMpvCommand(mpv, cmd, "af add", utf);
840
940
  } else {
841
941
  const char *cmd[] = {"af", "del", utf, nullptr};
842
- mpv_command(mpv, cmd);
942
+ runMpvCommand(mpv, cmd, "af del", utf);
843
943
  }
844
944
  env->ReleaseStringUTFChars(filter, utf);
845
945
  }
@@ -68,6 +68,7 @@ object PipManager {
68
68
  sourceRectHint: Rect? = null,
69
69
  chapterTitle: String? = null,
70
70
  progressPercentage: String? = null,
71
+ autoEnter: Boolean = false,
71
72
  ): PictureInPictureParams {
72
73
  val actions = mutableListOf<RemoteAction>()
73
74
 
@@ -132,6 +133,18 @@ object PipManager {
132
133
  builder.setSeamlessResizeEnabled(true)
133
134
  }
134
135
 
136
+ // Auto-enter PiP when the user leaves the app (Android 12+).
137
+ //
138
+ // This is the platform's OWN switch: with it set, the system
139
+ // transitions the activity into PiP when the user swipes home,
140
+ // instead of the app having to request it. Below API 31 the
141
+ // platform has no equivalent - an app would have to override
142
+ // `onUserLeaveHint()` in its own Activity, and this library ships
143
+ // no Activity - so PiP entry stays manual there.
144
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
145
+ builder.setAutoEnterEnabled(autoEnter)
146
+ }
147
+
135
148
  // Source rect hint for smooth entry animation (Android 12+)
136
149
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && sourceRectHint != null) {
137
150
  builder.setSourceRectHint(sourceRectHint)
@@ -119,6 +119,15 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
119
119
  @Volatile
120
120
  private var currentConfig: Map<String, Any?>? = null
121
121
 
122
+ /**
123
+ * Whether PiP should auto-enter when the user leaves the app.
124
+ *
125
+ * Read from `pip.autoEnterOnLeave` in the resolved config (and
126
+ * gated by `pip.enabled`, which is the master switch for every PiP
127
+ * entry request). It used to be a public flag that NOTHING read.
128
+ */
129
+ private var pipAutoEnter: Boolean = false
130
+
122
131
  /**
123
132
  * Phase 21: recursive JSONObject → Kotlin Map converter. Used
124
133
  * by [setConfig] so the stored config can be consumed
@@ -291,6 +300,13 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
291
300
  "surfaceAttached" -> "onSurfaceAttached"
292
301
  else -> event
293
302
  }
303
+ // The video's dimensions just changed. The params the SYSTEM
304
+ // reads for an auto-enter carry the aspect ratio, so they
305
+ // have to be refreshed with the new one - otherwise the
306
+ // auto-entered window has the shape of the previous video.
307
+ if (event == "videoReconfig") {
308
+ applyActivityPipParams()
309
+ }
294
310
  try {
295
311
  val payload = JsonUtil.jsonStringToReactMap(jsonPayload)
296
312
  eventEmitter.emit(jsEvent, payload)
@@ -2171,14 +2187,22 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2171
2187
  }
2172
2188
 
2173
2189
  /**
2174
- * Whether a video surface is currently mounted and usable.
2190
+ * Whether a video picture view is currently mounted.
2175
2191
  *
2176
2192
  * Lets a control decide its own affordance instead of assuming a surface
2177
2193
  * exists because the user is on a video screen.
2194
+ *
2195
+ * The answer comes from [MpvRenderViewRegistry], which
2196
+ * [MpvRenderViewManager] writes when React Native creates a picture
2197
+ * view. It used to come from `PlayerSurface.current()`, whose only
2198
+ * writer — `PlayerSurface.mount()` — the V22 architecture never calls,
2199
+ * so the answer was `false` forever and `commands.openPlayer(...)`
2200
+ * refused **every** video, including the ones a consumer had a picture
2201
+ * mounted for.
2178
2202
  */
2179
2203
  @ReactMethod(isBlockingSynchronousMethod = true)
2180
2204
  @Override
2181
- override fun isSurfaceMounted(): Boolean = PlayerSurface.current() != null
2205
+ override fun isSurfaceMounted(): Boolean = MpvRenderViewRegistry.hasLiveView()
2182
2206
 
2183
2207
  /**
2184
2208
  * `ReadableMap` reads that tolerate absent keys.
@@ -2244,6 +2268,10 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2244
2268
  jsonObjectToMap(obj)
2245
2269
  }
2246
2270
  currentConfig = parsed
2271
+ // The config is STORED; now ACT on it. `pip.autoEnterOnLeave`
2272
+ // was a documented public flag that nothing read, so pressing
2273
+ // home never entered PiP - the value was already here.
2274
+ applyPipAutoEnterOnLeave(parsed)
2247
2275
  val keys = parsed?.keys?.sorted()?.joinToString(", ") ?: "(none)"
2248
2276
  Log.i(
2249
2277
  TAG,
@@ -2264,6 +2292,94 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2264
2292
  }
2265
2293
  }
2266
2294
 
2295
+ /**
2296
+ * Apply `pip.autoEnterOnLeave` to the Activity.
2297
+ *
2298
+ * `Activity.setAutoEnterEnabled(true)` (API 31+ / Android 12) is the
2299
+ * platform's own switch for "enter PiP when the user leaves the app".
2300
+ *
2301
+ * Below API 31 there is NO platform equivalent: an app has to
2302
+ * override `onUserLeaveHint()` in its own Activity, and this library
2303
+ * ships NO Activity - the consumer's launcher Activity hosts
2304
+ * playback (the one-Activity architecture). So below Android 12 this
2305
+ * is a documented no-op and PiP entry stays manual.
2306
+ *
2307
+ * The consumer's Activity must also declare
2308
+ * `android:supportsPictureInPicture="true"` for the OS to honour it.
2309
+ * That is the consumer's manifest, not this library's.
2310
+ *
2311
+ * @param config the RESOLVED config map, as parsed by `setConfig`.
2312
+ */
2313
+ private fun applyPipAutoEnterOnLeave(config: Map<String, Any?>?) {
2314
+ try {
2315
+ val desired = PipAutoEnterPolicy.desiredAutoEnter(config) ?: return
2316
+ pipAutoEnter = desired
2317
+ applyActivityPipParams()
2318
+ } catch (t: Throwable) {
2319
+ // Never let this reject the `setConfig` promise: the config
2320
+ // itself was stored fine, and a rejected promise would tell
2321
+ // the consumer its WHOLE configuration failed.
2322
+ Log.w(TAG, "[PlaybackTrace][Bridge][pip] applying auto-enter failed", t)
2323
+ }
2324
+ }
2325
+
2326
+ /**
2327
+ * Push the PiP params the SYSTEM will use onto the Activity.
2328
+ *
2329
+ * `Activity.setPictureInPictureParams` is what the platform reads
2330
+ * when it transitions the activity into PiP BY ITSELF - which is
2331
+ * exactly the swipe-home path that `pip.autoEnterOnLeave` asks for.
2332
+ * The params `enterPip` passes to `enterPictureInPictureMode` only
2333
+ * describe a MANUAL entry.
2334
+ *
2335
+ * So the auto-enter flag has to live on the activity's params, and
2336
+ * it has to carry the video's CURRENT aspect ratio - a stale aspect
2337
+ * means the auto-entered window has the shape of the previous video.
2338
+ * That is why this runs again on every `videoReconfig`: that is the
2339
+ * moment mpv reports new dimensions.
2340
+ *
2341
+ * `Activity.setAutoEnterEnabled` does NOT exist - the platform's
2342
+ * switch is `PictureInPictureParams.Builder.setAutoEnterEnabled`,
2343
+ * which is API 31+. Below that the OS cannot auto-enter at all.
2344
+ */
2345
+ private fun applyActivityPipParams() {
2346
+ try {
2347
+ if (!pipAutoEnter) return
2348
+ val activity = reactApplicationContext.currentActivity
2349
+ if (activity == null) {
2350
+ Log.w(
2351
+ TAG,
2352
+ "[PlaybackTrace][Bridge][pip] no activity yet; auto-enter PiP not applied",
2353
+ )
2354
+ return
2355
+ }
2356
+ if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.S) {
2357
+ Log.w(
2358
+ TAG,
2359
+ "[PlaybackTrace][Bridge][pip] auto-enter PiP needs Android 12 (API 31)+; " +
2360
+ "below that the OS cannot auto-enter, so PiP entry stays manual",
2361
+ )
2362
+ return
2363
+ }
2364
+ val aspect = currentVideoAspect() ?: (16f / 9f)
2365
+ val params = com.simba.player.PipManager.buildPipParams(
2366
+ context = activity,
2367
+ aspect = aspect,
2368
+ sourceRectHint = PlayerSurface.boundsInWindow(),
2369
+ autoEnter = true,
2370
+ )
2371
+ activity.runOnUiThread {
2372
+ activity.setPictureInPictureParams(params)
2373
+ Log.i(
2374
+ TAG,
2375
+ "[PlaybackTrace][Bridge][pip] activity PiP params set, autoEnter=true",
2376
+ )
2377
+ }
2378
+ } catch (t: Throwable) {
2379
+ Log.w(TAG, "[PlaybackTrace][Bridge][pip] applying activity params failed", t)
2380
+ }
2381
+ }
2382
+
2267
2383
  // ── Picture-in-Picture ─────────────────────────────────────────────────
2268
2384
 
2269
2385
  /**
@@ -2355,6 +2471,7 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2355
2471
  sourceRectHint = sourceRect,
2356
2472
  chapterTitle = title,
2357
2473
  progressPercentage = pct,
2474
+ autoEnter = pipAutoEnter,
2358
2475
  )
2359
2476
  // `enterPictureInPictureMode` ANSWERS whether the OS
2360
2477
  // accepted the request, and the answer was being
@@ -2769,13 +2886,75 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2769
2886
  }
2770
2887
  }
2771
2888
 
2889
+ /**
2890
+ * Map an mpv error code to the lib's stable string contract.
2891
+ *
2892
+ * The mapping itself lives in [MpvErrorContract] — one owner for the
2893
+ * contract, and a seam a plain JUnit test can reach without a React
2894
+ * context.
2895
+ */
2896
+ private fun mapMpvErrorCode(code: Int, message: String): String =
2897
+ MpvErrorContract.mapCode(code, message)
2898
+
2899
+ /**
2900
+ * T28.03: stable integer mapping for the structured error codes emitted
2901
+ * by [emitErrorEvent]. The TS `onError` interface declares `code: number`
2902
+ * - this helper provides the integer so programmatic handlers can switch
2903
+ * on a stable value across versions. Numeric codes are PERMANENT: do
2904
+ * not reuse a number once it ships (use a new range instead). Ranges:
2905
+ *
2906
+ * 1xxx - Initialization lifecycle (mount order, warm-up, ensurePtr)
2907
+ * 2xxx - Activity / Intent / launch failures (PlayerActivity missing,
2908
+ * SecurityException, manifest mismatches)
2909
+ * 3xxx - Playback failures (load failed, audio/video output init
2910
+ * failed, unknown format, unsupported, network, file not
2911
+ * found) - in use since v1.17.0
2912
+ * 4xxx - Configuration / IPC errors (setConfig parse failures,
2913
+ * bridge serialisation mismatches)
2914
+ *
2915
+ * Returns `0` for unknown codes so unrecognised values degrade to
2916
+ * a single sentinel rather than throwing.
2917
+ */
2918
+ private fun codeToNumeric(code: String): Int = MpvErrorContract.numeric(code)
2919
+ }
2920
+
2921
+ /**
2922
+ * The mpv error-code contract — the ONE place where an mpv error code
2923
+ * becomes the lib's stable `{codeName, code}` pair.
2924
+ *
2925
+ * WHY IT IS AN OBJECT AND NOT TWO METHODS ON [MpvBridgeModule]
2926
+ * -----------------------------------------------------------
2927
+ * The mapping is PURE: it reads a number and a string and returns a
2928
+ * string and a number. It touches no Android API and no React context.
2929
+ *
2930
+ * That purity is what makes it testable at all. The path that USES it
2931
+ * (`onMpvError` -> `Arguments.createMap()` -> `eventEmitter.emit`) runs
2932
+ * through React Native's native-backed `WritableMap`, which needs the
2933
+ * JNI library that a JVM unit test does not have — so a unit test
2934
+ * cannot drive the emit. It CAN drive the mapping, as long as the
2935
+ * mapping is reachable without a module instance.
2936
+ *
2937
+ * So the contract lives here, `internal` (visible to this module's unit
2938
+ * tests, invisible to consumers), and [MpvBridgeModule] delegates to
2939
+ * it. One owner, one truth, and a seam that a plain JUnit test can
2940
+ * reach.
2941
+ *
2942
+ * B-007: MPV_ERROR_COMMAND (-12) is now ALSO the landing spot for a
2943
+ * command mpv REFUSED — a seek, a relative seek, a playlist clear.
2944
+ * Before this, the native layer threw that code away and the app never
2945
+ * heard about it. The mapping itself did not have to change: -12 was
2946
+ * already "E_COMMAND_FAILED" / 3016. This object is where that
2947
+ * coincidence is now load-bearing, so it is pinned by a test.
2948
+ */
2949
+ internal object MpvErrorContract {
2950
+
2772
2951
  /**
2773
2952
  * Map an mpv error code to the lib's stable string contract.
2774
2953
  *
2775
2954
  * mpv's numeric codes are authoritative (`include/mpv/client.h`,
2776
- * `mpv_error`): -13 LOADING_FAILED, -14 AO_INIT_FAILED, -15
2777
- * VO_INIT_FAILED, -16 NOTHING_TO_PLAY, -17 UNKNOWN_FORMAT, -18
2778
- * UNSUPPORTED, -20 GENERIC, plus the API-level codes -1..-12.
2955
+ * `mpv_error`): -12 COMMAND, -13 LOADING_FAILED, -14 AO_INIT_FAILED,
2956
+ * -15 VO_INIT_FAILED, -16 NOTHING_TO_PLAY, -17 UNKNOWN_FORMAT, -18
2957
+ * UNSUPPORTED, -20 GENERIC, plus the API-level codes -1..-11.
2779
2958
  *
2780
2959
  * The message heuristics are the FALLBACK, for the codes that carry
2781
2960
  * no information of their own.
@@ -2783,7 +2962,7 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2783
2962
  * `E_RENDERER_GONE` is deliberately NOT the catch-all any more: it
2784
2963
  * means "the video output died", and a load failure is not that.
2785
2964
  */
2786
- private fun mapMpvErrorCode(code: Int, message: String): String = when (code) {
2965
+ fun mapCode(code: Int, message: String): String = when (code) {
2787
2966
  -13 -> "E_LOAD_FAILED"
2788
2967
  -14 -> "E_AUDIO_INIT_FAILED"
2789
2968
  -15 -> "E_VIDEO_INIT_FAILED"
@@ -2818,7 +2997,7 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2818
2997
 
2819
2998
  /**
2820
2999
  * T28.03: stable integer mapping for the structured error codes emitted
2821
- * by [emitErrorEvent]. The TS `onError` interface declares `code: number`
3000
+ * by the bridge. The TS `onError` interface declares `code: number`
2822
3001
  * - this helper provides the integer so programmatic handlers can switch
2823
3002
  * on a stable value across versions. Numeric codes are PERMANENT: do
2824
3003
  * not reuse a number once it ships (use a new range instead). Ranges:
@@ -2835,7 +3014,7 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2835
3014
  * Returns `0` for unknown codes so unrecognised values degrade to
2836
3015
  * a single sentinel rather than throwing.
2837
3016
  */
2838
- private fun codeToNumeric(code: String): Int = when (code) {
3017
+ fun numeric(code: String): Int = when (code) {
2839
3018
  // 1xxx - Initialization
2840
3019
  "E_NOT_INITIALIZED" -> 1001
2841
3020
  // 2xxx - Activity / Intent / launch
@@ -42,7 +42,13 @@ class MpvRenderViewManager : SimpleViewManager<MpvRenderView>() {
42
42
  override fun getName(): String = REACT_CLASS
43
43
 
44
44
  override fun createViewInstance(reactContext: ThemedReactContext): MpvRenderView {
45
- return MpvRenderView(reactContext)
45
+ val view = MpvRenderView(reactContext)
46
+ // The picture is now a child of the React tree, so this manager is the
47
+ // only thing that knows when one exists. It publishes the view to
48
+ // [MpvRenderViewRegistry], which is what `isSurfaceMounted()` asks —
49
+ // the answer is true by construction instead of by a call nobody makes.
50
+ MpvRenderViewRegistry.register(view)
51
+ return view
46
52
  }
47
53
 
48
54
  /**
@@ -123,5 +129,9 @@ class MpvRenderViewManager : SimpleViewManager<MpvRenderView>() {
123
129
  super.onDropViewInstance(view)
124
130
  Log.i(TAG, "onDropViewInstance: releasing surface binding, engine untouched")
125
131
  view.detachSurfaceForViewDrop()
132
+ // The view is going away, so there is nowhere left to put a video.
133
+ // `isSurfaceMounted()` must go back to answering false — otherwise a
134
+ // control would keep offering "play video" for a picture that is gone.
135
+ MpvRenderViewRegistry.unregister(view)
126
136
  }
127
137
  }