@simba-dev/react-native-media-player 1.8.4 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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` |
@@ -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.4",
3
+ "version": "1.9.1",
4
4
  "description": "React Native video & audio player powered by libmpv — Picture-in-Picture, MediaSession, foreground service, and a customizable TypeScript UI. Built for Android. Designed as a drop-in replacement for react-native-video / react-native-track-player / expo-av. See CHANGELOG.md for per-version notes.",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -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;
@@ -300,6 +300,27 @@ const OBSERVED_PROPERTIES: readonly string[] = [
300
300
  'paused-for-cache',
301
301
  'cache-buffering-state',
302
302
  'demuxer-cache-state',
303
+ // V19 W8.3.1 — `mute` was MISSING from this list, and its absence was
304
+ // invisible in every test because the whole emitter is mocked.
305
+ //
306
+ // `PlayerState.isMuted` is documented and written as
307
+ // "`onPropertyChanged('mute')` + hydration" (src/types/player.ts:29),
308
+ // and `applyPlayerEvent` really does handle `case 'mute'`. But mpv
309
+ // only emits PROPERTY_CHANGE for names passed to
310
+ // `mpv_observe_property` — and `mute` was not one of them. So
311
+ // `commands.setMuted(true)` muted the audio while no event ever
312
+ // reached JS, `state.isMuted` stayed `false`, and a mute button
313
+ // rendered from that state looked completely inert: the glyph never
314
+ // changed, the label never changed, and the volume slider kept
315
+ // showing the real level.
316
+ //
317
+ // Measured on device (emulator-5554) with SIMBA W8.3: tapping "Mute"
318
+ // left the accessible label reading "Mute" and the slider reading
319
+ // "Volume, 100 percent". The command was correct; the OBSERVATION
320
+ // was missing. Same class of defect as the `seekable` gap above —
321
+ // the command surface and the state surface have to be wired
322
+ // separately, and wiring one does not wire the other.
323
+ 'mute',
303
324
  ];
304
325
 
305
326
  /**
@@ -583,6 +604,76 @@ export function PlayerProvider({
583
604
  }
584
605
  }
585
606
 
607
+ // ── 2b. Re-read the LEVEL-only progress fields ───────────────────────
608
+ //
609
+ // `seekable` is a LEVEL value that mpv delivers only as an EDGE:
610
+ // MPV_EVENT_PROPERTY_CHANGE is emitted once, at the instant the flag
611
+ // flips from false to true. Any provider that mounts — or remounts,
612
+ // e.g. in a second React root — after that flip never observes the
613
+ // event, so the field stays at DEFAULT_PROGRESS forever and the
614
+ // consumer's seek bar renders permanently disabled.
615
+ //
616
+ // Measured on device (Android 37): `onCacheState` — which changes
617
+ // continuously — reached JS 827 times, while `onSeekable` arrived
618
+ // ZERO times across both a cold start and an app restart, because by
619
+ // then the flag had already settled and mpv will not repeat it.
620
+ //
621
+ // So read the level once at mount. The event keeps driving updates
622
+ // afterwards; this only closes the gap for a provider that starts
623
+ // mid-session. Without it the only correct usage pattern is
624
+ // "subscribe strictly before loadFile", which no consumer can be
625
+ // asked to guarantee across activities.
626
+ try {
627
+ const raw = bridge.getProperty('seekable');
628
+ // The bridge serialises MPV_FORMAT_FLAG to the JSON literals
629
+ // `true` / `false` (property.cpp, appendNode). Anything else -
630
+ // "null" for an unavailable property, "" for the NOOP bridge -
631
+ // is not a value, and must not be coerced to false.
632
+ if (raw === 'true' || raw === 'false') {
633
+ const seekable = raw === 'true';
634
+ if (seekable !== progressRef.current.seekable) {
635
+ const seeded: PlayerProgress = {
636
+ ...progressRef.current,
637
+ seekable,
638
+ };
639
+ progressRef.current = seeded;
640
+ setProgress(seeded);
641
+ }
642
+ }
643
+ } catch (e) {
644
+ // Best-effort: a bridge without `getProperty` (or no live mpv
645
+ // instance yet) leaves the field to the event stream.
646
+ // eslint-disable-next-line no-console
647
+ console.warn('[simba-player] seekable seed failed:', e);
648
+ }
649
+
650
+ // ── 2c. Seed the `mute` LEVEL too (same reasoning as `seekable`) ───
651
+ //
652
+ // `mute` is edge-triggered for the same reason `seekable` is: mpv
653
+ // fires PROPERTY_CHANGE when the flag CHANGES, so a provider that
654
+ // mounts while the player is already muted never learns it from the
655
+ // stream. `hydratePlayerState` covers a cold start, but not a
656
+ // provider mounted mid-session in a second React root.
657
+ //
658
+ // Reading it here closes that gap, and it is a cheap boolean.
659
+ try {
660
+ const raw = bridge.getProperty('mute');
661
+ if (raw === 'true' || raw === 'false') {
662
+ const isMuted = raw === 'true';
663
+ if (isMuted !== stateRef.current.isMuted) {
664
+ const seeded: PlayerState = {
665
+ ...stateRef.current,
666
+ isMuted,
667
+ };
668
+ stateRef.current = seeded;
669
+ setState(seeded);
670
+ }
671
+ }
672
+ } catch (e) {
673
+ // eslint-disable-next-line no-console
674
+ console.warn('[simba-player] mute seed failed:', e);
675
+ }
676
+
586
677
  // ── 3. 1Hz position/duration poll ───────────────────────────────────
587
678
  // Both `getPosition` and `getDuration` are sync React methods
588
679
  // on the bridge, so the poll doesn't queue microtasks. We
@@ -34,7 +34,7 @@ import {
34
34
  useRenderControls,
35
35
  } from '../PlayerProvider';
36
36
  import { DEFAULT_PLAYER_CONFIG, DEFAULT_THEME } from '../../types/config';
37
- import { usePlayerProgress } from '../../types/player';
37
+ import {usePlayer, usePlayerProgress} from '../../types/player';
38
38
 
39
39
  // Helper to clear all bridge mock call counts between tests.
40
40
  function clearBridgeMocks() {
@@ -307,20 +307,81 @@ describe('mpv property observation', () => {
307
307
  NativeModules.MpvPlayerModule.observeProperty as jest.Mock
308
308
  ).mock.calls.map((call: unknown[]) => call[0]);
309
309
 
310
- // These four are the ones that are invisible until they are wrong:
310
+ // These are the ones that are invisible until they are wrong:
311
311
  // nothing polls them, so a missing registration is silent.
312
+ //
313
+ // `mute` is in this group for a measured reason. `PlayerState
314
+ // .isMuted` is documented as "`onPropertyChanged('mute')` +
315
+ // hydration" and `applyPlayerEvent` really does handle
316
+ // `case 'mute'` — but mpv only emits PROPERTY_CHANGE for names
317
+ // passed to `mpv_observe_property`, and `mute` was not one of them.
318
+ // So `commands.setMuted(true)` muted the audio while no event ever
319
+ // reached JS, `state.isMuted` stayed `false`, and a mute button
320
+ // rendered from that state looked inert: the glyph never changed
321
+ // and the label never changed. Found on device (emulator-5554)
322
+ // with SIMBA W8.3 — tapping "Mute" left the accessible label
323
+ // reading "Mute".
324
+ //
325
+ // Hydration did not save it: `hydratePlayerState` reads
326
+ // `getMuted()` once, which covers a cold start but not a provider
327
+ // that mounts mid-session. Hence the separate level seed as well.
312
328
  expect(observed).toEqual(
313
329
  expect.arrayContaining([
314
330
  'seekable',
315
331
  'seeking',
316
332
  'paused-for-cache',
317
333
  'demuxer-cache-state',
334
+ 'mute',
318
335
  ]),
319
336
  );
