@simba-dev/react-native-media-player 2.0.1 → 3.0.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 (38) 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/src/components/PlayerProvider.tsx +5 -5
  8. package/src/index.ts +25 -12
  9. package/android/src/test/java/com/simba/player/PipActionReceiverTest.kt +0 -123
  10. package/android/src/test/java/com/simba/player/PipManagerTest.kt +0 -281
  11. package/android/src/test/java/com/simba/player/TestApplication.kt +0 -26
  12. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleNullInstanceTest.kt +0 -117
  13. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleTest.kt +0 -212
  14. package/android/src/test/java/com/simba/player/mpv/MpvRenderViewRegistryTest.kt +0 -120
  15. package/android/src/test/java/com/simba/player/mpv/MpvRenderViewTest.kt +0 -249
  16. package/scripts/override_react_methods.js +0 -184
  17. package/scripts/override_react_methods.py +0 -150
  18. package/src/bridge/__tests__/MpvPlayerModule.test.ts +0 -163
  19. package/src/bridge/__tests__/debugMode.test.ts +0 -138
  20. package/src/bridge/__tests__/errorContract.test.ts +0 -175
  21. package/src/bridge/__tests__/loadAndPlay.startPosition.test.tsx +0 -142
  22. package/src/components/PlayerRoot.tsx +0 -124
  23. package/src/components/PlayerSurface.tsx +0 -62
  24. package/src/components/__tests__/PlayerProvider.performance.test.tsx +0 -242
  25. package/src/components/__tests__/PlayerProvider.progressContext.test.tsx +0 -194
  26. package/src/components/__tests__/PlayerProvider.test.tsx +0 -558
  27. package/src/components/__tests__/PlayerRoot.test.tsx +0 -71
  28. package/src/components/__tests__/SimbaVideo.test.tsx +0 -164
  29. package/src/hooks/__tests__/resolveStreamType.test.ts +0 -159
  30. package/src/hooks/__tests__/useLaunchPlayback.test.tsx +0 -278
  31. package/src/hooks/__tests__/useResumeThumbnail.test.ts +0 -154
  32. package/src/stores/__tests__/playerQueueSelectionStore.test.ts +0 -73
  33. package/src/stores/__tests__/playerQueueStore.test.ts +0 -171
  34. package/src/types/__tests__/config.test.ts +0 -188
  35. package/src/types/__tests__/player.pipAnswer.test.tsx +0 -87
  36. package/src/types/__tests__/player.pipArity.test.tsx +0 -74
  37. package/src/types/__tests__/player.test.tsx +0 -1365
  38. package/src/types/__tests__/playerLoading.test.ts +0 -170
