@simba-dev/react-native-media-player 1.20.0 → 1.22.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.
@@ -2260,12 +2260,23 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2260
2260
  *
2261
2261
  * @param chapterTitle Optional — current chapter title shown in PiP notification.
2262
2262
  * @param progressPct Optional — progress percentage string like "45 %".
2263
+ * @return true when the OS accepted the Picture-in-Picture request,
2264
+ * false when it refused it (no activity, SDK too old, PiP not
2265
+ * permitted, or the call threw). The caller MUST NOT assume
2266
+ * PiP is up just because it asked for it.
2263
2267
  */
2264
2268
  @ReactMethod
2265
2269
  @Override
2266
- override fun enterPip(chapterTitle: String?, progressPct: String?) {
2270
+ override fun enterPip(chapterTitle: String?, progressPct: String?): Boolean {
2267
2271
  val activity = getCurrentActivity()
2268
- if (activity == null || android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) return
2272
+ // The two refusals below are ANSWERED, not swallowed. The caller
2273
+ // hides its fullscreen chrome when PiP is up, so a request that
2274
+ // quietly did nothing left the app in "PiP" mode with no chrome
2275
+ // and no way back. `false` tells it to keep the chrome.
2276
+ if (activity == null || android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) {
2277
+ Log.w(TAG, "[PlaybackTrace][Bridge][enterPip] refused: no activity or SDK < N")
2278
+ return false
2279
+ }
2269
2280
  // v1.9.3 — SPEC invariant I7 (a TS signature must agree with the
2270
2281
  // native reality it forwards to).
2271
2282
  //
@@ -2317,7 +2328,14 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2317
2328
  // animate from. That degrades to the no-hint behaviour, which costs a
2318
2329
  // black transition but never a distorted one.
2319
2330
  val sourceRect = PlayerSurface.boundsInWindow()
2320
- try {
2331
+ // `return try`, not a bare `try`. A `try`/`catch` in STATEMENT
2332
+ // position is not this function's return value in Kotlin — not
2333
+ // even as the last statement of a function with a non-`Unit`
2334
+ // return type. The compiler says "Missing return statement",
2335
+ // which is precisely what it said the first time round. Only an
2336
+ // EXPRESSION `try` produces a value, and the branches inside it
2337
+ // are the ones that carry the OS's answer.
2338
+ return try {
2321
2339
  if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
2322
2340
  val pipParams = com.simba.player.PipManager.buildPipParams(
2323
2341
  context = activity,
@@ -2326,19 +2344,36 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2326
2344
  chapterTitle = title,
2327
2345
  progressPercentage = pct,
2328
2346
  )
2347
+ // `enterPictureInPictureMode` ANSWERS whether the OS
2348
+ // accepted the request, and the answer was being
2349
+ // discarded. It is the only authority on this: the app
2350
+ // hides its chrome when PiP is up, so "we think it worked"
2351
+ // is not good enough.
2329
2352
  activity.enterPictureInPictureMode(pipParams)
2330
2353
  } else {
2331
2354
  // API 24–25 support PiP but not PictureInPictureParams.
2355
+ // The no-arg overload returns Unit, so those versions
2356
+ // have no answer to relay; the PiP mode-change event is
2357
+ // the only confirmation available there.
2332
2358
  activity.enterPictureInPictureMode()
2359
+ true
2333
2360
  }
2334
2361
  } catch (throwable: Throwable) {
2335
2362
  // P1: the previous `catch (_: IllegalStateException)` was
2336
2363
  // too narrow. `enterPictureInPictureMode` can also throw
2337
2364
  // `IllegalArgumentException` (bad params), `RuntimeException`
2338
2365
  // (OEM customisations), or `SecurityException` (PiP not
2339
- // permitted). We log the actual cause and let the JS-side
2340
- // 5 s recovery timer in `VideoPipAdapter` take over.
2366
+ // permitted). We log the actual cause, and the `false` below
2367
+ // tells the JS side that PiP did NOT happen.
2368
+ //
2369
+ // (This block used to say a "5 s recovery timer in
2370
+ // `VideoPipAdapter`" would take over. There is no
2371
+ // `VideoPipAdapter` in this repository — it was removed with
2372
+ // the V12 single-activity architecture — so nothing was
2373
+ // taking over, and a refused request simply stranded the app
2374
+ // with no chrome. The `false` return is the recovery.)
2341
2375
  Log.w(TAG, "[PlaybackTrace][Bridge][enterPip:threw]", throwable)
2376
+ false
2342
2377
  }
2343
2378
  }
2344
2379
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.20.0",
3
+ "version": "1.22.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",
@@ -503,8 +503,15 @@ export interface MpvPlayerModuleBridge {
503
503
  setConfig(configJson: string): Promise<number>;
504
504
 
505
505
  // ── Picture-in-Picture ─────────────────────────────────────────────────
506
- /** Enter PiP mode; optional chapter title + progress percent for notification. */
507
- enterPip(chapterTitle?: string | null, progressPct?: string | null): void;
506
+ /**
507
+ * Enter PiP mode; optional chapter title + progress percent for notification.
508
+ *
509
+ * Returns whether the OS accepted the request. `false` means PiP did NOT
510
+ * happen — the native side has the answer (`enterPictureInPictureMode`
511
+ * returns it) and the caller needs it, because a caller that hides its
512
+ * chrome on a refused request has no way to bring it back.
513
+ */
514
+ enterPip(chapterTitle?: string | null, progressPct?: string | null): boolean;
508
515
  /** Exit PiP by bringing the activity to the front. */
509
516
  exitPip(): void;
510
517
  /** Exit PiP and finish the activity. */
@@ -745,9 +752,13 @@ const NOOP_BRIDGE: MpvPlayerModuleBridge = {
745
752
  },
746
753
 
747
754
  // PiP
748
- enterPip: (_chapterTitle?: string, _progressPct?: string) => {
755
+ enterPip: (_chapterTitle?: string | null, _progressPct?: string | null) => {
749
756
  void _chapterTitle;
750
757
  void _progressPct;
758
+ // This stub does nothing, so the honest answer is `false` — PiP did
759
+ // not happen. Returning `true` here would tell a caller to hide its
760
+ // chrome for a PiP window that will never exist.
761
+ return false;
751
762
  },
752
763
  exitPip: () => {},
753
764
  exitPipAndFinish: () => {},
@@ -937,6 +948,58 @@ export function applyForceMediaTitle(bridge: MpvPlayerModuleBridge, title?: stri
937
948
  }
938
949
  }
939
950
 
951
+ /**
952
+ * Tell mpv where the next file must START, BEFORE the file is loaded.
953
+ *
954
+ * ## Why an option and not a `seek` command
955
+ *
956
+ * A `seek` issued right after `loadFile` is **refused by mpv**: `cmd_seek`
957
+ * bails out with `cmd->success = false` while `!mpctx->playback_initialized`
958
+ * (mpv `player/command.c`), and `playback_initialized` is only set once the
959
+ * file has actually opened (mpv `player/loadfile.c`, immediately before
960
+ * `MPV_EVENT_FILE_LOADED`). So `loadfile` + `seek` in the same tick meant
961
+ * the seek never happened — and because the native side discarded mpv's
962
+ * return code, **nothing at all happened**: a resume silently played the
963
+ * file from 0:00 and the transport bar showed a truthful 0:00 for a video
964
+ * the user had asked to resume 20 minutes in.
965
+ *
966
+ * `start` is mpv's own option for "begin this file at this position", and
967
+ * mpv applies it while the file opens (mpv `player/loadfile.c` reads
968
+ * `opts->play_start` and queues the seek there). Writing it before the load
969
+ * makes the start position part of the load: no race, no dropped command,
970
+ * and the first frame is already the resumed frame.
971
+ *
972
+ * `options/start` is mpv's documented property path for an option by name
973
+ * (`mp_property_options` → `access_option_list` → `m_config_set_option_raw`).
974
+ *
975
+ * ## The value is ALWAYS written
976
+ *
977
+ * `start` is a persistent option. Writing it only when there is a resume
978
+ * would leak the last resume position into the NEXT file, so a plain load
979
+ * writes `0` and a resumed load writes the position. There is no "leave it
980
+ * alone" case.
981
+ *
982
+ * ## Not throwing
983
+ *
984
+ * A rejected option write must never abort the load — the video matters more
985
+ * than where it starts, and mpv would play the file from the beginning. It
986
+ * is warned about instead, because a silent failure here is a resume that
987
+ * quietly did not happen.
988
+ */
989
+ export function applyStartPosition(
990
+ bridge: MpvPlayerModuleBridge,
991
+ startPositionSec: number,
992
+ ): void {
993
+ const seconds =
994
+ Number.isFinite(startPositionSec) && startPositionSec > 0 ? startPositionSec : 0;
995
+ try {
996
+ bridge.setProperty('options/start', seconds.toFixed(3));
997
+ } catch (e) {
998
+ // eslint-disable-next-line no-console
999
+ console.warn('[simba-player] options/start rejected:', e);
1000
+ }
1001
+ }
1002
+
940
1003
  /**
941
1004
  * V13 Phase 50c: subscribe to a native event. Returns an
942
1005
  * unsubscribe function that callers should invoke from
@@ -320,7 +320,16 @@ export interface Spec extends TurboModule {
320
320
  // here said "you may call this with no arguments", which is exactly
321
321
  // the licence the zero-argument call site took — and the crash it
322
322
  // produced was an "expected argument count: 2" rejection.
323
- enterPip(chapterTitle: string | null, progressPct: string | null): void;
323
+ //
324
+ // The return type is `boolean`, and it is the OS's own answer to
325
+ // "did PiP happen?". `Activity.enterPictureInPictureMode` returns
326
+ // exactly that, and the previous `void` threw the answer away: a
327
+ // REFUSED request (no activity, PiP not permitted, bad params) then
328
+ // looked identical to a successful one, so a caller that hides its
329
+ // chrome on the strength of a successful request was left with no
330
+ // chrome and no way back. Declaring the answer here is what lets it
331
+ // survive codegen.
332
+ enterPip(chapterTitle: string | null, progressPct: string | null): boolean;
324
333
  exitPip(): void;
325
334
  exitPipAndFinish(): void;
326
335
 
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The resume contract: a launch that resumes must START at the saved
3
+ * position, and the start position must be part of the LOAD.
4
+ *
5
+ * ## The defect this pins
6
+ *
7
+ * A resuming launch used to do `loadFile(uri)` and then
8
+ * `seekAbsolute(seconds)`. mpv **refuses** a seek until the file has
9
+ * actually opened — `cmd_seek` bails out with `cmd->success = false`
10
+ * while `!mpctx->playback_initialized` (mpv `player/command.c`) — and
11
+ * `playback_initialized` is only set once the file is open (mpv
12
+ * `player/loadfile.c`, immediately before `MPV_EVENT_FILE_LOADED`).
13
+ *
14
+ * The native side discarded mpv's return code, so the refusal was
15
+ * completely silent: the file played from 0:00, the transport bar
16
+ * truthfully showed 0:00, and the resume simply did not happen. Measured
17
+ * on device: `seekAbsolute position=1060.727` was logged and mpv never
18
+ * emitted a `seek` event — while a manual scrub (a seek issued after the
19
+ * file was open) landed exactly where it was aimed.
20
+ *
21
+ * The fix writes mpv's own `start` option BEFORE the load. mpv reads it
22
+ * while the file opens, so the start position becomes part of the load
23
+ * and cannot be dropped.
24
+ *
25
+ * ## What is pinned here
26
+ *
27
+ * - the start position is written, in SECONDS, before the load;
28
+ * - the load does NOT issue a `seek` (that was the defect);
29
+ * - the start position is written on EVERY load, including `0` — mpv's
30
+ * `start` option is persistent, so skipping the write would carry the
31
+ * last resume position into the NEXT file;
32
+ * - a rejected write still loads and plays the file;
33
+ * - `onPlaybackRestart` does not zero the position — the position is
34
+ * owned by `time-pos` and by nothing else.
35
+ */
36
+
37
+ import { NativeModules } from 'react-native';
38
+ import { loadAndPlay } from '../loadAndPlay';
39
+ import type { MpvPlayerModuleBridge } from '../MpvPlayerModule';
40
+ import {
41
+ applyPlayerEvent,
42
+ DEFAULT_PROGRESS,
43
+ DEFAULT_STATE,
44
+ } from '../../types/player';
45
+
46
+ const bridge = () =>
47
+ NativeModules.MpvPlayerModule as unknown as MpvPlayerModuleBridge & {
48
+ setProperty: jest.Mock;
49
+ loadFile: jest.Mock;
50
+ play: jest.Mock;
51
+ seekAbsolute: jest.Mock;
52
+ };
53
+
54
+ function clearBridgeMocks() {
55
+ for (const key of Object.keys(bridge())) {
56
+ const fn = (bridge() as unknown as Record<string, unknown>)[key];
57
+ if (typeof (fn as { mockClear?: () => void })?.mockClear === 'function') {
58
+ (fn as { mockClear: () => void }).mockClear();
59
+ }
60
+ }
61
+ }
62
+
63
+ const URI = 'https://example.test/movie.mp4';
64
+
65
+ describe('loadAndPlay — the start position is part of the load', () => {
66
+ beforeEach(() => {
67
+ clearBridgeMocks();
68
+ });
69
+
70
+ it('writes the start position in SECONDS before the load', () => {
71
+ // 90 000 ms is 90 s. A unit error here seeks to the wrong place with
72
+ // no error anywhere.
73
+ loadAndPlay(bridge(), {uri: URI, startPositionMs: 90_000});
74
+
75
+ const order: string[] = [];
76
+ bridge().setProperty.mockImplementation((name: string) => {
77
+ order.push(`setProperty:${name}`);
78
+ });
79
+ bridge().loadFile.mockImplementation(() => {
80
+ order.push('loadFile');
81
+ });
82
+
83
+ loadAndPlay(bridge(), {uri: URI, startPositionMs: 90_000});
84
+
85
+ expect(bridge().setProperty).toHaveBeenCalledWith('options/start', '90.000');
86
+ expect(order).toEqual(['setProperty:options/start', 'loadFile']);
87
+ });
88
+
89
+ it('does NOT issue a seek at load time — mpv refuses it', () => {
90
+ // The defect: `loadFile` + `seekAbsolute` in the same tick. mpv
91
+ // refuses the seek (playback is not initialised yet) and the refusal
92
+ // is silent, so the resume plays from 0:00.
93
+ loadAndPlay(bridge(), {uri: URI, startPositionMs: 90_000});
94
+ expect(bridge().seekAbsolute).not.toHaveBeenCalled();
95
+ });
96
+
97
+ it('always writes the start position, so a resume cannot leak into the next file', () => {
98
+ // mpv's `start` option is persistent. A plain load MUST write 0, or
99
+ // the next file starts where the last one was resumed to.
100
+ loadAndPlay(bridge(), {uri: URI});
101
+ expect(bridge().setProperty).toHaveBeenCalledWith('options/start', '0.000');
102
+ });
103
+
104
+ it('writes 0 for a negative or non-finite start position', () => {
105
+ loadAndPlay(bridge(), {uri: URI, startPositionMs: -5_000});
106
+ expect(bridge().setProperty).toHaveBeenCalledWith('options/start', '0.000');
107
+
108
+ clearBridgeMocks();
109
+ loadAndPlay(bridge(), {uri: URI, startPositionMs: Number.NaN});
110
+ expect(bridge().setProperty).toHaveBeenCalledWith('options/start', '0.000');
111
+ });
112
+
113
+ it('still loads and plays the file when the option write is rejected', () => {
114
+ // A rejected option must never cost the user their video. mpv plays
115
+ // the file from the beginning and the resume is simply not honoured.
116
+ bridge().setProperty.mockImplementationOnce(() => {
117
+ throw new Error('property rejected');
118
+ });
119
+
120
+ loadAndPlay(bridge(), {uri: URI, startPositionMs: 90_000});
121
+
122
+ expect(bridge().loadFile).toHaveBeenCalledWith(URI);
123
+ expect(bridge().play).toHaveBeenCalledTimes(1);
124
+ });
125
+ });
126
+
127
+ describe('onPlaybackRestart does not own the position', () => {
128
+ it('keeps the position it was given', () => {
129
+ // mpv fires `playback-restart` when playback (re)starts — including
130
+ // right after a seek. Zeroing the position there restarted the
131
+ // transport bar's clock at 0:00 while the video sat at the position
132
+ // the user had just seeked to (or resumed to).
133
+ const progress = {...DEFAULT_PROGRESS, positionMs: 1_060_727};
134
+ const state = {...DEFAULT_STATE, isPlaying: false, positionMs: 1_060_727};
135
+
136
+ const next = applyPlayerEvent(state, progress, 'onPlaybackRestart', {});
137
+
138
+ expect(next.progress.positionMs).toBe(1_060_727);
139
+ expect(next.state.positionMs).toBe(1_060_727);
140
+ expect(next.state.isPlaying).toBe(true);
141
+ });
142
+ });
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  applyForceMediaTitle,
3
+ applyStartPosition,
3
4
  type MpvPlayerModuleBridge,
4
5
  } from './MpvPlayerModule';
5
6
 
@@ -19,8 +20,13 @@ import {
19
20
  * 1. `force-media-title` is read by mpv **at load time**. Set after
20
21
  * `loadFile`, it applies to the next file instead of this one, and the
21
22
  * header shows a signed CDN token or a filename.
22
- * 2. `loadFile` must precede `seekAbsolute`, or the seek is applied to
23
- * the previous file.
23
+ * 2. The start position is written to mpv's `start` option **before** the
24
+ * load, and it is therefore part of the load — not a `seek` command
25
+ * issued after it. mpv refuses a seek until the file has opened (it
26
+ * accepts seeks only once playback is initialised), so `loadfile` +
27
+ * `seek` in the same tick dropped the seek on the floor and the resume
28
+ * silently played from 0:00. See `applyStartPosition` for the full
29
+ * reasoning and the mpv sources behind it.
24
30
  * 3. `play` last. A launch means "play this" — the way to ask for
25
31
  * something paused is `pause()` afterwards, never a launch that
26
32
  * silently loads and sits there.
@@ -39,11 +45,11 @@ import {
39
45
  * rather than here.
40
46
  *
41
47
  * `startPositionMs` is authored in milliseconds because that is what
42
- * every launch payload carries; `seekAbsolute` speaks seconds, mpv's own
43
- * unit. The conversion happens here so no caller can get it wrong.
48
+ * every launch payload carries; mpv's `start` option speaks seconds, mpv's
49
+ * own unit. The conversion happens here so no caller can get it wrong.
44
50
  *
45
51
  * Synchronous by design: the underlying bridge methods are fire-and-forget
46
- * (`loadFile`, `seekAbsolute`, `play` all return `void`). A load failure
52
+ * (`setProperty`, `loadFile`, `play` all return `void`). A load failure
47
53
  * is not observable at this layer at all — it surfaces through mpv's own
48
54
  * `file-loaded` / `end-file` events, which the consumer's state layer
49
55
  * already observes. Returning a Promise here would promise a resolution
@@ -57,9 +63,7 @@ export function loadAndPlay(
57
63
  const startPositionSec = startPositionMs > 0 ? startPositionMs / 1000 : 0;
58
64
 
59
65
  applyForceMediaTitle(bridge, title);
66
+ applyStartPosition(bridge, startPositionSec);
60
67
  bridge.loadFile(uri);
61
- if (startPositionSec > 0) {
62
- bridge.seekAbsolute(startPositionSec);
63
- }
64
68
  bridge.play();
65
69
  }
@@ -11,9 +11,9 @@
11
11
  * ## What these pin
12
12
  *
13
13
  * - The payload is loaded EXACTLY ONCE per launch identity.
14
- * - `startPositionMs` is authored in ms; mpv's `seekAbsolute` is in
15
- * seconds. A silent unit error here seeks to the wrong place with no
16
- * error anywhere.
14
+ * - `startPositionMs` is authored in ms; mpv's `start` option is in
15
+ * seconds. A silent unit error here starts the file at the wrong place
16
+ * with no error anywhere.
17
17
  * - A `null` payload is a no-op, not a `loadFile(null)`.
18
18
  * - The title is applied BEFORE the load, because mpv reads
19
19
  * `force-media-title` at load time.
@@ -129,13 +129,16 @@ describe('useLaunchPlayback', () => {
129
129
  await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
130
130
  });
131
131
 
132
- it('converts startPositionMs from milliseconds to seconds', async () => {
132
+ it('converts startPositionMs from milliseconds to seconds for mpv\'s start option', async () => {
133
133
  render(<Harness params={{...PARAMS, startPositionMs: 90_000}} />);
134
134
  await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
135
- expect(bridge().seekAbsolute).toHaveBeenCalledWith(90);
135
+ expect(bridge().setProperty).toHaveBeenCalledWith('options/start', '90.000');
136
136
  });
137
137
 
138
- it('does not seek when the start position is 0', async () => {
138
+ it('never seeks at load time — mpv refuses a seek before the file is open', async () => {
139
+ // The defect this pins: `loadFile` + `seekAbsolute` in the same tick.
140
+ // mpv refuses the seek (playback is not initialised yet) and the
141
+ // refusal is silent, so the resume played from 0:00.
139
142
  render(<Harness params={PARAMS} />);
140
143
  await waitFor(() => expect(bridge().play).toHaveBeenCalledTimes(1));
141
144
  expect(bridge().seekAbsolute).not.toHaveBeenCalled();
@@ -176,8 +179,8 @@ describe('useLaunchPlayback', () => {
176
179
 
177
180
  it('sets the title BEFORE the load — mpv reads the option at load time', async () => {
178
181
  const order: string[] = [];
179
- bridge().setProperty.mockImplementation(() => {
180
- order.push('setProperty');
182
+ bridge().setProperty.mockImplementation((name: string) => {
183
+ order.push(`setProperty:${name}`);
181
184
  });
182
185
  bridge().loadFile.mockImplementation(() => {
183
186
  order.push('loadFile');
@@ -185,7 +188,11 @@ describe('useLaunchPlayback', () => {
185
188
 
186
189
  render(<Harness params={{...PARAMS, title: 'Overrun!'}} />);
187
190
  await waitFor(() => expect(bridge().loadFile).toHaveBeenCalledTimes(1));
188
- expect(order).toEqual(['setProperty', 'loadFile']);
191
+ expect(order).toEqual([
192
+ 'setProperty:force-media-title',
193
+ 'setProperty:options/start',
194
+ 'loadFile',
195
+ ]);
189
196
  });
190
197
 
191
198
  it('trims the launch title', async () => {
@@ -35,9 +35,11 @@ import { loadAndPlay } from '../bridge/loadAndPlay';
35
35
  * would press play and see nothing. The inline comment above the
36
36
  * key carries the same rationale next to the code.
37
37
  *
38
- * `startPositionMs` is converted to seconds because mpv's
39
- * `seekAbsolute` is in seconds, while the launch payload is authored
40
- * in milliseconds.
38
+ * `startPositionMs` is converted to seconds because mpv's `start` option
39
+ * is in seconds, while the launch payload is authored in milliseconds.
40
+ * The position is written as that option BEFORE the load, so it is part
41
+ * of the load — a `seek` issued after the load is refused by mpv, and
42
+ * that refusal is silent. See `loadAndPlay` for the full reasoning.
41
43
  *
42
44
  * ## Contract
43
45
  *
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The PiP command must RELAY the OS's answer.
3
+ *
4
+ * ## The defect
5
+ *
6
+ * The native `enterPip` returned `Unit` and swallowed every failure:
7
+ *
8
+ * - no activity → silent `return`
9
+ * - SDK < N → silent `return`
10
+ * - `enterPictureInPictureMode` returned false → the boolean was DISCARDED
11
+ * - it threw → caught, logged, swallowed
12
+ *
13
+ * A REFUSED PiP request was therefore indistinguishable from a successful
14
+ * one, at the JS boundary.
15
+ *
16
+ * That matters because of what the caller does with the request. The app
17
+ * suppresses its fullscreen chrome when PiP is up, so a refused request
18
+ * that went unreported left the app in "PiP" mode with no transport bar, no
19
+ * top bar, and no way out — the same latch the unmount bug produced,
20
+ * reached by a different road.
21
+ *
22
+ * `Activity.enterPictureInPictureMode(PictureInPictureParams)` returns the
23
+ * OS's own answer, so the fix is to stop throwing it away.
24
+ *
25
+ * ## What this asserts
26
+ *
27
+ * The RESULT, not just that the bridge was called. A test that only checked
28
+ * "enterPip was called" would pass with the old `void` contract and the
29
+ * bug would survive — which is exactly the mistake the arity test
30
+ * (`player.pipArity.test.tsx`) was written to avoid.
31
+ */
32
+
33
+ import {NativeModules} from 'react-native';
34
+ import {renderHook} from '@testing-library/react-native';
35
+ import {usePlayer} from '../player';
36
+
37
+ function enterPipMock(): jest.Mock {
38
+ return (NativeModules.MpvPlayerModule as unknown as Record<string, jest.Mock>)
39
+ .enterPip;
40
+ }
41
+
42
+ describe('commands.enterPip — the native answer is relayed', () => {
43
+ beforeEach(() => {
44
+ enterPipMock().mockClear();
45
+ // The shared setup mock answers `true` (a successful entry). Each
46
+ // test that cares sets the answer it needs.
47
+ enterPipMock().mockReturnValue(true);
48
+ });
49
+
50
+ it('returns true when the OS accepted the request', async () => {
51
+ const {result} = await renderHook(() => usePlayer());
52
+
53
+ expect(result.current.commands.enterPip()).toBe(true);
54
+ });
55
+
56
+ it('returns false when the OS REFUSED the request', async () => {
57
+ // No activity, PiP not permitted, bad params — the native side now
58
+ // answers `false` instead of swallowing the failure.
59
+ enterPipMock().mockReturnValue(false);
60
+ const {result} = await renderHook(() => usePlayer());
61
+
62
+ expect(result.current.commands.enterPip()).toBe(false);
63
+ });
64
+
65
+ it('does not swallow a refusal — the result is the caller\'s only signal', async () => {
66
+ enterPipMock().mockReturnValue(false);
67
+ const {result} = await renderHook(() => usePlayer());
68
+
69
+ const answer = result.current.commands.enterPip();
70
+
71
+ // A falsy-but-present answer is what the caller branches on. A
72
+ // `undefined` (the old `void` contract) is indistinguishable from
73
+ // "the native module is missing", so the assertion is on `false`
74
+ // specifically, not on falsiness.
75
+ expect(answer).not.toBeUndefined();
76
+ expect(answer).toBe(false);
77
+ });
78
+
79
+ it('still calls the bridge with TWO arguments while answering', async () => {
80
+ const {result} = await renderHook(() => usePlayer());
81
+ result.current.commands.enterPip('Chapter 3', '45 %');
82
+
83
+ const enterPip = enterPipMock();
84
+ expect(enterPip.mock.calls[0]).toHaveLength(2);
85
+ expect(enterPip).toHaveBeenCalledWith('Chapter 3', '45 %');
86
+ });
87
+ });
@@ -292,16 +292,26 @@ describe('usePlayer (no provider)', () => {
292
292
  startPositionMs: 5000,
293
293
  });
294
294
  expect(ok).toBe(true);
295
- // Ordering is the contract: force-media-title is read at load time,
296
- // and seek must follow load or it applies to the previous file.
295
+ // Ordering is the contract: force-media-title AND the start position
296
+ // are both read when the file is opened, so they must both be written
297
+ // before the load.
298
+ //
299
+ // The start position is NOT a `seek` issued after the load: mpv
300
+ // refuses a seek until the file is open, and that refusal is silent
301
+ // (the native side discarded mpv's return code), so the resume
302
+ // quietly played from 0:00.
297
303
  expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
298
304
  'force-media-title',
299
305
  'Film',
300
306
  );
307
+ expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
308
+ 'options/start',
309
+ '5.000',
310
+ );
301
311
  expect(NativeModules.MpvPlayerModule.loadFile).toHaveBeenCalledWith(
302
312
  'file:///film.mp4',
303
313
  );
304
- expect(NativeModules.MpvPlayerModule.seekAbsolute).toHaveBeenCalledWith(5);
314
+ expect(NativeModules.MpvPlayerModule.seekAbsolute).not.toHaveBeenCalled();
305
315
  expect(NativeModules.MpvPlayerModule.play).toHaveBeenCalled();
306
316
  });
307
317
 
@@ -1090,6 +1100,10 @@ describe('commands.loadFile applies the launch title (v1.9.3)', () => {
1090
1100
  // is read when the file is loaded, so setting it afterwards would
1091
1101
  // leave the already-loaded file with mpv's derived title — which
1092
1102
  // for a signed CDN URL is an opaque token, not a movie name.
1103
+ //
1104
+ // `options/start` is written in the same breath, and for the same
1105
+ // reason: mpv reads it when the file OPENS, and it must be 0 here
1106
+ // so the last resume position cannot leak into this load.
1093
1107
  const { result } = await renderHook(() => usePlayer());
1094
1108
  await result.current.commands.loadFile('file:///a.mp4', 'Overrun!');
1095
1109
 
@@ -1097,15 +1111,19 @@ describe('commands.loadFile applies the launch title (v1.9.3)', () => {
1097
1111
  const setProperty = NativeModules
1098
1112
  .MpvPlayerModule.setProperty as jest.Mock;
1099
1113
  const loadFile = NativeModules.MpvPlayerModule.loadFile as jest.Mock;
1100
- setProperty.mockImplementation(() => {
1101
- order.push('setProperty');
1114
+ setProperty.mockImplementation((name: string) => {
1115
+ order.push(`setProperty:${name}`);
1102
1116
  });
1103
1117
  loadFile.mockImplementation(() => {
1104
1118
  order.push('loadFile');
1105
1119
  });
1106
1120
 
1107
1121
  await result.current.commands.loadFile('file:///b.mp4', 'Second');
1108
- expect(order).toEqual(['setProperty', 'loadFile']);
1122
+ expect(order).toEqual([
1123
+ 'setProperty:force-media-title',
1124
+ 'setProperty:options/start',
1125
+ 'loadFile',
1126
+ ]);
1109
1127
  });
1110
1128
 
1111
1129
  it('trims the title — a blank or padded value would render as whitespace', async () => {
@@ -9,6 +9,7 @@ import {
9
9
  MpvPlaybackState,
10
10
  MpvFileInfo,
11
11
  applyForceMediaTitle,
12
+ applyStartPosition,
12
13
  } from '../bridge/MpvPlayerModule';
13
14
  import { loadAndPlay } from '../bridge/loadAndPlay';
14
15
 
@@ -251,6 +252,12 @@ export interface PlayerCommands {
251
252
  * load, so `media-title` — and therefore `PlayerState.title` — carries
252
253
  * the real name of the media rather than a URL fragment. Omit it and
253
254
  * mpv derives its own title as before.
255
+ *
256
+ * The file starts at the beginning. mpv's `start` option is persistent,
257
+ * so this entry point writes `0` before the load — otherwise the last
258
+ * resume position would be carried into whatever file is loaded next.
259
+ * To start at a position, use the launch path (`useLaunchPlayback`),
260
+ * which owns the resume position.
254
261
  */
255
262
  loadFile(uri: string, title?: string): void;
256
263
  /** Load a playlist of media files, starting at `startIndex` (default 0). */
@@ -287,8 +294,18 @@ export interface PlayerCommands {
287
294
  * arguments and TurboModule enforces its arity — so the bridge call
288
295
  * always passes two, never zero. See `enterPip` in the command
289
296
  * implementation below.
297
+ *
298
+ * Returns whether the OS ACCEPTED the request. This is not a nicety: the
299
+ * caller suppresses its fullscreen chrome when PiP is up, so a request
300
+ * that was refused — no activity, PiP not permitted, a bad `PictureInPictureParams`
301
+ * — and went unreported left the app in "PiP" mode with no chrome and no
302
+ * way back. The native `enterPictureInPictureMode` knows the answer, so
303
+ * it is relayed instead of guessed.
304
+ *
305
+ * `false` means PiP did NOT happen. It does not mean the app is in a bad
306
+ * state: the caller keeps its chrome, exactly as before the request.
290
307
  */
291
- enterPip(chapterTitle?: string | null, progressPct?: string | null): void;
308
+ enterPip(chapterTitle?: string | null, progressPct?: string | null): boolean;
292
309
  /** Exit PiP by bringing the activity to the front. */
293
310
  exitPip(): void;
294
311
  /** Exit PiP and finish the activity. */
@@ -663,6 +680,11 @@ function buildCommands(): PlayerCommands {
663
680
  // `force-media-title` is mpv's own option for exactly this. The
664
681
  // set-then-load ordering is the contract — see the helper.
665
682
  applyForceMediaTitle(getMpvPlayerModule(), title);
683
+ // This entry point has no start position, so the file starts at the
684
+ // beginning — and mpv's `start` option is persistent, so it MUST be
685
+ // written here too. Leaving it would carry the last resume position
686
+ // into whatever file is loaded next.
687
+ applyStartPosition(getMpvPlayerModule(), 0);
666
688
  dlog('commands.loadFile(', uri, ')');
667
689
  getMpvPlayerModule().loadFile(uri);
668
690
  },
@@ -704,7 +726,17 @@ function buildCommands(): PlayerCommands {
704
726
  // The Kotlin side is nullable, so `null` is the right "not
705
727
  // supplied" value — the native falls back to a title and a
706
728
  // progress string of its own.
707
- getMpvPlayerModule().enterPip(chapterTitle ?? null, progressPct ?? null);
729
+ //
730
+ // The result is the OS's own answer to "did PiP happen?". It used
731
+ // to be dropped, which meant a REFUSED request (no activity, PiP
732
+ // not permitted, a bad PictureInPictureParams) was indistinguishable
733
+ // from a successful one — and a caller that suppresses its chrome
734
+ // on the strength of a successful request was then stuck with no
735
+ // chrome and no way back. Relaying the answer is the whole fix.
736
+ return getMpvPlayerModule().enterPip(
737
+ chapterTitle ?? null,
738
+ progressPct ?? null,
739
+ );
708
740
  },
709
741
  exitPip: () => {
710
742
  dlog('commands.exitPip()');
@@ -1408,9 +1440,14 @@ export function applyPlayerEvent(
1408
1440
  // The file is over (ended, or failed). No load is in flight.
1409
1441
  return { state: { ...state, isPlaying: false, isLoading: false }, progress };
1410
1442
  case 'onPlaybackRestart':
1443
+ // mpv fires this when playback (re)starts — including right after a
1444
+ // seek. The POSITION belongs to `time-pos` and to nothing else: a new
1445
+ // file resets it in the `onFileLoaded` branch above. Zeroing it here
1446
+ // restarted the transport bar's clock at 0:00 while the video sat at
1447
+ // the position the user had just seeked to (or resumed to).
1411
1448
  return {
1412
- state: { ...state, isPlaying: true, positionMs: 0 },
1413
- progress: { ...progress, positionMs: 0 },
1449
+ state: { ...state, isPlaying: true },
1450
+ progress,
1414
1451
  };
1415
1452
  case 'onEndReached':
1416
1453
  return { state: { ...state, isPlaying: false }, progress };