320
337
 
321
338
  await unmount();
322
339
  });
323
340
 
341
+ it('seeds `mute` as a LEVEL at mount, not only from the event stream', async () => {
342
+ // SPEC invariant I10: an edge-triggered event is not a level. mpv
343
+ // fires PROPERTY_CHANGE when `mute` CHANGES, so a provider mounted
344
+ // while the player is already muted never sees the event — the same
345
+ // gap that left `seekable` stuck at its default until W7 read it
346
+ // once at mount.
347
+ //
348
+ // The test emits NO event and still expects the correct value, which
349
+ // is the only shape that proves a SEED exists. A test that emits
350
+ // the event would pass whether or not the seed is there.
351
+ clearBridgeMocks();
352
+ (NativeModules.MpvPlayerModule.getProperty as jest.Mock).mockImplementation(
353
+ (name: string) => (name === 'mute' ? 'true' : 'null'),
354
+ );
355
+
356
+ const { result, unmount } = await renderHook(() => usePlayer(), {
357
+ wrapper,
358
+ });
359
+
360
+ expect(result.current.state.isMuted).toBe(true);
361
+
362
+ await unmount();
363
+ });
364
+
365
+ it('does not coerce a non-boolean `mute` property to false', async () => {
366
+ // The bridge serialises MPV_FORMAT_FLAG to the JSON literals
367
+ // `true` / `false`. Anything else — "null" for an unavailable
368
+ // property, "" for the NOOP bridge — is not a value, and coercing it
369
+ // to `false` would silently claim the player is unmuted when it may
370
+ // not be. This is the same guard the `seekable` seed has.
371
+ clearBridgeMocks();
372
+ (NativeModules.MpvPlayerModule.getProperty as jest.Mock).mockImplementation(
373
+ () => 'null',
374
+ );
375
+
376
+ const { result, unmount } = await renderHook(() => usePlayer(), {
377
+ wrapper,
378
+ });
379
+
380
+ expect(result.current.state.isMuted).toBe(false);
381
+
382
+ await unmount();
383
+ });
384
+
324
385
  it('observes the properties that back the polled events too', async () => {
325
386
  // Lower latency than the 1 Hz poll, and `pause` / `eof-reached` are
326
387
  // only reachable this way for a state change that happens between
@@ -379,3 +440,108 @@ describe('mpv property observation', () => {
379
440
  await unmount();
380
441
  });
381
442
  });
