@simba-dev/react-native-media-player 1.9.3 → 1.10.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.
@@ -3,6 +3,7 @@
3
3
  #include <string>
4
4
  #include <cstring>
5
5
  #include <cstdio>
6
+ #include <ctime>
6
7
  #include <client.h>
7
8
  #include <native_state.h>
8
9
 
@@ -11,6 +12,34 @@
11
12
  #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
12
13
  #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
13
14
 
15
+ // ── Hot-path logging gate (v1.10.0) ────────────────────────────────────────
16
+ //
17
+ // `MPV_EVENT_PROPERTY_CHANGE` fires for `time-pos` roughly ONCE PER VIDEO
18
+ // FRAME (mpv's own manual documents `time-pos` as the per-frame position
19
+ // property). `MPV_EVENT_LOG_MESSAGE` fires once per mpv/FFmpeg log line,
20
+ // which during network playback is dozens per second.
21
+ //
22
+ // So this loop is the single hottest thread in the app, and writing to
23
+ // logcat from it is not free: `__android_log_print` is a synchronous write
24
+ // into logd's ring buffer, and the string is formatted by snprintf BEFORE
25
+ // any level filtering is considered. Android's own `Log` documentation
26
+ // warns that building the message already costs "at least three
27
+ // allocations"; measured Android studies (FDroid EMSE 2019) report up to
28
+ // ~3x response-time overhead when logging is hot, and droidcon's 2025
29
+ // benchmark shows the cost is paid even when the log is filtered out.
30
+ //
31
+ // A player cannot ship that. `SIMBA_MPV_TRACE` compiles the hot-path logs
32
+ // to nothing; flip it locally when debugging a property/event path.
33
+ // It is OFF by default and is intentionally NOT runtime-configurable:
34
+ // a runtime flag would still evaluate the arguments at every call site.
35
+ #ifdef SIMBA_MPV_TRACE
36
+ #define TRACE_PROPERTY(...) __android_log_print(ANDROID_LOG_DEBUG, "MpvProperty", __VA_ARGS__)
37
+ #define TRACE_MPVLOG(...) __android_log_print(ANDROID_LOG_DEBUG, "mpv", __VA_ARGS__)
38
+ #else
39
+ #define TRACE_PROPERTY(...) do { } while (0)
40
+ #define TRACE_MPVLOG(...) do { } while (0)
41
+ #endif
42
+
14
43
  // ── External globals set by main.cpp ────────────────────────────────────────
15
44
 
16
45
  extern JavaVM *g_vm;
@@ -20,6 +49,14 @@ extern jmethodID g_mid_onEvent;
20
49
  extern jmethodID g_mid_onPropertyChanged;
21
50
  extern jmethodID g_mid_onError;
22
51
 
52
+ // ── Coalescing state (v1.10.0) ─────────────────────────────────────────────
53
+ //
54
+ // Only touched by the mpv event thread (mpvEventLoop), so plain int64_t is
55
+ // sufficient — no atomics or locks on the hottest path in the app. 0 means
56
+ // "nothing forwarded yet", so the first event of each property always passes.
57
+ static int64_t g_lastPositionForwardUs = 0;
58
+ static int64_t g_lastCacheForwardUs = 0;
59
+
23
60
  // ── Helper: attach current thread to JVM and call static void method ────────
24
61
 
