@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,1365 +0,0 @@
1
- /**
2
- * Unit tests for `src/types/player.ts` — the player state/commands API.
3
- *
4
- * V13 Phase 51: the surface expanded from 4/2/6 to 20/7/38. The
5
- * tests pin the documented baseline (via `EXPECTED_DEFAULT_STATE`)
6
- * and verify the contract that matters for consumers:
7
- * - `usePlayer()` outside a provider returns the default state
8
- * (no throw — a consumer's controls must be able to render anywhere)
9
- * - `usePlayer()` inside a provider returns the live state
10
- * - `usePlayer()` returns stable command references across renders
11
- * - `commands.<method>` delegates to the native bridge
12
- * - `usePlayerProgress()` returns the documented initial progress
13
- * - The 1Hz-pollable progress hook is separate from the full state
14
- *
15
- * The MpvPlayerModule bridge mock is installed globally in
16
- * `jest.setup.ts` (it extends the @react-native/jest-preset's own
17
- * `NativeModules` mock rather than overriding it).
18
- */
19
-
20
- import React from 'react';
21
- import { NativeModules } from 'react-native';
22
- import { act, renderHook } from '@testing-library/react-native';
23
- import {
24
- usePlayer,
25
- usePlayerProgress,
26
- toMpvPropertyString,
27
- DEFAULT_PROGRESS,
28
- DEFAULT_STATE,
29
- type PlayerState,
30
- type PlayerProgress,
31
- } from '../player';
32
- import { PlayerProvider } from '../../components/PlayerProvider';
33
- import * as BridgeModule from '../../bridge/MpvPlayerModule';
34
-
35
- // The default state is module-public (DEFAULT_STATE), so we import it
36
- // directly. Pin the import here so a refactor that moves the default
37
- // out of this module would surface as a TypeScript error at the
38
- // import site — not as a silent test failure.
39
-
40
- // ── Helpers ────────────────────────────────────────────────────────────────
41
-
42
- /** Clear all bridge mock call counts between tests. */
43
- function clearBridgeMocks() {
44
- for (const key of Object.keys(NativeModules.MpvPlayerModule)) {
45
- const fn = (NativeModules.MpvPlayerModule as Record<string, jest.Mock>)[key];
46
- if (typeof fn?.mockClear === 'function') {
47
- fn.mockClear();
48
- }
49
- }
50
- }
51
-
52
- /**
53
- * Install a `subscribePlayerEvent` mock that captures every
54
- * registered handler so the test can fire events directly. Also
55
- * mocks `removeAllListeners` to a no-op (the captured handlers
56
- * are cleaned up in the `restoreSubscribes()` helper).
57
- */
58
- function captureSubscribes(): {
59
- handlers: Map<string, Array<(payload: unknown) => void>>;
60
- restore: () => void;
61
- } {
62
- const handlers = new Map<string, Array<(payload: unknown) => void>>();
63
- const subSpy = jest
64
- .spyOn(BridgeModule, 'subscribePlayerEvent')
65
- .mockImplementation(
66
- (
67
- event: string,
68
- handler: (payload: unknown) => void,
69
- ): (() => void) => {
70
- if (!handlers.has(event)) handlers.set(event, []);
71
- handlers.get(event)!.push(handler);
72
- return () => {
73
- // No-op unsubscribe for tests; captured handlers live
74
- // for the lifetime of the test.
75
- };
76
- },
77
- );
78
- const removeSpy = jest
79
- .spyOn(BridgeModule, 'removeAllListeners')
80
- .mockImplementation(() => {
81
- // No-op for tests.
82
- });
83
- return {
84
- handlers,
85
- restore: () => {
86
- subSpy.mockRestore();
87
- removeSpy.mockRestore();
88
- },
89
- };
90
- }
91
-
92
- // ── usePlayer (no provider) ────────────────────────────────────────────────
93
-
94
- describe('usePlayer (no provider)', () => {
95
- beforeEach(() => {
96
- clearBridgeMocks();
97
- });
98
-
99
- it('returns the documented default state', async () => {
100
- // Outside a <PlayerProvider>, usePlayer must NOT throw — it
101
- // returns DEFAULT_STATE so a consumer's controls can render in any
102
- // environment (jest, web preview, Storybook).
103
- const { result } = await renderHook(() => usePlayer());
104
- expect(result.current.state).toEqual(DEFAULT_STATE);
105
- });
106
-
107
- it('returns the expected V12 fields at their baseline', async () => {
108
- // Pin the V12 contract: isPlaying=false, title='Simba Player',
109
- // artist='', album=''. A refactor that changes the baseline
110
- // would silently break every consumer's controls.
111
- const { result } = await renderHook(() => usePlayer());
112
- const s = result.current.state;
113
- expect(s.isPlaying).toBe(false);
114
- expect(s.title).toBe('Simba Player');
115
- expect(s.artist).toBe('');
116
- expect(s.album).toBe('');
117
- });
118
-
119
- it('returns the V13 expanded fields at their baseline', async () => {
120
- // Pin the V13 expansion: numeric fields at 0, booleans at false,
121
- // collection fields empty, currentChapter / videoParams / error
122
- // at null.
123
- const { result } = await renderHook(() => usePlayer());
124
- const s = result.current.state;
125
- expect(s.positionMs).toBe(0);
126
- expect(s.durationMs).toBe(0);
127
- expect(s.isBuffering).toBe(false);
128
- expect(s.isSeeking).toBe(false);
129
- expect(s.seekable).toBe(false);
130
- expect(s.volume).toBe(100);
131
- expect(s.isMuted).toBe(false);
132
- expect(s.speed).toBe(1);
133
- expect(s.loopMode).toBe('none');
134
- expect(s.playlist).toEqual([]);
135
- expect(s.currentIndex).toBe(-1);
136
- expect(s.tracks).toEqual([]);
137
- expect(s.chapters).toEqual([]);
138
- expect(s.currentChapter).toBeNull();
139
- expect(s.videoParams).toBeNull();
140
- expect(s.error).toBeNull();
141
- // V22.0.0 / 1.6.0 additions
142
- expect(s.shuffle).toBe(false);
143
- });
144
-
145
- it('exposes the V12 commands object', async () => {
146
- // The five V12 methods remain on the new commands object —
147
- // Consumer controls depend on them.
148
- const { result } = await renderHook(() => usePlayer());
149
- expect(typeof result.current.commands.play).toBe('function');
150
- expect(typeof result.current.commands.pause).toBe('function');
151
- expect(typeof result.current.commands.seek).toBe('function');
152
- expect(typeof result.current.commands.skipBackward).toBe('function');
153
- expect(typeof result.current.commands.skipForward).toBe('function');
154
- });
155
-
156
- it('exposes the V13 expanded commands object', async () => {
157
- // Spot-check the new commands. (We don't enumerate every method —
158
- // that would be a redundant duplication of the interface itself.)
159
- const { result } = await renderHook(() => usePlayer());
160
- const c = result.current.commands;
161
- expect(typeof c.togglePlayPause).toBe('function');
162
- expect(typeof c.stop).toBe('function');
163
- expect(typeof c.seekBy).toBe('function');
164
- expect(typeof c.next).toBe('function');
165
- expect(typeof c.previous).toBe('function');
166
- expect(typeof c.setVolume).toBe('function');
167
- expect(typeof c.setMuted).toBe('function');
168
- expect(typeof c.toggleMute).toBe('function');
169
- expect(typeof c.setSpeed).toBe('function');
170
- expect(typeof c.setLoopMode).toBe('function');
171
- expect(typeof c.loadFile).toBe('function');
172
- expect(typeof c.loadPlaylist).toBe('function');
173
- expect(typeof c.playlistRemove).toBe('function');
174
- expect(typeof c.shuffle).toBe('function');
175
- expect(typeof c.clear).toBe('function');
176
- // `stopPlayback` is the FULL teardown (engine + foreground service).
177
- // It must exist alongside `stop`, which only halts the engine and
178
- // leaves the session and notification alive. Video's back button
179
- // needs the full one: `exitPipAndFinish()` finishes the Activity, and
180
- // the process-global engine would otherwise keep playing behind a
181
- // closed window.
182
- expect(typeof c.stopPlayback).toBe('function');
183
- // The old lane-specific name must NOT survive — a consumer reaching
184
- // for it would silently get undefined and skip the teardown.
185
- expect((c as unknown as Record<string, unknown>).stopAudioPlayback).toBeUndefined();
186
- expect(typeof c.cycleTrack).toBe('function');
187
- expect(typeof c.setTrack).toBe('function');
188
- expect(typeof c.enterPip).toBe('function');
189
- expect(typeof c.exitPip).toBe('function');
190
- expect(typeof c.exitPipAndFinish).toBe('function');
191
- expect(typeof c.setKeepScreenOn).toBe('function');
192
- expect(typeof c.setOrientation).toBe('function');
193
- expect(typeof c.setImmersive).toBe('function');
194
- expect(typeof c.setScreenBrightness).toBe('function');
195
- expect(typeof c.requestNotificationPermission).toBe('function');
196
- expect(typeof c.openPlayer).toBe('function');
197
- // V21 F5: `getLaunchParams` is gone. It read a one-shot native queue
198
- // that only the deleted Activity ever filled, so it would have
199
- // resolved `null` forever.
200
- expect((c as Record<string, unknown>).getLaunchParams).toBeUndefined();
201
- expect(typeof c.getProperty).toBe('function');
202
- expect(typeof c.setProperty).toBe('function');
203
- expect(typeof c.observeProperty).toBe('function');
204
- expect(typeof c.unobserveProperty).toBe('function');
205
- expect(typeof c.grantPersistablePermission).toBe('function');
206
- expect(typeof c.verifyContentUri).toBe('function');
207
- // V22.0.0 / 1.6.0 additions
208
- expect(typeof c.getScreenBrightness).toBe('function');
209
- expect(typeof c.setAudioFilter).toBe('function');
210
- expect(typeof c.setVideoFilter).toBe('function');
211
- expect(typeof c.setShuffle).toBe('function');
212
- });
213
-
214
- it('commands.play delegates to the native bridge', async () => {
215
- const { result } = await renderHook(() => usePlayer());
216
- await result.current.commands.play();
217
- expect(NativeModules.MpvPlayerModule.play).toHaveBeenCalledTimes(1);
218
- });
219
-
220
- it('commands.pause delegates to the native bridge', async () => {
221
- const { result } = await renderHook(() => usePlayer());
222
- await result.current.commands.pause();
223
- expect(NativeModules.MpvPlayerModule.pause).toHaveBeenCalledTimes(1);
224
- });
225
-
226
- it('commands.seek(ms) calls seekAbsolute on the bridge', async () => {
227
- // V12 wiring: commands.seek() translates to
228
- // bridge.seekAbsolute(positionSec) — seconds vs ms.
229
- const { result } = await renderHook(() => usePlayer());
230
- await result.current.commands.seek(10000); // 10s in ms
231
- expect(NativeModules.MpvPlayerModule.seekAbsolute).toHaveBeenCalledWith(10);
232
- });
233
-
234
- it('commands.seek accepts zero', async () => {
235
- const { result } = await renderHook(() => usePlayer());
236
- expect(() => result.current.commands.seek(0)).not.toThrow();
237
- expect(NativeModules.MpvPlayerModule.seekAbsolute).toHaveBeenCalledWith(0);
238
- });
239
-
240
- it('commands.skipForward(seconds) calls seekForward on bridge', async () => {
241
- const { result } = await renderHook(() => usePlayer());
242
- await result.current.commands.skipForward(15);
243
- expect(NativeModules.MpvPlayerModule.seekForward).toHaveBeenCalledWith(15);
244
- });
245
-
246
- it('commands.skipBackward(seconds) calls seekBackward on bridge', async () => {
247
- const { result } = await renderHook(() => usePlayer());
248
- await result.current.commands.skipBackward(10);
249
- expect(NativeModules.MpvPlayerModule.seekBackward).toHaveBeenCalledWith(10);
250
- });
251
-
252
- it('commands.seekBy(+ms) calls seekForward with the absolute seconds', async () => {
253
- const { result } = await renderHook(() => usePlayer());
254
- await result.current.commands.seekBy(5000); // +5s
255
- expect(NativeModules.MpvPlayerModule.seekForward).toHaveBeenCalledWith(5);
256
- });
257
-
258
- it('commands.seekBy(-ms) calls seekBackward with the absolute seconds', async () => {
259
- const { result } = await renderHook(() => usePlayer());
260
- await result.current.commands.seekBy(-3000); // -3s
261
- expect(NativeModules.MpvPlayerModule.seekBackward).toHaveBeenCalledWith(3);
262
- });
263
-
264
- it('commands.openPlayer sends audio to the foreground service, not a window', async () => {
265
- const { result } = await renderHook(() => usePlayer());
266
- await result.current.commands.openPlayer({
267
- uri: 'file:///song.mp3',
268
- title: 'Song',
269
- type: 'audio',
270
- startPositionMs: 12345,
271
- });
272
- expect(NativeModules.MpvPlayerModule.startAudioPlayback).toHaveBeenCalledWith({
273
- uri: 'file:///song.mp3',
274
- title: 'Song',
275
- startPositionMs: 12345,
276
- autoPlay: true,
277
- });
278
- // Video never touches the service, and nothing starts an Activity.
279
- expect(NativeModules.MpvPlayerModule.loadFile).not.toHaveBeenCalled();
280
- });
281
-
282
- // V21 F5: video used to be handed to a dedicated Activity via
283
- // `startActivity`. It now loads into the surface the consumer already
284
- // mounted. These two tests pin the halves of that that matter.
285
- it('commands.openPlayer loads video into the mounted surface', async () => {
286
- NativeModules.MpvPlayerModule.isSurfaceMounted.mockReturnValue(true);
287
- const { result } = await renderHook(() => usePlayer());
288
- const ok = await result.current.commands.openPlayer({
289
- uri: 'file:///film.mp4',
290
- title: 'Film',
291
- type: 'video',
292
- startPositionMs: 5000,
293
- });
294
- expect(ok).toBe(true);
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.
303
- expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
304
- 'force-media-title',
305
- 'Film',
306
- );
307
- expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
308
- 'options/start',
309
- '5.000',
310
- );
311
- expect(NativeModules.MpvPlayerModule.loadFile).toHaveBeenCalledWith(
312
- 'file:///film.mp4',
313
- );
314
- expect(NativeModules.MpvPlayerModule.seekAbsolute).not.toHaveBeenCalled();
315
- expect(NativeModules.MpvPlayerModule.play).toHaveBeenCalled();
316
- });
317
-
318
- // "Must not" test: loading into a surface that does not exist starts
319
- // audio the user cannot see and reports success. Faithful mutant =
320
- // delete the `isSurfaceMounted()` guard.
321
- it('commands.openPlayer REFUSES video when no surface is mounted', async () => {
322
- NativeModules.MpvPlayerModule.isSurfaceMounted.mockReturnValue(false);
323
- const { result } = await renderHook(() => usePlayer());
324
- const ok = await result.current.commands.openPlayer({
325
- uri: 'file:///film.mp4',
326
- title: 'Film',
327
- type: 'video',
328
- });
329
- expect(ok).toBe(false);
330
- expect(NativeModules.MpvPlayerModule.loadFile).not.toHaveBeenCalled();
331
- expect(NativeModules.MpvPlayerModule.play).not.toHaveBeenCalled();
332
- });
333
-
334
- // V22.0.0 / 1.6.0 additions — surface-widening for the V19 vertical-swipe
335
- // chrome (brightness pill) + mpv filter toggle hooks + readback of
336
- // `playlist-shuffle` via the existing `setProperty` plumbing.
337
- it('commands.getScreenBrightness delegates to the bridge', async () => {
338
- const { result } = await renderHook(() => usePlayer());
339
- const brightness = result.current.commands.getScreenBrightness();
340
- expect(NativeModules.MpvPlayerModule.getScreenBrightness).toHaveBeenCalledTimes(1);
341
- // Mock returns 1.0 (the no-op fallback default).
342
- expect(brightness).toBe(1.0);
343
- });
344
-
345
- it('commands.setAudioFilter(filter, enabled) forwards both args to the bridge', async () => {
346
- const { result } = await renderHook(() => usePlayer());
347
- result.current.commands.setAudioFilter('scaletempo2=max-speed=32.0', true);
348
- expect(NativeModules.MpvPlayerModule.setAudioFilter).toHaveBeenCalledWith(
349
- 'scaletempo2=max-speed=32.0',
350
- true,
351
- );
352
- });
353
-
354
- it('commands.setVideoFilter(filter, enabled) forwards both args to the bridge', async () => {
355
- const { result } = await renderHook(() => usePlayer());
356
- result.current.commands.setVideoFilter('scale=720:trunc(ow/a/2)*2', true);
357
- expect(NativeModules.MpvPlayerModule.setVideoFilter).toHaveBeenCalledWith(
358
- 'scale=720:trunc(ow/a/2)*2',
359
- true,
360
- );
361
- });
362
-
363
- it('commands.setShuffle(enabled) routes through bridge.setProperty("playlist-shuffle", …)', async () => {
364
- // `setShuffle` is a thin wrapper over the existing `setProperty`
365
- // plumbing — the bridge has no dedicated `setShuffle` method.
366
- //
367
- // The encoded value is '1' rather than `true`: `playlist-shuffle` is
368
- // an mpv *integer* option, so a boolean cannot be sent even once
369
- // stringified ("true" is not a value mpv's int parser accepts).
370
- const { result } = await renderHook(() => usePlayer());
371
- result.current.commands.setShuffle(true);
372
- expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
373
- 'playlist-shuffle',
374
- '1',
375
- );
376
- });
377
-
378
- it('returns stable command references across renders', async () => {
379
- // Spec §Phase 34.5: stable command references let a consumer's
380
- // controls memo their handlers. The V13 commands object is a module-scope
381
- // singleton, so the reference is identical for every render.
382
- const { result, rerender } = await renderHook(() => usePlayer());
383
- const firstCommands = result.current.commands;
384
- await rerender({});
385
- expect(result.current.commands).toBe(firstCommands);
386
- });
387
-
388
- it('returns stable state reference when re-rendered with the same provider state', async () => {
389
- // Outside a provider, usePlayer returns DEFAULT_STATE every time.
390
- // The reference should be stable (same object identity) so
391
- // downstream consumers can memoise on it.
392
- const { result, rerender } = await renderHook(() => usePlayer());
393
- const firstState = result.current.state;
394
- await rerender({});
395
- expect(result.current.state).toBe(firstState);
396
- });
397
- });
398
-
399
- // ── usePlayer (inside provider) ────────────────────────────────────────────
400
-
401
- describe('usePlayer (inside PlayerProvider)', () => {
402
- let subs: ReturnType<typeof captureSubscribes>;
403
-
404
- beforeEach(() => {
405
- clearBridgeMocks();
406
- subs = captureSubscribes();
407
- });
408
-
409
- afterEach(() => {
410
- subs.restore();
411
- });
412
-
413
- it('returns the state from the provider context', async () => {
414
- // The provider's mount effect hydrates state from the bridge
415
- // (synchronous getters); the jest mock returns 0/0/'idle'/
416
- // 100/false/1/'none'/'[]'/null — so the post-hydration state
417
- // is just DEFAULT_STATE with `title` and `loopMode` re-derived
418
- // from the bridge.
419
- const wrapper = ({ children }: { children: React.ReactNode }) => (
420
- <PlayerProvider>{children}</PlayerProvider>
421
- );
422
- const { result } = await renderHook(() => usePlayer(), { wrapper });
423
- // The bridge mock returns '' for getProperty, so title stays at
424
- // DEFAULT_STATE.title. Position/duration at 0. isPlaying false.
425
- expect(result.current.state.isPlaying).toBe(false);
426
- expect(result.current.state.positionMs).toBe(0);
427
- expect(result.current.state.durationMs).toBe(0);
428
- });
429
-
430
- it('subscribes to all 22 mpv events on mount', async () => {
431
- const wrapper = ({ children }: { children: React.ReactNode }) => (
432
- <PlayerProvider>{children}</PlayerProvider>
433
- );
434
- await renderHook(() => usePlayer(), { wrapper });
435
- // Every PlayerEventName should have at least one captured handler.
436
- const expectedEvents = [
437
- 'onFileLoaded',
438
- 'onPlaybackStateChanged',
439
- 'onPositionChanged',
440
- 'onDurationChanged',
441
- 'onPropertyChanged',
442
- 'onTracksChanged',
443
- 'onChapterChanged',
444
- 'onVideoParamsChanged',
445
- 'onError',
446
- 'onBuffering',
447
- 'onCacheFill',
448
- 'onCacheState',
449
- 'onSeekable',
450
- 'onSeeking',
451
- 'onEndFile',
452
- 'onPlaybackRestart',
453
- 'onEndReached',
454
- 'onAudioDeviceChanged',
455
- 'onVolumeChanged',
456
- 'onSpeedChanged',
457
- 'videoReconfig',
458
- 'onPipModeChanged',
459
- 'onPipPlayPause',
460
- 'onPipExpand',
461
- 'onPipClose',
462
- ];
463
- for (const event of expectedEvents) {
464
- expect(subs.handlers.get(event)?.length ?? 0).toBeGreaterThan(0);
465
- }
466
- });
467
-
468
- it('updates state when an onPlaybackStateChanged event fires', async () => {
469
- // Mount the provider, then call the onPlaybackStateChanged
470
- // handler directly. The provider's event subscription should
471
- // dispatch through applyPlayerEvent and update the state.
472
- const wrapper = ({ children }: { children: React.ReactNode }) => (
473
- <PlayerProvider>{children}</PlayerProvider>
474
- );
475
- const { result } = await renderHook(() => usePlayer(), { wrapper });
476
- const listeners = subs.handlers.get('onPlaybackStateChanged') ?? [];
477
- expect(listeners.length).toBeGreaterThan(0);
478
- // Fire the event with a "playing" payload.
479
- await act(async () => {
480
- for (const l of listeners) {
481
- l({ state: 'playing' });
482
- }
483
- });
484
- expect(result.current.state.isPlaying).toBe(true);
485
- });
486
-
487
- // ── The buffering contract: one fact, one owner ────────────────────────
488
- //
489
- // Three mpv properties, three facts, and they were tangled into two
490
- // events with contradictory rules:
491
- //
492
- // `paused-for-cache` -> is the player STALLED? (a boolean)
493
- // `cache-buffering-state` -> how full is the cache? (a percentage)
494
- // `demuxer-cache-state` -> what is the TIMELINE? (ranges)
495
- //
496
- // `cache-buffering-state` used to write `isBuffering` as
497
- // "percent < 100", which is true for most of a stream's life — a
498
- // partially-filled cache is the NORMAL state during playback — so the
499
- // spinner could latch on during perfectly healthy playback. And
500
- // `paused-for-cache` invented a percentage (0 when stalled, 100 when
501
- // not) that overwrote the real fill with a fabricated number.
502
- //
503
- // Each fact now has exactly one owner, and each event touches exactly
504
- // one field. These tests are what keeps it that way.
505
- describe('the buffering contract', () => {
506
- let subs: ReturnType<typeof captureSubscribes>;
507
-
508
- beforeEach(() => {
509
- clearBridgeMocks();
510
- subs = captureSubscribes();
511
- });
512
-
513
- afterEach(() => {
514
- subs.restore();
515
- });
516
-
517
- const wrapper = ({ children }: { children: React.ReactNode }) => (
518
- <PlayerProvider>{children}</PlayerProvider>
519
- );
520
-
521
- async function fire(event: string, payload: Record<string, unknown>) {
522
- const listeners = subs.handlers.get(event) ?? [];
523
- expect(listeners.length).toBeGreaterThan(0);
524
- await act(async () => {
525
- for (const l of listeners) l(payload);
526
- });
527
- }
528
-
529
- it('onBuffering sets the stall flag and nothing else', async () => {
530
- const { result } = await renderHook(() => usePlayerProgress(), {
531
- wrapper,
532
- });
533
-
534
- await fire('onBuffering', { isBuffering: true });
535
-
536
- expect(result.current.isBuffering).toBe(true);
537
- // The stall signal does not know the fill, so it must not invent
538
- // one. It used to write 0/100, which destroyed the real fill.
539
- expect(result.current.cacheFill).toBe(0);
540
- });
541
-
542
- it('onBuffering clears the stall flag when the stall ends', async () => {
543
- const { result } = await renderHook(() => usePlayerProgress(), {
544
- wrapper,
545
- });
546
-
547
- await fire('onBuffering', { isBuffering: true });
548
- expect(result.current.isBuffering).toBe(true);
549
-
550
- // The `false` case is the one that matters: `paused-for-cache` goes
551
- // false the moment the cache recovers, and a consumer that cannot see
552
- // that transition keeps a spinner on a player that is running.
553
- await fire('onBuffering', { isBuffering: false });
554
- expect(result.current.isBuffering).toBe(false);
555
- });
556
-
557
- it('onCacheFill sets the fill and never the stall flag', async () => {
558
- const { result } = await renderHook(() => usePlayerProgress(), {
559
- wrapper,
560
- });
561
-
562
- await fire('onCacheFill', { percent: 37 });
563
-
564
- expect(result.current.cacheFill).toBe(37);
565
- // A partially-filled cache is the NORMAL state during playback. It
566
- // is not a stall, and reading it as one pinned the spinner on.
567
- expect(result.current.isBuffering).toBe(false);
568
- });
569
-
570
- it('onCacheState sets the buffered ranges and never the fill', async () => {
571
- const { result } = await renderHook(() => usePlayerProgress(), {
572
- wrapper,
573
- });
574
-
575
- // The ranges arrive in MILLISECONDS: the native bridge converts,
576
- // because it is the only layer that knows the payload's unit.
577
- await fire('onCacheState', { ranges: [{ start: 0, end: 60000 }] });
578
-
579
- expect(result.current.cacheRanges).toEqual([{ start: 0, end: 60000 }]);
580
- expect(result.current.cacheFill).toBe(0);
581
- });
582
-
583
- it('onCacheState keeps the last known ranges when the payload carries none', async () => {
584
- const { result } = await renderHook(() => usePlayerProgress(), {
585
- wrapper,
586
- });
587
-
588
- await fire('onCacheState', { ranges: [{ start: 0, end: 60000 }] });
589
- await fire('onCacheState', {});
590
-
591
- expect(result.current.cacheRanges).toEqual([{ start: 0, end: 60000 }]);
592
- });
593
-
594
- it('onCacheState with an explicit empty array clears the ranges', async () => {
595
- const { result } = await renderHook(() => usePlayerProgress(), {
596
- wrapper,
597
- });
598
-
599
- await fire('onCacheState', { ranges: [{ start: 0, end: 60000 }] });
600
- await fire('onCacheState', { ranges: [] });
601
-
602
- // mpv saying "the cache is empty" is different from saying nothing,
603
- // and the difference is the difference between an honest bar and a
604
- // stale one.
605
- expect(result.current.cacheRanges).toEqual([]);
606
- });
607
- });
608
-
609
- // ── The mute flag arrives as a STRING ─────────────────────────────────
610
- //
611
- // `applyPlayerEvent`'s `mute` case used to be
612
- // `isMuted: Boolean(value)`. mpv serialises MPV_FORMAT_FLAG to the
613
- // JSON literals `true` / `false`, which reach JS as the STRINGS
614
- // `"true"` / `"false"`. Every non-empty string is truthy, so
615
- // `Boolean("false") === true` and the state was INVERTED on every
616
- // mute event.
617
- //
618
- // Measured on device (emulator-5554, SIMBA W8.3 + lib 1.9.1): native
619
- // logged `name=mute value=false`, the bridge dispatched `value=false`,
620
- // and the transport still rendered "Unmute" on an audible player.
621
- //
622
- // These tests drive the REAL event path through the provider, so they
623
- // cover the reducer as well as the wiring.
624
-
625
- it('reads the mute flag string "false" as FALSE, not as truthy', async () => {
626
- const wrapper = ({ children }: { children: React.ReactNode }) => (
627
- <PlayerProvider>{children}</PlayerProvider>
628
- );
629
- const { result } = await renderHook(() => usePlayer(), { wrapper });
630
-
631
- const listeners = subs.handlers.get('onPropertyChanged') ?? [];
632
- expect(listeners.length).toBeGreaterThan(0);
633
-
634
- await act(async () => {
635
- for (const l of listeners) {
636
- l({property: 'mute', value: 'false'});
637
- }
638
- });
639
-
640
- // The default is already false, so this is the state that a
641
- // `Boolean()` coercion would have flipped.
642
- expect(result.current.state.isMuted).toBe(false);
643
- });
644
-
645
- it('reads the mute flag string "true" as TRUE', async () => {
646
- const wrapper = ({ children }: { children: React.ReactNode }) => (
647
- <PlayerProvider>{children}</PlayerProvider>
648
- );
649
- const { result } = await renderHook(() => usePlayer(), { wrapper });
650
-
651
- const listeners = subs.handlers.get('onPropertyChanged') ?? [];
652
- await act(async () => {
653
- for (const l of listeners) {
654
- l({property: 'mute', value: 'true'});
655
- }
656
- });
657
-
658
- expect(result.current.state.isMuted).toBe(true);
659
- });
660
-
661
- it('also accepts a real boolean mute flag', async () => {
662
- // `getMuted()` on the bridge returns an actual boolean while the
663
- // event payload is a string. Both feed the same field, so both must
664
- // parse.
665
- const wrapper = ({ children }: { children: React.ReactNode }) => (
666
- <PlayerProvider>{children}</PlayerProvider>
667
- );
668
- const { result } = await renderHook(() => usePlayer(), { wrapper });
669
-
670
- const listeners = subs.handlers.get('onPropertyChanged') ?? [];
671
- await act(async () => {
672
- for (const l of listeners) {
673
- l({property: 'mute', value: true});
674
- }
675
- });
676
- expect(result.current.state.isMuted).toBe(true);
677
-
678
- await act(async () => {
679
- for (const l of listeners) {
680
- l({property: 'mute', value: false});
681
- }
682
- });
683
- expect(result.current.state.isMuted).toBe(false);
684
- });
685
-
686
- it('leaves the mute state alone for an unreadable flag value', async () => {
687
- // `"null"` is what the bridge returns for an unavailable property
688
- // and `""` comes from the NOOP bridge. Neither is a boolean, and
689
- // coercing them would report a state the player is not in — the
690
- // same rule the `seekable` level seed follows.
691
- const wrapper = ({ children }: { children: React.ReactNode }) => (
692
- <PlayerProvider>{children}</PlayerProvider>
693
- );
694
- const { result } = await renderHook(() => usePlayer(), { wrapper });
695
-
696
- const listeners = subs.handlers.get('onPropertyChanged') ?? [];
697
- await act(async () => {
698
- for (const l of listeners) {
699
- l({property: 'mute', value: 'true'});
700
- }
701
- });
702
- expect(result.current.state.isMuted).toBe(true);
703
-
704
- await act(async () => {
705
- for (const l of listeners) {
706
- l({property: 'mute', value: 'null'});
707
- }
708
- });
709
- // Still muted — an unreadable value must not silently unmute.
710
- expect(result.current.state.isMuted).toBe(true);
711
- });
712
-
713
- it('updates state when an onError event fires', async () => {
714
- const wrapper = ({ children }: { children: React.ReactNode }) => (
715
- <PlayerProvider>{children}</PlayerProvider>
716
- );
717
- const { result } = await renderHook(() => usePlayer(), { wrapper });
718
- const listeners = subs.handlers.get('onError') ?? [];
719
- expect(listeners.length).toBeGreaterThan(0);
720
- await act(async () => {
721
- for (const l of listeners) {
722
- l({ code: 42, recoverable: true, message: 'test error' });
723
- }
724
- });
725
- expect(result.current.state.error).toEqual({
726
- code: 42,
727
- recoverable: true,
728
- message: 'test error',
729
- });
730
- });
731
-
732
- it('updates state when an onFileLoaded event fires', async () => {
733
- const wrapper = ({ children }: { children: React.ReactNode }) => (
734
- <PlayerProvider>{children}</PlayerProvider>
735
- );
736
- const { result } = await renderHook(() => usePlayer(), { wrapper });
737
- const listeners = subs.handlers.get('onFileLoaded') ?? [];
738
- expect(listeners.length).toBeGreaterThan(0);
739
- await act(async () => {
740
- for (const l of listeners) {
741
- l({
742
- file: { path: '/song.mp3', title: 'New Title', duration: 120 },
743
- });
744
- }
745
- });
746
- expect(result.current.state.title).toBe('New Title');
747
- expect(result.current.state.durationMs).toBe(120000);
748
- expect(result.current.state.isPlaying).toBe(true);
749
- expect(result.current.state.positionMs).toBe(0);
750
- });
751
- });
752
-
753
- // ── usePlayerProgress ──────────────────────────────────────────────────────
754
-
755
- describe('usePlayerProgress', () => {
756
- it('returns the documented default progress outside a provider', async () => {
757
- const { result } = await renderHook(() => usePlayerProgress());
758
- expect(result.current).toEqual(DEFAULT_PROGRESS);
759
- });
760
-
761
- it('returns the expected V12 fields at their baseline', async () => {
762
- const { result } = await renderHook(() => usePlayerProgress());
763
- expect(result.current.positionMs).toBe(0);
764
- expect(result.current.durationMs).toBe(0);
765
- });
766
-
767
- it('returns the V13 expanded fields at their baseline', async () => {
768
- const { result } = await renderHook(() => usePlayerProgress());
769
- expect(result.current.isBuffering).toBe(false);
770
- expect(result.current.isSeeking).toBe(false);
771
- expect(result.current.seekable).toBe(false);
772
- expect(result.current.cacheRanges).toEqual([]);
773
- expect(result.current.cacheFill).toBe(0);
774
- });
775
-
776
- it('returns the full DEFAULT_PROGRESS shape', async () => {
777
- // Pin the contract: usePlayerProgress returns all 7 fields, not
778
- // just 2. The V12 surface is a strict subset.
779
- const expected: PlayerProgress = {
780
- positionMs: 0,
781
- durationMs: 0,
782
- isBuffering: false,
783
- isSeeking: false,
784
- seekable: false,
785
- cacheRanges: [],
786
- cacheFill: 0,
787
- };
788
- const { result } = await renderHook(() => usePlayerProgress());
789
- expect(result.current).toEqual(expected);
790
- });
791
- });
792
-
793
- // ── PlayerState default integrity ───────────────────────────────────────────
794
-
795
- describe('PlayerState default integrity', () => {
796
- it('PlayerState has 22 fields in DEFAULT_STATE', async () => {
797
- // Sanity check: V13 expanded the V12 4-field state to 20 fields.
798
- // V22.0.0 / 1.6.0 added `shuffle`, bringing it to 21.
799
- // v1.17.0 added `isLoading` — the "a load is in flight" fact — 22.
800
- // If a future refactor accidentally drops a field (e.g. by
801
- // using `Partial<PlayerState>` somewhere), this catches it.
802
- const keys = Object.keys(DEFAULT_STATE).sort();
803
- expect(keys).toEqual([
804
- 'album',
805
- 'artist',
806
- 'chapters',
807
- 'currentChapter',
808
- 'currentIndex',
809
- 'durationMs',
810
- 'error',
811
- 'isBuffering',
812
- 'isLoading',
813
- 'isMuted',
814
- 'isPlaying',
815
- 'isSeeking',
816
- 'loopMode',
817
- 'playlist',
818
- 'positionMs',
819
- 'seekable',
820
- 'shuffle',
821
- 'speed',
822
- 'title',
823
- 'tracks',
824
- 'videoParams',
825
- 'volume',
826
- ]);
827
- });
828
- });
829
-
830
- // ── setProperty value encoding ─────────────────────────────────────────────
831
-
832
- /**
833
- * `MpvBridgeModule.setProperty(name: String, value: String)` declares both
834
- * arguments as Kotlin `String`, and React Native's JS→native marshalling
835
- * *throws* on a mismatch instead of coercing:
836
- *
837
- * Expected argument 1 of method "setProperty" to be a string,
838
- * but got a number (24.000000)
839
- *
840
- * which surfaces as a red-box `Exception in HostFunction` and unmounts the
841
- * React tree. These tests pin that every value crossing that boundary has
842
- * already been encoded to a string by the time it reaches the bridge.
843
- */
844
- describe('toMpvPropertyString', () => {
845
- it('passes a string through unchanged', () => {
846
- expect(toMpvPropertyString('#FFFFFF00')).toBe('#FFFFFF00');
847
- });
848
-
849
- it('encodes an empty string as-is', () => {
850
- expect(toMpvPropertyString('')).toBe('');
851
- });
852
-
853
- it('encodes integers without a decimal point', () => {
854
- // The reported crash value was `24.000000` — a Double reaching a
855
- // String parameter. Pin that the encoding drops the fraction.
856
- expect(toMpvPropertyString(24)).toBe('24');
857
- expect(toMpvPropertyString(0)).toBe('0');
858
- expect(toMpvPropertyString(-1)).toBe('-1');
859
- });
860
-
861
- it('preserves meaningful decimals', () => {
862
- // mpv float options need the fractional part; blind rounding would
863
- // silently change the value rather than fix the crash.
864
- expect(toMpvPropertyString(1.5)).toBe('1.5');
865
- expect(toMpvPropertyString(0.25)).toBe('0.25');
866
- });
867
-
868
- it('encodes booleans as mpv textual flags', () => {
869
- expect(toMpvPropertyString(true)).toBe('true');
870
- expect(toMpvPropertyString(false)).toBe('false');
871
- });
872
-
873
- it('maps null and undefined to the empty string, never the word undefined', () => {
874
- // `String(undefined)` would send the literal text "undefined" to
875
- // mpv, which is worse than useless — it looks like a real value.
876
- expect(toMpvPropertyString(null)).toBe('');
877
- expect(toMpvPropertyString(undefined)).toBe('');
878
- });
879
-
880
- it('JSON-encodes objects and arrays for structured options', () => {
881
- // mpv has no other textual form for a `vf`/`af` parameter list.
882
- expect(toMpvPropertyString({lavfi: 'scale=640:-1'})).toBe(
883
- '{"lavfi":"scale=640:-1"}',
884
- );
885
- expect(toMpvPropertyString([1, 2, 3])).toBe('[1,2,3]');
886
- });
887
-
888
- it('returns the empty string for a circular structure instead of throwing', () => {
889
- const circular: Record<string, unknown> = {};
890
- circular.self = circular;
891
- expect(() => toMpvPropertyString(circular)).not.toThrow();
892
- expect(toMpvPropertyString(circular)).toBe('');
893
- });
894
- });
895
-
896
- describe('commands.setProperty encoding', () => {
897
- beforeEach(() => {
898
- clearBridgeMocks();
899
- });
900
-
901
- it('encodes a numeric value before it reaches the bridge', async () => {
902
- // The exact shape that crashed the caption bridge.
903
- const { result } = await renderHook(() => usePlayer());
904
- result.current.commands.setProperty('sub-font-size', 24);
905
- expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
906
- 'sub-font-size',
907
- '24',
908
- );
909
- });
910
-
911
- it('accepts a string value unchanged', async () => {
912
- const { result } = await renderHook(() => usePlayer());
913
- result.current.commands.setProperty('sub-color', '#FFFFFFF');
914
- expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
915
- 'sub-color',
916
- '#FFFFFFF',
917
- );
918
- });
919
-
920
- it('never sends a non-string to the bridge, whatever the caller passes', async () => {
921
- const { result } = await renderHook(() => usePlayer());
922
- const values: unknown[] = [24, 0, -1, 1.5, true, false, null, undefined, {a: 1}, [1]];
923
- for (const value of values) {
924
- result.current.commands.setProperty('sub-pos', value);
925
- }
926
- const calls = (NativeModules.MpvPlayerModule.setProperty as jest.Mock)
927
- .mock.calls;
928
- expect(calls).toHaveLength(values.length);
929
- for (const [, sent] of calls) {
930
- expect(typeof sent).toBe('string');
931
- }
932
- });
933
- });
934
-
935
- describe('commands that route through setProperty', () => {
936
- beforeEach(() => {
937
- clearBridgeMocks();
938
- });
939
-
940
- it('commands.seekToChapter(index) sends the index as a string', async () => {
941
- // Regression: this call site passed a raw number and would have
942
- // thrown inside HostFunction, red-boxing on every chapter jump.
943
- const { result } = await renderHook(() => usePlayer());
944
- await result.current.commands.seekToChapter(3);
945
- expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
946
- 'chapter',
947
- '3',
948
- );
949
- });
950
-
951
- it('commands.setShuffle(false) sends 0, because playlist-shuffle is an int option', async () => {
952
- // The `true` half is pinned in the delegation block above; this
953
- // covers the other branch, which previously would have sent the
954
- // boolean `false` straight into a Kotlin String parameter.
955
- const { result } = await renderHook(() => usePlayer());
956
- await result.current.commands.setShuffle(false);
957
- expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
958
- 'playlist-shuffle',
959
- '0',
960
- );
961
- });
962
- });
963
-
964
- describe('PlayerState.title comes from mpv media-title (v1.9.3)', () => {
965
- // The other half of the fix. Registering `media-title` only matters if
966
- // a `media-title` event actually moves `state.title` — and the reason
967
- // the header said "Simba Player" is that neither half was in place:
968
- // the property was never registered, so the event never arrived.
969
- const wrapper = ({ children }: { children: React.ReactNode }) => (
970
- <PlayerProvider>{children}</PlayerProvider>
971
- );
972
-
973
- let subs: ReturnType<typeof captureSubscribes>;
974
- beforeEach(() => {
975
- clearBridgeMocks();
976
- subs = captureSubscribes();
977
- });
978
- afterEach(() => {
979
- subs.restore();
980
- });
981
-
982
- it('starts at the placeholder, so a passing test below is meaningful', async () => {
983
- const { result } = await renderHook(() => usePlayer(), { wrapper });
984
- expect(result.current.state.title).toBe('Simba Player');
985
- });
986
-
987
- it('adopts a media-title property change', async () => {
988
- const { result } = await renderHook(() => usePlayer(), { wrapper });
989
- const listeners = subs.handlers.get('onPropertyChanged') ?? [];
990
- expect(listeners.length).toBeGreaterThan(0);
991
-
992
- await act(async () => {
993
- for (const l of listeners) {
994
- l({property: 'media-title', value: 'Overrun!'});
995
- }
996
- });
997
-
998
- expect(result.current.state.title).toBe('Overrun!');
999
- });
1000
-
1001
- it('adopts the title embedded in a metadata property change', async () => {
1002
- const { result } = await renderHook(() => usePlayer(), { wrapper });
1003
- const listeners = subs.handlers.get('onPropertyChanged') ?? [];
1004
-
1005
- // mpv's `metadata` is a NODE LIST, so it arrives as an array of
1006
- // {key, value} entries — not as a flat object. `parseMetadata`
1007
- // correctly rejects a flat object with `{}`; the first draft of
1008
- // this test sent one and failed, which is the test having been
1009
- // wrong rather than the parser being loose.
1010
- await act(async () => {
1011
- for (const l of listeners) {
1012
- l({
1013
- property: 'metadata',
1014
- value: JSON.stringify([
1015
- {key: 'title', value: 'Overrun!'},
1016
- {key: 'artist', value: 'Monica Strebel'},
1017
- ]),
1018
- });
1019
- }
1020
- });
1021
-
1022
- expect(result.current.state.title).toBe('Overrun!');
1023
- expect(result.current.state.artist).toBe('Monica Strebel');
1024
- });
1025
-
1026
- it('never adopts mpv\'s "null" sentinel as the title', async () => {
1027
- // mpv serialises a null string as the four-character literal
1028
- // "null" across the JSON boundary. Assigning it produces a header
1029
- // reading literally `null` — a regression this codebase has already
1030
- // been bitten by once (D-035).
1031
- const { result } = await renderHook(() => usePlayer(), { wrapper });
1032
- const listeners = subs.handlers.get('onPropertyChanged') ?? [];
1033
-
1034
- await act(async () => {
1035
- for (const l of listeners) {
1036
- l({property: 'media-title', value: 'null'});
1037
- }
1038
- });
1039
-
1040
- expect(result.current.state.title).toBe('Simba Player');
1041
- });
1042
-
1043
- it('adopts a real title that arrives after the placeholder was replaced', async () => {
1044
- // Switching items must not leave the previous item's title behind.
1045
- const { result } = await renderHook(() => usePlayer(), { wrapper });
1046
- const listeners = subs.handlers.get('onPropertyChanged') ?? [];
1047
-
1048
- await act(async () => {
1049
- for (const l of listeners) {
1050
- l({property: 'media-title', value: 'First film'});
1051
- }
1052
- });
1053
- await act(async () => {
1054
- for (const l of listeners) {
1055
- l({property: 'media-title', value: 'Second film'});
1056
- }
1057
- });
1058
-
1059
- expect(result.current.state.title).toBe('Second film');
1060
- });
1061
- });
1062
-
1063
- /**
1064
- * v1.9.3 — the title that was accepted and thrown away.
1065
- *
1066
- * `openPlayer({uri, title})` has always accepted a title, and it has
1067
- * always reached `PlayerActivity`. What never happened was anyone
1068
- * APPLYING it:
1069
- *
1070
- * - `useLaunchPlayback` destructures only `uri` and `startPositionMs`
1071
- * out of the launch params, then calls `loadFile(uri)`;
1072
- * - `onFileLoaded`'s handler reads `file?.title` from a native payload
1073
- * that contains `requestId` and `resolvedPath` and no `file` key, so
1074
- * the branch never fired;
1075
- * - `media-title` and `metadata` were absent from OBSERVED_PROPERTIES,
1076
- * so mpv's own title could not arrive either.
1077
- *
1078
- * The net effect for every consumer was `PlayerState.title` pinned at the
1079
- * `DEFAULT_STATE` placeholder, and a player header reading "Simba
1080
- * Player" over whatever film was actually playing.
1081
- *
1082
- * The fix applies mpv's own `force-media-title` option BEFORE the load.
1083
- */
1084
- describe('commands.loadFile applies the launch title (v1.9.3)', () => {
1085
- beforeEach(() => {
1086
- clearBridgeMocks();
1087
- });
1088
-
1089
- it('writes force-media-title with the supplied title', async () => {
1090
- const { result } = await renderHook(() => usePlayer());
1091
- await result.current.commands.loadFile('file:///a.mp4', 'Overrun!');
1092
- expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
1093
- 'force-media-title',
1094
- 'Overrun!',
1095
- );
1096
- });
1097
-
1098
- it('sets the option BEFORE loading, because mpv applies it at load time', async () => {
1099
- // Order is the contract, not an optimisation. `force-media-title`
1100
- // is read when the file is loaded, so setting it afterwards would
1101
- // leave the already-loaded file with mpv's derived title — which
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.
1107
- const { result } = await renderHook(() => usePlayer());
1108
- await result.current.commands.loadFile('file:///a.mp4', 'Overrun!');
1109
-
1110
- const order: string[] = [];
1111
- const setProperty = NativeModules
1112
- .MpvPlayerModule.setProperty as jest.Mock;
1113
- const loadFile = NativeModules.MpvPlayerModule.loadFile as jest.Mock;
1114
- setProperty.mockImplementation((name: string) => {
1115
- order.push(`setProperty:${name}`);
1116
- });
1117
- loadFile.mockImplementation(() => {
1118
- order.push('loadFile');
1119
- });
1120
-
1121
- await result.current.commands.loadFile('file:///b.mp4', 'Second');
1122
- expect(order).toEqual([
1123
- 'setProperty:force-media-title',
1124
- 'setProperty:options/start',
1125
- 'loadFile',
1126
- ]);
1127
- });
1128
-
1129
- it('trims the title — a blank or padded value would render as whitespace', async () => {
1130
- const { result } = await renderHook(() => usePlayer());
1131
- await result.current.commands.loadFile('file:///a.mp4', ' Overrun! ');
1132
- expect(NativeModules.MpvPlayerModule.setProperty).toHaveBeenCalledWith(
1133
- 'force-media-title',
1134
- 'Overrun!',
1135
- );
1136
- });
1137
-
1138
- it('omits the option entirely when no title is supplied', async () => {
1139
- // No title means "let mpv derive one", which is the pre-1.9.3
1140
- // behaviour. Writing `force-media-title` with an empty string would
1141
- // blank the header instead of falling back.
1142
- const { result } = await renderHook(() => usePlayer());
1143
- await result.current.commands.loadFile('file:///a.mp4');
1144
- expect(NativeModules.MpvPlayerModule.setProperty).not.toHaveBeenCalledWith(
1145
- 'force-media-title',
1146
- expect.anything(),
1147
- );
1148
- expect(NativeModules.MpvPlayerModule.loadFile).toHaveBeenCalledWith(
1149
- 'file:///a.mp4',
1150
- );
1151
- });
1152
-
1153
- it('still loads the file when the property write is rejected', async () => {
1154
- // A rejected `force-media-title` must not cost the user their video.
1155
- // The video plays; the title falls back to whatever mpv derives.
1156
- const setProperty = NativeModules.MpvPlayerModule
1157
- .setProperty as jest.Mock;
1158
- setProperty.mockImplementationOnce(() => {
1159
- throw new Error('property rejected');
1160
- });
1161
-
1162
- const { result } = await renderHook(() => usePlayer());
1163
- // `loadFile` is a SYNCHRONOUS command (void), so it throws rather
1164
- // than rejecting — asserting "does not throw" is the contract.
1165
- expect(() =>
1166
- result.current.commands.loadFile('file:///a.mp4', 'Overrun!'),
1167
- ).not.toThrow();
1168
- expect(NativeModules.MpvPlayerModule.loadFile).toHaveBeenCalledWith(
1169
- 'file:///a.mp4',
1170
- );
1171
- });
1172
- });
1173
-
1174
- // ── V21: seekable re-seed on file load ──────────────────────────────────────
1175
-
1176
- describe('seekable re-seed on file load', () => {
1177
- it('re-reads seekable when a file loads, because mpv only emits it as an edge', async () => {
1178
- clearBridgeMocks();
1179
- const getProperty = NativeModules.MpvPlayerModule
1180
- .getProperty as jest.Mock;
1181
-
1182
- // At mount nothing is loaded yet, so mpv legitimately reports false.
1183
- // This is the ordinary launch order — the seed at mount alone can
1184
- // therefore never be the thing that makes a seek bar usable.
1185
- getProperty.mockImplementation((name: string) =>
1186
- name === 'seekable' ? 'false' : 'null',
1187
- );
1188
-
1189
- const capture = captureSubscribes();
1190
- const wrapper = ({ children }: { children: React.ReactNode }) => (
1191
- <PlayerProvider>{children}</PlayerProvider>
1192
- );
1193
-
1194
- const { result, unmount } = await renderHook(() => usePlayerProgress(), {
1195
- wrapper,
1196
- });
1197
-
1198
- expect(result.current.seekable).toBe(false);
1199
-
1200
- // The file is loaded now and mpv has flipped the flag. Measured on
1201
- // device, the PROPERTY_CHANGE edge for `seekable` reached JS zero
1202
- // times, so the provider has to re-read the level itself.
1203
- getProperty.mockImplementation((name: string) =>
1204
- name === 'seekable' ? 'true' : 'null',
1205
- );
1206
-
1207
- await act(async () => {
1208
- for (const handler of capture.handlers.get('onFileLoaded') ?? []) {
1209
- handler({ file: { uri: 'file:///a.mp4', title: 'A', duration: 3600 } });
1210
- }
1211
- });
1212
-
1213
- // The seek bar must become usable. This is the assertion that fails
1214
- // with the pre-fix provider, where `seekable` stayed at
1215
- // DEFAULT_PROGRESS and the bar rendered permanently disabled.
1216
- expect(result.current.seekable).toBe(true);
1217
-
1218
- capture.restore();
1219
- await unmount();
1220
- });
1221
-
1222
- it('does not treat a reported duration as proof of seekability', async () => {
1223
- // The tempting app-side "fix" was `state.seekable || state.durationMs > 0`.
1224
- // A live stream can report a duration and still have no seekable range;
1225
- // inferring seekability from duration lights up a seek bar that cannot
1226
- // work, which is the same "control that looks live and is not" class
1227
- // this refactor is removing elsewhere.
1228
- clearBridgeMocks();
1229
- const getProperty = NativeModules.MpvPlayerModule
1230
- .getProperty as jest.Mock;
1231
- // A live stream: duration known, seekable still false, and no flip.
1232
- getProperty.mockImplementation((name: string) =>
1233
- name === 'seekable' ? 'false' : 'null',
1234
- );
1235
-
1236
- const capture = captureSubscribes();
1237
- const wrapper = ({ children }: { children: React.ReactNode }) => (
1238
- <PlayerProvider>{children}</PlayerProvider>
1239
- );
1240
-
1241
- const { result, unmount } = await renderHook(() => usePlayerProgress(), {
1242
- wrapper,
1243
- });
1244
-
1245
- await act(async () => {
1246
- for (const handler of capture.handlers.get('onFileLoaded') ?? []) {
1247
- handler({ file: { uri: 'live/hls', title: 'Live', duration: 0 } });
1248
- }
1249
- });
1250
-
1251
- expect(result.current.seekable).toBe(false);
1252
-
1253
- capture.restore();
1254
- await unmount();
1255
- });
1256
- });
1257
-
1258
- // ── V21: single-Activity surface control ────────────────────────────────────
1259
-
1260
- describe('V21 surface control (setVideoBounds family)', () => {
1261
- beforeEach(() => {
1262
- clearBridgeMocks();
1263
- });
1264
-
1265
- it('exposes the surface commands on the command surface', async () => {
1266
- const { result } = await renderHook(() => usePlayer());
1267
- const c = result.current.commands;
1268
- expect(typeof c.setVideoBounds).toBe('function');
1269
- expect(typeof c.fillVideoBounds).toBe('function');
1270
- expect(typeof c.setSurfaceVisible).toBe('function');
1271
- expect(typeof c.isSurfaceMounted).toBe('function');
1272
- });
1273
-
1274
- it('forwards the rect verbatim to the bridge', async () => {
1275
- // The whole design rests on these exact numbers reaching native: the
1276
- // surface is placed by mutating its layout bounds, so a rounded,
1277
- // clamped, or reordered argument would put the picture in the wrong
1278
- // rect with no error anywhere.
1279
- const setVideoBounds = NativeModules.MpvPlayerModule
1280
- .setVideoBounds as jest.Mock;
1281
- setVideoBounds.mockResolvedValue(true);
1282
-
1283
- const { result } = await renderHook(() => usePlayer());
1284
- await act(async () => {
1285
- await result.current.commands.setVideoBounds(12, 34, 56, 78);
1286
- });
1287
-
1288
- expect(setVideoBounds).toHaveBeenCalledWith(12, 34, 56, 78);
1289
- });
1290
-
1291
- it('propagates a false result so callers can refuse to present video', async () => {
1292
- // This is the reason these return a Promise<boolean> instead of
1293
- // fire-and-forget: `false` means "there was no surface to move".
1294
- // A caller that cannot see that would render chrome over a video
1295
- // that was never shown - a control that looks live and is not.
1296
- const setVideoBounds = NativeModules.MpvPlayerModule
1297
- .setVideoBounds as jest.Mock;
1298
- setVideoBounds.mockResolvedValue(false);
1299
-
1300
- const { result } = await renderHook(() => usePlayer());
1301
- let applied: boolean | undefined;
1302
- await act(async () => {
1303
- applied = await result.current.commands.setVideoBounds(0, 0, 10, 10);
1304
- });
1305
-
1306
- expect(applied).toBe(false);
1307
- });
1308
-
1309
- it('reports isSurfaceMounted from the bridge rather than assuming true', async () => {
1310
- const isSurfaceMounted = NativeModules.MpvPlayerModule
1311
- .isSurfaceMounted as jest.Mock;
1312
- isSurfaceMounted.mockReturnValue(false);
1313
-
1314
- const { result } = await renderHook(() => usePlayer());
1315
- expect(result.current.commands.isSurfaceMounted()).toBe(false);
1316
-
1317
- isSurfaceMounted.mockReturnValue(true);
1318
- expect(result.current.commands.isSurfaceMounted()).toBe(true);
1319
- });
1320
-
1321
- it('forwards the visibility flag, including the hide direction', async () => {
1322
- const setSurfaceVisible = NativeModules.MpvPlayerModule
1323
- .setSurfaceVisible as jest.Mock;
1324
- setSurfaceVisible.mockResolvedValue(true);
1325
-
1326
- const { result } = await renderHook(() => usePlayer());
1327
- await act(async () => {
1328
- await result.current.commands.setSurfaceVisible(false);
1329
- });
1330
- expect(setSurfaceVisible).toHaveBeenCalledWith(false);
1331
-
1332
- setSurfaceVisible.mockClear();
1333
- await act(async () => {
1334
- await result.current.commands.setSurfaceVisible(true);
1335
- });
1336
- expect(setSurfaceVisible).toHaveBeenCalledWith(true);
1337
- });
1338
- });
1339
-
1340
- describe('NOOP fallback honesty (V21)', () => {
1341
- const original = NativeModules.MpvPlayerModule;
1342
-
1343
- afterEach(() => {
1344
- NativeModules.MpvPlayerModule = original;
1345
- });
1346
-
1347
- it('reports that no surface exists instead of claiming success', async () => {
1348
- // With no native module present, `getMpvPlayerModule()` hands back the
1349
- // NOOP bridge. Every surface mutator must report failure there.
1350
- //
1351
- // If any of these returned success, a consumer would light up
1352
- // mini-player chrome over a surface that was never mounted: a control
1353
- // that looks live and is not, which is exactly the class of bug this
1354
- // module's fallback exists to prevent.
1355
- (NativeModules as { MpvPlayerModule?: unknown }).MpvPlayerModule =
1356
- undefined;
1357
-
1358
- const bridge = BridgeModule.getMpvPlayerModule();
1359
-
1360
- expect(bridge.isSurfaceMounted()).toBe(false);
1361
- await expect(bridge.fillVideoBounds()).resolves.toBe(false);
1362
- await expect(bridge.setSurfaceVisible(true)).resolves.toBe(false);
1363
- await expect(bridge.setVideoBounds(0, 0, 10, 10)).resolves.toBe(false);
1364
- });
1365
- });