@simba-dev/react-native-media-player 1.21.0 → 1.23.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.
@@ -1868,14 +1868,26 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1868
1868
  // no-op by design
1869
1869
  }
1870
1870
 
1871
+ /**
1872
+ * `override` because the TurboModule spec declares the pair: the
1873
+ * generated `NativeMpvPlayerSpec` declares `addListener` /
1874
+ * `removeListeners`, so this class has to implement them. Without
1875
+ * them in the spec, the new-architecture interop proxy exposed no
1876
+ * `addListener` and RN's `NativeEventEmitter` never attached the
1877
+ * native module (see `src/bridge/NativeMpvPlayer.ts`).
1878
+ */
1871
1879
  @ReactMethod
1872
- fun addListener(eventName: String) {
1880
+ override fun addListener(eventName: String) {
1873
1881
  // Required by NativeEventEmitter. MPVLib listener registration is
1874
1882
  // owned by initialize()/onCatalystInstanceDestroy(), not JS callers.
1875
1883
  }
1876
1884
 
1885
+ /**
1886
+ * `override` for the same reason as `addListener` above: the pair is
1887
+ * declared in the TurboModule spec.
1888
+ */
1877
1889
  @ReactMethod
1878
- fun removeListeners(count: Double) {
1890
+ override fun removeListeners(count: Double) {
1879
1891
  // Required by NativeEventEmitter. Keep the native listener attached
1880
1892
  // for the lifetime of this module instance.
1881
1893
  }
@@ -2437,13 +2449,23 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2437
2449
  /**
2438
2450
  * Exit PiP mode and finish the activity (close player session).
2439
2451
  * Called from JS when user taps "Close" in PiP RemoteActions.
2452
+ *
2453
+ * `finish()`, NOT `finishAndRemoveTask()`.
2454
+ *
2455
+ * The consumer app has ONE Activity, so `getCurrentActivity()` IS
2456
+ * that Activity. `finishAndRemoveTask()` removes the whole TASK
2457
+ * from Recents — not just the PiP window — so closing the player
2458
+ * made the entire app disappear from the Recents list.
2459
+ * `finish()` closes the PiP window and leaves the task (and the
2460
+ * app's Recents entry) in place, which is what "close the player"
2461
+ * means.
2440
2462
  */
2441
2463
  @ReactMethod
2442
2464
  @Override
2443
2465
  override fun exitPipAndFinish() {
2444
2466
  val activity = getCurrentActivity()
2445
2467
  if (activity == null) return
2446
- activity.finishAndRemoveTask()
2468
+ activity.finish()
2447
2469
  }
2448
2470
 
2449
2471
  // ── Media Notification Service ─────────────────────────────────────────
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.23.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
@@ -351,6 +351,25 @@ export interface Spec extends TurboModule {
351
351
  // ── Debug (V12 Phase 39) ───────────────────────────────────────────────
352
352
  setDebugLogging(enabled: boolean): void;
353
353
  dumpObservedProperties(): number;
354
+
355
+ // ── Event emitter plumbing (React Native's NativeEventEmitter) ─────────
356
+ //
357
+ // React Native's `NativeEventEmitter` REQUIRES the native module to
358
+ // expose `addListener` / `removeListeners`. TurboModule codegen only
359
+ // exposes spec-declared methods, so while these two were missing from
360
+ // this spec the interop proxy had no `addListener` at all — and RN
361
+ // 0.86's `NativeEventEmitter` warns twice and never attaches the
362
+ // native module.
363
+ //
364
+ // The Kotlin side already declares the pair (`MpvBridgeModule
365
+ // .addListener` / `removeListeners`), so this is the spec catching up
366
+ // with the implementation, not a new API.
367
+ //
368
+ // Types: Kotlin `String` ↔ TS `string`; Kotlin `Double` ↔ TS `number`
369
+ // (codegen maps a TS `number` onto `double` in the generated Java
370
+ // spec).
371
+ addListener(eventName: string): void;
372
+ removeListeners(count: number): void;
354
373
  }
355
374
 
356
375
  export default TurboModuleRegistry.getEnforcing<Spec>('MpvPlayerModule');
@@ -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
  }
@@ -516,6 +516,50 @@ export function PlayerProvider({
516
516
  [JSON.stringify(config ?? {})],
517
517
  );
518
518
 
519
+ // ── Engine initialisation (B-010) ─────────────────────────────────────
520
+ //
521
+ // `initPlayer()` runs HERE, in the render phase, and NOT in the mount
522
+ // effect. React commits passive effects CHILD-FIRST, so an effect here
523
+ // would run AFTER every descendant's effect — and after a
524
+ // descendant's RENDER, which is earlier still.
525
+ //
526
+ // The bridge's `play / pause / loadFile / seek*` methods all hit
527
+ // `ensurePtr()` first, which throws
528
+ // `IllegalStateException("MpvPlayerModule not initialized. Call
529
+ // initPlayer() first.")` while `nativePtr == 0`. `<SimbaVideo>` reads
530
+ // the handle during ITS render, so an effect-based init left the
531
+ // surface bound to a null handle for the life of that mount.
532
+ //
533
+ // A parent's render function completes before any child's render
534
+ // begins, so initialising here means the handle exists before ANY
535
+ // descendant renders.
536
+ //
537
+ // TRADE-OFF: this is a side effect in the render phase, which React
538
+ // does not recommend. It is safe ONLY because `initPlayer()` is
539
+ // idempotent: the Kotlin side short-circuits with `return true` when
540
+ // `nativePtr != 0` (`MpvBridgeModule.initPlayer()`), so a second call
541
+ // — a StrictMode double render, a second provider — is a no-op and
542
+ // never a second engine.
543
+ const bridge = getMpvPlayerModule();
544
+ const engineInitialisedRef = useRef(false);
545
+ if (!engineInitialisedRef.current) {
546
+ engineInitialisedRef.current = true;
547
+ try {
548
+ const ok = bridge.initPlayer();
549
+ if (!ok) {
550
+ // eslint-disable-next-line no-console
551
+ console.warn(
552
+ '[simba-player] initPlayer returned false on provider mount - ' +
553
+ 'the native mpv instance did not allocate. Check MpvBridgeModule logs.',
554
+ );
555
+ }
556
+ } catch (e) {
557
+ // Silent HERE on purpose: the bridge is absent in jest / web, so
558
+ // there is no native engine to initialise and nothing to report.
559
+ // The provider still serves the config to TS consumers.
560
+ }
561
+ }
562
+
519
563
  useEffect(() => {
520
564
  const native = getNativeModule();
521
565
  if (native === null) {
@@ -551,32 +595,12 @@ export function PlayerProvider({
551
595
  // desync during the gap between hydration and subscription mount.)
552
596
  // The 1Hz position poll this effect used to also start was removed in
553
597
  // v1.10.0 — the event stream is authoritative for position and duration.
598
+ //
599
+ // The engine is NOT initialised here. `initPlayer()` runs in the render
600
+ // phase above (see the B-010 note there), so the native handle already
601
+ // exists by the time this effect runs — and, more importantly, before
602
+ // any descendant renders.
554
603
  useEffect(() => {
555
- const bridge = getMpvPlayerModule();
556
-
557
- // V22.0.0 / 1.5.7 (B-010 final / D-035): ensure the native mpv
558
- // instance is created BEFORE the user can tap any playback
559
- // control. The bridge's `play / pause / loadFile / seek*`
560
- // methods all hit `ensurePtr()` first, which throws
561
- // `IllegalStateException("MpvPlayerModule not initialized. Call
562
- // initPlayer() first.")` when `nativePtr == 0`. Calling
563
- // `initPlayer()` here in the provider's mount effect is
564
- // idempotent (`nativePtr != 0` on the Kotlin side short-circuits
565
- // with `return true`) so this is safe even if a future caller
566
- // also initialises. Runs once per PlayerProvider mount.
567
- try {
568
- const ok = bridge.initPlayer();
569
- if (!ok) {
570
- // eslint-disable-next-line no-console
571
- console.warn(
572
- '[simba-player] initPlayer returned false on provider mount - ' +
573
- 'the native mpv instance did not allocate. Check MpvBridgeModule logs.',
574
- );
575
- }
576
- } catch (e) {
577
- // The bridge is missing (jest / web) - fall through silently.
578
- }
579
-
580
604
  // ── 1. Initial hydration from sync bridge getters ───────────────────
581
605
  try {
582
606
  const initial = hydratePlayerState(bridge);
@@ -740,9 +764,11 @@ export function PlayerProvider({
740
764
  // ── 2b. Observe the mpv properties those events are derived from ───
741
765
  // Step 2 subscribes to the JS event names, but mpv only *emits*
742
766
  // them for properties JS registered with `mpv_observe_property`.
743
- // Registration must happen after `initPlayer()` (step 0) so the
744
- // native handle exists; the Kotlin side also queues any name that
745
- // arrives early, so ordering is safe either way.
767
+ // Registration must happen after `initPlayer()` so the native handle
768
+ // exists. `initPlayer()` runs in the render phase above, so by the
769
+ // time this effect runs the handle is already there; the Kotlin side
770
+ // also queues any name that arrives early, so ordering is safe
771
+ // either way.
746
772
  //
747
773
  // A failure here must not abort the subscription above or the poll
748
774
  // below — this list is additive.
@@ -61,20 +61,30 @@ export function SimbaVideo(props: SimbaVideoProps): React.ReactElement {
61
61
  const { nativePtr, resizeMode = 'contain', paused, muted, volume, style, ...rest } = props;
62
62
 
63
63
  /**
64
- * `PlayerProvider` calls `initPlayer()` on mount, and the native side
65
- * short-circuits when a handle already exists, so inside a provider the
66
- * handle is always available before any child renders. Resolving it during
67
- * render rather than in an effect is deliberate: an effect would mount the
68
- * surface unbound first and leave `MpvRenderView` waiting for a
69
- * `setNativePtr` that only arrives on a later commit.
64
+ * The native handle this surface is bound to.
65
+ *
66
+ * `PlayerProvider` initialises the engine during ITS OWN render, not
67
+ * in an effect, and the native side short-circuits when a handle
68
+ * already exists — so inside a provider the handle is available before
69
+ * any child renders (a parent's render completes before any child's
70
+ * render begins).
71
+ *
72
+ * The handle is read during render rather than in an effect on
73
+ * purpose: an effect would mount the surface unbound first and leave
74
+ * `MpvRenderView` waiting for a `setNativePtr` that only arrives on a
75
+ * later commit.
76
+ *
77
+ * The bridge read is deliberately NOT memoised. `getNativePtr()` does
78
+ * not throw when the engine does not exist yet — it answers 0 — so a
79
+ * memoised read could latch that 0 and keep the surface bound to
80
+ * nothing for the life of the mount. mpv's handle is stable for the
81
+ * life of the engine, so re-reading it per render is one cheap sync
82
+ * call and can never be stale.
70
83
  *
71
84
  * Outside a provider, or when an app manages more than one engine, pass
72
85
  * `nativePtr` explicitly.
73
86
  */
74
- const resolvedPtr = useMemo(
75
- () => nativePtr ?? getMpvPlayerModule().getNativePtr(),
76
- [nativePtr],
77
- );
87
+ const resolvedPtr = nativePtr ?? getMpvPlayerModule().getNativePtr();
78
88
 
79
89
  const videoZoom = useMemo(() => {
80
90
  switch (resizeMode) {
@@ -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 };