@simba-dev/react-native-media-player 2.0.1 → 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 (34) 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 +177 -6
  5. package/android/src/main/java/com/simba/player/mpv/PipAutoEnterPolicy.kt +54 -0
  6. package/package.json +11 -2
  7. package/android/src/test/java/com/simba/player/PipActionReceiverTest.kt +0 -123
  8. package/android/src/test/java/com/simba/player/PipManagerTest.kt +0 -281
  9. package/android/src/test/java/com/simba/player/TestApplication.kt +0 -26
  10. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleNullInstanceTest.kt +0 -117
  11. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleTest.kt +0 -212
  12. package/android/src/test/java/com/simba/player/mpv/MpvRenderViewRegistryTest.kt +0 -120
  13. package/android/src/test/java/com/simba/player/mpv/MpvRenderViewTest.kt +0 -249
  14. package/scripts/override_react_methods.js +0 -184
  15. package/scripts/override_react_methods.py +0 -150
  16. package/src/bridge/__tests__/MpvPlayerModule.test.ts +0 -163
  17. package/src/bridge/__tests__/debugMode.test.ts +0 -138
  18. package/src/bridge/__tests__/errorContract.test.ts +0 -175
  19. package/src/bridge/__tests__/loadAndPlay.startPosition.test.tsx +0 -142
  20. package/src/components/__tests__/PlayerProvider.performance.test.tsx +0 -242
  21. package/src/components/__tests__/PlayerProvider.progressContext.test.tsx +0 -194
  22. package/src/components/__tests__/PlayerProvider.test.tsx +0 -558
  23. package/src/components/__tests__/PlayerRoot.test.tsx +0 -71
  24. package/src/components/__tests__/SimbaVideo.test.tsx +0 -164
  25. package/src/hooks/__tests__/resolveStreamType.test.ts +0 -159
  26. package/src/hooks/__tests__/useLaunchPlayback.test.tsx +0 -278
  27. package/src/hooks/__tests__/useResumeThumbnail.test.ts +0 -154
  28. package/src/stores/__tests__/playerQueueSelectionStore.test.ts +0 -73
  29. package/src/stores/__tests__/playerQueueStore.test.ts +0 -171
  30. package/src/types/__tests__/config.test.ts +0 -188
  31. package/src/types/__tests__/player.pipAnswer.test.tsx +0 -87
  32. package/src/types/__tests__/player.pipArity.test.tsx +0 -74
  33. package/src/types/__tests__/player.test.tsx +0 -1365
  34. package/src/types/__tests__/playerLoading.test.ts +0 -170
