@simba-dev/react-native-media-player 2.0.0 → 2.1.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.
Files changed (39) hide show
  1. package/README.md +317 -560
  2. package/android/src/main/cpp/main.cpp +117 -17
  3. package/android/src/main/java/com/simba/player/PipManager.kt +13 -0
  4. package/android/src/main/java/com/simba/player/mpv/MpvBridgeModule.kt +187 -8
  5. package/android/src/main/java/com/simba/player/mpv/MpvRenderViewManager.kt +11 -1
  6. package/android/src/main/java/com/simba/player/mpv/MpvRenderViewRegistry.kt +132 -0
  7. package/android/src/main/java/com/simba/player/mpv/PipAutoEnterPolicy.kt +54 -0
  8. package/android/src/main/java/com/simba/player/mpv/PlayerSurface.kt +41 -1
  9. package/package.json +11 -2
  10. package/src/bridge/MpvPlayerModule.ts +7 -1
  11. package/src/bridge/NativeMpvPlayer.ts +3 -3
  12. package/src/types/player.ts +7 -1
  13. package/android/src/test/java/com/simba/player/PipActionReceiverTest.kt +0 -123
  14. package/android/src/test/java/com/simba/player/PipManagerTest.kt +0 -281
  15. package/android/src/test/java/com/simba/player/TestApplication.kt +0 -26
  16. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleNullInstanceTest.kt +0 -117
  17. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleTest.kt +0 -212
  18. package/android/src/test/java/com/simba/player/mpv/MpvRenderViewTest.kt +0 -249
  19. package/scripts/override_react_methods.js +0 -184
  20. package/scripts/override_react_methods.py +0 -150
  21. package/src/bridge/__tests__/MpvPlayerModule.test.ts +0 -110
  22. package/src/bridge/__tests__/debugMode.test.ts +0 -138
  23. package/src/bridge/__tests__/errorContract.test.ts +0 -175
  24. package/src/bridge/__tests__/loadAndPlay.startPosition.test.tsx +0 -142
  25. package/src/components/__tests__/PlayerProvider.performance.test.tsx +0 -242
  26. package/src/components/__tests__/PlayerProvider.progressContext.test.tsx +0 -194
  27. package/src/components/__tests__/PlayerProvider.test.tsx +0 -558
  28. package/src/components/__tests__/PlayerRoot.test.tsx +0 -71
  29. package/src/components/__tests__/SimbaVideo.test.tsx +0 -164
  30. package/src/hooks/__tests__/resolveStreamType.test.ts +0 -159
  31. package/src/hooks/__tests__/useLaunchPlayback.test.tsx +0 -278
  32. package/src/hooks/__tests__/useResumeThumbnail.test.ts +0 -154
  33. package/src/stores/__tests__/playerQueueSelectionStore.test.ts +0 -73
  34. package/src/stores/__tests__/playerQueueStore.test.ts +0 -171
  35. package/src/types/__tests__/config.test.ts +0 -188
  36. package/src/types/__tests__/player.pipAnswer.test.tsx +0 -87
  37. package/src/types/__tests__/player.pipArity.test.tsx +0 -74
  38. package/src/types/__tests__/player.test.tsx +0 -1365
  39. package/src/types/__tests__/playerLoading.test.ts +0 -170
