@simba-dev/react-native-media-player 1.21.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.21.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",
@@ -948,6 +948,58 @@ export function applyForceMediaTitle(bridge: MpvPlayerModuleBridge, title?: stri
948
948
  }
949
949
  }
950
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
+
951
1003
  /**
952
1004
  * V13 Phase 50c: subscribe to a native event. Returns an
953
1005
  * unsubscribe function that callers should invoke from
@@ -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
  *
@@ -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). */
@@ -673,6 +680,11 @@ function buildCommands(): PlayerCommands {
673
680
  // `force-media-title` is mpv's own option for exactly this. The
674
681
  // set-then-load ordering is the contract — see the helper.
675
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);
676
688
  dlog('commands.loadFile(', uri, ')');
677
689
  getMpvPlayerModule().loadFile(uri);
678
690
  },
@@ -1428,9 +1440,14 @@ export function applyPlayerEvent(
1428
1440
  // The file is over (ended, or failed). No load is in flight.
1429
1441
  return { state: { ...state, isPlaying: false, isLoading: false }, progress };
1430
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).
1431
1448
  return {
1432
- state: { ...state, isPlaying: true, positionMs: 0 },
1433
- progress: { ...progress, positionMs: 0 },
1449
+ state: { ...state, isPlaying: true },
1450
+ progress,
1434
1451
  };
1435
1452
  case 'onEndReached':
1436
1453
  return { state: { ...state, isPlaying: false }, progress };