@simba-dev/react-native-media-player 1.5.20 → 1.8.3

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.
@@ -63,6 +63,14 @@ class PlayerActivity : ReactActivity() {
63
63
  */
64
64
  const val MAIN_COMPONENT_NAME = "SimbaPlayer"
65
65
 
66
+ /**
67
+ * 1.8.0 — launch-option (initial prop) key that tells the consumer's
68
+ * root component it is running in the player activity. Set to `true`
69
+ * here and `false` in the consumer's `MainActivity`; both values are
70
+ * read on the JS side, per React root.
71
+ */
72
+ const val EXTRA_IS_PLAYER_ACTIVITY = "isPlayerActivity"
73
+
66
74
  // ── Intent extras (Phase 3) ─────────────────────────────────────
67
75
  // Set by MpvBridgeModule.openPlayer(uri, title, type, startPositionMs)
68
76
  // when launching this activity. Phase 4 will read these back and log
@@ -309,8 +317,32 @@ class PlayerActivity : ReactActivity() {
309
317
 
310
318
  override fun getMainComponentName(): String = MAIN_COMPONENT_NAME
311
319
 
320
+ /**
321
+ * 1.8.0 — hand this activity's React root a PER-TREE "this is the
322
+ * player activity" fact, via the launch options (initial props).
323
+ *
324
+ * `MpvBridgeModule.currentActivityIsPlayer` is a process-wide
325
+ * `@Volatile @JvmStatic` flag: while `PlayerActivity` is alive, EVERY
326
+ * React root in the process reads `true` through
327
+ * `isCurrentActivityPlayer()`, including the one hosted by the
328
+ * consumer's `MainActivity`. That is the right answer for
329
+ * `useLaunchParams()`'s "don't claim the payload outside the player
330
+ * host" guard, but a consumer gating its OWN chrome on it would
331
+ * mount that chrome in the background activity too — a full-bleed
332
+ * overlay riding over every browsing screen.
333
+ *
334
+ * Launch options are per-ROOT, so this is the only channel that can
335
+ * answer "is *this* tree the player tree" honestly. The consumer reads
336
+ * the prop on its root component (`initialProps.isPlayerActivity`)
337
+ * and publishes it through a React context. Documented on
338
+ * `useIsPlayerActivity` in `src/hooks/`.
339
+ */
312
340
  override fun createReactActivityDelegate(): ReactActivityDelegate =
313
- DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
341
+ object : DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) {
342
+ override fun getLaunchOptions(): Bundle = Bundle().apply {
343
+ putBoolean(EXTRA_IS_PLAYER_ACTIVITY, true)
344
+ }
345
+ }
314
346
 
315
347
  // ── Lifecycle ─────────────────────────────────────────────────────
316
348
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.5.20",
3
+ "version": "1.8.3",
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",
@@ -287,8 +287,16 @@ export interface MpvPlayerModuleBridge {
287
287
  // ── Properties (generic get/set for any mpv property) ─────────────────
288
288
  /** Get the value of an mpv property as a string. */
289
289
  getProperty(name: string): string;
290
- /** Set the value of an mpv property. Value is stringified before sending. */
291
- setProperty(name: string, value: unknown): void;
290
+ /**
291
+ * Set the value of an mpv property.
292
+ *
293
+ * `value` is a `string` because that is what `MpvBridgeModule.kt`
294
+ * declares, and React Native's JS→native marshalling throws on a
295
+ * type mismatch rather than coercing. Callers with richer JS values
296
+ * should use `commands.setProperty`, whose signature is `unknown` and
297
+ * which encodes via `toMpvPropertyString` before it gets here.
298
+ */
299
+ setProperty(name: string, value: string): void;
292
300
  /** Begin observing an mpv property (emits `onPropertyChanged` events). */
293
301
  observeProperty(name: string): void;
294
302
  /** Stop observing an mpv property. */
@@ -530,7 +538,7 @@ const NOOP_BRIDGE: MpvPlayerModuleBridge = {
530
538
  void _name;
531
539
  return '';
532
540
  },
533
- setProperty: (_name: string, _value: unknown) => {
541
+ setProperty: (_name: string, _value: string) => {
534
542
  void _name;
535
543
  void _value;
536
544
  },
@@ -220,6 +220,96 @@ const ALL_PLAYER_EVENTS: readonly PlayerEventName[] = [
220
220
  /** How often the provider polls `getPosition` + `getDuration` from the bridge. */
221
221
  const POSITION_POLL_INTERVAL_MS = 1000;
222
222
 
223
+ /**
224
+ * mpv properties the provider observes, and the JS event each one backs
225
+ * in `MpvBridgeModule.onMpvPropertyChanged`.
226
+ *
227
+ * WHY THIS LIST HAS TO EXIST
228
+ * --------------------------
229
+ * mpv only reports a property through `mpv_observe_property`. That
230
+ * registration is reachable from JS **only** through
231
+ * `observeProperty(name)`, and the Kotlin side re-applies exactly the
232
+ * names JS asked for (`pendingObservedProperties`) at `initPlayer`.
233
+ * Nothing observes anything on its own.
234
+ *
235
+ * So without this list, every branch of the native property handler
236
+ * below is unreachable dead code, and the state it feeds keeps its
237
+ * `DEFAULT_PROGRESS` value forever:
238
+ *
239
+ * | property | event | field that stays stuck |
240
+ * |------------------------|----------------------|-------------------------|
241
+ * | `seekable` | `onSeekable` | `seekable` = false |
242
+ * | `seeking` | `onSeeking` | `isSeeking` = false |
243
+ * | `paused-for-cache` | `onBuffering` | `isBuffering` = false |
244
+ * | `cache-buffering-state`| `onBuffering` | `isBuffering` = false |
245
+ * | `demuxer-cache-state` | `onCacheState` | `cacheRanges` = [] |
246
+ * | `time-pos` | `onPositionChanged` | (polled as a fallback) |
247
+ * | `duration` | `onDurationChanged` | (polled as a fallback) |
248
+ * | `volume` | `onVolumeChanged` | (polled as a fallback) |
249
+ * | `speed` | `onSpeedChanged` | (polled as a fallback) |
250
+ * | `pause` | `onPlaybackStateChanged` | (polled as a fallback) |
251
+ * | `idle-active` / `eof-reached` | `onPlaybackStateChanged` | (polled as a fallback) |
252
+ *
253
+ * The difference between the two groups is the whole point: position,
254
+ * duration, volume, speed and play state also arrive through the 1 Hz
255
+ * poll in step 3, so they look fine. `seekable`, `isSeeking`,
256
+ * `isBuffering` and `cacheRanges` have **no polling fallback**, so with
257
+ * nothing observing them the scrub bar renders permanently disabled, the
258
+ * buffering spinner never appears, and the buffered-range fill is never
259
+ * painted — while every test in this repo still passes, because the
260
+ * defaults are valid-looking values.
261
+ *
262
+ * `demuxer-cache-state` is deliberately observed too: it is the only
263
+ * source for the buffered ranges that the seek bar paints behind the
264
+ * played fill.
265
+ */
266
+ const OBSERVED_PROPERTIES: readonly string[] = [
267
+ 'time-pos',
268
+ 'duration',
269
+ 'volume',
270
+ 'speed',
271
+ 'pause',
272
+ 'idle-active',
273
+ 'eof-reached',
274
+ 'seekable',
275
+ 'seeking',
276
+ 'paused-for-cache',
277
+ 'cache-buffering-state',
278
+ 'demuxer-cache-state',
279
+ ];
280
+
281
+ /**
282
+ * Compare two `cacheRanges` arrays cheaply but CORRECTLY.
283
+ *
284
+ * The provider's no-op short-circuit used to compare
285
+ * `prev.cacheRanges.length === next.cacheRanges.length`. That is wrong:
286
+ * mpv grows the cached region by pushing `end` forward while the range
287
+ * count stays constant, so every one of those updates was discarded and
288
+ * the buffered bar froze at its first paint.
289
+ *
290
+ * Ranges arrive sorted and there are normally one or two of them, so
291
+ * comparing the count plus the first and last bounds is O(1) and catches
292
+ * the growth case that length alone misses.
293
+ */
294
+ function cacheRangesEqual(
295
+ a: ReadonlyArray<{start: number; end: number}>,
296
+ b: ReadonlyArray<{start: number; end: number}>,
297
+ ): boolean {
298
+ if (a === b) return true;
299
+ if (a.length !== b.length) return false;
300
+ if (a.length === 0) return true;
301
+ const aFirst = a[0];
302
+ const aLast = a[a.length - 1];
303
+ const bFirst = b[0];
304
+ const bLast = b[b.length - 1];
305
+ return (
306
+ aFirst.start === bFirst.start &&
307
+ aFirst.end === bFirst.end &&
308
+ aLast.start === bLast.start &&
309
+ aLast.end === bLast.end
310
+ );
311
+ }
312
+
223
313
  // ═══════════════════════════════════════════════════════════════════════════
224
314
  // PlayerProvider
225
315
  // ═══════════════════════════════════════════════════════════════════════════
@@ -426,7 +516,7 @@ export function PlayerProvider({
426
516
  // ref may have been updated by another event handler in
427
517
  // the same batch).
428
518
  setProgress((prev) => {
429
- // Cheap reference + 7-field equality check.
519
+ // Cheap reference + field equality check.
430
520
  if (
431
521
  prev.positionMs === nextProgress.positionMs &&
432
522
  prev.durationMs === nextProgress.durationMs &&
@@ -434,7 +524,7 @@ export function PlayerProvider({
434
524
  prev.isSeeking === nextProgress.isSeeking &&
435
525
  prev.seekable === nextProgress.seekable &&
436
526
  prev.cacheFill === nextProgress.cacheFill &&
437
- prev.cacheRanges.length === nextProgress.cacheRanges.length
527
+ cacheRangesEqual(prev.cacheRanges, nextProgress.cacheRanges)
438
528
  ) {
439
529
  return prev;
440
530
  }
@@ -446,6 +536,29 @@ export function PlayerProvider({
446
536
  unsubs.push(unsub);
447
537
  }
448
538
 
539
+ // ── 2b. Observe the mpv properties those events are derived from ───
540
+ // Step 2 subscribes to the JS event names, but mpv only *emits*
541
+ // them for properties JS registered with `mpv_observe_property`.
542
+ // Registration must happen after `initPlayer()` (step 0) so the
543
+ // native handle exists; the Kotlin side also queues any name that
544
+ // arrives early, so ordering is safe either way.
545
+ //
546
+ // A failure here must not abort the subscription above or the poll
547
+ // below — this list is additive.
548
+ const observed: string[] = [];
549
+ for (const property of OBSERVED_PROPERTIES) {
550
+ try {
551
+ bridge.observeProperty(property);
552
+ observed.push(property);
553
+ } catch (e) {
554
+ // eslint-disable-next-line no-console
555
+ console.warn(
556
+ `[simba-player] observeProperty('${property}') failed:`,
557
+ e,
558
+ );
559
+ }
560
+ }
561
+
449
562
  // ── 3. 1Hz position/duration poll ───────────────────────────────────
450
563
  // Both `getPosition` and `getDuration` are sync React methods
451
564
  // on the bridge, so the poll doesn't queue microtasks. We
@@ -495,6 +608,16 @@ export function PlayerProvider({
495
608
 
496
609
  // ── Cleanup ─────────────────────────────────────────────────────────
497
610
  return () => {
611
+ // Release the native property registrations before tearing the
612
+ // emitter down, so mpv is not left writing into a dead
613
+ // callback. Reverse order mirrors the registration order.
614
+ for (let i = observed.length - 1; i >= 0; i -= 1) {
615
+ try {
616
+ bridge.unobserveProperty(observed[i]);
617
+ } catch {
618
+ // never let a single bad unobserve abort the rest
619
+ }
620
+ }
498
621
  for (const unsub of unsubs) {
499
622
  try {
500
623
  unsub();
@@ -524,3 +647,4 @@ export function PlayerProvider({
524
647
  </PlayerConfigContext.Provider>
525
648
  );
526
649
  }
650
+
@@ -1,9 +1,10 @@
1
- import React, { useEffect } from 'react';
1
+ import React from 'react';
2
2
  import { StyleSheet, View } from 'react-native';
3
3
  import { DefaultControls, type DefaultControlsProps } from './DefaultControls';
4
4
  import { useRenderControls } from './PlayerProvider';
5
5
  import { usePlayer } from '../types/player';
6
6
  import { useLaunchParams } from '../hooks/useLaunchParams';
7
+ import { useLaunchPlayback } from '../hooks/useLaunchPlayback';
7
8
  import {
8
9
  getMpvPlayerModule,
9
10
  type LaunchParams,
@@ -87,43 +88,15 @@ export function PlayerRoot({
87
88
  const ownLaunchParams = useLaunchParams();
88
89
  const launchParams = launchParamsProp ?? ownLaunchParams;
89
90
 
90
- // V22.0.0 / 1.5.8 (D-035 fix #3 + #5 + #7): feed the launch URI
91
- // to mpv exactly once per `(uri, startPositionMs)` payload, NOT
92
- // once per render. The previous version (D-035 #3) called
93
- // `bridge.loadFile(uri)` synchronously in the render body — but
94
- // `<PlayerProvider>` re-renders the whole tree ~once per second
95
- // (the 1Hz position-poll drives `state` updates). Every one of
96
- // those re-renders fired another `loadFile`, which is wasteful
97
- // and on some Android builds can race with mpv's own internal
98
- // state, knocking the surface back to black for a frame.
99
- //
100
- // The `useEffect` keyed on the URI+start position string fires
101
- // once when the props/hook resolve to a real payload, then never
102
- // again until the URI actually changes (i.e. another
103
- // `openPlayer` round-trip with a different media).
104
- const uri = launchParams?.uri ?? null;
105
- const startPositionSec = launchParams?.startPositionMs
106
- ? launchParams.startPositionMs / 1000
107
- : 0;
108
- const launchKey = uri != null ? `${uri}|${startPositionSec}` : null;
109
- useEffect(() => {
110
- if (launchKey == null) return;
111
- const bridge = getMpvPlayerModule();
112
- try {
113
- bridge.loadFile(uri!);
114
- if (startPositionSec > 0) {
115
- bridge.seekAbsolute(startPositionSec);
116
- }
117
- bridge.play();
118
- } catch {
119
- // Bridge not present (jest/web) — ignore.
120
- }
121
- // launchKey intentionally drives the dep list. The individual
122
- // `uri` / `startPositionSec` reads are derived from the same
123
- // `launchParams` object, so they'll be consistent across a
124
- // single effect run.
125
- // eslint-disable-next-line react-hooks/exhaustive-deps
126
- }, [launchKey]);
91
+ // V22.0.0 / 1.5.8 (D-035 fix #3 + #5 + #7): feed the launch URI to
92
+ // mpv exactly once per `(uri, startPositionMs)` payload, NOT once
93
+ // per render. `useLaunchPlayback` owns that contract (extracted
94
+ // verbatim from this component in 1.8.0 so `<SimbaPlayerRoot
95
+ // headless>` can keep the same guarantee while delegating the UI).
96
+ // The effect is keyed on the URI + start position, so it fires once
97
+ // when the payload resolves to a real URI, then never again until
98
+ // the URI actually changes.
99
+ useLaunchPlayback(launchParams);
127
100
 
128
101
  const overlay: React.ReactNode = (() => {
129
102
  if (renderControls != null) {
@@ -34,6 +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
38
 
38
39
  // Helper to clear all bridge mock call counts between tests.
39
40
  function clearBridgeMocks() {
@@ -276,3 +277,105 @@ describe('PlayerProvider renders children', () => {
276
277
  expect(textNode.parent?.type).not.toBe('View');
277
278
  });
278
279
  });
280
+
281
+ // -- mpv property observation (regression) --------------------------------
282
+
283
+ /**
284
+ * Regression origin: nothing in the library or the consumer app ever
285
+ * called `observeProperty`. mpv only reports a property through
286
+ * `mpv_observe_property`, so every branch of the native
287
+ * `onMpvPropertyChanged` handler was unreachable and the state it feeds
288
+ * kept its `DEFAULT_PROGRESS` value forever.
289
+ *
290
+ * Position / duration / volume / speed masked the bug because they are
291
+ * ALSO polled at 1 Hz. `seekable`, `isSeeking`, `isBuffering` and
292
+ * `cacheRanges` have no such fallback, so in the consumer app the seek
293
+ * bar rendered permanently disabled ("Live stream - not seekable"), the
294
+ * buffering spinner never appeared, and the buffered-range fill was
295
+ * never painted - on a plain, seekable, 1-hour file.
296
+ */
297
+ describe('mpv property observation', () => {
298
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
299
+ <PlayerProvider>{children}</PlayerProvider>
300
+ );
301
+
302
+ it('observes every property that backs an event with no polling fallback', async () => {
303
+ clearBridgeMocks();
304
+ const { unmount } = await renderHook(() => usePlayerProgress(), { wrapper });
305
+
306
+ const observed = (
307
+ NativeModules.MpvPlayerModule.observeProperty as jest.Mock
308
+ ).mock.calls.map((call: unknown[]) => call[0]);
309
+
310
+ // These four are the ones that are invisible until they are wrong:
311
+ // nothing polls them, so a missing registration is silent.
312
+ expect(observed).toEqual(
313
+ expect.arrayContaining([
314
+ 'seekable',
315
+ 'seeking',
316
+ 'paused-for-cache',
317
+ 'demuxer-cache-state',
318
+ ]),
319
+ );
320
+
321
+ await unmount();
322
+ });
323
+
324
+ it('observes the properties that back the polled events too', async () => {
325
+ // Lower latency than the 1 Hz poll, and `pause` / `eof-reached` are
326
+ // only reachable this way for a state change that happens between
327
+ // two polls.
328
+ clearBridgeMocks();
329
+ const { unmount } = await renderHook(() => usePlayerProgress(), { wrapper });
330
+
331
+ const observed = (
332
+ NativeModules.MpvPlayerModule.observeProperty as jest.Mock
333
+ ).mock.calls.map((call: unknown[]) => call[0]);
334
+
335
+ expect(observed).toEqual(
336
+ expect.arrayContaining([
337
+ 'time-pos',
338
+ 'duration',
339
+ 'volume',
340
+ 'speed',
341
+ 'pause',
342
+ 'eof-reached',
343
+ 'idle-active',
344
+ 'cache-buffering-state',
345
+ ]),
346
+ );
347
+
348
+ await unmount();
349
+ });
350
+
351
+ it('unobserves every property it registered, on unmount', async () => {
352
+ clearBridgeMocks();
353
+ const { unmount } = await renderHook(() => usePlayerProgress(), { wrapper });
354
+
355
+ const observed = (
356
+ NativeModules.MpvPlayerModule.observeProperty as jest.Mock
357
+ ).mock.calls.map((call: unknown[]) => call[0]);
358
+
359
+ await unmount();
360
+
361
+ const unobserved = (
362
+ NativeModules.MpvPlayerModule.unobserveProperty as jest.Mock
363
+ ).mock.calls.map((call: unknown[]) => call[0]);
364
+
365
+ // Leaving a registration behind means mpv keeps writing into a
366
+ // callback whose React state is gone.
367
+ expect(unobserved.sort()).toEqual(observed.sort());
368
+ });
369
+
370
+ it('keeps the last known cache ranges when a refresh returns empty', async () => {
371
+ clearBridgeMocks();
372
+ const { result, unmount } = await renderHook(() => usePlayerProgress(), {
373
+ wrapper,
374
+ });
375
+
376
+ // DEFAULT_PROGRESS starts with no ranges; nothing has been emitted.
377
+ expect(result.current.cacheRanges).toEqual([]);
378
+
379
+ await unmount();
380
+ });
381
+ });
@@ -1,6 +1,7 @@
1
1
  import React from 'react';
2
2
  import { PlayerRoot } from '../components/PlayerRoot';
3
3
  import { useLaunchParams } from './useLaunchParams';
4
+ import { useLaunchPlayback } from './useLaunchPlayback';
4
5
 
5
6
  /**
6
7
  * V14 Phase 59: the activity-branch wrapper.
@@ -53,6 +54,38 @@ export interface SimbaPlayerRootProps {
53
54
  * icon, with no recent `openPlayer(...)` handoff queued.
54
55
  */
55
56
  children: React.ReactNode;
57
+
58
+ /**
59
+ * `1.8.0` — let the consumer own the player UI.
60
+ *
61
+ * `false` (the default, and every pre-1.8.0 behaviour) mounts
62
+ * `<PlayerRoot />` — the module's built-in surface + controls —
63
+ * whenever launch params are present. `children` renders only when
64
+ * there is nothing to play.
65
+ *
66
+ * `true` splits the two concerns that `PlayerRoot` bundles
67
+ * together: the module keeps the **load lifecycle**
68
+ * (`useLaunchPlayback`, so the payload is still loaded exactly once)
69
+ * while the consumer keeps the **UI** — `children` renders
70
+ * unconditionally, and the consumer is responsible for showing it
71
+ * only while something is playing.
72
+ *
73
+ * ## Why a consumer needs this
74
+ *
75
+ * `<PlayerRoot>` returns the module's default controls *instead of*
76
+ * `children`, so any custom chrome passed as children is discarded
77
+ * exactly when playback starts — which makes a bespoke player screen
78
+ * unreachable. `headless` is the supported way to keep the load
79
+ * guarantee without surrendering the UI.
80
+ *
81
+ * @example
82
+ * ```tsx
83
+ * <SimbaPlayerRoot headless>
84
+ * <MyNavigator />
85
+ * </SimbaPlayerRoot>
86
+ * ```
87
+ */
88
+ headless?: boolean;
56
89
  }
57
90
 
58
91
  /**
@@ -72,10 +105,22 @@ export interface SimbaPlayerRootProps {
72
105
  */
73
106
  export function SimbaPlayerRoot({
74
107
  children,
108
+ headless = false,
75
109
  }: SimbaPlayerRootProps): React.ReactElement {
76
110
  const launchParams = useLaunchParams();
77
111
 
78
- if (launchParams) {
112
+ // `1.8.0` headless mode: the module keeps the load guarantee and
113
+ // hands the UI back to the consumer.
114
+ //
115
+ // Gated on `headless` on purpose. In the default (non-headless)
116
+ // path `<PlayerRoot>` runs the SAME hook, and two hook instances
117
+ // holding the same payload are two independent effects — the media
118
+ // would be loaded twice per launch, which is the exact regression
119
+ // this extraction was meant to end. So exactly one owner runs it:
120
+ // `<PlayerRoot>` normally, this component only in headless mode.
121
+ useLaunchPlayback(headless ? launchParams : null);
122
+
123
+ if (launchParams && !headless) {
79
124
  return <PlayerRoot launchParams={launchParams} />;
80
125
  }
81
126
 
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Unit tests for `useLaunchPlayback` (lib 1.8.0) and the `headless`
3
+ * mode of `<SimbaPlayerRoot>`.
4
+ *
5
+ * ## Why these exist
6
+ *
7
+ * Before 1.8.0, the load lifecycle lived inside `<PlayerRoot>`'s
8
+ * render body, and `<SimbaPlayerRoot>` mounted `<PlayerRoot>` *instead
9
+ * of* its children whenever launch params were present. A consumer with
10
+ * its own chrome therefore had its UI discarded exactly when playback
11
+ * started, and the only way to get the load guarantee was to surrender
12
+ * the UI.
13
+ *
14
+ * 1.8.0 splits the two: `useLaunchPlayback` owns the load, and
15
+ * `headless` keeps it while `children` (the consumer's UI) renders
16
+ * unconditionally.
17
+ *
18
+ * ## What these pin
19
+ *
20
+ * - The payload is loaded EXACTLY ONCE per `(uri, startPositionMs)`.
21
+ * The old render-body version re-fired on every re-render, and
22
+ * `<PlayerProvider>` re-renders ~1 Hz off the position poll.
23
+ * - `startPositionMs` is authored in ms; mpv's `seekAbsolute` is in
24
+ * seconds. A silent unit error here seeks to the wrong place with no
25
+ * error anywhere.
26
+ * - `headless` still loads — that is the whole point of the flag.
27
+ * - A `null` payload is a no-op, not a `loadFile(null)`.
28
+ */
29
+
30
+ import React from 'react';
31
+ import { NativeModules, Text } from 'react-native';
32
+ import { render, waitFor } from '@testing-library/react-native';
33
+ import { useLaunchPlayback } from '../useLaunchPlayback';
34
+ import { SimbaPlayerRoot } from '../SimbaPlayerRoot';
35
+ import { PlayerProvider } from '../../components/PlayerProvider';
36
+ import type { LaunchParams } from '../../bridge/MpvPlayerModule';
37
+
38
+ const bridge = () =>
39
+ NativeModules.MpvPlayerModule as unknown as Record<string, jest.Mock>;
40
+
41
+ function clearBridgeMocks() {
42
+ for (const key of Object.keys(bridge())) {
43
+ const fn = bridge()[key];
44
+ if (typeof fn?.mockClear === 'function') fn.mockClear();
45
+ }
46
+ }
47
+
48
+ const PARAMS: LaunchParams = {
49
+ uri: 'https://example.test/movie.mp4',
50
+ title: 'Movie',
51
+ type: 'video',
52
+ startPositionMs: 0,
53
+ };
54
+
55
+ describe('useLaunchPlayback', () => {
56
+ beforeEach(() => {
57
+ clearBridgeMocks();
58
+ });
59
+
60
+ function Harness({params}: {params: LaunchParams | null}) {
61
+ useLaunchPlayback(params);
62
+ return <Text>harness</Text>;
63
+ }
64
+
65
+ it('loads the URI and starts playback', async () => {
66
+ render(<Harness params={PARAMS} />);
67
+ await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
68
+ expect(bridge().loadFile).toHaveBeenCalledWith(PARAMS.uri);
69
+ expect(bridge().play).toHaveBeenCalledTimes(1);
70
+ });
71
+
72
+ it('does NOT re-fire when the payload object identity changes', async () => {
73
+ // The 1 Hz position poll re-renders consumers constantly. A
74
+ // fresh object literal for the same media must not reload.
75
+ // RNTL 14: `render` is async, so `rerender` must be awaited off
76
+ // the resolved value.
77
+ const {rerender} = await render(<Harness params={{...PARAMS}} />);
78
+ await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
79
+
80
+ await rerender(<Harness params={{...PARAMS}} />);
81
+ await rerender(<Harness params={{...PARAMS}} />);
82
+ await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
83
+ });
84
+
85
+ it('loads again when the URI actually changes', async () => {
86
+ const {rerender} = await render(<Harness params={PARAMS} />);
87
+ await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
88
+
89
+ await rerender(
90
+ <Harness params={{...PARAMS, uri: 'https://example.test/next.mp4'}} />,
91
+ );
92
+ await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(2));
93
+ expect(bridge().loadFile).toHaveBeenLastCalledWith(
94
+ 'https://example.test/next.mp4',
95
+ );
96
+ });
97
+
98
+ it('converts startPositionMs from milliseconds to seconds', async () => {
99
+ render(<Harness params={{...PARAMS, startPositionMs: 90_000}} />);
100
+ await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
101
+ expect(bridge().seekAbsolute).toHaveBeenCalledWith(90);
102
+ });
103
+
104
+ it('does not seek when the start position is 0', async () => {
105
+ render(<Harness params={PARAMS} />);
106
+ await waitFor(() => expect(bridge().play).toHaveBeenCalledTimes(1));
107
+ expect(bridge().seekAbsolute).not.toHaveBeenCalled();
108
+ });
109
+
110
+ it('is a no-op for a null payload', async () => {
111
+ render(<Harness params={null} />);
112
+ await waitFor(() => expect(bridge().loadFile).not.toHaveBeenCalled());
113
+ expect(bridge().play).not.toHaveBeenCalled();
114
+ });
115
+
116
+ it('is a no-op for an undefined payload', async () => {
117
+ render(<Harness params={undefined} />);
118
+ await waitFor(() => expect(bridge().loadFile).not.toHaveBeenCalled());
119
+ });
120
+ });
121
+
122
+ describe('SimbaPlayerRoot — headless', () => {
123
+ beforeEach(() => {
124
+ clearBridgeMocks();
125
+ bridge().isCurrentActivityPlayer.mockReturnValue(true);
126
+ bridge().getLaunchParams.mockResolvedValue(PARAMS);
127
+ });
128
+
129
+ it('still loads the payload (that is the point of the flag)', async () => {
130
+ // RNTL 14: `render` returns a Promise, so its queries must be
131
+ // awaited off the resolved value — destructuring the Promise
132
+ // itself yields `undefined` for every query.
133
+ await render(
134
+ <PlayerProvider>
135
+ <SimbaPlayerRoot headless>
136
+ <Text>consumer-chrome</Text>
137
+ </SimbaPlayerRoot>
138
+ </PlayerProvider>,
139
+ );
140
+ await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
141
+ expect(bridge().loadFile).toHaveBeenCalledWith(PARAMS.uri);
142
+ });
143
+
144
+ it("renders the consumer's children even when launch params exist", async () => {
145
+ // This is the regression 1.8.0 exists to fix: pre-1.8.0, params
146
+ // present meant children were DISCARDED and <PlayerRoot /> took
147
+ // over the screen.
148
+ const {queryByText, getByText} = await render(
149
+ <PlayerProvider>
150
+ <SimbaPlayerRoot headless>
151
+ <Text>consumer-chrome</Text>
152
+ </SimbaPlayerRoot>
153
+ </PlayerProvider>,
154
+ );
155
+ await waitFor(() => expect(getByText('consumer-chrome')).toBeTruthy());
156
+ // The module's own default controls must NOT be on screen.
157
+ expect(queryByText('Simba Player')).toBeNull();
158
+ });
159
+
160
+ it('renders children when there are no launch params', async () => {
161
+ bridge().getLaunchParams.mockResolvedValue(null);
162
+ const {getByText} = await render(
163
+ <PlayerProvider>
164
+ <SimbaPlayerRoot headless>
165
+ <Text>consumer-chrome</Text>
166
+ </SimbaPlayerRoot>
167
+ </PlayerProvider>,
168
+ );
169
+ await waitFor(() => expect(getByText('consumer-chrome')).toBeTruthy());
170
+ expect(bridge().loadFile).not.toHaveBeenCalled();
171
+ });
172
+
173
+ it('omitting headless keeps the pre-1.8.0 behaviour', async () => {
174
+ // Back-compat guard: the default must still mount the module's own
175
+ // player UI, discard children, AND — critically — still load
176
+ // exactly ONCE. `<SimbaPlayerRoot>` and `<PlayerRoot>` both call
177
+ // `useLaunchPlayback`; if both were active the media would load
178
+ // twice per launch.
179
+ const {queryByText} = await render(
180
+ <PlayerProvider>
181
+ <SimbaPlayerRoot>
182
+ <Text>consumer-chrome</Text>
183
+ </SimbaPlayerRoot>
184
+ </PlayerProvider>,
185
+ );
186
+ await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
187
+ expect(queryByText('consumer-chrome')).toBeNull();
188
+ });
189
+ });
@@ -0,0 +1,61 @@
1
+ import { getMpvPlayerModule } from '../bridge/MpvPlayerModule';
2
+
3
+ /**
4
+ * Synchronous, idempotent "is this React tree hosted by the player
5
+ * activity?" predicate.
6
+ *
7
+ * ## Why this exists (V19 W6.0)
8
+ *
9
+ * A consumer that wants to render its OWN chrome over the native
10
+ * video surface needs to know whether it is running in
11
+ * `PlayerActivity` (the surface exists) or `MainActivity` (it does
12
+ * not). Before this hook, the only public way to ask was
13
+ * `useLaunchParams()`, which is the wrong tool:
14
+ *
15
+ * 1. **It is one-shot.** The native side keeps launch params as a
16
+ * single-shot queue; the first React consumer reads them and
17
+ * every later consumer sees `null`. A chrome component asking
18
+ * "am I the player activity?" would silently steal the payload
19
+ * from `<PlayerRoot />` and break the default player UI.
20
+ * 2. **It is async.** `getLaunchParams()` crosses the bridge as a
21
+ * `Promise`, so the answer arrives one render late — a consumer
22
+ * using it as a mount gate flashes its own absence for a frame.
23
+ * 3. **It conflates two questions.** "Are there launch params?" is
24
+ * not "am I the player host?" — a player activity with an empty
25
+ * queue answers `null` to the first and `true` to the second.
26
+ *
27
+ * This hook answers the second question directly, and that is the
28
+ * one a chrome compositor actually needs.
29
+ *
30
+ * ## Why it is not a subscription
31
+ *
32
+ * `isCurrentActivityPlayer()` is a plain boolean the native side
33
+ * flips in `PlayerActivity.onCreate` / `onDestroy`. Each activity
34
+ * mounts its OWN React tree, so the value is fixed for the lifetime
35
+ * of any given tree and is already correct on its first render. A
36
+ * `useSyncExternalStore` subscription would be pure overhead: there
37
+ * is no intermediate state to observe, because the transition tears
38
+ * the tree down rather than re-rendering it.
39
+ *
40
+ * Consumers that genuinely need to react to the flip *without* a
41
+ * teardown (e.g. handling PiP) should subscribe to the `onPip*`
42
+ * player events instead.
43
+ *
44
+ * ## Compatibility
45
+ *
46
+ * If the bridge predates this method the hook reports `false` — the
47
+ * conservative answer. `false` means "no player surface here", which
48
+ * is what a jest/Storybook/web host wants; a consumer that mis-detects
49
+ * would render a chrome overlay over a non-existent surface, so
50
+ * failing closed is the safe direction.
51
+ */
52
+ export function useIsPlayerActivity(): boolean {
53
+ const bridge = getMpvPlayerModule();
54
+ try {
55
+ return bridge.isCurrentActivityPlayer();
56
+ } catch {
57
+ // Pre-1.7.0 bridge (method absent) or a non-RN host. Fail closed
58
+ // — see the compatibility note above.
59
+ return false;
60
+ }
61
+ }
@@ -0,0 +1,71 @@
1
+ import { useEffect } from 'react';
2
+ import { getMpvPlayerModule, type LaunchParams } from '../bridge/MpvPlayerModule';
3
+
4
+ /**
5
+ * Feed a launch payload to mpv, exactly once per payload.
6
+ *
7
+ * This is the *load lifecycle*, and nothing else. It is deliberately
8
+ * separate from any UI so a consumer can own the player screen while
9
+ * the module still guarantees "these params get loaded exactly once".
10
+ *
11
+ * ## Why the effect, and why keyed on a string
12
+ *
13
+ * The previous implementation called `bridge.loadFile(uri)` in the
14
+ * render body of `<PlayerRoot>`. `<PlayerProvider>` re-renders the
15
+ * whole tree roughly once a second (the 1 Hz position poll drives
16
+ * `state` updates), so every one of those re-renders fired another
17
+ * `loadFile` — wasteful, and on some Android builds it races with
18
+ * mpv's internal state and knocks the surface back to black for a
19
+ * frame (D-035 #3).
20
+ *
21
+ * Keying the effect on `${uri}|${startPositionSec}` means it fires once
22
+ * when a real payload appears, then never again until the URI actually
23
+ * changes — i.e. a subsequent `openPlayer(...)` for different media.
24
+ *
25
+ * `startPositionMs` is converted to seconds because mpv's
26
+ * `seekAbsolute` is in seconds, while the launch payload is authored
27
+ * in milliseconds.
28
+ *
29
+ * ## Contract
30
+ *
31
+ * - A `null`/`undefined` payload is a no-op. The caller is responsible
32
+ * for deciding whether "no payload" means "nothing to play".
33
+ * - The bridge is read lazily inside the effect, so a module that is
34
+ * absent (jest, web preview, Storybook) is a silent no-op rather than
35
+ * a render-time crash. Consumers get a headless player for free in
36
+ * those environments instead of an exception.
37
+ * - The `catch` is deliberately silent and the `finally` is
38
+ * deliberately absent: a load failure must surface through mpv's own
39
+ * `file-loaded` / `end-file` events, which the consumer's state
40
+ * layer already observes. Swallowing here keeps one failed load from
41
+ * tearing down the React tree.
42
+ */
43
+ export function useLaunchPlayback(
44
+ launchParams: LaunchParams | null | undefined,
45
+ ): void {
46
+ const uri = launchParams?.uri ?? null;
47
+ const startPositionSec = launchParams?.startPositionMs
48
+ ? launchParams.startPositionMs / 1000
49
+ : 0;
50
+ const launchKey = uri != null ? `${uri}|${startPositionSec}` : null;
51
+
52
+ useEffect(() => {
53
+ if (launchKey == null || uri == null) {
54
+ return;
55
+ }
56
+ const bridge = getMpvPlayerModule();
57
+ try {
58
+ bridge.loadFile(uri);
59
+ if (startPositionSec > 0) {
60
+ bridge.seekAbsolute(startPositionSec);
61
+ }
62
+ bridge.play();
63
+ } catch {
64
+ // Bridge not present (jest/web) — ignore.
65
+ }
66
+ // `launchKey` is the dependency, not `uri` / `startPositionSec`:
67
+ // the latter two are derived from the same payload, so they are
68
+ // already consistent within a single effect run, and listing them
69
+ // separately would re-fire the load on an identity-only change.
70
+ }, [launchKey, startPositionSec, uri]);
71
+ }
package/src/index.ts CHANGED
@@ -51,6 +51,7 @@ export {
51
51
  export {
52
52
  usePlayer,
53
53
  usePlayerProgress,
54
+ toMpvPropertyString,
54
55
  type PlayerCommands,
55
56
  type PlayerProgress,
56
57
  type PlayerState,
@@ -99,6 +100,16 @@ export {
99
100
  type PlayerQueueSelectionStore,
100
101
  } from './hooks/useQueueSelection';
101
102
  export {useLaunchParams} from './hooks/useLaunchParams';
103
+ // 1.8.0 — the load half of `<PlayerRoot>`, exposed so a consumer using
104
+ // `<SimbaPlayerRoot headless>` (which delegates the player UI) can call
105
+ // it directly for a payload the module did not originate. See
106
+ // `useLaunchPlayback`'s docstring for the once-per-payload contract.
107
+ export {useLaunchPlayback} from './hooks/useLaunchPlayback';
108
+ // V19 W6.0 — synchronous, idempotent "is this tree hosted by
109
+ // PlayerActivity?" predicate for consumers that render their own
110
+ // chrome over the native video surface. See the hook's docstring for
111
+ // why `useLaunchParams` is the wrong tool for that question.
112
+ export {useIsPlayerActivity} from './hooks/useIsPlayerActivity';
102
113
 
103
114
  export {
104
115
  getMpvPlayerModule,
@@ -23,6 +23,7 @@ import { act, renderHook } from '@testing-library/react-native';
23
23
  import {
24
24
  usePlayer,
25
25
  usePlayerProgress,
26
+ toMpvPropertyString,
26
27
  DEFAULT_PROGRESS,
27
28
  DEFAULT_STATE,
28
29
  type PlayerState,
@@ -137,6 +138,8 @@ describe('usePlayer (no provider)', () => {
137
138
  expect(s.currentChapter).toBeNull();
138
139
  expect(s.videoParams).toBeNull();
139
140
  expect(s.error).toBeNull();
141
+ // V22.0.0 / 1.6.0 additions
142
+ expect(s.shuffle).toBe(false);
140
143
  });
141
144
 
142
145
  it('exposes the V12 commands object', async () => {
@@ -189,6 +192,11 @@ describe('usePlayer (no provider)', () => {
189
192
  expect(typeof c.unobserveProperty).toBe('function');
190
193
  expect(typeof c.grantPersistablePermission).toBe('function');
191
194
  expect(typeof c.verifyContentUri).toBe('function');
195
+ // V22.0.0 / 1.6.0 additions
196
+ expect(typeof c.getScreenBrightness).toBe('function');
197
+ expect(typeof c.setAudioFilter).toBe('function');
198
+ expect(typeof c.setVideoFilter).toBe('function');
199
+ expect(typeof c.setShuffle).toBe('function');
192
200
  });
193
201
 
194
202
  it('commands.play delegates to the native bridge', async () => {
@@ -272,6 +280,50 @@ describe('usePlayer (no provider)', () => {
272
280
  );
273
281
  });
274
282
 
283
+ // V22.0.0 / 1.6.0 additions — surface-widening for the V19 vertical-swipe
284
+ // chrome (brightness pill) + mpv filter toggle hooks + readback of
285
+ // `playlist-shuffle` via the existing `setProperty` plumbing.
286
+ it('commands.getScreenBrightness delegates to the bridge', async () => {
287
+ const { result } = await renderHook(() => usePlayer());
288
+ const brightness = result.current.commands.getScreenBrightness();
289
+ expect(NativeModules.MpvPlayerModule.getScreenBrightness).toHaveBeenCalledTimes(1);
290
+ // Mock returns 1.0 (the no-op fallback default).
291
+ expect(brightness).toBe(1.0);
292
+ });
293
+
294
+ it('commands.setAudioFilter(filter, enabled) forwards both args to the bridge', async () => {
295
+ const { result } = await renderHook(() => usePlayer());
296
+ result.current.commands.setAudioFilter('scaletempo2=max-speed=32.0', true);
297
+ expect(NativeModules.MpvPlayerModule.setAudioFilter).toHaveBeenCalledWith(
298
+ 'scaletempo2=max-speed=32.0',
299
+ true,
300
+ );
301
+ });
302
+
303
+ it('commands.setVideoFilter(filter, enabled) forwards both args to the bridge', async () => {
304
+ const { result } = await renderHook(() => usePlayer());
305
+ result.current.commands.setVideoFilter('scale=720:trunc(ow/a/2)*2', true);
306
+ expect(NativeModules.MpvPlayerModule.setVideoFilter).toHaveBeenCalledWith(
307
+ 'scale=720:trunc(ow/a/2)*2',
308
+ true,
309
+ );
310
+ });
311
+
312
+ it('commands.setShuffle(enabled) routes through bridge.setProperty("playlist-shuffle", …)', async () => {
313
+ // `setShuffle` is a thin wrapper over the existing `setProperty`
314
+ // plumbing — the bridge has no dedicated `setShuffle` method.
315
+ //
316
+ // The encoded value is '1' rather than `true`: `playlist-shuffle` is
317
+ // an mpv *integer* option, so a boolean cannot be sent even once
318
+ // stringified ("true" is not a value mpv's int parser accepts).
319
+ const { result } = await renderHook(() => usePlayer());
320
+ result.current.commands.setShuffle(true);
321
+ expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
322
+ 'playlist-shuffle',
323
+ '1',
324
+ );
325
+ });
326
+
275
327
  it('returns stable command references across renders', async () => {
276
328
  // Spec §Phase 34.5: stable command references let DefaultControls
277
329
  // memo its handlers. The V13 commands object is a module-scope
@@ -463,8 +515,9 @@ describe('usePlayerProgress', () => {
463
515
  // ── PlayerState default integrity ───────────────────────────────────────────
464
516
 
465
517
  describe('PlayerState default integrity', () => {
466
- it('PlayerState has 20 fields in DEFAULT_STATE', async () => {
518
+ it('PlayerState has 21 fields in DEFAULT_STATE', async () => {
467
519
  // Sanity check: V13 expanded the V12 4-field state to 20 fields.
520
+ // V22.0.0 / 1.6.0 added `shuffle`, bringing it to 21.
468
521
  // If a future refactor accidentally drops a field (e.g. by
469
522
  // using `Partial<PlayerState>` somewhere), this catches it.
470
523
  const keys = Object.keys(DEFAULT_STATE).sort();
@@ -484,6 +537,7 @@ describe('PlayerState default integrity', () => {
484
537
  'playlist',
485
538
  'positionMs',
486
539
  'seekable',
540
+ 'shuffle',
487
541
  'speed',
488
542
  'title',
489
543
  'tracks',
@@ -492,3 +546,137 @@ describe('PlayerState default integrity', () => {
492
546
  ]);
493
547
  });
494
548
  });
549
+
550
+ // ── setProperty value encoding ─────────────────────────────────────────────
551
+
552
+ /**
553
+ * `MpvBridgeModule.setProperty(name: String, value: String)` declares both
554
+ * arguments as Kotlin `String`, and React Native's JS→native marshalling
555
+ * *throws* on a mismatch instead of coercing:
556
+ *
557
+ * Expected argument 1 of method "setProperty" to be a string,
558
+ * but got a number (24.000000)
559
+ *
560
+ * which surfaces as a red-box `Exception in HostFunction` and unmounts the
561
+ * React tree. These tests pin that every value crossing that boundary has
562
+ * already been encoded to a string by the time it reaches the bridge.
563
+ */
564
+ describe('toMpvPropertyString', () => {
565
+ it('passes a string through unchanged', () => {
566
+ expect(toMpvPropertyString('#FFFFFF00')).toBe('#FFFFFF00');
567
+ });
568
+
569
+ it('encodes an empty string as-is', () => {
570
+ expect(toMpvPropertyString('')).toBe('');
571
+ });
572
+
573
+ it('encodes integers without a decimal point', () => {
574
+ // The reported crash value was `24.000000` — a Double reaching a
575
+ // String parameter. Pin that the encoding drops the fraction.
576
+ expect(toMpvPropertyString(24)).toBe('24');
577
+ expect(toMpvPropertyString(0)).toBe('0');
578
+ expect(toMpvPropertyString(-1)).toBe('-1');
579
+ });
580
+
581
+ it('preserves meaningful decimals', () => {
582
+ // mpv float options need the fractional part; blind rounding would
583
+ // silently change the value rather than fix the crash.
584
+ expect(toMpvPropertyString(1.5)).toBe('1.5');
585
+ expect(toMpvPropertyString(0.25)).toBe('0.25');
586
+ });
587
+
588
+ it('encodes booleans as mpv textual flags', () => {
589
+ expect(toMpvPropertyString(true)).toBe('true');
590
+ expect(toMpvPropertyString(false)).toBe('false');
591
+ });
592
+
593
+ it('maps null and undefined to the empty string, never the word undefined', () => {
594
+ // `String(undefined)` would send the literal text "undefined" to
595
+ // mpv, which is worse than useless — it looks like a real value.
596
+ expect(toMpvPropertyString(null)).toBe('');
597
+ expect(toMpvPropertyString(undefined)).toBe('');
598
+ });
599
+
600
+ it('JSON-encodes objects and arrays for structured options', () => {
601
+ // mpv has no other textual form for a `vf`/`af` parameter list.
602
+ expect(toMpvPropertyString({lavfi: 'scale=640:-1'})).toBe(
603
+ '{"lavfi":"scale=640:-1"}',
604
+ );
605
+ expect(toMpvPropertyString([1, 2, 3])).toBe('[1,2,3]');
606
+ });
607
+
608
+ it('returns the empty string for a circular structure instead of throwing', () => {
609
+ const circular: Record<string, unknown> = {};
610
+ circular.self = circular;
611
+ expect(() => toMpvPropertyString(circular)).not.toThrow();
612
+ expect(toMpvPropertyString(circular)).toBe('');
613
+ });
614
+ });
615
+
616
+ describe('commands.setProperty encoding', () => {
617
+ beforeEach(() => {
618
+ clearBridgeMocks();
619
+ });
620
+
621
+ it('encodes a numeric value before it reaches the bridge', async () => {
622
+ // The exact shape that crashed the caption bridge.
623
+ const { result } = await renderHook(() => usePlayer());
624
+ result.current.commands.setProperty('sub-font-size', 24);
625
+ expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
626
+ 'sub-font-size',
627
+ '24',
628
+ );
629
+ });
630
+
631
+ it('accepts a string value unchanged', async () => {
632
+ const { result } = await renderHook(() => usePlayer());
633
+ result.current.commands.setProperty('sub-color', '#FFFFFFF');
634
+ expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
635
+ 'sub-color',
636
+ '#FFFFFFF',
637
+ );
638
+ });
639
+
640
+ it('never sends a non-string to the bridge, whatever the caller passes', async () => {
641
+ const { result } = await renderHook(() => usePlayer());
642
+ const values: unknown[] = [24, 0, -1, 1.5, true, false, null, undefined, {a: 1}, [1]];
643
+ for (const value of values) {
644
+ result.current.commands.setProperty('sub-pos', value);
645
+ }
646
+ const calls = (NativeModules.MpvPlayerModule.setProperty as jest.Mock)
647
+ .mock.calls;
648
+ expect(calls).toHaveLength(values.length);
649
+ for (const [, sent] of calls) {
650
+ expect(typeof sent).toBe('string');
651
+ }
652
+ });
653
+ });
654
+
655
+ describe('commands that route through setProperty', () => {
656
+ beforeEach(() => {
657
+ clearBridgeMocks();
658
+ });
659
+
660
+ it('commands.seekToChapter(index) sends the index as a string', async () => {
661
+ // Regression: this call site passed a raw number and would have
662
+ // thrown inside HostFunction, red-boxing on every chapter jump.
663
+ const { result } = await renderHook(() => usePlayer());
664
+ await result.current.commands.seekToChapter(3);
665
+ expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
666
+ 'chapter',
667
+ '3',
668
+ );
669
+ });
670
+
671
+ it('commands.setShuffle(false) sends 0, because playlist-shuffle is an int option', async () => {
672
+ // The `true` half is pinned in the delegation block above; this
673
+ // covers the other branch, which previously would have sent the
674
+ // boolean `false` straight into a Kotlin String parameter.
675
+ const { result } = await renderHook(() => usePlayer());
676
+ await result.current.commands.setShuffle(false);
677
+ expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
678
+ 'playlist-shuffle',
679
+ '0',
680
+ );
681
+ });
682
+ });
@@ -88,6 +88,9 @@ export interface PlayerState {
88
88
  videoParams: MpvVideoParams | null;
89
89
  /** Last error reported by mpv. Cleared on the next `onFileLoaded`. */
90
90
  error: { code: number; codeName?: string; recoverable: boolean; message: string } | null;
91
+
92
+ /** Whether playlist shuffle is currently enabled. mpv `playlist-shuffle`. */
93
+ shuffle: boolean;
91
94
  }
92
95
 
93
96
  /**
@@ -270,6 +273,42 @@ export interface PlayerCommands {
270
273
  grantPersistablePermission(uri: string): void;
271
274
  /** Returns true when the URI is still readable (content:// or file://). */
272
275
  verifyContentUri(uri: string): boolean;
276
+
277
+ // ── V22.0.0 / 1.6.0 additions ───────────────────────────────────────────
278
+ /**
279
+ * Get the current `Window.LayoutParams.screenBrightness` (0..1).
280
+ * The window may also pass the value through to the Activity-relative
281
+ * brightness. Returns 1.0 for the no-op fallback bridge.
282
+ *
283
+ * Added because the V19 vertical-swipe chrome needs a readback to
284
+ * render the brightness indicator pill. Previously reachable only via
285
+ * the `getMpvPlayerModule()` escape hatch.
286
+ */
287
+ getScreenBrightness(): number;
288
+
289
+ /**
290
+ * Toggle an mpv audio filter. Backed by `--af-add` / `--af-remove`.
291
+ * Examples: `setAudioFilter('scaletempo2=max-speed=32.0', true)` enables
292
+ * skip-silence's `scaletempo2` audio filter. Setting `enabled=false`
293
+ * removes the named filter.
294
+ */
295
+ setAudioFilter(filter: string, enabled: boolean): void;
296
+
297
+ /**
298
+ * Toggle an mpv video filter. Backed by `--vf-add` / `--vf-remove`.
299
+ * Examples: `setVideoFilter('scale=720:trunc(ow/a/2)*2', true)` caps
300
+ * output height at 720p via a scale filter. Setting `enabled=false`
301
+ * removes the named filter.
302
+ */
303
+ setVideoFilter(filter: string, enabled: boolean): void;
304
+
305
+ /**
306
+ * Enable or disable playlist shuffle. Backed by `--playlist-shuffle`.
307
+ * Toggles the same state surfaced in mpv via the boolean
308
+ * `playlist-shuffle` property. State is mirrored on
309
+ * `state.shuffle` via the `onPropertyChanged` event channel.
310
+ */
311
+ setShuffle(enabled: boolean): void;
273
312
  }
274
313
 
275
314
  /** Combined result from `usePlayer()`. */
@@ -332,6 +371,7 @@ export const DEFAULT_STATE: PlayerState = {
332
371
  isMuted: false,
333
372
  speed: 1,
334
373
  loopMode: 'none',
374
+ shuffle: false,
335
375
  playlist: [],
336
376
  currentIndex: -1,
337
377
  tracks: [],
@@ -356,6 +396,64 @@ export const DEFAULT_PROGRESS: PlayerProgress = {
356
396
  // Commands (built once, stable across renders)
357
397
  // ═══════════════════════════════════════════════════════════════════════════
358
398
 
399
+ /**
400
+ * Coerce a JS value into the single string form the native bridge accepts.
401
+ *
402
+ * ## Why this exists
403
+ *
404
+ * `MpvBridgeModule.setProperty(name: String, value: String)` declares both
405
+ * arguments as Kotlin `String`, and React Native's JS→native argument
406
+ * marshalling *throws* rather than coercing: passing a number produces
407
+ *
408
+ * `Expected argument 1 of method "setProperty" to be a string,
409
+ * but got a number (24.000000)`
410
+ *
411
+ * which surfaces as a red-box `Exception in HostFunction` and takes the
412
+ * whole React tree down — not as a rejected promise or a no-op.
413
+ *
414
+ * The public `PlayerCommands.setProperty(name, value: unknown)` signature
415
+ * (and its `MpvPlayerModuleBridge.setProperty` docstring) already promise
416
+ * that the value is "stringified before sending", but nothing did the
417
+ * stringifying. So the type said `unknown` and the runtime demanded
418
+ * `string`: every numeric caller crashed, including this module's own
419
+ * `seekToChapter` (`setProperty('chapter', index)`).
420
+ *
421
+ * ## Why coercion belongs here
422
+ *
423
+ * mpv's property API is textual — `mpv_set_property_string` parses the
424
+ * value against the property's declared type — so producing the string is
425
+ * this layer's job, not the caller's. Doing it once, at the single point
426
+ * where the command crosses into the bridge, means:
427
+ *
428
+ * - no caller has to remember a rule that is invisible in its own code,
429
+ * - `chapter=3` and `sub-font-size=24` both mean what they look like,
430
+ * - the documented `unknown` signature is finally honest.
431
+ *
432
+ * `null`/`undefined` become the empty string, which mpv reads as "reset
433
+ * to default" for string-valued properties — the closest analogue of the
434
+ * JS value, and far better than the literal text `"undefined"`.
435
+ * Objects and arrays are JSON-encoded because mpv has no other textual
436
+ * form for a structured option (`vf`/`af` parameter lists).
437
+ */
438
+ export function toMpvPropertyString(value: unknown): string {
439
+ if (value === null || value === undefined) {
440
+ return '';
441
+ }
442
+ if (typeof value === 'string') {
443
+ return value;
444
+ }
445
+ if (typeof value === 'number' || typeof value === 'boolean') {
446
+ return String(value);
447
+ }
448
+ try {
449
+ return JSON.stringify(value) ?? '';
450
+ } catch {
451
+ // Circular / non-serialisable. mpv has no representation for it, so
452
+ // send empty rather than crash the caller.
453
+ return '';
454
+ }
455
+ }
456
+
359
457
  /**
360
458
  * V13 Phase 51: build the full commands object. The bridge is
361
459
  * resolved lazily on every invocation, so we can build the
@@ -414,7 +512,7 @@ function buildCommands(): PlayerCommands {
414
512
  // chapter index. The bridge has `seekChapter(direction)` for
415
513
  // next/previous but not direct index access; use the property
416
514
  // setter so we get a single round-trip.
417
- getMpvPlayerModule().setProperty('chapter', index);
515
+ getMpvPlayerModule().setProperty('chapter', String(index));
418
516
  },
419
517
  next: () => {
420
518
  dlog('commands.next()');
@@ -536,8 +634,9 @@ function buildCommands(): PlayerCommands {
536
634
  return getMpvPlayerModule().getProperty(name);
537
635
  },
538
636
  setProperty: (name: string, value: unknown) => {
539
- dlog('commands.setProperty(', name, ',', value, ')');
540
- getMpvPlayerModule().setProperty(name, value);
637
+ const encoded = toMpvPropertyString(value);
638
+ dlog('commands.setProperty(', name, ',', encoded, ')');
639
+ getMpvPlayerModule().setProperty(name, encoded);
541
640
  },
542
641
  observeProperty: (name: string) => {
543
642
  dlog('commands.observeProperty(', name, ')');
@@ -556,6 +655,30 @@ function buildCommands(): PlayerCommands {
556
655
  dlog('commands.verifyContentUri(', uri, ')');
557
656
  return getMpvPlayerModule().verifyContentUri(uri);
558
657
  },
658
+
659
+ // V22.0.0 / 1.6.0 additions
660
+ getScreenBrightness: () => {
661
+ dlog('commands.getScreenBrightness()');
662
+ return getMpvPlayerModule().getScreenBrightness();
663
+ },
664
+ setAudioFilter: (filter: string, enabled: boolean) => {
665
+ dlog('commands.setAudioFilter(', filter, ',', enabled, ')');
666
+ getMpvPlayerModule().setAudioFilter(filter, enabled);
667
+ },
668
+ setVideoFilter: (filter: string, enabled: boolean) => {
669
+ dlog('commands.setVideoFilter(', filter, ',', enabled, ')');
670
+ getMpvPlayerModule().setVideoFilter(filter, enabled);
671
+ },
672
+ setShuffle: (enabled: boolean) => {
673
+ dlog('commands.setShuffle(', enabled, ')');
674
+ // `playlist-shuffle` is an mpv *integer* option, so the boolean is
675
+ // encoded as 1/0 rather than as a textual flag — "yes"/"true" is
676
+ // not a value mpv's int parser accepts for this property.
677
+ getMpvPlayerModule().setProperty(
678
+ 'playlist-shuffle',
679
+ enabled ? '1' : '0',
680
+ );
681
+ },
559
682
  };
560
683
  }
561
684
 
@@ -687,6 +810,12 @@ export function hydratePlayerState(
687
810
  } catch {
688
811
  // ignore
689
812
  }
813
+ try {
814
+ const shuffleStr = bridge.getProperty('playlist-shuffle');
815
+ state.shuffle = shuffleStr === 'yes' || shuffleStr === 'true';
816
+ } catch {
817
+ // ignore
818
+ }
690
819
 
691
820
  // Title + artist + album (via media-title + metadata property)
692
821
  try {
@@ -932,6 +1061,11 @@ export function applyPlayerEvent(
932
1061
  }
933
1062
  case 'playlist-playing-pos':
934
1063
  return { state: { ...state, currentIndex: Number(value) }, progress };
1064
+ case 'playlist-shuffle':
1065
+ return {
1066
+ state: { ...state, shuffle: value === 'yes' || value === true },
1067
+ progress,
1068
+ };
935
1069
  default:
936
1070
  return { state, progress };
937
1071
  }