@@ -1,110 +0,0 @@
1
- /**
2
- * Unit tests for `src/bridge/MpvPlayerModule.ts`.
3
- *
4
- * Spec §Phase 34 doesn't have an explicit bullet for bridge tests,
5
- * but they're foundational — every hook/component ultimately routes
6
- * through `getMpvPlayerModule()` so we need to verify the typed
7
- * wrapper's contract.
8
- *
9
- * Test surface:
10
- * - `getMpvPlayerModule()` returns the underlying module when
11
- * `NativeModules.MpvPlayerModule` is defined
12
- * - The returned object exposes every documented method (typed
13
- * `MpvPlayerModuleBridge` interface)
14
- * - Each method delegates to the same name on the underlying
15
- * NativeModule
16
- *
17
- * What we DON'T test:
18
- * - The "no native module" path returns null. We can't easily
19
- * unmock the global mock in jest.setup.ts; the production code
20
- * path is `const native = NativeModules.MpvPlayerModule; return
21
- * native === undefined ? null : native;` — a pure lookup that
22
- * needs no test beyond its existence.
23
- */
24
-
25
- // The MpvPlayerModule bridge mock is installed globally in
26
- // `jest.setup.ts` (it extends the @react-native/jest-preset's own
27
- // `NativeModules` mock rather than overriding it). Every test file
28
- // in this module shares the same `NativeModules.MpvPlayerModule`
29
- // instance, so `mockClear()` in beforeEach is the way to reset
30
- // call counts between tests.
31
-
32
- import { NativeModules } from 'react-native';
33
- import {
34
- getMpvPlayerModule,
35
- type MpvPlayerModuleBridge,
36
- } from '../MpvPlayerModule';
37
-
38
- describe('getMpvPlayerModule', () => {
39
- beforeEach(() => {
40
- // The global mock is shared across all test files in this
41
- // module — clear call history between tests so .toHaveBeenCalledTimes
42
- // assertions are deterministic.
43
- for (const key of Object.keys(NativeModules.MpvPlayerModule)) {
44
- const fn = (NativeModules.MpvPlayerModule as Record<string, jest.Mock>)[key];
45
- if (typeof fn?.mockClear === 'function') {
46
- fn.mockClear();
47
- }
48
- }
49
- });
50
-
51
- it('returns a non-null typed bridge when NativeModules.MpvPlayerModule exists', () => {
52
- const bridge = getMpvPlayerModule();
53
- expect(bridge).not.toBeNull();
54
- expect(bridge).toBeDefined();
55
- });
56
-
57
- it('returns the underlying NativeModule reference (same instance)', () => {
58
- // The wrapper is a transparent pass-through — consumers can rely
59
- // on reference equality with `NativeModules.MpvPlayerModule` if
60
- // they need to. Phase 24 design.
61
- const bridge = getMpvPlayerModule();
62
- expect(bridge).toBe(NativeModules.MpvPlayerModule);
63
- });
64
-
65
- it('exposes every documented method on the typed bridge interface', () => {
66
- const bridge = getMpvPlayerModule() as MpvPlayerModuleBridge;
67
- const expectedMethods = [
68
- 'play',
69
- 'pause',
70
- 'seekAbsolute',
71
- 'seekForward',
72
- 'seekBackward',
73
- 'playlistNext',
74
- 'playlistPrev',
75
- ];
76
- for (const method of expectedMethods) {
77
- expect(typeof bridge[method as keyof MpvPlayerModuleBridge]).toBe(
78
- 'function',
79
- );
80
- }
81
- });
82
-
83
- it('each method is callable and returns a thenable (Promise)', async () => {
84
- const bridge = getMpvPlayerModule() as MpvPlayerModuleBridge;
85
- // All methods are documented as `Promise<void>`. We don't
86
- // exhaustively call them — just smoke-test the most common ones.
87
- await expect(bridge.play()).resolves.toBeUndefined();
88
- await expect(bridge.pause()).resolves.toBeUndefined();
89
- await expect(bridge.seekAbsolute(42)).resolves.toBeUndefined();
90
- await expect(bridge.seekForward(10)).resolves.toBeUndefined();
91
- await expect(bridge.seekBackward(10)).resolves.toBeUndefined();
92
- });
93
-
94
- it('play() forwards arguments through to the native module', async () => {
95
- const bridge = getMpvPlayerModule() as MpvPlayerModuleBridge;
96
- (NativeModules.MpvPlayerModule.play as jest.Mock).mockClear();
97
- await bridge.play();
98
- expect(NativeModules.MpvPlayerModule.play).toHaveBeenCalledTimes(1);
99
- expect(NativeModules.MpvPlayerModule.play).toHaveBeenCalledWith();
100
- });
101
-
102
- it('seekAbsolute(seconds) forwards the position argument', async () => {
103
- const bridge = getMpvPlayerModule() as MpvPlayerModuleBridge;
104
- (NativeModules.MpvPlayerModule.seekAbsolute as jest.Mock).mockClear();
105
- await bridge.seekAbsolute(123.456);
106
- expect(NativeModules.MpvPlayerModule.seekAbsolute).toHaveBeenCalledWith(
107
- 123.456,
108
- );
109
- });
110
- });
@@ -1,138 +0,0 @@
1
- /**
2
- * Tests for the Phase 39 debug-mode API.
3
- *
4
- * Spec §39 — Logging & debug mode.
5
- *
6
- * Covers:
7
- * - `setDebugLogging(true/false)` toggles verbose logging
8
- * - `dumpObservedProperties()` returns the count
9
- * - The module-scoped `_debugLoggingEnabled` flag gates `dlog`
10
- * - `__DEV__` conditional behaviour (only logs in debug builds)
11
- * - The no-op fallback in jest (no native module) doesn't throw
12
- */
13
-
14
- import {
15
- getMpvPlayerModule,
16
- setDebugLogging,
17
- dumpObservedProperties,
18
- dlog,
19
- } from '../MpvPlayerModule';
20
-
21
- describe('Phase 39 — debug mode API', () => {
22
- beforeEach(() => {
23
- // Reset debug flag between tests
24
- setDebugLogging(false);
25
- });
26
-
27
- afterAll(() => {
28
- setDebugLogging(false);
29
- });
30
-
31
- it('setDebugLogging(true) toggles the module-scoped flag', () => {
32
- const result = setDebugLogging(true);
33
- expect(result).toBe(true);
34
- });
35
-
36
- it('setDebugLogging(false) toggles back off', () => {
37
- setDebugLogging(true);
38
- const result = setDebugLogging(false);
39
- expect(result).toBe(false);
40
- });
41
-
42
- it('setDebugLogging is idempotent', () => {
43
- setDebugLogging(true);
44
- setDebugLogging(true);
45
- const result = setDebugLogging(false);
46
- expect(result).toBe(false);
47
- });
48
-
49
- it('setDebugLogging forwards to the bridge (via getMpvPlayerModule)', () => {
50
- const bridge = getMpvPlayerModule();
51
- // The bridge exposes setDebugLogging as a function (when the
52
- // mock provides it; see jest.setup.ts)
53
- const bridgeAny = bridge as unknown as Record<string, unknown>;
54
- if (typeof bridgeAny.setDebugLogging === 'function') {
55
- // Live bridge: verify the typed wrapper exposes it
56
- expect(typeof bridge.setDebugLogging).toBe('function');
57
- }
58
- // setDebugLogging must not throw regardless of whether the
59
- // underlying bridge method exists (it catches + logs via dlog)
60
- expect(() => setDebugLogging(true)).not.toThrow();
61
- });
62
-
63
- it('dumpObservedProperties returns a number', () => {
64
- const count = dumpObservedProperties();
65
- expect(typeof count).toBe('number');
66
- expect(count).toBeGreaterThanOrEqual(0);
67
- });
68
-
69
- it('dlog is a no-op when debug logging is off', () => {
70
- setDebugLogging(false);
71
- const originalLog = console.log;
72
- let logCalls = 0;
73
- console.log = () => {
74
- logCalls++;
75
- };
76
- try {
77
- dlog('test message');
78
- expect(logCalls).toBe(0);
79
- } finally {
80
- console.log = originalLog;
81
- }
82
- });
83
-
84
- it('dlog is a no-op when __DEV__ is false (even if flag is true)', () => {
85
- // The `IS_DEV` flag is set at module load time based on
86
- // `typeof __DEV__`. In jest test runs, `__DEV__` is typically
87
- // undefined or false. Verify dlog respects this by NOT calling
88
- // console.log even when the user-facing flag is true.
89
- //
90
- // Note: this test is robust to both `__DEV__ === true` (debug
91
- // build) and `__DEV__ === undefined/false` (release) — it only
92
- // verifies that the count doesn't INCREASE from before to
93
- // after.
94
- setDebugLogging(true);
95
- const originalLog = console.log;
96
- let logCallsBefore = 0;
97
- console.log = () => {
98
- logCallsBefore++;
99
- };
100
- // The act of setting the flag may itself log via getMpvPlayerModule.
101
- // To get a stable measurement, we set a known count first.
102
- console.log = originalLog;
103
- logCallsBefore = 0;
104
- console.log = () => {
105
- logCallsBefore++;
106
- };
107
- // Trigger 5 dlog calls
108
- dlog('1');
109
- dlog('2');
110
- dlog('3');
111
- dlog('4');
112
- dlog('5');
113
- const calls = logCallsBefore;
114
- console.log = originalLog;
115
- // In jest, __DEV__ is typically false (the production build path),
116
- // so all 5 dlog calls should be no-ops. If __DEV__ is true (debug
117
- // build), all 5 would log — also acceptable.
118
- expect(calls === 0 || calls === 5).toBe(true);
119
- });
120
-
121
- it('no-op fallback setDebugLogging does not throw', () => {
122
- // When the native module is absent (jest), setDebugLogging
123
- // must not throw even though the no-op fallback is used.
124
- expect(() => setDebugLogging(true)).not.toThrow();
125
- expect(() => setDebugLogging(false)).not.toThrow();
126
- });
127
-
128
- it('no-op fallback dumpObservedProperties returns 0', () => {
129
- // When the native module is absent, dumpObservedProperties
130
- // returns 0 (the no-op fallback's default return value).
131
- // Note: this only holds if the test runs without the mock
132
- // native module — in our setup, the jest.setup.ts installs a
133
- // mock, so dumpObservedProperties delegates to it. Either way,
134
- // the function returns a non-negative number.
135
- const count = dumpObservedProperties();
136
- expect(count).toBeGreaterThanOrEqual(0);
137
- });
138
- });
@@ -1,175 +0,0 @@
1
- /**
2
- * Tests for the Phase 38 error contract — verifies the typed bridge
3
- * wrapper emits structured error events that JS consumers can
4
- * listen to without writing try/catch boilerplate.
5
- *
6
- * Spec §38 — Error handling & recovery.
7
- *
8
- * Test surface:
9
- * - The typed `MpvPlayerModuleBridge` interface is the source of
10
- * truth for the consumer-facing error shape
11
- * - The no-op fallback bridge (used in jest unit tests + Storybook
12
- * + web previews) doesn't throw on error scenarios
13
- * - Promise-returning bridge methods reject with structured codes
14
- *
15
- * Note: most error-handling lives in the Kotlin bridge (emitErrorEvent)
16
- * and can only be exercised end-to-end on a real device. The unit
17
- * tests here cover the TypeScript-side contract: the typed wrapper
18
- * interface, the no-op fallback, and the consumer-facing types.
19
- */
20
-
21
- import { getMpvPlayerModule } from '../MpvPlayerModule';
22
-
23
- describe('Phase 38 — error contract (TypeScript side)', () => {
24
- it('getMpvPlayerModule returns a bridge even when native module is absent', async () => {
25
- // The no-op fallback is what keeps jest unit tests renderable
26
- // without a real native module. Phase 38 guarantees it doesn't
27
- // throw on any error scenario (it just no-ops).
28
- const bridge = getMpvPlayerModule();
29
- expect(bridge).toBeDefined();
30
- expect(typeof bridge.play).toBe('function');
31
- expect(typeof bridge.pause).toBe('function');
32
-
33
- // The native module isn't wired in jest — verify by checking
34
- // that a setConfig call (the only Promise-returning method)
35
- // resolves immediately rather than rejecting with the documented
36
- // E_CONFIG_PARSE_FAILED code. V13 Phase 50: setConfig now
37
- // resolves with the count of parsed top-level keys (matches the
38
- // Kotlin implementation at MpvBridgeModule.kt). The no-op
39
- // fallback resolves to 0.
40
- await expect(bridge.setConfig('not-valid-json{')).resolves.toBe(0);
41
- });
42
-
43
- it('no-op bridge methods do not throw on edge-case inputs', () => {
44
- // The no-op fallback should be safe to call with any arguments
45
- // — including malformed input that the typed bridge would reject.
46
- // This guarantees the fallback doesn't crash React render passes.
47
- const bridge = getMpvPlayerModule();
48
- expect(() => bridge.play()).not.toThrow();
49
- expect(() => bridge.pause()).not.toThrow();
50
- expect(() => bridge.seekAbsolute(NaN)).not.toThrow();
51
- expect(() => bridge.seekAbsolute(-1)).not.toThrow();
52
- expect(() => bridge.seekAbsolute(Infinity)).not.toThrow();
53
- expect(() => bridge.seekBackward(NaN)).not.toThrow();
54
- expect(() => bridge.seekForward(NaN)).not.toThrow();
55
- });
56
-
57
- it('no-op bridge setConfig resolves (does not reject) for any input', async () => {
58
- // The real bridge rejects setConfig with E_CONFIG_PARSE_FAILED
59
- // for malformed JSON. The no-op fallback resolves silently —
60
- // this is by design: jest unit tests should not crash on
61
- // malformed config; the real parsing happens at runtime on a
62
- // device. V13 Phase 50: the resolution value is the parsed-key
63
- // count (0 for malformed input, matches Kotlin).
64
- const bridge = getMpvPlayerModule();
65
- await expect(bridge.setConfig('')).resolves.toBe(0);
66
- await expect(bridge.setConfig('not-json')).resolves.toBe(0);
67
- await expect(bridge.setConfig('{')).resolves.toBe(0);
68
- });
69
-
70
- it('typed bridge interface exposes the 6 documented methods', () => {
71
- // Pin the contract: getMpvPlayerModule returns a bridge with at
72
- // least these 6 methods (Phase 24 contract, unchanged by Phase
73
- // 38). The native bridge exposes more methods (the full Kotlin
74
- // API surface); this test pins the MINIMUM, not the exact list.
75
- const bridge = getMpvPlayerModule();
76
- // The 6 typed-method names that the consumer-facing wrapper
77
- // documents as the public API
78
- const EXPECTED_METHODS = [
79
- 'pause',
80
- 'play',
81
- 'seekAbsolute',
82
- 'seekBackward',
83
- 'seekForward',
84
- 'setConfig',
85
- ];
86
- EXPECTED_METHODS.forEach((method) => {
87
- expect(typeof (bridge as unknown as Record<string, unknown>)[method]).toBe('function');
88
- });
89
- });
90
-
91
- it('typed bridge methods are callable', () => {
92
- // The Phase 38 error contract relies on consumers being able to
93
- // call each of the 6 documented methods without throwing. The
94
- // return-value contract is documented in MpvPlayerModule.ts
95
- // (setConfig returns Promise<void>; the other 5 return void),
96
- // but a refactor that changes the return type would be caught
97
- // by the TS compiler — not by these unit tests. We just verify
98
- // each method is callable without throwing.
99
- const bridge = getMpvPlayerModule();
100
- expect(() => bridge.play()).not.toThrow();
101
- expect(() => bridge.pause()).not.toThrow();
102
- expect(() => bridge.seekAbsolute(0)).not.toThrow();
103
- expect(() => bridge.seekBackward(0)).not.toThrow();
104
- expect(() => bridge.seekForward(0)).not.toThrow();
105
- });
106
- });
107
-
108
- describe('Phase 38 — error code constants (consumer contract)', () => {
109
- /**
110
- * The error codes emitted by MpvBridgeModule are documented in
111
- * SIMBA_PLAYER_MODULE_V12_ERROR_CONTRACT.md §2.1. These tests
112
- * pin the codes so a refactor doesn't accidentally rename them
113
- * (which would silently break every consumer's switch statement).
114
- *
115
- * We don't import the codes from the native module (they're
116
- * emitted as event payloads, not exported constants) — instead
117
- * we test that the documentation in ERROR_CONTRACT.md matches
118
- * what the bridge emits. The Kotlin bridge emits these strings
119
- * as the `code` field of the `onError` payload.
120
- *
121
- * If any of these change, both ERROR_CONTRACT.md §2.1 AND the
122
- * Kotlin emitErrorEvent() callers must change together.
123
- */
124
- const DOCUMENTED_ERROR_CODES = [
125
- 'E_NOT_INITIALIZED',
126
- 'E_INVALID_TYPE',
127
- 'E_NO_ACTIVITY',
128
- 'E_ACTIVITY_NOT_FOUND',
129
- 'E_SECURITY',
130
- 'E_OPEN_PLAYER_FAILED',
131
- 'E_CONFIG_PARSE_FAILED',
132
- 'E_NETWORK_FAILURE',
133
- 'E_DECODE_FAILED',
134
- 'E_UNSUPPORTED_CODEC',
135
- 'E_FILE_NOT_FOUND',
136
- 'E_RENDERER_GONE',
137
- 'E_OUT_OF_MEMORY',
138
- 'E_AUDIO_FOCUS_LOST',
139
- 'E_SURFACE_LOST',
140
- // v1.17.0 — the mpv error codes, mapped from `mpv_error` in mpv's
141
- // `include/mpv/client.h`. These replaced the "every terminal
142
- // failure is E_RENDERER_GONE" catch-all, which made a load failure
143
- // indistinguishable from a dead video output.
144
- 'E_LOAD_FAILED',
145
- 'E_AUDIO_INIT_FAILED',
146
- 'E_VIDEO_INIT_FAILED',
147
- 'E_NOTHING_TO_PLAY',
148
- 'E_UNKNOWN_FORMAT',
149
- 'E_GENERIC',
150
- 'E_NOT_IMPLEMENTED',
151
- 'E_INVALID_PARAMETER',
152
- 'E_OPTION_NOT_FOUND',
153
- 'E_PROPERTY_NOT_FOUND',
154
- 'E_COMMAND_FAILED',
155
- ];
156
-
157
- it('exposes the 26 documented error codes as a frozen contract', () => {
158
- // The list itself is not exported from the module — it's
159
- // documented in ERROR_CONTRACT.md. This test pins the list so
160
- // a drift between docs and code fails CI.
161
- expect(DOCUMENTED_ERROR_CODES).toHaveLength(26);
162
- });
163
-
164
- it('error codes follow the E_UPPER_SNAKE_CASE convention', () => {
165
- // Stable naming convention — any future code should match.
166
- DOCUMENTED_ERROR_CODES.forEach((code) => {
167
- expect(code).toMatch(/^E_[A-Z_]+$/);
168
- });
169
- });
170
-
171
- it('error codes are unique', () => {
172
- const unique = new Set(DOCUMENTED_ERROR_CODES);
173
- expect(unique.size).toBe(DOCUMENTED_ERROR_CODES.length);
174
- });
175
- });
@@ -1,142 +0,0 @@
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
- });