@simba-dev/react-native-media-player 2.0.1 → 3.0.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 (38) 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 +177 -6
  5. package/android/src/main/java/com/simba/player/mpv/PipAutoEnterPolicy.kt +54 -0
  6. package/package.json +11 -2
  7. package/src/components/PlayerProvider.tsx +5 -5
  8. package/src/index.ts +25 -12
  9. package/android/src/test/java/com/simba/player/PipActionReceiverTest.kt +0 -123
  10. package/android/src/test/java/com/simba/player/PipManagerTest.kt +0 -281
  11. package/android/src/test/java/com/simba/player/TestApplication.kt +0 -26
  12. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleNullInstanceTest.kt +0 -117
  13. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleTest.kt +0 -212
  14. package/android/src/test/java/com/simba/player/mpv/MpvRenderViewRegistryTest.kt +0 -120
  15. package/android/src/test/java/com/simba/player/mpv/MpvRenderViewTest.kt +0 -249
  16. package/scripts/override_react_methods.js +0 -184
  17. package/scripts/override_react_methods.py +0 -150
  18. package/src/bridge/__tests__/MpvPlayerModule.test.ts +0 -163
  19. package/src/bridge/__tests__/debugMode.test.ts +0 -138
  20. package/src/bridge/__tests__/errorContract.test.ts +0 -175
  21. package/src/bridge/__tests__/loadAndPlay.startPosition.test.tsx +0 -142
  22. package/src/components/PlayerRoot.tsx +0 -124
  23. package/src/components/PlayerSurface.tsx +0 -62
  24. package/src/components/__tests__/PlayerProvider.performance.test.tsx +0 -242
  25. package/src/components/__tests__/PlayerProvider.progressContext.test.tsx +0 -194
  26. package/src/components/__tests__/PlayerProvider.test.tsx +0 -558
  27. package/src/components/__tests__/PlayerRoot.test.tsx +0 -71
  28. package/src/components/__tests__/SimbaVideo.test.tsx +0 -164
  29. package/src/hooks/__tests__/resolveStreamType.test.ts +0 -159
  30. package/src/hooks/__tests__/useLaunchPlayback.test.tsx +0 -278
  31. package/src/hooks/__tests__/useResumeThumbnail.test.ts +0 -154
  32. package/src/stores/__tests__/playerQueueSelectionStore.test.ts +0 -73
  33. package/src/stores/__tests__/playerQueueStore.test.ts +0 -171
  34. package/src/types/__tests__/config.test.ts +0 -188
  35. package/src/types/__tests__/player.pipAnswer.test.tsx +0 -87
  36. package/src/types/__tests__/player.pipArity.test.tsx +0 -74
  37. package/src/types/__tests__/player.test.tsx +0 -1365
  38. 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)
@@ -2252,6 +2268,10 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2252
2268
  jsonObjectToMap(obj)
2253
2269
  }
2254
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)
2255
2275
  val keys = parsed?.keys?.sorted()?.joinToString(", ") ?: "(none)"
2256
2276
  Log.i(
2257
2277
  TAG,
@@ -2272,6 +2292,94 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2272
2292
  }
2273
2293
  }
2274
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
+
2275
2383
  // ── Picture-in-Picture ─────────────────────────────────────────────────
2276
2384
 
2277
2385
  /**
@@ -2363,6 +2471,7 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2363
2471
  sourceRectHint = sourceRect,
2364
2472
  chapterTitle = title,
2365
2473
  progressPercentage = pct,
2474
+ autoEnter = pipAutoEnter,
2366
2475
  )
2367
2476
  // `enterPictureInPictureMode` ANSWERS whether the OS
2368
2477
  // accepted the request, and the answer was being
@@ -2777,13 +2886,75 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2777
2886
  }
2778
2887
  }
2779
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
+
2780
2951
  /**
2781
2952
  * Map an mpv error code to the lib's stable string contract.
2782
2953
  *
2783
2954
  * mpv's numeric codes are authoritative (`include/mpv/client.h`,
2784
- * `mpv_error`): -13 LOADING_FAILED, -14 AO_INIT_FAILED, -15
2785
- * VO_INIT_FAILED, -16 NOTHING_TO_PLAY, -17 UNKNOWN_FORMAT, -18
2786
- * 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.
2787
2958
  *
2788
2959
  * The message heuristics are the FALLBACK, for the codes that carry
2789
2960
  * no information of their own.
@@ -2791,7 +2962,7 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2791
2962
  * `E_RENDERER_GONE` is deliberately NOT the catch-all any more: it
2792
2963
  * means "the video output died", and a load failure is not that.
2793
2964
  */