@@ -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
- });
@@ -1,194 +0,0 @@
1
- /**
2
- * Regression tests: the PROGRESS context must not lose a field that the
3
- * STATE context already holds.
4
- *
5
- * THE DEFECT (found on device, emulator-5554, 2026-10-20, lib 1.17.0):
6
- *
7
- * mpv delivers `duration` and `time-pos` inside ONE batch, ~3 ms apart
8
- * (measured: `fileLoaded` 19:29:59.615, `time-pos` 19:29:59.616,
9
- * `duration` 19:29:59.619). The provider handled each event with
10
- * `applyPlayerEvent(stateRef.current, progressRef.current, ...)` and then
11
- * wrote the two refs:
12
- *
13
- * - `stateRef.current` was written SYNCHRONOUSLY, in the event handler.
14
- * - `progressRef.current` was written INSIDE the `setProgress` updater,
15
- * which React DEFERS to the render phase.
16
- *
17
- * So the progress ref was one flush behind the state ref. The second event
18
- * of the batch therefore computed its `nextProgress` from a STALE progress
19
- * — one that did not yet contain the duration the first event had just
20
- * delivered — and overwrote it with 0.
21
- *
22
- * MEASURED on device:
23
- *
24
- * state.durationMs = 7673792 (correct)
25
- * progress.durationMs = 0 (WRONG)
26
- *
27
- * The visible damage was a seek bar with no played fill, NO buffered range
28
- * at all (the consumer gates the buffered window on `durationMs > 0`), and
29
- * "--:--" for the remaining time — on a video that was demonstrably
30
- * playing.
31
- *
32
- * These tests pin the fix: the progress ref is written synchronously, in
33
- * lockstep with the state ref.
34
- *
35
- * Test surface:
36
- * - duration survives in the progress context when duration and position
37
- * arrive in one batch (the exact device order)
38
- * - duration survives when the order is reversed
39
- * - duration survives across a longer run of interleaved events
40
- * - the buffered ranges survive the same interleaving
41
- * - the two contexts agree on the duration — the invariant the seek bar
42
- * depends on
43
- *
44
- * The MpvPlayerModule bridge mock is installed globally in
45
- * `jest.setup.ts`; its `getDuration` returns 0, so the hydrated baseline
46
- * duration is 0 and every value asserted here arrives through the EVENT
47
- * path. A test that passed on the hydrated baseline would prove nothing.
48
- */
49
-
50
- import React from 'react';
51
- import { act, renderHook } from '@testing-library/react-native';
52
- import { PlayerProvider } from '../PlayerProvider';
53
- import { usePlayer, usePlayerProgress } from '../../types/player';
54
-
55
- const wrapper = ({ children }: { children: React.ReactNode }) => (
56
- <PlayerProvider>{children}</PlayerProvider>
57
- );
58
-
59
- /**
60
- * Deliver an event through the SAME emitter production uses.
61
- *
62
- * The bridge's `resolveEmitter()` builds a `NativeEventEmitter` over
63
- * `NativeModules.MpvPlayerModule`, and on the native side the events are
64
- * published through `RCTDeviceEventEmitter`. RN's own jest preset mocks
65
- * `DeviceEventEmitter`, and `NativeEventEmitter` delegates to it, so
66
- * emitting there drives the real subscription the provider registered.
67
- */
68
- function emit(eventName: string, payload: Record<string, unknown>): void {
69
- const {
70
- DeviceEventEmitter,
71
- } = require('react-native') as typeof import('react-native');
72
- DeviceEventEmitter.emit(eventName, payload);
73
- }
74
-
75
- /** The real movie length from the device session: 7673.792 seconds. */
76
- const DURATION_S = 7673.792;
77
- const DURATION_MS = 7673792;
78
-
79
- describe('PlayerProvider progress context keeps the duration', () => {
80
- it('keeps the duration when duration and position arrive in ONE batch', async () => {
81
- // The exact device scenario: two events, one batch, duration FIRST.
82
- const { result, unmount } = await renderHook(
83
- () => ({ state: usePlayer().state, progress: usePlayerProgress() }),
84
- { wrapper },
85
- );
86
-
87
- // The hydrated baseline is 0 (the bridge mock's getDuration returns 0),
88
- // so anything asserted below arrived through the event path.
89
- expect(result.current.state.durationMs).toBe(0);
90
- expect(result.current.progress.durationMs).toBe(0);
91
-
92
- await act(async () => {
93
- emit('onDurationChanged', { duration: DURATION_S });
94
- emit('onPositionChanged', { position: 12.5 });
95
- });
96
-
97
- expect(result.current.state.durationMs).toBe(DURATION_MS);
98
- // THE assertion this file exists for. Before the fix this was 0:
99
- // the position event was computed from a stale progress and replaced
100
- // the duration with the stale 0.
101
- expect(result.current.progress.durationMs).toBe(DURATION_MS);
102
- // The position must not be the casualty of the fix.
103
- expect(result.current.progress.positionMs).toBe(12500);
104
-
105
- await unmount();
106
- });
107
-
108
- it('keeps the duration when the position arrives FIRST in the batch', async () => {
109
- // The mirror order. A fix that only special-cased "duration first"
110
- // would pass the test above and fail this one.
111
- const { result, unmount } = await renderHook(
112
- () => ({ state: usePlayer().state, progress: usePlayerProgress() }),
113
- { wrapper },
114
- );
115
-
116
- await act(async () => {
117
- emit('onPositionChanged', { position: 12.5 });
118
- emit('onDurationChanged', { duration: DURATION_S });
119
- });
120
-
121
- expect(result.current.progress.durationMs).toBe(DURATION_MS);
122
- expect(result.current.progress.positionMs).toBe(12500);
123
-
124
- await unmount();
125
- });
126
-
127
- it('keeps the duration across a long run of interleaved events', async () => {
128
- // The real event stream is not two events: mpv keeps sending
129
- // `time-pos` for the whole session. Every one of them used to carry a
130
- // stale duration into the progress context.
131
- const { result, unmount } = await renderHook(
132
- () => ({ state: usePlayer().state, progress: usePlayerProgress() }),
133
- { wrapper },
134
- );
135
-
136
- await act(async () => {
137
- emit('onDurationChanged', { duration: DURATION_S });
138
- for (let i = 1; i <= 25; i++) {
139
- emit('onPositionChanged', { position: i * 0.5 });
140
- }
141
- });
142
-
143
- expect(result.current.progress.durationMs).toBe(DURATION_MS);
144
- expect(result.current.progress.positionMs).toBe(12500);
145
-
146
- await unmount();
147
- });
148
-
149
- it('keeps the buffered ranges through the same interleaving', async () => {
150
- // The buffered ranges are the other half of the damage: the consumer
151
- // gates the buffered window on `durationMs > 0`, so a lost duration
152
- // silently removed the buffered indicator from the seek bar.
153
- const { result, unmount } = await renderHook(
154
- () => ({ state: usePlayer().state, progress: usePlayerProgress() }),
155
- { wrapper },
156
- );
157
-
158
- await act(async () => {
159
- emit('onDurationChanged', { duration: DURATION_S });
160
- emit('onCacheState', { ranges: [{ start: 0, end: 130713.917 }] });
161
- emit('onPositionChanged', { position: 12.5 });
162
- });
163
-
164
- expect(result.current.progress.durationMs).toBe(DURATION_MS);
165
- expect(result.current.progress.cacheRanges).toEqual([
166
- { start: 0, end: 130713.917 },
167
- ]);
168
-
169
- await unmount();
170
- });
171
-
172
- it('keeps the state context and the progress context in agreement', async () => {
173
- // The invariant the seek bar depends on: it reads the duration from
174
- // the progress context and the play state from the state context, so
175
- // the two must never disagree about the length of the file.
176
- const { result, unmount } = await renderHook(
177
- () => ({ state: usePlayer().state, progress: usePlayerProgress() }),
178
- { wrapper },
179
- );
180
-
181
- await act(async () => {
182
- emit('onDurationChanged', { duration: DURATION_S });
183
- emit('onPositionChanged', { position: 12.5 });
184
- emit('onCacheState', { ranges: [{ start: 0, end: 130713.917 }] });
185
- });
186
-
187
- expect(result.current.progress.durationMs).toBe(
188
- result.current.state.durationMs,
189
- );
190
- expect(result.current.progress.durationMs).toBe(DURATION_MS);
191
-
192
- await unmount();
193
- });
194
- });