@@ -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
- });
@@ -1,242 +0,0 @@
1
- /**
2
- * v1.10.0 — performance contract tests for `PlayerProvider`.
3
- *
4
- * WHY THIS FILE EXISTS SEPARATELY
5
- * -------------------------------
6
- * The pre-1.10.0 suite passed 177/177 while the provider was re-rendering
7
- * all 12 chrome components once per video frame. Nothing was broken in a way
8
- * the existing tests could see, because the suite asserts VALUES ("the
9
- * title is right", "seekable is true") and never asserts HOW OFTEN React
10
- * was asked to re-render.
11
- *
12
- * That is the whole point of these tests: they pin WORK, not values. Each
13
- * one fails if its fix is reverted.
14
- *
15
- * The defect being pinned (see the notes on `playerStateEqual` in
16
- * PlayerProvider.tsx):
17
- * `applyPlayerEvent` returns a freshly-spread object for every event, so
18
- * the provider's `nextState !== stateRef.current` guard was comparing a
19
- * brand-new object against itself and was therefore ALWAYS true. Every
20
- * event produced a setState and a context-value replacement.
21
- */
22
-
23
- import React from 'react';
24
- import { NativeModules } from 'react-native';
25
- import { act, renderHook } from '@testing-library/react-native';
26
- import { PlayerProvider } from '../PlayerProvider';
27
- import { usePlayer } from '../../types/player';
28
-
29
- const wrapper = ({ children }: { children: React.ReactNode }) => (
30
- <PlayerProvider>{children}</PlayerProvider>
31
- );
32
-
33
- /**
34
- * Deliver an event through the SAME emitter production uses.
35
- *
36
- * The bridge's `resolveEmitter()` builds a `NativeEventEmitter` over
37
- * `NativeModules.MpvPlayerModule`, and on the native side the events are
38
- * published through `RCTDeviceEventEmitter` (documented in
39
- * MpvPlayerModule.ts: "the events are emitted via RCTDeviceEventEmitter").
40
- * RN's own jest preset mocks `DeviceEventEmitter`/`RCTDeviceEventEmitter`,
41
- * and `NativeEventEmitter` delegates to it, so emitting there drives the
42
- * real subscription the provider registered — not a stub.
43
- */
44
- function emit(eventName: string, payload: Record<string, unknown>): void {
45
- const {
46
- DeviceEventEmitter,
47
- } = require('react-native') as typeof import('react-native');
48
- DeviceEventEmitter.emit(eventName, payload);
49
- }
50
-
51
- /**
52
- * Count how many times a `usePlayer()` consumer actually re-rendered.
53
- *
54
- * `usePlayer()` reads ONLY `PlayerStateContext` (it does not read progress —
55
- * that is what `usePlayerProgress()` is for), so this counter measures the
56
- * STATE channel specifically. That is the channel `onPlaybackStateChanged`
57
- * writes to, and the channel whose guard was dead code.
58
- *
59
- * The probe returns the hook value so the tests can assert on it too.
60
- */
61
- function createRenderCounter() {
62
- let renders = 0;
63
- const probe = () => {
64
- renders += 1;
65
- return usePlayer();
66
- };
67
- return { probe, count: () => renders };
68
- }
69
-
70
- // ═══════════════════════════════════════════════════════════════════════════
71
- // 1. The no-op guard
72
- // ═══════════════════════════════════════════════════════════════════════════
73
-
74
- describe('PlayerProvider no-op event guard', () => {
75
- /**
76
- * `isPlaying` defaults to `false`, so 'playing' is a REAL change and
77
- * 'paused' is a no-op from the default baseline. Every test here has to
78
- * establish a known baseline before it can assert on a no-op — otherwise
79
- * it silently asserts the wrong thing, which is exactly the failure mode
80
- * this file exists to prevent.
81
- */
82
- it('does NOT re-render state consumers when an event changes no field', async () => {
83
- // `onPlaybackStateChanged` is handled by a pure spread-and-return in
84
- // applyPlayerEvent. Before v1.10.0 this produced a new object every
85
- // time and re-rendered every usePlayer() consumer, even when
86
- // `isPlaying` was unchanged — and mpv emits this on pause, seek,
87
- // speed change and file load.
88
- const { probe, count } = createRenderCounter();
89
- const { result, unmount } = await renderHook(probe, { wrapper });
90
-
91
- // Baseline: get INTO 'playing' first. This render is expected.
92
- await act(async () => {
93
- emit('onPlaybackStateChanged', { state: 'playing' });
94
- });
95
- expect(result.current.state.isPlaying).toBe(true);
96
-
97
- const rendersAfterBaseline = count();
98
-
99
- // Now fire five events that change NOTHING.
100
- await act(async () => {
101
- emit('onPlaybackStateChanged', { state: 'playing' });
102
- emit('onPlaybackStateChanged', { state: 'playing' });
103
- emit('onPlaybackStateChanged', { state: 'playing' });
104
- emit('onPlaybackStateChanged', { state: 'playing' });
105
- emit('onPlaybackStateChanged', { state: 'playing' });
106
- });
107
-
108
- expect(count()).toBe(rendersAfterBaseline);
109
-
110
- await unmount();
111
- });
112
-
113
- it('DOES re-render when an event changes a field', async () => {
114
- // The mirror image of the test above, and the reason the guard above is
115
- // safe: a guard that never fires is a dropped update, which is worse
116
- // than a wasted render. Flipping isPlaying must still get through.
117
- const { probe, count } = createRenderCounter();
118
- const { result, unmount } = await renderHook(probe, { wrapper });
119
-
120
- await act(async () => {
121
- emit('onPlaybackStateChanged', { state: 'playing' });
122
- });
123
- const rendersAfterBaseline = count();
124
-
125
- await act(async () => {
126
- emit('onPlaybackStateChanged', { state: 'paused' });
127
- });
128
-
129
- expect(result.current.state.isPlaying).toBe(false);
130
- expect(count()).toBeGreaterThan(rendersAfterBaseline);
131
-
132
- await unmount();
133
- });
134
-
135
- it('propagates a field change that only exists on a NESTED value', async () => {
136
- // The reason the key list is derived from DEFAULT_STATE at runtime
137
- // rather than hand-written: `error` is a nested object, and a
138
- // hand-written comparison that forgot it would silently drop errors.
139
- const { probe, count } = createRenderCounter();
140
- const { result, unmount } = await renderHook(probe, { wrapper });
141
-
142
- const rendersAfterMount = count();
143
-
144
- await act(async () => {
145
- emit('onError', {
146
- code: 3,
147
- codeName: 'E_NETWORK_FAILURE',
148
- recoverable: true,
149
- message: 'boom',
150
- });
151
- });
152
-
153
- expect(result.current.state.error).not.toBeNull();
154
- expect(count()).toBeGreaterThan(rendersAfterMount);
155
-
156
- await unmount();
157
- });
158
- });
159
-
160
- // ═══════════════════════════════════════════════════════════════════════════
161
- // 2. The removed position poll
162
- // ═══════════════════════════════════════════════════════════════════════════
163
-
164
- describe('PlayerProvider position source', () => {
165
- beforeEach(() => {
166
- jest.useFakeTimers();
167
- });
168
-
169
- afterEach(() => {
170
- jest.useRealTimers();
171
- });
172
-
173
- it('does NOT call the synchronous getPosition/getDuration getters on a timer', async () => {
174
- // v1.10.0 removed the 1Hz poll. Those two getters are SYNC
175
- // TurboModule methods: React Native's own guidance is to use sync
176
- // methods only for sub-5ms work and never on a recurring timer,
177
- // because they block the JS thread for the JNI round-trip.
178
- //
179
- // If a poll is reintroduced, this fails — which is the point. A second
180
- // writer to `positionMs` is how a seek bar ends up jumping backwards.
181
- const { unmount } = await renderHook(() => usePlayer().state, { wrapper });
182
-
183
- const getPosition = NativeModules.MpvPlayerModule
184
- .getPosition as jest.Mock;
185
- const getDuration = NativeModules.MpvPlayerModule
186
- .getDuration as jest.Mock;
187
- getPosition.mockClear();
188
- getDuration.mockClear();
189
-
190
- await act(async () => {
191
- jest.advanceTimersByTime(5000);
192
- });
193
-
194
- expect(getPosition).not.toHaveBeenCalled();
195
- expect(getDuration).not.toHaveBeenCalled();
196
-
197
- await unmount();
198
- });
199
-
200
- it('still advances position from the event stream alone', async () => {
201
- // Removing the poll is only safe if the event path carries position
202
- // end to end. This proves it does — the seek bar does not depend on
203
- // the poll it no longer has.
204
- const { result, unmount } = await renderHook(() => usePlayer().state, {
205
- wrapper,
206
- });
207
-
208
- await act(async () => {
209
- emit('onPositionChanged', { position: 42.5 });
210
- });
211
-
212
- expect(result.current.positionMs).toBe(42500);
213
-
214
- await unmount();
215
- });
216
- });
217
-
218
- // ═══════════════════════════════════════════════════════════════════════════
219
- // 3. The observation contract (regression guard for the native coalescing)
220
- // ═══════════════════════════════════════════════════════════════════════════
221
-
222
- describe('PlayerProvider observed property contract', () => {
223
- it('observes the properties whose events carry position and cache state', async () => {
224
- // The native layer (event.cpp) now COALESCES `time-pos` and
225
- // `demuxer-cache-state` before forwarding them, precisely because
226
- // mpv emits them once per frame / on every cache tick. That
227
- // optimisation is only correct if these names are actually observed —
228
- // an unregistered name never reaches the coalescer and the field goes
229
- // dead, which is the same defect class as `mute` in 1.9.1.
230
- const { unmount } = await renderHook(() => usePlayer(), { wrapper });
231
-
232
- const observed = (
233
- NativeModules.MpvPlayerModule.observeProperty as jest.Mock
234
- ).mock.calls.map((call: unknown[]) => call[0]);
235
-
236
- expect(observed).toEqual(
237
- expect.arrayContaining(['time-pos', 'duration', 'demuxer-cache-state']),
238
- );
239
-
240
- await unmount();
241
- });
242
- });