2794
- private fun mapMpvErrorCode(code: Int, message: String): String = when (code) {
2965
+ fun mapCode(code: Int, message: String): String = when (code) {
2795
2966
  -13 -> "E_LOAD_FAILED"
2796
2967
  -14 -> "E_AUDIO_INIT_FAILED"
2797
2968
  -15 -> "E_VIDEO_INIT_FAILED"
@@ -2826,7 +2997,7 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2826
2997
 
2827
2998
  /**
2828
2999
  * T28.03: stable integer mapping for the structured error codes emitted
2829
- * by [emitErrorEvent]. The TS `onError` interface declares `code: number`
3000
+ * by the bridge. The TS `onError` interface declares `code: number`
2830
3001
  * - this helper provides the integer so programmatic handlers can switch
2831
3002
  * on a stable value across versions. Numeric codes are PERMANENT: do
2832
3003
  * not reuse a number once it ships (use a new range instead). Ranges:
@@ -2843,7 +3014,7 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2843
3014
  * Returns `0` for unknown codes so unrecognised values degrade to
2844
3015
  * a single sentinel rather than throwing.
2845
3016
  */
2846
- private fun codeToNumeric(code: String): Int = when (code) {
3017
+ fun numeric(code: String): Int = when (code) {
2847
3018
  // 1xxx - Initialization
2848
3019
  "E_NOT_INITIALIZED" -> 1001
2849
3020
  // 2xxx - Activity / Intent / launch
@@ -0,0 +1,54 @@
1
+ package com.simba.player.mpv
2
+
3
+ /**
4
+ * The Picture-in-Picture auto-enter policy.
5
+ *
6
+ * ## Why this is its own object
7
+ *
8
+ * `PipConfig.autoEnterOnLeave` was declared in the public TypeScript
9
+ * config type, documented in the README as "auto-enter on home /
10
+ * recents / app-switcher", and defaulted to `true` — and NOTHING read
11
+ * it. Not the JS layer, not the native layer. The flag was a public
12
+ * promise with no implementation behind it: a consumer who set it got
13
+ * exactly the same behaviour as one who did not, and the README
14
+ * described a feature that could not happen.
15
+ *
16
+ * The config already reaches the native module — `setConfig` parses
17
+ * the whole RESOLVED config into a map — so the value was sitting
18
+ * there, unread, on the Kotlin side.
19
+ *
20
+ * The DECISION is what is worth testing, and it is pure: read a config
21
+ * map, answer "should the Activity auto-enter PiP?". That is this
22
+ * object. Applying it to an Activity needs an Android runtime, so that
23
+ * half lives in `MpvBridgeModule` and is as thin as it can be.
24
+ */
25
+ internal object PipAutoEnterPolicy {
26
+
27
+ /**
28
+ * The flag the Activity should carry, or `null` when the config
29
+ * says nothing about auto-enter.
30
+ *
31
+ * `null` is a DIFFERENT answer from `false`, and the difference
32
+ * matters:
33
+ *
34
+ * - `null` — the config does not mention auto-enter. Leave the
35
+ * Activity alone. Do NOT turn the feature off just
36
+ * because nobody asked for it.
37
+ * - `false` — the config asks for auto-enter to be off.
38
+ * - `true` — the config asks for auto-enter to be on.
39
+ *
40
+ * `pip.enabled` is the master switch for every PiP entry request,
41
+ * so a disabled PiP means auto-enter is off whatever
42
+ * `autoEnterOnLeave` says. The two flags are not independent.
43
+ *
44
+ * A value of the wrong type is treated as "not mentioned" rather
45
+ * than as `false`: a config that says something this code does
46
+ * not understand must not silently disable a feature.
47
+ */
48
+ fun desiredAutoEnter(config: Map<String, Any?>?): Boolean? {
49
+ val pip = config?.get("pip") as? Map<*, *> ?: return null
50
+ val enabled = pip["enabled"] as? Boolean ?: return null
51
+ val autoEnter = pip["autoEnterOnLeave"] as? Boolean ?: return null
52
+ return enabled && autoEnter
53
+ }
54
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "2.0.1",
3
+ "version": "3.0.0",
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",
@@ -8,7 +8,11 @@
8
8
  "files": [
9
9
  "src/",
10
10
  "!src/README.example.tsx",
11
+ "!src/**/__tests__/",
12
+ "!src/**/__mocks__/",
11
13
  "scripts/",
14
+ "!scripts/override_react_methods.js",
15
+ "!scripts/override_react_methods.py",
12
16
  "android/",
13
17
  "android/build.gradle",
14
18
  "android/consumer-rules.pro",
@@ -16,12 +20,17 @@
16
20
  "!android/.cxx/",
17
21
  "!android/.gradle/",
18
22
  "!android/build/",
23
+ "!android/src/test/",
24
+ "!android/src/main/jniLibs/",
19
25
  "assets/",
20
26
  "LICENSE",
21
27
  "README.md",
22
28
  "react-native.config.js",
23
29
  "tsconfig.json",
24
- "!.npmignore"
30
+ "!.npmignore",
31
+ "!example/",
32
+ "!.git/",
33
+ "!md/"
25
34
  ],
26
35
  "keywords": [
27
36
  "react-native",
@@ -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: