@simba-dev/react-native-media-player 1.8.3 → 1.9.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.
package/README.md CHANGED
@@ -477,7 +477,7 @@ Every public export lives in [`src/index.ts`](./src/index.ts). The **V13+ surfac
477
477
  |---|---|
478
478
  | `PlayerState` | 20 fields: `isPlaying`, `title`, `artist`, `album`, `positionMs`, `durationMs`, `isBuffering`, `isSeeking`, `seekable`, `volume`, `isMuted`, `speed`, `loopMode`, `playlist`, `currentIndex`, `tracks`, `chapters`, `currentChapter`, `videoParams`, `error` |
479
479
  | `PlayerProgress` | 7 fields: `positionMs`, `durationMs`, `isBuffering`, `isSeeking`, `seekable`, `cacheRanges`, `cacheFill` |
480
- | `PlayerCommands` | 38 methods: `play`, `pause`, `seek`, `skipBackward`, `skipForward`, `togglePlayPause`, `stop`, `seekBy`, `seekToChapter`, `next`, `previous`, `setVolume`, `setMuted`, `toggleMute`, `setSpeed`, `setLoopMode`, `loadFile`, `loadPlaylist`, `playlistRemove`, `shuffle`, `clear`, `selectTrack`, `cycleTrack`, `setTrack`, `enterPip`, `exitPip`, `exitPipAndFinish`, `setKeepScreenOn`, `setOrientation`, `setImmersive`, `setScreenBrightness`, `requestNotificationPermission`, `openPlayer`, `getLaunchParams`, `getProperty`, `setProperty`, `observeProperty`, `unobserveProperty`, `grantPersistablePermission`, `verifyContentUri` |
480
+ | `PlayerCommands` | 38 methods: `play`, `pause`, `seek`, `skipBackward`, `skipForward`, `togglePlayPause`, `stop`, `seekBy`, `seekToChapter`, `next`, `previous`, `setVolume`, `setMuted`, `toggleMute`, `setSpeed`, `setLoopMode`, `loadFile`, `loadPlaylist`, `playlistRemove`, `shuffle`, `clear`, `cycleTrack`, `setTrack`, `enterPip`, `exitPip`, `exitPipAndFinish`, `setKeepScreenOn`, `setOrientation`, `setImmersive`, `setScreenBrightness`, `requestNotificationPermission`, `openPlayer`, `getLaunchParams`, `getProperty`, `setProperty`, `observeProperty`, `unobserveProperty`, `grantPersistablePermission`, `verifyContentUri` |
481
481
  | `OpenPlayerOptions` | `{ uri, title, type: 'video' \| 'audio', startPositionMs? }` — the V13 `openPlayer` arg shape (replaces V11's positional args) |
482
482
  | `LaunchParams` | `{ uri, title, type, startPositionMs }` — read from the activity via `useLaunchParams()` |
483
483
  | `ContentKind` | `'video' \| 'audio' \| 'music' \| 'movie' \| 'podcast' \| 'live-tv' \| 'radio' \| 'audiobook' \| 'archive-audio' \| 'episode' \| 'video-file' \| string` |
@@ -214,12 +214,43 @@ static std::string currentMpvPath() {
214
214
  void eventLoop() {
215
215
  TRACEI("Event loop started");
216
216
 
217
+ // ── Why this drains instead of blocking ────────────────────────────────
218
+ // mpv's own client.h states the rule this loop has to respect:
219
+ //
220
+ // "Property changes are coalesced: the change events are returned
221
+ // only once the event queue becomes empty (e.g. mpv_wait_event()
222
+ // would block or return MPV_EVENT_NONE), and then only one event
223
+ // per changed property is returned."
224
+ //
225
+ // So MPV_EVENT_PROPERTY_CHANGE is not delivered when the property
226
+ // changes — it is delivered when the queue happens to drain. A loop
227
+ // that blocks on `mpv_wait_event(-1)` and handles exactly one event
228
+ // before blocking again can starve every property event for as long
229
+ // as anything else keeps the queue non-empty. That is precisely the
230
+ // failure this used to have: MPV_EVENT_PROPERTY_CHANGE events were
231
+ // never observed on the handle the properties were observed on, so
232
+ // `onSeekable` / `onPositionChanged` / `onCacheState` never reached
233
+ // JS and the seek bar stayed permanently disabled.
234
+ //
235
+ // The drain below is the documented shape: poll with a zero timeout
236
+ // first, and only block when mpv reports MPV_EVENT_NONE — the exact
237
+ // state in which mpv is obliged to release the coalesced property
238
+ // changes. One queue-drained iteration costs one non-blocking call.
217
239
  while (g_running.load()) {
218
- mpv_event *event = mpv_wait_event(g_mpv, -1);
240
+ mpv_event *event = mpv_wait_event(g_mpv, 0);
219
241
  if (!event) {
220
242
  LOGE("[PlaybackTrace][Native][eventLoop] mpv_wait_event returned null");
221
243
  continue;
222
244
  }
245
+ if (event->event_id == MPV_EVENT_NONE) {
246
+ // Queue is empty. Block until mpv has something for us; the
247
+ // wake-up will also flush any coalesced property changes.
248
+ event = mpv_wait_event(g_mpv, -1);
249
+ if (!event) {
250
+ LOGE("[PlaybackTrace][Native][eventLoop] mpv_wait_event returned null");
251
+ continue;
252
+ }
253
+ }
223
254
  TRACEI("[PlaybackTrace][Native][eventLoop] event_id=%d error=%d", event->event_id, event->error);
224
255
 
225
256
  switch (event->event_id) {
@@ -326,6 +357,15 @@ void eventLoop() {
326
357
  json = "null";
327
358
  }
328
359
  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"
365
+ // 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());
329
369
  callJavaPropertyChanged(prop->name, json.c_str());
330
370
  break;
331
371
  }
@@ -753,16 +753,10 @@ Java_com_simba_player_mpv_MPVLib_nativePlaylistClear(
753
753
  mpv_command(mpv, clearArgs);
754
754
  }
755
755
 
756
- // ── Tracks ──────────────────────────────────────────────────────────────────
757
-
758
- extern "C" JNIEXPORT void JNICALL
759
- Java_com_simba_player_mpv_MPVLib_nativeSelectTrack(
760
- JNIEnv *env, jclass, jlong nativePtr, jint trackId) {
761
- NativeMpvReadLease lease(nativePtr);
762
- if (!lease.valid()) return;
763
- mpv_handle *mpv = lease.get();
764
- mpv_set_property(mpv, "vid", MPV_FORMAT_INT64, &trackId);
765
- }
756
+ // `nativeSelectTrack()` was REMOVED — it carried no track type, and it
757
+ // hardcoded mpv's "vid" property, so selecting a subtitle track retargeted
758
+ // the VIDEO track. `setTrack(type, trackId)` in MpvBridgeModule.kt routes to
759
+ // vid/aid/sid via `nativeSetPropertyString` instead.
766
760
 
767
761
  // ── Filters ─────────────────────────────────────────────────────────────────
768
762
 
@@ -71,10 +71,6 @@ object MPVLib {
71
71
  external fun nativePlaylistShuffle(nativePtr: Long)
72
72
  external fun nativePlaylistClear(nativePtr: Long)
73
73
 
74
- // ── Tracks ─────────────────────────────────────────────────────────────
75
-
76
- external fun nativeSelectTrack(nativePtr: Long, trackId: Int)
77
-
78
74
  // ── Properties ─────────────────────────────────────────────────────────
79
75
 
80
76
  external fun nativeGetProperty(nativePtr: Long, name: String): String
@@ -813,13 +813,13 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
813
813
  } catch (_: Exception) { "[]" }
814
814
  }
815
815
 
816
- @ReactMethod
817
- @Override
818
- override fun selectTrack(trackId: Double) {
819
- ensurePtr()
820
- MPVLib.nativeSelectTrack(nativePtr, trackId.toInt())
821
- }
822
-
816
+ /**
817
+ * `selectTrack(trackId)` was REMOVED. It carried no track type, and its
818
+ * native implementation hardcoded mpv's "vid" property, so selecting a
819
+ * subtitle retargeted the VIDEO track. Use `setTrack(type, trackId)`
820
+ * instead — it maps video/audio/sub to vid/aid/sid and handles disabling
821
+ * via a negative id.
822
+ */
823
823
  @ReactMethod
824
824
  @Override
825
825
  override fun setTrack(type: String, trackId: Double) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.8.3",
3
+ "version": "1.9.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",
@@ -235,8 +235,9 @@ export interface MpvPlayerModuleBridge {
235
235
  // ── Tracks ─────────────────────────────────────────────────────────────
236
236
  /** Get the mpv track list as a JSON string. */
237
237
  getTracks(): string;
238
- /** Select the track by ID. */
239
- selectTrack(trackId: number): void;
238
+ // `selectTrack(trackId)` was REMOVED — it carried no track type, and its
239
+ // native implementation hardcoded mpv's "vid" property, so selecting a
240
+ // subtitle retargeted the VIDEO track. Use `setTrack(type, trackId)`.
240
241
  /** Cycle to the next/previous track of the given type. */
241
242
  cycleTrack(type: 'video' | 'audio' | 'sub'): void;
242
243
  /** Set the active track for a type (trackId < 0 means "no"). */
@@ -482,9 +483,6 @@ const NOOP_BRIDGE: MpvPlayerModuleBridge = {
482
483
 
483
484
  // Tracks
484
485
  getTracks: () => '[]',
485
- selectTrack: (_trackId: number) => {
486
- void _trackId;
487
- },
488
486
  cycleTrack: (_type: 'video' | 'audio' | 'sub') => {
489
487
  void _type;
490
488
  },
@@ -78,7 +78,9 @@ export interface Spec extends TurboModule {
78
78
 
79
79
  // ── Tracks ─────────────────────────────────────────────────────────────
80
80
  getTracks(): string;
81
- selectTrack(trackId: number): void;
81
+ // `selectTrack(trackId)` was REMOVED — it carried no track type, and its
82
+ // native implementation hardcoded mpv's "vid" property, so selecting a
83
+ // subtitle retargeted the VIDEO track. Use `setTrack(type, trackId)`.
82
84
  cycleTrack(type: string): void;
83
85
  setTrack(type: string, trackId: number): void;
84
86
  setTrackVisibility(trackType: string, visible: boolean): void;
@@ -262,6 +262,30 @@ const POSITION_POLL_INTERVAL_MS = 1000;
262
262
  * `demuxer-cache-state` is deliberately observed too: it is the only
263
263
  * source for the buffered ranges that the seek bar paints behind the
264
264
  * played fill.
265
+ *
266
+ * ---------------------------------------------------------------------------
267
+ * OPEN NATIVE DEFECT (1.8.4) — registration is fixed, delivery is not
268
+ * ---------------------------------------------------------------------------
269
+ * This list is necessary but NOT sufficient. Measured on emulator-5554
270
+ * (API 37) with the 1.8.3 code running and a file actively playing
271
+ * (`time-pos` advancing, `pause=false`):
272
+ *
273
+ * - `mpv_observe_property(...)` returns `result=0` for all twelve —
274
+ * registration genuinely succeeds.
275
+ * - `onPlaybackRestart` arrives 7,418 times; `onFileLoaded` arrives.
276
+ * So the native event loop IS pumping and IS dispatching to JS.
277
+ * - `onSeekable` / `onPositionChanged` / `onDurationChanged` /
278
+ * `onCacheState` / `onPlaybackStateChanged` arrive **0 times**.
279
+ *
280
+ * `MPV_EVENT_PROPERTY_CHANGE` is therefore never delivered to this
281
+ * handle even though the property is observed on it. The next release
282
+ * must fix the native property-event path (observe handle vs. pumped
283
+ * handle in `android/src/main/cpp/event.cpp` / `property.cpp`).
284
+ *
285
+ * Until that lands, the observable symptom is unchanged: the scrub bar
286
+ * still renders disabled ("Live stream — not seekable") because
287
+ * `seekable` never leaves `DEFAULT_PROGRESS`. Do not read a green test
288
+ * suite as evidence this works — the whole suite mocks the emitter.
265
289
  */
266
290
  const OBSERVED_PROPERTIES: readonly string[] = [
267
291
  'time-pos',
@@ -559,6 +583,49 @@ export function PlayerProvider({
559
583
  }
560
584
  }
561
585
 
586
+ // ── 2b. Re-read the LEVEL-only progress fields ───────────────────────
587
+ //
588
+ // `seekable` is a LEVEL value that mpv delivers only as an EDGE:
589
+ // MPV_EVENT_PROPERTY_CHANGE is emitted once, at the instant the flag
590
+ // flips from false to true. Any provider that mounts — or remounts,
591
+ // e.g. in a second React root — after that flip never observes the
592
+ // event, so the field stays at DEFAULT_PROGRESS forever and the
593
+ // consumer's seek bar renders permanently disabled.
594
+ //
595
+ // Measured on device (Android 37): `onCacheState` — which changes
596
+ // continuously — reached JS 827 times, while `onSeekable` arrived
597
+ // ZERO times across both a cold start and an app restart, because by
598
+ // then the flag had already settled and mpv will not repeat it.
599
+ //
600
+ // So read the level once at mount. The event keeps driving updates
601
+ // afterwards; this only closes the gap for a provider that starts
602
+ // mid-session. Without it the only correct usage pattern is
603
+ // "subscribe strictly before loadFile", which no consumer can be
604
+ // asked to guarantee across activities.
605
+ try {
606
+ const raw = bridge.getProperty('seekable');
607
+ // The bridge serialises MPV_FORMAT_FLAG to the JSON literals
608
+ // `true` / `false` (property.cpp, appendNode). Anything else -
609
+ // "null" for an unavailable property, "" for the NOOP bridge -
610
+ // is not a value, and must not be coerced to false.
611
+ if (raw === 'true' || raw === 'false') {
612
+ const seekable = raw === 'true';
613
+ if (seekable !== progressRef.current.seekable) {
614
+ const seeded: PlayerProgress = {
615
+ ...progressRef.current,
616
+ seekable,
617
+ };
618
+ progressRef.current = seeded;
619
+ setProgress(seeded);
620
+ }
621
+ }
622
+ } catch (e) {
623
+ // Best-effort: a bridge without `getProperty` (or no live mpv
624
+ // instance yet) leaves the field to the event stream.
625
+ // eslint-disable-next-line no-console
626
+ console.warn('[simba-player] seekable seed failed:', e);
627
+ }
628
+
562
629
  // ── 3. 1Hz position/duration poll ───────────────────────────────────
563
630
  // Both `getPosition` and `getDuration` are sync React methods
564
631
  // on the bridge, so the poll doesn't queue microtasks. We
@@ -379,3 +379,108 @@ describe('mpv property observation', () => {
379
379
  await unmount();
380
380
  });
381
381
  });
382
+
383
+ // -- `seekable` is edge-only, so mount must read the level -----------------
384
+
385
+ /**
386
+ * mpv delivers `seekable` as a LEVEL value but only reports it as an
387
+ * EDGE: MPV_EVENT_PROPERTY_CHANGE fires once, at the instant the flag
388
+ * flips. A provider that mounts after that flip never sees the event.
389
+ *
390
+ * Measured on device, that meant `progress.seekable` stayed false
391
+ * forever and every consumer's seek bar rendered permanently disabled
392
+ * on ordinary seekable files. `onCacheState` — which changes
393
+ * continuously — arrived 827 times over the same window, which is what
394
+ * proved the subscription path itself was fine and isolated the fault
395
+ * to the missed edge.
396
+ *
397
+ * These tests pin the compensating level read. They use NO emitted
398
+ * event at all: the provider must know `seekable` on its own.
399
+ */
400
+ describe('PlayerProvider seekable seeding', () => {
401
+ const seekableProp = (
402
+ NativeModules.MpvPlayerModule as unknown as {
403
+ getProperty: jest.Mock;
404
+ }
405
+ ).getProperty;
406
+
407
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
408
+ <PlayerProvider>{children}</PlayerProvider>
409
+ );
410
+
411
+ beforeEach(() => {
412
+ clearBridgeMocks();
413
+ seekableProp.mockReturnValue('');
414
+ });
415
+
416
+ afterEach(() => {
417
+ seekableProp.mockReturnValue('');
418
+ });
419
+
420
+ it('reads seekable at mount even though no event was ever emitted', async () => {
421
+ // The regression: the flag is already true in mpv, but the edge was
422
+ // consumed before this provider existed.
423
+ seekableProp.mockImplementation((name: string) =>
424
+ name === 'seekable' ? 'true' : 'null',
425
+ );
426
+
427
+ const { result, unmount } = await renderHook(() => usePlayerProgress(), {
428
+ wrapper,
429
+ });
430
+
431
+ expect(result.current.seekable).toBe(true);
432
+ // And it must be read, not inferred.
433
+ expect(seekableProp).toHaveBeenCalledWith('seekable');
434
+
435
+ await unmount();
436
+ });
437
+
438
+ it('leaves seekable false when mpv reports it false', async () => {
439
+ seekableProp.mockImplementation((name: string) =>
440
+ name === 'seekable' ? 'false' : 'null',
441
+ );
442
+
443
+ const { result, unmount } = await renderHook(() => usePlayerProgress(), {
444
+ wrapper,
445
+ });
446
+
447
+ expect(result.current.seekable).toBe(false);
448
+
449
+ await unmount();
450
+ });
451
+
452
+ it('does not coerce an unreadable property into a value', async () => {
453
+ // `getProperty` returns "" on the NOOP bridge and "null" from the
454
+ // native side for an unavailable property. Neither is a boolean,
455
+ // and silently mapping them to false would be a guess - the same
456
+ // class of defect as inventing a title. They must simply be
457
+ // ignored, leaving DEFAULT_PROGRESS in place.
458
+ seekableProp.mockReturnValue('null');
459
+
460
+ const { result, unmount } = await renderHook(() => usePlayerProgress(), {
461
+ wrapper,
462
+ });
463
+
464
+ expect(result.current.seekable).toBe(false);
465
+ expect(result.current.cacheRanges).toEqual([]);
466
+
467
+ await unmount();
468
+ });
469
+
470
+ it('survives a bridge whose getProperty throws', async () => {
471
+ // Hydration is best-effort everywhere else in this effect, so the
472
+ // seed must not be the one call that takes the provider down.
473
+ seekableProp.mockImplementation(() => {
474
+ throw new Error('no mpv instance yet');
475
+ });
476
+
477
+ const { result, unmount } = await renderHook(() => usePlayerProgress(), {
478
+ wrapper,
479
+ });
480
+
481
+ expect(result.current).toBeDefined();
482
+ expect(result.current.seekable).toBe(false);
483
+
484
+ await unmount();
485
+ });
486
+ });
@@ -173,7 +173,6 @@ describe('usePlayer (no provider)', () => {
173
173
  expect(typeof c.playlistRemove).toBe('function');
174
174
  expect(typeof c.shuffle).toBe('function');
175
175
  expect(typeof c.clear).toBe('function');
176
- expect(typeof c.selectTrack).toBe('function');
177
176
  expect(typeof c.cycleTrack).toBe('function');
178
177
  expect(typeof c.setTrack).toBe('function');
179
178
  expect(typeof c.enterPip).toBe('function');
@@ -199,11 +199,17 @@ export interface PlayerCommands {
199
199
  clear(): void;
200
200
 
201
201
  // Tracks
202
- /** Select a track by ID. */
203
- selectTrack(trackId: number): void;
204
202
  /** Cycle to the next/previous track of the given type. */
205
203
  cycleTrack(type: 'video' | 'audio' | 'sub'): void;
206
- /** Set the active track for a type (trackId < 0 means "no track"). */
204
+ /**
205
+ * Set the active track for a type (trackId < 0 means "no track").
206
+ *
207
+ * `selectTrack(trackId)` was REMOVED. It carried no track type, and its
208
+ * native implementation hardcoded mpv's "vid" property, so selecting a
209
+ * subtitle retargeted the VIDEO track. Use `setTrack(type, trackId)`
210
+ * instead — it maps video/audio/sub to vid/aid/sid and handles disabling
211
+ * via a negative id.
212
+ */
207
213
  setTrack(type: 'video' | 'audio' | 'sub', trackId: number): void;
208
214
 
209
215
  // PiP
@@ -567,10 +573,6 @@ function buildCommands(): PlayerCommands {
567
573
  getMpvPlayerModule().playlistClear();
568
574
  },
569
575
 
570
- selectTrack: (trackId: number) => {
571
- dlog('commands.selectTrack(', trackId, ')');
572
- getMpvPlayerModule().selectTrack(trackId);
573
- },
574
576
  cycleTrack: (type: 'video' | 'audio' | 'sub') => {
575
577
  dlog('commands.cycleTrack(', type, ')');
576
578
  getMpvPlayerModule().cycleTrack(type);