25
62
  static std::string jsonQuote(const char *value) {
@@ -187,6 +224,67 @@ static void callJavaPropertyChanged(const char *name, const char *jsonValue) {
187
224
  if (jValue) env->DeleteLocalRef(jValue);
188
225
  }
189
226
 
227
+ // ── High-frequency property coalescing (v1.10.0) ──────────────────────────
228
+ //
229
+ // `time-pos` is mpv's PER-FRAME position property (mpv manual, "Playback
230
+ // Control": `time-pos` "updates about once per frame"). `demuxer-cache-state`
231
+ // is a NODE map containing `seekable-ranges` (an array of maps) plus
232
+ // `fw-bytes`, `reader-pts`, `raw-input-rate` — a large payload that changes
233
+ // on essentially every cache tick.
234
+ //
235
+ // Forwarding both verbatim costs, per frame: a std::string build, two JNI
236
+ // local refs, a JNI static call, a WritableMap alloc on the Kotlin side, an
237
+ // RN event dispatch, and a React setState that re-renders the entire player
238
+ // chrome. Measured on-device: 1168 `demuxer-cache-state` events inside one
239
+ // short window, dominating every other event combined.
240
+ //
241
+ // Media3's own guidance for the reference Android player is the opposite of
242
+ // this: "the listener interface doesn't include any callbacks to track normal
243
+ // playback progression. To continuously monitor playback progress ... you
244
+ // should query the current position at proper intervals."
245
+ //
246
+ // So: drop frames we are not going to render. Dropping happens here, at the
247
+ // cheapest possible point — BEFORE jsonNode()/jsonQuote() serialization and
248
+ // before the JNI crossing, so a dropped frame costs one strcmp.
249
+ //
250
+ // This is a RATE LIMIT, not a filter: the most recent value always wins and
251
+ // is always delivered, so the UI stays truthful. It is only a trailing-edge
252
+ // rate limit, and it is deliberately NOT applied to properties whose value is
253
+ // itself the signal (pause, eof-reached, seekable, muted, speed, loop-mode,
254
+ // media-title, chapter, track-list): losing one of those is a lost event, not
255
+ // a dropped duplicate frame.
256
+ static const int64_t kPositionCoalesceUs = 250000; // 250 ms -> 4 Hz
257
+ static const int64_t kCacheCoalesceUs = 500000; // 500 ms -> 2 Hz
258
+
259
+ static int64_t nowMicros() {
260
+ struct timespec ts;
261
+ clock_gettime(CLOCK_MONOTONIC, &ts);
262
+ return static_cast<int64_t>(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000;
263
+ }
264
+
265
+ // Returns true when the property should be forwarded to the JVM.
266
+ // `nowUs` is passed in rather than sampled per call so a single iteration
267
+ // of the loop shares one clock read.
268
+ static bool shouldForwardProperty(const char *name, int64_t nowUs) {
269
+ if (!name) return true;
270
+
271
+ int64_t *lastUs = nullptr;
272
+ int64_t windowUs = 0;
273
+ if (strcmp(name, "time-pos") == 0) {
274
+ lastUs = &g_lastPositionForwardUs;
275
+ windowUs = kPositionCoalesceUs;
276
+ } else if (strcmp(name, "demuxer-cache-state") == 0) {
277
+ lastUs = &g_lastCacheForwardUs;
278
+ windowUs = kCacheCoalesceUs;
279
+ } else {
280
+ return true;
281
+ }
282
+
283
+ if (*lastUs != 0 && nowUs - *lastUs < windowUs) return false;
284
+ *lastUs = nowUs;
285
+ return true;
286
+ }
287
+
190
288
  static void callJavaError(int code, const char *message, const char *requestId, bool recoverable) {
191
289
  JNIEnv *env = getEventEnv();
192
290
  if (!env || !g_cls_MPVLib || !g_mid_onError) return;
@@ -237,6 +335,9 @@ void eventLoop() {
237
335
  // state in which mpv is obliged to release the coalesced property
238
336
  // changes. One queue-drained iteration costs one non-blocking call.
239
337
  while (g_running.load()) {
338
+ // Sampled once per iteration (not per property) so a drain batch that
339
+ // releases several coalesced property changes shares one clock read.
340
+ const int64_t nowUs = nowMicros();
240
341
  mpv_event *event = mpv_wait_event(g_mpv, 0);
241
342
  if (!event) {
242
343
  LOGE("[PlaybackTrace][Native][eventLoop] mpv_wait_event returned null");
@@ -338,6 +439,14 @@ void eventLoop() {
338
439
  TRACEI("[PlaybackTrace][Native][eventLoop] property=%s format=NONE", prop->name);
339
440
  break;
340
441
  }
442
+ // Coalesce BEFORE serializing. `demuxer-cache-state` is a
443
+ // NODE map (seekable-ranges array of maps + fw-bytes +
444
+ // reader-pts), so skipping it here skips the most expensive
445
+ // payload in the whole loop rather than just a scalar.
446
+ if (!shouldForwardProperty(prop->name, nowUs)) {
447
+ TRACEI("[PlaybackTrace][Native][property] coalesced name=%s", prop->name);
448
+ break;
449
+ }
341
450
  std::string json;
342
451
  if (prop->format == MPV_FORMAT_NODE && prop->data) {
343
452
  json = jsonNode(static_cast<const mpv_node *>(prop->data));
@@ -357,15 +466,21 @@ void eventLoop() {
357
466
  json = "null";
358
467
  }
359
468
  TRACEI("[PlaybackTrace][Native][property] name=%s format=%d value=%s", prop->name, prop->format, json.c_str());
360
- // DEBUG (not TRACEI) on purpose. TRACEI is compiled to a
361
- // no-op, which is why a broken property path was
362
- // completely invisible in logcat for as long as it
363
- // existed. This is the one line that makes
364
- // "properties are observed but events never arrive"
469
+ // This line deliberately existed as a VISIBLE DEBUG log
470
+ // rather than TRACEI: TRACEI compiles to a no-op, which is
471
+ // why a broken property path was completely invisible in
472
+ // logcat for as long as it existed. It is the one line that
473
+ // makes "properties are observed but events never arrive"
365
474
  // distinguishable from "the loop never saw them".
366
- __android_log_print(ANDROID_LOG_DEBUG, "MpvProperty",
367
- "[PlaybackTrace][Native][property] name=%s format=%d value=%s",
368
- prop->name, prop->format, json.c_str());
475
+ //
476
+ // v1.10.0: it is now behind the SIMBA_MPV_TRACE compile-time
477
+ // gate instead. Leaving it unconditional cost a synchronous
478
+ // logd write PER VIDEO FRAME (time-pos) on the hottest
479
+ // thread in the app, which is a shipping-performance defect,
480
+ // not a diagnostic. Build with -DSIMBA_MPV_TRACE to restore
481
+ // exactly this visibility while debugging.
482
+ TRACE_PROPERTY("[PlaybackTrace][Native][property] name=%s format=%d value=%s",
483
+ prop->name, prop->format, json.c_str());
369
484
  callJavaPropertyChanged(prop->name, json.c_str());
370
485
  break;
371
486
  }
@@ -373,8 +488,7 @@ void eventLoop() {
373
488
  case MPV_EVENT_LOG_MESSAGE: {
374
489
  auto *log = (mpv_event_log_message *)event->data;
375
490
  TRACEI("[PlaybackTrace][Native][mpv-log] prefix=%s level=%s text=%s", log && log->prefix ? log->prefix : "", log && log->level ? log->level : "", log && log->text ? log->text : "");
376
- __android_log_print(ANDROID_LOG_DEBUG, "mpv", "[%s] %s: %s",
377
- log->prefix, log->level, log->text);
491
+ TRACE_MPVLOG("[%s] %s: %s", log->prefix, log->level, log->text);
378
492
  // Do not promote every `error`-level mpv log to a playback
379
493
  // failure. Decoder warnings such as recoverable mjpeg overread
380
494
  // messages are common during network playback and previously
@@ -35,6 +35,19 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
35
35
  const val NAME = "MpvPlayerModule"
36
36
  private const val TAG = "MpvBridgeModule"
37
37
 
38
+ // v1.10.0 — hot-path property tracing.
39
+ //
40
+ // `time-pos` is mpv's per-frame property, so tracing every property
41
+ // change costs a logd write 30-60x/second on the player event
42
+ // thread. Off in every build config; flip to `true` locally when
43
+ // diagnosing a property that is observed but never arrives.
44
+ //
45
+ // Deliberately a `const val`, not a system property or env lookup:
46
+ // a runtime lookup would itself run on the hot path, and
47
+ // `Log.isLoggable()` is not free either. A constant lets R8 inline
48
+ // the branch away in release entirely.
49
+ private const val TRACE_PROPERTY_EVENTS = false
50
+
38
51
  // V22.0.0 / 1.5.10 (D-034): activity-aware launchParams guard.
39
52
  //
40
53
  // Background: `lastLaunchParams` (declared further down) is the
@@ -277,15 +290,42 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
277
290
  }
278
291
 
279
292
  override fun onMpvPropertyChanged(name: String, jsonValue: String) {
280
- Log.i(TAG, "[PlaybackTrace][Bridge][listener:property] name=$name value=$jsonValue")
281
- try {
282
- val payload = Arguments.createMap().apply {
283
- putString("property", name)
284
- putString("value", jsonValue)
293
+ // v1.10.0: this was an unconditional Log.i carrying the full
294
+ // JSON payload of EVERY property change. `time-pos` changes once
295
+ // per video frame, so this fired 30-60x/second on the player's
296
+ // event thread, each call building the message string
297
+ // (Kotlin string templates are evaluated before Log.i can decide
298
+ // to discard them) and performing a synchronous write to logd.
299
+ // Gate it behind the same debug switch as the JS dlog(); the
300
+ // property value is still delivered to JS regardless.
301
+ if (TRACE_PROPERTY_EVENTS) {
302
+ Log.d(TAG, "[PlaybackTrace][Bridge][listener:property] name=$name value=$jsonValue")
303
+ }
304
+ // v1.10.0: dedupe the generic stream. Every property below already
305
+ // gets a dedicated, typed event (onPositionChanged, onBuffering,
306
+ // onCacheState, onSeekable, ...), and `onPropertyChanged` was
307
+ // emitted for all of them too — so `time-pos` crossed the bridge
308
+ // twice per frame and the JS reducer ran twice. Emitting the
309
+ // generic event ONLY for properties that have no dedicated event
310
+ // keeps the JS `onPropertyChanged` contract intact for anything
311
+ // that reads it while removing the double delivery.
312
+ val hasDedicatedEvent = when (name) {
313
+ "time-pos", "duration", "volume", "speed", "pause",
314
+ "idle-active", "eof-reached", "seekable", "seeking",
315
+ "cache-buffering-state", "paused-for-cache",
316
+ "demuxer-cache-state" -> true
317
+ else -> false
318
+ }
319
+ if (!hasDedicatedEvent) {
320
+ try {
321
+ val payload = Arguments.createMap().apply {
322
+ putString("property", name)
323
+ putString("value", jsonValue)
324
+ }
325
+ eventEmitter.emit("onPropertyChanged", payload)
326
+ } catch (e: Exception) {
327
+ Log.w(TAG, "Property change emit failed: ${e.message}")
285
328
  }
286
- eventEmitter.emit("onPropertyChanged", payload)
287
- } catch (e: Exception) {
288
- Log.w(TAG, "Property change emit failed: ${e.message}")
289
329
  }
290
330
  // P33.4: re-emit `cache-buffering-state` updates as `onBuffering`
291
331
  // so the JS UI can show a buffering spinner for slow streams
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.9.3",
3
+ "version": "1.10.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",
@@ -752,6 +752,42 @@ export function getMpvPlayerModule(): MpvPlayerModuleBridge {
752
752
  return bridge;
753
753
  }
754
754
 
755
+ /**
756
+ * v1.9.3 — override the media title mpv will report, BEFORE the file is
757
+ * loaded.
758
+ *
759
+ * mpv derives `media-title` from the container's metadata tags, falling
760
+ * back to the URL's last path segment. Neither is usable for a streaming
761
+ * catalogue: a signed CDN URL ends in something like
762
+ * `abc123?sig=…&exp=…`, so an un-overridden player header shows that
763
+ * token. `force-media-title` is mpv's own option for replacing it.
764
+ *
765
+ * Two things are load-bearing here:
766
+ *
767
+ * 1. **Ordering.** The option is read at load time, so this must run
768
+ * before `loadFile`. Callers that put it after would leave the
769
+ * already-loaded file with mpv's derived title.
770
+ * 2. **Not throwing.** A rejected property write must never abort the
771
+ * load — the video matters more than its title, and mpv falls back
772
+ * to deriving one. It is warned about instead, because a silent
773
+ * failure here is a wrong title that nobody can explain.
774
+ *
775
+ * Shared by `commands.loadFile` and `useLaunchPlayback`, which are two
776
+ * genuinely different entry points (`openPlayer` → activity → launch
777
+ * params versus a direct programmatic load) and would otherwise each
778
+ * re-implement the set-then-load ordering.
779
+ */
780
+ export function applyForceMediaTitle(bridge: MpvPlayerModuleBridge, title?: string): void {
781
+ const trimmed = title?.trim();
782
+ if (!trimmed) return;
783
+ try {
784
+ bridge.setProperty('force-media-title', trimmed);
785
+ } catch (e) {
786
+ // eslint-disable-next-line no-console
787
+ console.warn('[simba-player] force-media-title rejected:', e);
788
+ }
789
+ }
790
+
755
791
  /**
756
792
  * V13 Phase 50c: subscribe to a native event. Returns an
757
793
  * unsubscribe function that callers should invoke from
@@ -217,9 +217,6 @@ const ALL_PLAYER_EVENTS: readonly PlayerEventName[] = [
217
217
  'onPipClose',
218
218
  ];
219
219
 
220
- /** How often the provider polls `getPosition` + `getDuration` from the bridge. */
221
- const POSITION_POLL_INTERVAL_MS = 1000;
222
-
223
220
  /**
224
221
  * mpv properties the provider observes, and the JS event each one backs
225
222
  * in `MpvBridgeModule.onMpvPropertyChanged`.
@@ -371,6 +368,48 @@ function cacheRangesEqual(
371
368
  );
372
369
  }
373
370
 
371
+ /**
372
+ * v1.10.0 — make the provider's existing no-op guard actually WORK.
373
+ *
374
+ * `applyPlayerEvent` is written as pure spread-and-return, so it allocates
375
+ * a NEW `PlayerState` object for every event it handles, even when not a
376
+ * single field changed. The provider then did:
377
+ *
378
+ * if (nextState !== stateRef.current) { ... setState(nextState) }
379
+ *
380
+ * That is a reference comparison against an object the reducer JUST
381
+ * created, so it was true for every event, always. The guard was dead code.
382
+ *
383
+ * Consequence: `setState` fired on every single player event, replacing the
384
+ * `PlayerStateContext` value and re-rendering every `usePlayer()` consumer —
385
+ * all 12 chrome components in the app — including on `onPositionChanged`,
386
+ * which mpv emits once per video frame. `videoReconfig` and the PiP no-ops
387
+ * the comment above cites were never skipped either.
388
+ *
389
+ * WHY A GENERIC SHALLOW COMPARE INSTEAD OF A HAND-WRITTEN FIELD LIST:
390
+ * a hand-written `a.foo === b.foo && ...` list silently goes stale the
391
+ * moment a field is added to `PlayerState` — the new field is simply not
392
+ * compared, the function reports "equal" when it is not, and the guard
393
+ * starts dropping real updates. That is worse than no guard at all, and it
394
+ * is invisible in tests. Deriving the key list from the object at runtime
395
+ * means the contract cannot drift.
396
+ *
397
+ * Shallow reference equality is the correct depth here: `applyPlayerEvent`
398
+ * only ever REPLACES these nested values (`playlist`, `tracks`, `chapters`,
399
+ * `currentChapter`, `videoParams`), it never mutates one in place, so a
400
+ * changed reference reliably means changed content.
401
+ */
402
+ const PLAYER_STATE_SCALAR_KEYS = Object.keys(DEFAULT_STATE) as Array<
403
+ keyof PlayerState
404
+ >;
405
+
406
+ function playerStateEqual(a: PlayerState, b: PlayerState): boolean {
407
+ for (const key of PLAYER_STATE_SCALAR_KEYS) {
408
+ if (a[key] !== b[key]) return false;
409
+ }
410
+ return true;
411
+ }
412
+
374
413
  // ═══════════════════════════════════════════════════════════════════════════
375
414
  // PlayerProvider
376
415
  // ═══════════════════════════════════════════════════════════════════════════
@@ -435,8 +474,14 @@ export interface PlayerProviderProps {
435
474
  * loop / playlist / tracks / chapters / video params.
436
475
  * - **Event subscriptions** (mount): all 22 mpv events are subscribed
437
476
  * via `subscribePlayerEvent` and dispatched to `applyPlayerEvent`.
438
- * - **1Hz position/duration poll** (mount): `setInterval` calls the
439
- * sync `getPosition` / `getDuration` getters every 1000ms.
477
+ * - **Mount-time level seeds** (mount): `seekable` and `mute` are read once
478
+ * via the sync `getProperty` getter, because mpv emits those two as
479
+ * EDGES and a provider mounted mid-session would otherwise never see them.
480
+ *
481
+ * v1.10.0 removed a 1Hz `setPosition`/`getDuration` poll that used to run
482
+ * alongside the event stream. The event stream is authoritative and
483
+ * delivers position at 4Hz after native coalescing; the poll was a second
484
+ * writer to the same fields and blocked the JS thread twice a second.
440
485
  *
441
486
  * State is held in a `useState` (rendered, for React) + `useRef`
442
487
  * (current, for event handlers to read without stale closures) pair.
@@ -487,15 +532,13 @@ export function PlayerProvider({
487
532
  // subscriptions.
488
533
  const stateRef = useRef<PlayerState>(DEFAULT_STATE);
489
534
  const progressRef = useRef<PlayerProgress>(DEFAULT_PROGRESS);
490
- // Tracks whether the 1Hz poll should fire. The poll runs in a child
491
- // effect that mounts the interval; the unmount cleanup is symmetric.
492
- // We mount/unmount ONCE for the provider's lifetime (no deps), so
493
- // the poll survives config changes.
494
535
 
495
- // Initial hydration + event subscriptions + 1Hz poll all live in a
496
- // single mount-only effect so they share the same lifecycle. (If we
497
- // split them across multiple effects, the ref + state would briefly
536
+ // Initial hydration + event subscriptions + mount-time level seeds all
537
+ // live in a single mount-only effect so they share the same lifecycle.
538
+ // (If we split them across multiple effects, the ref + state would briefly
498
539
  // desync during the gap between hydration and subscription mount.)
540
+ // The 1Hz position poll this effect used to also start was removed in
541
+ // v1.10.0 — the event stream is authoritative for position and duration.
499
542
  useEffect(() => {
500
543
  const bridge = getMpvPlayerModule();
501
544
 
@@ -565,10 +608,12 @@ export function PlayerProvider({
565
608
  event,
566
609
  payload,
567
610
  );
568
- // Skip the setState if the new state is reference-equal
569
- // (a true no-op event for this state) — prevents
570
- // re-render storms on `videoReconfig` / PiP no-ops.
571
- if (nextState !== stateRef.current) {
611
+ // Skip the setState when no FIELD changed. This must be a field-wise
612
+ // compare, not a reference compare: `applyPlayerEvent` always
613
+ // returns a freshly-spread object, so `nextState !== stateRef.current`
614
+ // was true for literally every event and never skipped anything.
615
+ // See playerStateEqual() for why the key list is derived, not typed.
616
+ if (!playerStateEqual(nextState, stateRef.current)) {
572
617
  stateRef.current = nextState;
573
618
  setState(nextState);
574
619
  }
@@ -690,52 +735,32 @@ export function PlayerProvider({
690
735
  console.warn('[simba-player] mute seed failed:', e);
691
736
  }
692
737
 
693
- // ── 3. 1Hz position/duration poll ───────────────────────────────────
694
- // Both `getPosition` and `getDuration` are sync React methods
695
- // on the bridge, so the poll doesn't queue microtasks. We
696
- // also pick up the playback state (`getPlaybackState`) here
697
- // as a backup for the event stream (e.g. if the consumer is
698
- // mounted mid-playback and missed the `onPlaybackStateChanged`
699
- // event).
700
- const pollId = setInterval(() => {
701
- try {
702
- const posSec = bridge.getPosition();
703
- const durSec = bridge.getDuration();
704
- const positionMs = Number.isFinite(posSec)
705
- ? Math.round(posSec * 1000)
706
- : stateRef.current.positionMs;
707
- const durationMs = Number.isFinite(durSec)
708
- ? Math.round(durSec * 1000)
709
- : stateRef.current.durationMs;
710
-
711
- if (
712
- positionMs === stateRef.current.positionMs &&
713
- durationMs === stateRef.current.durationMs
714
- ) {
715
- return; // no movement — skip the setState
716
- }
717
- const next: PlayerState = {
718
- ...stateRef.current,
719
- positionMs,
720
- durationMs,
721
- };
722
- stateRef.current = next;
723
- setState(next);
724
- const nextProgress: PlayerProgress = {
725
- ...progressRef.current,
726
- positionMs,
727
- durationMs,
728
- };
729
- progressRef.current = nextProgress;
730
- setProgress(nextProgress);
731
- } catch (e) {
732
- // Bridge threw — keep the last known position. (The no-op
733
- // bridge returns 0/0, which falls into the "no movement"
734
- // early-return above, so it doesn't spam setState.)
735
- // eslint-disable-next-line no-console
736
- console.warn('[simba-player] position poll failed:', e);
737
- }
738
- }, POSITION_POLL_INTERVAL_MS);
738
+ // ── 3. No position poll (v1.10.0) ─────────────────────────────────
739
+ //
740
+ // This used to be a 1Hz `setInterval` calling the SYNCHRONOUS
741
+ // `getPosition()` / `getDuration()` bridge getters. It was removed, not
742
+ // tuned, for three reasons:
743
+ //
744
+ // a) It was a SECOND source of truth for the same two numbers. mpv's
745
+ // `time-pos` and `duration` are already observed (step 2b) and
746
+ // arrive as `onPositionChanged` / `onDurationChanged`. Two writers
747
+ // to one field means the value on screen is whatever landed last,
748
+ // which is how a seek bar ends up jumping backwards.
749
+ //
750
+ // b) Both getters are sync TurboModule methods, so each tick blocked
751
+ // the JS thread for the duration of two JNI round-trips. The RN
752
+ // guidance for sync methods is to use them only for sub-5ms work
753
+ // and never on a recurring timer.
754
+ //
755
+ // c) It bought nothing. The event stream is authoritative and, since
756
+ // the native coalescing landed, delivers position at 4Hz — faster
757
+ // than the 1Hz it replaced, while doing ~15x less total work than
758
+ // the old per-frame path.
759
+ //
760
+ // The mount-time LEVEL seeds above (seekable, mute) are deliberately
761
+ // KEPT: mpv emits those as edges, so an event-only provider mounted
762
+ // mid-session would never learn them. Position and duration are levels
763
+ // that change continuously, so the event stream always repopulates them.
739
764
 
740
765
  // ── Cleanup ─────────────────────────────────────────────────────────
741
766
  return () => {
@@ -756,7 +781,7 @@ export function PlayerProvider({
756
781
  // never let a single bad unsub abort the rest
757
782
  }
758
783
  }
759
- clearInterval(pollId);
784
+ // v1.10.0: no interval to clear — the position poll was removed.
760
785
  // Best-effort: remove any lingering listeners from the emitter
761
786
  // so the next mount of the provider starts clean. (Strict-mode
762
787
  // double-invocation can otherwise leave phantom listeners.)
@@ -0,0 +1,242 @@
1
+ /**
2
+ * v1.10.0 — performance contract tests for `PlayerProvider`.
3
+ *
4
+ * WHY THIS FILE EXISTS SEPARATELY
5
+ * -------------------------------
6
+ * The pre-1.10.0 suite passed 177/177 while the provider was re-rendering
7
+ * all 12 chrome components once per video frame. Nothing was broken in a way
8
+ * the existing tests could see, because the suite asserts VALUES ("the
9
+ * title is right", "seekable is true") and never asserts HOW OFTEN React
10
+ * was asked to re-render.
11
+ *
12
+ * That is the whole point of these tests: they pin WORK, not values. Each
13
+ * one fails if its fix is reverted.
14
+ *
15
+ * The defect being pinned (see the notes on `playerStateEqual` in
16
+ * PlayerProvider.tsx):
17
+ * `applyPlayerEvent` returns a freshly-spread object for every event, so
18
+ * the provider's `nextState !== stateRef.current` guard was comparing a
19
+ * brand-new object against itself and was therefore ALWAYS true. Every
20
+ * event produced a setState and a context-value replacement.
21
+ */
22
+
23
+ import React from 'react';
24
+ import { NativeModules } from 'react-native';
25
+ import { act, renderHook } from '@testing-library/react-native';
26
+ import { PlayerProvider } from '../PlayerProvider';
27
+ import { usePlayer } from '../../types/player';
28
+
29
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
30
+ <PlayerProvider>{children}</PlayerProvider>
31
+ );
32
+
33
+ /**
34
+ * Deliver an event through the SAME emitter production uses.
35
+ *
36
+ * The bridge's `resolveEmitter()` builds a `NativeEventEmitter` over
37
+ * `NativeModules.MpvPlayerModule`, and on the native side the events are
38
+ * published through `RCTDeviceEventEmitter` (documented in
39
+ * MpvPlayerModule.ts: "the events are emitted via RCTDeviceEventEmitter").
40
+ * RN's own jest preset mocks `DeviceEventEmitter`/`RCTDeviceEventEmitter`,
41
+ * and `NativeEventEmitter` delegates to it, so emitting there drives the
42
+ * real subscription the provider registered — not a stub.
43
+ */
44
+ function emit(eventName: string, payload: Record<string, unknown>): void {
45
+ const {
46
+ DeviceEventEmitter,
47
+ } = require('react-native') as typeof import('react-native');
48
+ DeviceEventEmitter.emit(eventName, payload);
49
+ }
50
+
51
+ /**
52
+ * Count how many times a `usePlayer()` consumer actually re-rendered.
53
+ *
54
+ * `usePlayer()` reads ONLY `PlayerStateContext` (it does not read progress —
55
+ * that is what `usePlayerProgress()` is for), so this counter measures the
56
+ * STATE channel specifically. That is the channel `onPlaybackStateChanged`
57
+ * writes to, and the channel whose guard was dead code.
58
+ *
59
+ * The probe returns the hook value so the tests can assert on it too.
60
+ */
61
+ function createRenderCounter() {
62
+ let renders = 0;
63
+ const probe = () => {
64
+ renders += 1;
65
+ return usePlayer();
66
+ };
67
+ return { probe, count: () => renders };
68
+ }
69
+
70
+ // ═══════════════════════════════════════════════════════════════════════════
71
+ // 1. The no-op guard
72
+ // ═══════════════════════════════════════════════════════════════════════════
73
+
74
+ describe('PlayerProvider no-op event guard', () => {
75
+ /**
76
+ * `isPlaying` defaults to `false`, so 'playing' is a REAL change and
77
+ * 'paused' is a no-op from the default baseline. Every test here has to
78
+ * establish a known baseline before it can assert on a no-op — otherwise
79
+ * it silently asserts the wrong thing, which is exactly the failure mode
80
+ * this file exists to prevent.
81
+ */
82
+ it('does NOT re-render state consumers when an event changes no field', async () => {
83
+ // `onPlaybackStateChanged` is handled by a pure spread-and-return in
84
+ // applyPlayerEvent. Before v1.10.0 this produced a new object every
85
+ // time and re-rendered every usePlayer() consumer, even when
86
+ // `isPlaying` was unchanged — and mpv emits this on pause, seek,
87
+ // speed change and file load.
88
+ const { probe, count } = createRenderCounter();
89
+ const { result, unmount } = await renderHook(probe, { wrapper });
90
+
91
+ // Baseline: get INTO 'playing' first. This render is expected.
92
+ await act(async () => {
93
+ emit('onPlaybackStateChanged', { state: 'playing' });
94
+ });
95
+ expect(result.current.state.isPlaying).toBe(true);
96
+
97
+ const rendersAfterBaseline = count();
98
+
99
+ // Now fire five events that change NOTHING.
100
+ await act(async () => {
101
+ emit('onPlaybackStateChanged', { state: 'playing' });
102
+ emit('onPlaybackStateChanged', { state: 'playing' });
103
+ emit('onPlaybackStateChanged', { state: 'playing' });
104
+ emit('onPlaybackStateChanged', { state: 'playing' });
105
+ emit('onPlaybackStateChanged', { state: 'playing' });
106
+ });
107
+
108
+ expect(count()).toBe(rendersAfterBaseline);
109
+
110
+ await unmount();
111
+ });
112
+
113
+ it('DOES re-render when an event changes a field', async () => {
114
+ // The mirror image of the test above, and the reason the guard above is
115
+ // safe: a guard that never fires is a dropped update, which is worse
116
+ // than a wasted render. Flipping isPlaying must still get through.
117
+ const { probe, count } = createRenderCounter();
118
+ const { result, unmount } = await renderHook(probe, { wrapper });
119
+
120
+ await act(async () => {
121
+ emit('onPlaybackStateChanged', { state: 'playing' });
122
+ });
123
+ const rendersAfterBaseline = count();
124
+
125
+ await act(async () => {
126
+ emit('onPlaybackStateChanged', { state: 'paused' });
127
+ });
128
+
129
+ expect(result.current.state.isPlaying).toBe(false);
130
+ expect(count()).toBeGreaterThan(rendersAfterBaseline);
131
+
132
+ await unmount();
133
+ });
134
+
135
+ it('propagates a field change that only exists on a NESTED value', async () => {
136
+ // The reason the key list is derived from DEFAULT_STATE at runtime
137
+ // rather than hand-written: `error` is a nested object, and a
138
+ // hand-written comparison that forgot it would silently drop errors.
139
+ const { probe, count } = createRenderCounter();
140
+ const { result, unmount } = await renderHook(probe, { wrapper });
141
+
142
+ const rendersAfterMount = count();
143
+
144
+ await act(async () => {
145
+ emit('onError', {
146
+ code: 3,
147
+ codeName: 'E_NETWORK_FAILURE',
148
+ recoverable: true,
149
+ message: 'boom',
150
+ });
151
+ });
152
+
153
+ expect(result.current.state.error).not.toBeNull();
154
+ expect(count()).toBeGreaterThan(rendersAfterMount);
155
+
156
+ await unmount();
157
+ });
158
+ });
159
+
160
+ // ═══════════════════════════════════════════════════════════════════════════
161
+ // 2. The removed position poll
162
+ // ═══════════════════════════════════════════════════════════════════════════
163
+
164
+ describe('PlayerProvider position source', () => {
165
+ beforeEach(() => {
166
+ jest.useFakeTimers();
167
+ });
168
+
169
+ afterEach(() => {
170
+ jest.useRealTimers();
171
+ });
172
+
173
+ it('does NOT call the synchronous getPosition/getDuration getters on a timer', async () => {
174
+ // v1.10.0 removed the 1Hz poll. Those two getters are SYNC
175
+ // TurboModule methods: React Native's own guidance is to use sync
176
+ // methods only for sub-5ms work and never on a recurring timer,
177
+ // because they block the JS thread for the JNI round-trip.
178
+ //
179
+ // If a poll is reintroduced, this fails — which is the point. A second
180
+ // writer to `positionMs` is how a seek bar ends up jumping backwards.
181
+ const { unmount } = await renderHook(() => usePlayer().state, { wrapper });
182
+
183
+ const getPosition = NativeModules.MpvPlayerModule
184
+ .getPosition as jest.Mock;
185
+ const getDuration = NativeModules.MpvPlayerModule
186
+ .getDuration as jest.Mock;
187
+ getPosition.mockClear();
188
+ getDuration.mockClear();
189
+
190
+ await act(async () => {
191
+ jest.advanceTimersByTime(5000);
192
+ });
193
+
194
+ expect(getPosition).not.toHaveBeenCalled();
195
+ expect(getDuration).not.toHaveBeenCalled();
196
+
197
+ await unmount();
198
+ });
199
+
200
+ it('still advances position from the event stream alone', async () => {
201
+ // Removing the poll is only safe if the event path carries position
202
+ // end to end. This proves it does — the seek bar does not depend on
203
+ // the poll it no longer has.
204
+ const { result, unmount } = await renderHook(() => usePlayer().state, {
205
+ wrapper,
206
+ });
207
+
208
+ await act(async () => {
209
+ emit('onPositionChanged', { position: 42.5 });
210
+ });
211
+
212
+ expect(result.current.positionMs).toBe(42500);
213
+
214
+ await unmount();
215
+ });
216
+ });
217
+
218
+ // ═══════════════════════════════════════════════════════════════════════════
219
+ // 3. The observation contract (regression guard for the native coalescing)
220
+ // ═══════════════════════════════════════════════════════════════════════════
221
+
222
+ describe('PlayerProvider observed property contract', () => {
223
+ it('observes the properties whose events carry position and cache state', async () => {
224
+ // The native layer (event.cpp) now COALESCES `time-pos` and
225
+ // `demuxer-cache-state` before forwarding them, precisely because
226
+ // mpv emits them once per frame / on every cache tick. That
227
+ // optimisation is only correct if these names are actually observed —
228
+ // an unregistered name never reaches the coalescer and the field goes
229
+ // dead, which is the same defect class as `mute` in 1.9.1.
230
+ const { unmount } = await renderHook(() => usePlayer(), { wrapper });
231
+
232
+ const observed = (
233
+ NativeModules.MpvPlayerModule.observeProperty as jest.Mock
234
+ ).mock.calls.map((call: unknown[]) => call[0]);
235
+
236
+ expect(observed).toEqual(
237
+ expect.arrayContaining(['time-pos', 'duration', 'demuxer-cache-state']),
238
+ );
239
+
240
+ await unmount();
241
+ });
242
+ });
@@ -117,6 +117,73 @@ describe('useLaunchPlayback', () => {
117
117
  render(<Harness params={undefined} />);
118
118
  await waitFor(() => expect(bridge().loadFile).not.toHaveBeenCalled());
119
119
  });
120
+
121
+ // ── v1.9.3: the title the launch payload always carried ──────────────
122
+ //
123
+ // `LaunchParams.title` has always existed and has always come straight
124
+ // from the host app's `openPlayer({uri, title})`. This hook — the ONE
125
+ // place that actually loads the file — read `uri` and
126
+ // `startPositionMs` and discarded it. With `media-title` also unobserved,
127
+ // `PlayerState.title` stayed at the DEFAULT_STATE placeholder and every
128
+ // player header rendered the literal string "Simba Player".
129
+ //
130
+ // This is the path the app actually takes (`openPlayer` → activity →
131
+ // launch params → this hook), which is why it is the assertion that
132
+ // matters, not just the one on `commands.loadFile`.
133
+
134
+ it('applies the launch title as mpv force-media-title before loading', async () => {
135
+ render(<Harness params={{...PARAMS, title: 'Overrun!'}} />);
136
+ await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
137
+ expect(bridge().setProperty).toHaveBeenCalledWith(
138
+ 'force-media-title',
139
+ 'Overrun!',
140
+ );
141
+ });
142
+
143
+ it('sets the title BEFORE the load — mpv reads the option at load time', async () => {
144
+ const order: string[] = [];
145
+ bridge().setProperty.mockImplementation(() => {
146
+ order.push('setProperty');
147
+ });
148
+ bridge().loadFile.mockImplementation(() => {
149
+ order.push('loadFile');
150
+ });
151
+
152
+ render(<Harness params={{...PARAMS, title: 'Overrun!'}} />);
153
+ await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
154
+ expect(order).toEqual(['setProperty', 'loadFile']);
155
+ });
156
+
157
+ it('trims the launch title', async () => {
158
+ render(<Harness params={{...PARAMS, title: ' Overrun! '}} />);
159
+ await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
160
+ expect(bridge().setProperty).toHaveBeenCalledWith(
161
+ 'force-media-title',
162
+ 'Overrun!',
163
+ );
164
+ });
165
+
166
+ it('omits the option when the title is blank — mpv keeps deriving its own', async () => {
167
+ // Writing an empty `force-media-title` would BLANK the header, which
168
+ // is worse than the derived fallback it replaced.
169
+ render(<Harness params={{...PARAMS, title: ' '}} />);
170
+ await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
171
+ expect(bridge().setProperty).not.toHaveBeenCalledWith(
172
+ 'force-media-title',
173
+ expect.anything(),
174
+ );
175
+ });
176
+
177
+ it('still loads the file when the title write is rejected', async () => {
178
+ // A rejected option must never cost the user their video.
179
+ bridge().setProperty.mockImplementationOnce(() => {
180
+ throw new Error('property rejected');
181
+ });
182
+
183
+ render(<Harness params={{...PARAMS, title: 'Overrun!'}} />);
184
+ await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
185
+ expect(bridge().play).toHaveBeenCalledTimes(1);
186
+ });
120
187
  });
121
188
 
122
189
  describe('SimbaPlayerRoot — headless', () => {
@@ -1,5 +1,9 @@
1
1
  import { useEffect } from 'react';
2
- import { getMpvPlayerModule, type LaunchParams } from '../bridge/MpvPlayerModule';
2
+ import {
3
+ applyForceMediaTitle,
4
+ getMpvPlayerModule,
5
+ type LaunchParams,
6
+ } from '../bridge/MpvPlayerModule';
3
7
 
4
8
  /**
5
9
  * Feed a launch payload to mpv, exactly once per payload.
@@ -44,6 +48,7 @@ export function useLaunchPlayback(
44
48
  launchParams: LaunchParams | null | undefined,
45
49
  ): void {
46
50
  const uri = launchParams?.uri ?? null;
51
+ const title = launchParams?.title ?? undefined;
47
52
  const startPositionSec = launchParams?.startPositionMs
48
53
  ? launchParams.startPositionMs / 1000
49
54
  : 0;
@@ -55,6 +60,15 @@ export function useLaunchPlayback(
55
60
  }
56
61
  const bridge = getMpvPlayerModule();
57
62
  try {
63
+ // v1.9.3 — `launchParams.title` was READ BY NOTHING here. The
64
+ // launch payload has always carried the real title (it comes
65
+ // straight from the host app's `openPlayer({uri, title})`), and
66
+ // this hook — the one place that actually loads the file — threw
67
+ // it away. Combined with `media-title` never being observed, that
68
+ // is why every player header read "Simba Player".
69
+ //
70
+ // Must precede `loadFile`: mpv reads the option at load time.
71
+ applyForceMediaTitle(bridge, title);
58
72
  bridge.loadFile(uri);
59
73
  if (startPositionSec > 0) {
60
74
  bridge.seekAbsolute(startPositionSec);
@@ -8,6 +8,7 @@ import {
8
8
  MpvVideoParams,
9
9
  MpvPlaybackState,
10
10
  MpvFileInfo,
11
+ applyForceMediaTitle,
11
12
  } from '../bridge/MpvPlayerModule';
12
13
 
13
14
  /**
@@ -561,36 +562,16 @@ function buildCommands(): PlayerCommands {
561
562
  loadFile: (uri: string, title?: string) => {
562
563
  // v1.9.3 — the launch TITLE is applied here, and this is the fix
563
564
  // for a long-standing defect: `openPlayer({uri, title})` accepted a
564
- // title, handed it to `PlayerActivity`, and then NOTHING ever
565
- // applied it. `useLaunchPlayback` destructures only `uri` and
566
- // `startPositionMs` out of the launch params, `onFileLoaded`'s
567
- // handler reads `file?.title` from a native payload that has no
568
- // `file` key at all, and `media-title` was missing from
569
- // OBSERVED_PROPERTIES — so `PlayerState.title` stayed pinned at the
570
- // `DEFAULT_STATE` placeholder and every consumer rendered the
571
- // string "Simba Player" no matter what was playing.
565
+ // title and handed it to `PlayerActivity`, and then NOTHING ever
566
+ // applied it. `onFileLoaded`'s handler reads `file?.title` from a
567
+ // native payload that has no `file` key, and `media-title` was
568
+ // missing from OBSERVED_PROPERTIES — so `PlayerState.title` stayed
569
+ // pinned at the `DEFAULT_STATE` placeholder and every consumer
570
+ // rendered "Simba Player" no matter what was playing.
572
571
  //
573
- // `force-media-title` is mpv's own option for exactly this: it
574
- // OVERRIDES the title mpv would otherwise derive from the
575
- // container's metadata or the URL's last path segment (which, for
576
- // a signed CDN URL, is an opaque token like "abc123?sig=...").
577
- //
578
- // It has to be set BEFORE the load, so the order below is load
579
- // bearing and is not an optimisation: set, then load. Both calls
580
- // are plain `@ReactMethod`s, which the bridge dispatches in call
581
- // order, so the ordering holds.
582
- if (title && title.trim()) {
583
- try {
584
- getMpvPlayerModule().setProperty('force-media-title', title.trim());
585
- } catch (e) {
586
- // A rejected property write must not abort the load — the
587
- // video is the priority, and mpv will fall back to deriving
588
- // its own title. Surfaced loudly in dev because it means the
589
- // title will be wrong.
590
- // eslint-disable-next-line no-console
591
- console.warn('[simba-player] force-media-title rejected:', e);
592
- }
593
- }
572
+ // `force-media-title` is mpv's own option for exactly this. The
573
+ // set-then-load ordering is the contract — see the helper.
574
+ applyForceMediaTitle(getMpvPlayerModule(), title);
594
575
  dlog('commands.loadFile(', uri, ')');
595
576
  getMpvPlayerModule().loadFile(uri);
596
577
  },