@simba-dev/react-native-media-player 1.9.4 → 1.11.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.
- package/android/src/main/cpp/event.cpp +124 -10
- package/android/src/main/java/com/simba/player/mpv/MpvBridgeModule.kt +402 -8
- package/package.json +1 -1
- package/src/bridge/MpvPlayerModule.ts +68 -1
- package/src/bridge/NativeMpvPlayer.ts +30 -0
- package/src/components/PlayerProvider.tsx +88 -63
- package/src/components/__tests__/PlayerProvider.performance.test.tsx +242 -0
- package/src/hooks/__tests__/useResumeThumbnail.test.ts +154 -0
- package/src/hooks/useResumeThumbnail.ts +153 -0
- package/src/index.ts +12 -0
|
@@ -153,6 +153,27 @@ export interface PlayerEventPayloads {
|
|
|
153
153
|
// Bridge surface (V13 Phase 50a — 78 methods)
|
|
154
154
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
155
155
|
|
|
156
|
+
/**
|
|
157
|
+
* Output geometry + JPEG quality for `captureFrame`.
|
|
158
|
+
*
|
|
159
|
+
* Every field is optional; an omitted field falls back to the
|
|
160
|
+
* poster-sized default the native side applies (mirrored in TS as
|
|
161
|
+
* `DEFAULT_FRAME_WIDTH` / `DEFAULT_FRAME_HEIGHT` /
|
|
162
|
+
* `DEFAULT_FRAME_QUALITY`, exported from `hooks/useResumeThumbnail`).
|
|
163
|
+
*/
|
|
164
|
+
export interface CaptureFrameOptions {
|
|
165
|
+
/**
|
|
166
|
+
* Target width in pixels. `0` means "do not constrain width" —
|
|
167
|
+
* the platform then keeps the source aspect ratio instead of
|
|
168
|
+
* squashing the frame into the requested box.
|
|
169
|
+
*/
|
|
170
|
+
readonly width?: number;
|
|
171
|
+
/** Target height in pixels. `0` means "leave the frame unscaled". */
|
|
172
|
+
readonly height?: number;
|
|
173
|
+
/** JPEG quality, 0–100. Out-of-range values are clamped natively. */
|
|
174
|
+
readonly quality?: number;
|
|
175
|
+
}
|
|
176
|
+
|
|
156
177
|
/**
|
|
157
178
|
* Typed shape of the `MpvPlayerModule` native bridge as exposed by
|
|
158
179
|
* `MpvBridgeModule.kt`. V13 Phase 50 expands the Phase 24 entry point
|
|
@@ -225,8 +246,39 @@ export interface MpvPlayerModuleBridge {
|
|
|
225
246
|
getFileInfo(): string;
|
|
226
247
|
/** Get the currently-loaded video params as a JSON string. */
|
|
227
248
|
getVideoParams(): string;
|
|
228
|
-
/**
|
|
249
|
+
/**
|
|
250
|
+
* LIVE-FRAME capture — the name is misleading, read this first.
|
|
251
|
+
*
|
|
252
|
+
* The `uri` argument is used ONLY to derive the output filename
|
|
253
|
+
* (`thumb_${hash}.png`); the pixels come from the currently
|
|
254
|
+
* initialised mpv handle. It therefore needs a live player AND a
|
|
255
|
+
* loaded file, and it cannot target a position.
|
|
256
|
+
*
|
|
257
|
+
* For a "thumbnail at position X" (resume rails, scrub previews,
|
|
258
|
+
* bookmark art) use `captureFrame` instead — that one takes a
|
|
259
|
+
* timestamp and needs no player at all.
|
|
260
|
+
*/
|
|
229
261
|
captureThumbnail(uri: string): string;
|
|
262
|
+
/**
|
|
263
|
+
* Extract one frame at `positionMs` from `uri` — WITHOUT a player
|
|
264
|
+
* instance, without playback, and without the mpv surface.
|
|
265
|
+
*
|
|
266
|
+
* The native implementation is
|
|
267
|
+
* `MediaMetadataRetriever.getScaledFrameAtTime()`, so it accepts a
|
|
268
|
+
* local path, `file://`, or an `http(s)` URL (fetched with range
|
|
269
|
+
* requests).
|
|
270
|
+
*
|
|
271
|
+
* **Resolves `null` — never rejects — when no frame exists:**
|
|
272
|
+
* live stream, unsupported container, unreachable URL, position
|
|
273
|
+
* past the end. `null` is the "no thumbnail, show poster art"
|
|
274
|
+
* signal, not a failure. Rejection is reserved for programmer
|
|
275
|
+
* error (blank `uri`, non-finite or negative `positionMs`).
|
|
276
|
+
*/
|
|
277
|
+
captureFrame(
|
|
278
|
+
uri: string,
|
|
279
|
+
positionMs: number,
|
|
280
|
+
options?: CaptureFrameOptions,
|
|
281
|
+
): Promise<string | null>;
|
|
230
282
|
/** Take a persistable read URI permission for a content:// URI. */
|
|
231
283
|
grantPersistablePermission(uri: string): void;
|
|
232
284
|
/** Returns true when the URI is still readable (content:// or file://). */
|
|
@@ -473,6 +525,21 @@ const NOOP_BRIDGE: MpvPlayerModuleBridge = {
|
|
|
473
525
|
void _uri;
|
|
474
526
|
return '';
|
|
475
527
|
},
|
|
528
|
+
// No-op fallback resolves `null` — the same "no frame available,
|
|
529
|
+
// use poster art" answer the real native path returns for a live
|
|
530
|
+
// stream or an unreachable URL. It must NOT reject, or every
|
|
531
|
+
// jest/Storybook/web host would see a red screen where a consumer
|
|
532
|
+
// sees a placeholder image.
|
|
533
|
+
captureFrame: (
|
|
534
|
+
_uri: string,
|
|
535
|
+
_positionMs: number,
|
|
536
|
+
_options?: CaptureFrameOptions,
|
|
537
|
+
) => {
|
|
538
|
+
void _uri;
|
|
539
|
+
void _positionMs;
|
|
540
|
+
void _options;
|
|
541
|
+
return Promise.resolve(null);
|
|
542
|
+
},
|
|
476
543
|
grantPersistablePermission: (_uri: string) => {
|
|
477
544
|
void _uri;
|
|
478
545
|
},
|
|
@@ -72,7 +72,37 @@ export interface Spec extends TurboModule {
|
|
|
72
72
|
loadPlaylist(paths: ReadonlyArray<string>, startIndex: number): void;
|
|
73
73
|
getFileInfo(): string;
|
|
74
74
|
getVideoParams(): string;
|
|
75
|
+
/**
|
|
76
|
+
* LIVE-FRAME capture. `uri` is used ONLY to derive the output
|
|
77
|
+
* filename (`thumb_${hash}.png`) — the pixels come from whatever
|
|
78
|
+
* mpv is playing right now, so this requires an initialised
|
|
79
|
+
* player AND a running/paused playback session. Do NOT use it
|
|
80
|
+
* for a "thumbnail at position X"; see `captureFrame` below.
|
|
81
|
+
*/
|
|
75
82
|
captureThumbnail(uri: string): string;
|
|
83
|
+
/**
|
|
84
|
+
* Extract a single frame at `positionMs` from `uri` WITHOUT a
|
|
85
|
+
* player instance, via `MediaMetadataRetriever
|
|
86
|
+
* .getScaledFrameAtTime()`. Works on a local path, `file://`, or
|
|
87
|
+
* an `http(s)` URL (range requests) — no mpv handle, no
|
|
88
|
+
* playback, no surface.
|
|
89
|
+
*
|
|
90
|
+
* Rejects ONLY for programmer error (blank `uri`, non-finite or
|
|
91
|
+
* negative `positionMs`). Every "cannot get a frame" outcome —
|
|
92
|
+
* live stream, unsupported container, unreachable URL, position
|
|
93
|
+
* past the end of the file — resolves `null`, which is the
|
|
94
|
+
* documented "no thumbnail, fall back to poster art" signal and
|
|
95
|
+
* NOT an error.
|
|
96
|
+
*
|
|
97
|
+
* Options are all optional; the Kotlin side substitutes a
|
|
98
|
+
* poster-sized default. `width: 0` means "do not constrain width"
|
|
99
|
+
* (the platform then preserves the source aspect ratio).
|
|
100
|
+
*/
|
|
101
|
+
captureFrame(
|
|
102
|
+
uri: string,
|
|
103
|
+
positionMs: number,
|
|
104
|
+
options?: {width: number; height: number; quality: number},
|
|
105
|
+
): Promise<string | null>;
|
|
76
106
|
grantPersistablePermission(uri: string): void;
|
|
77
107
|
verifyContentUri(uri: string): boolean;
|
|
78
108
|
|
|
@@ -217,9 +217,6 @@ const ALL_PLAYER_EVENTS: readonly PlayerEventName[] = [
|
|
|
217
217
|
'onPipClose',
|
|
218
218
|
];
|
|
219
219
|
|
|
220
|
-
/** How often the provider polls `getPosition` + `getDuration` from the bridge. */
|
|
221
|
-
const POSITION_POLL_INTERVAL_MS = 1000;
|
|
222
|
-
|
|
223
220
|
/**
|
|
224
221
|
* mpv properties the provider observes, and the JS event each one backs
|
|
225
222
|
* in `MpvBridgeModule.onMpvPropertyChanged`.
|
|
@@ -371,6 +368,48 @@ function cacheRangesEqual(
|
|
|
371
368
|
);
|
|
372
369
|
}
|
|
373
370
|
|
|
371
|
+
/**
|
|
372
|
+
* v1.10.0 — make the provider's existing no-op guard actually WORK.
|
|
373
|
+
*
|
|
374
|
+
* `applyPlayerEvent` is written as pure spread-and-return, so it allocates
|
|
375
|
+
* a NEW `PlayerState` object for every event it handles, even when not a
|
|
376
|
+
* single field changed. The provider then did:
|
|
377
|
+
*
|
|
378
|
+
* if (nextState !== stateRef.current) { ... setState(nextState) }
|
|
379
|
+
*
|
|
380
|
+
* That is a reference comparison against an object the reducer JUST
|
|
381
|
+
* created, so it was true for every event, always. The guard was dead code.
|
|
382
|
+
*
|
|
383
|
+
* Consequence: `setState` fired on every single player event, replacing the
|
|
384
|
+
* `PlayerStateContext` value and re-rendering every `usePlayer()` consumer —
|
|
385
|
+
* all 12 chrome components in the app — including on `onPositionChanged`,
|
|
386
|
+
* which mpv emits once per video frame. `videoReconfig` and the PiP no-ops
|
|
387
|
+
* the comment above cites were never skipped either.
|
|
388
|
+
*
|
|
389
|
+
* WHY A GENERIC SHALLOW COMPARE INSTEAD OF A HAND-WRITTEN FIELD LIST:
|
|
390
|
+
* a hand-written `a.foo === b.foo && ...` list silently goes stale the
|
|
391
|
+
* moment a field is added to `PlayerState` — the new field is simply not
|
|
392
|
+
* compared, the function reports "equal" when it is not, and the guard
|
|
393
|
+
* starts dropping real updates. That is worse than no guard at all, and it
|
|
394
|
+
* is invisible in tests. Deriving the key list from the object at runtime
|
|
395
|
+
* means the contract cannot drift.
|
|
396
|
+
*
|
|
397
|
+
* Shallow reference equality is the correct depth here: `applyPlayerEvent`
|
|
398
|
+
* only ever REPLACES these nested values (`playlist`, `tracks`, `chapters`,
|
|
399
|
+
* `currentChapter`, `videoParams`), it never mutates one in place, so a
|
|
400
|
+
* changed reference reliably means changed content.
|
|
401
|
+
*/
|
|
402
|
+
const PLAYER_STATE_SCALAR_KEYS = Object.keys(DEFAULT_STATE) as Array<
|
|
403
|
+
keyof PlayerState
|
|
404
|
+
>;
|
|
405
|
+
|
|
406
|
+
function playerStateEqual(a: PlayerState, b: PlayerState): boolean {
|
|
407
|
+
for (const key of PLAYER_STATE_SCALAR_KEYS) {
|
|
408
|
+
if (a[key] !== b[key]) return false;
|
|
409
|
+
}
|
|
410
|
+
return true;
|
|
411
|
+
}
|
|
412
|
+
|
|
374
413
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
375
414
|
// PlayerProvider
|
|
376
415
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
@@ -435,8 +474,14 @@ export interface PlayerProviderProps {
|
|
|
435
474
|
* loop / playlist / tracks / chapters / video params.
|
|
436
475
|
* - **Event subscriptions** (mount): all 22 mpv events are subscribed
|
|
437
476
|
* via `subscribePlayerEvent` and dispatched to `applyPlayerEvent`.
|
|
438
|
-
* - **
|
|
439
|
-
* sync `
|
|
477
|
+
* - **Mount-time level seeds** (mount): `seekable` and `mute` are read once
|
|
478
|
+
* via the sync `getProperty` getter, because mpv emits those two as
|
|
479
|
+
* EDGES and a provider mounted mid-session would otherwise never see them.
|
|
480
|
+
*
|
|
481
|
+
* v1.10.0 removed a 1Hz `setPosition`/`getDuration` poll that used to run
|
|
482
|
+
* alongside the event stream. The event stream is authoritative and
|
|
483
|
+
* delivers position at 4Hz after native coalescing; the poll was a second
|
|
484
|
+
* writer to the same fields and blocked the JS thread twice a second.
|
|
440
485
|
*
|
|
441
486
|
* State is held in a `useState` (rendered, for React) + `useRef`
|
|
442
487
|
* (current, for event handlers to read without stale closures) pair.
|
|
@@ -487,15 +532,13 @@ export function PlayerProvider({
|
|
|
487
532
|
// subscriptions.
|
|
488
533
|
const stateRef = useRef<PlayerState>(DEFAULT_STATE);
|
|
489
534
|
const progressRef = useRef<PlayerProgress>(DEFAULT_PROGRESS);
|
|
490
|
-
// Tracks whether the 1Hz poll should fire. The poll runs in a child
|
|
491
|
-
// effect that mounts the interval; the unmount cleanup is symmetric.
|
|
492
|
-
// We mount/unmount ONCE for the provider's lifetime (no deps), so
|
|
493
|
-
// the poll survives config changes.
|
|
494
535
|
|
|
495
|
-
// Initial hydration + event subscriptions +
|
|
496
|
-
// single mount-only effect so they share the same lifecycle.
|
|
497
|
-
// split them across multiple effects, the ref + state would briefly
|
|
536
|
+
// Initial hydration + event subscriptions + mount-time level seeds all
|
|
537
|
+
// live in a single mount-only effect so they share the same lifecycle.
|
|
538
|
+
// (If we split them across multiple effects, the ref + state would briefly
|
|
498
539
|
// desync during the gap between hydration and subscription mount.)
|
|
540
|
+
// The 1Hz position poll this effect used to also start was removed in
|
|
541
|
+
// v1.10.0 — the event stream is authoritative for position and duration.
|
|
499
542
|
useEffect(() => {
|
|
500
543
|
const bridge = getMpvPlayerModule();
|
|
501
544
|
|
|
@@ -565,10 +608,12 @@ export function PlayerProvider({
|
|
|
565
608
|
event,
|
|
566
609
|
payload,
|
|
567
610
|
);
|
|
568
|
-
// Skip the setState
|
|
569
|
-
//
|
|
570
|
-
//
|
|
571
|
-
|
|
611
|
+
// Skip the setState when no FIELD changed. This must be a field-wise
|
|
612
|
+
// compare, not a reference compare: `applyPlayerEvent` always
|
|
613
|
+
// returns a freshly-spread object, so `nextState !== stateRef.current`
|
|
614
|
+
// was true for literally every event and never skipped anything.
|
|
615
|
+
// See playerStateEqual() for why the key list is derived, not typed.
|
|
616
|
+
if (!playerStateEqual(nextState, stateRef.current)) {
|
|
572
617
|
stateRef.current = nextState;
|
|
573
618
|
setState(nextState);
|
|
574
619
|
}
|
|
@@ -690,52 +735,32 @@ export function PlayerProvider({
|
|
|
690
735
|
console.warn('[simba-player] mute seed failed:', e);
|
|
691
736
|
}
|
|
692
737
|
|
|
693
|
-
// ── 3.
|
|
694
|
-
//
|
|
695
|
-
//
|
|
696
|
-
//
|
|
697
|
-
//
|
|
698
|
-
//
|
|
699
|
-
//
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
positionMs,
|
|
720
|
-
durationMs,
|
|
721
|
-
};
|
|
722
|
-
stateRef.current = next;
|
|
723
|
-
setState(next);
|
|
724
|
-
const nextProgress: PlayerProgress = {
|
|
725
|
-
...progressRef.current,
|
|
726
|
-
positionMs,
|
|
727
|
-
durationMs,
|
|
728
|
-
};
|
|
729
|
-
progressRef.current = nextProgress;
|
|
730
|
-
setProgress(nextProgress);
|
|
731
|
-
} catch (e) {
|
|
732
|
-
// Bridge threw — keep the last known position. (The no-op
|
|
733
|
-
// bridge returns 0/0, which falls into the "no movement"
|
|
734
|
-
// early-return above, so it doesn't spam setState.)
|
|
735
|
-
// eslint-disable-next-line no-console
|
|
736
|
-
console.warn('[simba-player] position poll failed:', e);
|
|
737
|
-
}
|
|
738
|
-
}, POSITION_POLL_INTERVAL_MS);
|
|
738
|
+
// ── 3. No position poll (v1.10.0) ─────────────────────────────────
|
|
739
|
+
//
|
|
740
|
+
// This used to be a 1Hz `setInterval` calling the SYNCHRONOUS
|
|
741
|
+
// `getPosition()` / `getDuration()` bridge getters. It was removed, not
|
|
742
|
+
// tuned, for three reasons:
|
|
743
|
+
//
|
|
744
|
+
// a) It was a SECOND source of truth for the same two numbers. mpv's
|
|
745
|
+
// `time-pos` and `duration` are already observed (step 2b) and
|
|
746
|
+
// arrive as `onPositionChanged` / `onDurationChanged`. Two writers
|
|
747
|
+
// to one field means the value on screen is whatever landed last,
|
|
748
|
+
// which is how a seek bar ends up jumping backwards.
|
|
749
|
+
//
|
|
750
|
+
// b) Both getters are sync TurboModule methods, so each tick blocked
|
|
751
|
+
// the JS thread for the duration of two JNI round-trips. The RN
|
|
752
|
+
// guidance for sync methods is to use them only for sub-5ms work
|
|
753
|
+
// and never on a recurring timer.
|
|
754
|
+
//
|
|
755
|
+
// c) It bought nothing. The event stream is authoritative and, since
|
|
756
|
+
// the native coalescing landed, delivers position at 4Hz — faster
|
|
757
|
+
// than the 1Hz it replaced, while doing ~15x less total work than
|
|
758
|
+
// the old per-frame path.
|
|
759
|
+
//
|
|
760
|
+
// The mount-time LEVEL seeds above (seekable, mute) are deliberately
|
|
761
|
+
// KEPT: mpv emits those as edges, so an event-only provider mounted
|
|
762
|
+
// mid-session would never learn them. Position and duration are levels
|
|
763
|
+
// that change continuously, so the event stream always repopulates them.
|
|
739
764
|
|
|
740
765
|
// ── Cleanup ─────────────────────────────────────────────────────────
|
|
741
766
|
return () => {
|
|
@@ -756,7 +781,7 @@ export function PlayerProvider({
|
|
|
756
781
|
// never let a single bad unsub abort the rest
|
|
757
782
|
}
|
|
758
783
|
}
|
|
759
|
-
|
|
784
|
+
// v1.10.0: no interval to clear — the position poll was removed.
|
|
760
785
|
// Best-effort: remove any lingering listeners from the emitter
|
|
761
786
|
// so the next mount of the provider starts clean. (Strict-mode
|
|
762
787
|
// double-invocation can otherwise leave phantom listeners.)
|
|
@@ -0,0 +1,242 @@
|
|
|
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
|
+
});
|