443
+
444
+ // -- `seekable` is edge-only, so mount must read the level -----------------
445
+
446
+ /**
447
+ * mpv delivers `seekable` as a LEVEL value but only reports it as an
448
+ * EDGE: MPV_EVENT_PROPERTY_CHANGE fires once, at the instant the flag
449
+ * flips. A provider that mounts after that flip never sees the event.
450
+ *
451
+ * Measured on device, that meant `progress.seekable` stayed false
452
+ * forever and every consumer's seek bar rendered permanently disabled
453
+ * on ordinary seekable files. `onCacheState` — which changes
454
+ * continuously — arrived 827 times over the same window, which is what
455
+ * proved the subscription path itself was fine and isolated the fault
456
+ * to the missed edge.
457
+ *
458
+ * These tests pin the compensating level read. They use NO emitted
459
+ * event at all: the provider must know `seekable` on its own.
460
+ */
461
+ describe('PlayerProvider seekable seeding', () => {
462
+ const seekableProp = (
463
+ NativeModules.MpvPlayerModule as unknown as {
464
+ getProperty: jest.Mock;
465
+ }
466
+ ).getProperty;
467
+
468
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
469
+ <PlayerProvider>{children}</PlayerProvider>
470
+ );
471
+
472
+ beforeEach(() => {
473
+ clearBridgeMocks();
474
+ seekableProp.mockReturnValue('');
475
+ });
476
+
477
+ afterEach(() => {
478
+ seekableProp.mockReturnValue('');
479
+ });
480
+
481
+ it('reads seekable at mount even though no event was ever emitted', async () => {
482
+ // The regression: the flag is already true in mpv, but the edge was
483
+ // consumed before this provider existed.
484
+ seekableProp.mockImplementation((name: string) =>
485
+ name === 'seekable' ? 'true' : 'null',
486
+ );
487
+
488
+ const { result, unmount } = await renderHook(() => usePlayerProgress(), {
489
+ wrapper,
490
+ });
491
+
492
+ expect(result.current.seekable).toBe(true);
493
+ // And it must be read, not inferred.
494
+ expect(seekableProp).toHaveBeenCalledWith('seekable');
495
+
496
+ await unmount();
497
+ });
498
+
499
+ it('leaves seekable false when mpv reports it false', async () => {
500
+ seekableProp.mockImplementation((name: string) =>
501
+ name === 'seekable' ? 'false' : 'null',
502
+ );
503
+
504
+ const { result, unmount } = await renderHook(() => usePlayerProgress(), {
505
+ wrapper,
506
+ });
507
+
508
+ expect(result.current.seekable).toBe(false);
509
+
510
+ await unmount();
511
+ });
512
+
513
+ it('does not coerce an unreadable property into a value', async () => {
514
+ // `getProperty` returns "" on the NOOP bridge and "null" from the
515
+ // native side for an unavailable property. Neither is a boolean,
516
+ // and silently mapping them to false would be a guess - the same
517
+ // class of defect as inventing a title. They must simply be
518
+ // ignored, leaving DEFAULT_PROGRESS in place.
519
+ seekableProp.mockReturnValue('null');
520
+
521
+ const { result, unmount } = await renderHook(() => usePlayerProgress(), {
522
+ wrapper,
523
+ });
524
+
525
+ expect(result.current.seekable).toBe(false);
526
+ expect(result.current.cacheRanges).toEqual([]);
527
+
528
+ await unmount();
529
+ });
530
+
531
+ it('survives a bridge whose getProperty throws', async () => {
532
+ // Hydration is best-effort everywhere else in this effect, so the
533
+ // seed must not be the one call that takes the provider down.
534
+ seekableProp.mockImplementation(() => {
535
+ throw new Error('no mpv instance yet');
536
+ });
537
+
538
+ const { result, unmount } = await renderHook(() => usePlayerProgress(), {
539
+ wrapper,
540
+ });
541
+
542
+ expect(result.current).toBeDefined();
543
+ expect(result.current.seekable).toBe(false);
544
+
545
+ await unmount();
546
+ });
547
+ });
@@ -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);