@simba-dev/react-native-media-player 1.14.0 → 1.16.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.
@@ -201,6 +201,7 @@ const ALL_PLAYER_EVENTS: readonly PlayerEventName[] = [
201
201
  'onVideoParamsChanged',
202
202
  'onError',
203
203
  'onBuffering',
204
+ 'onCacheFill',
204
205
  'onCacheState',
205
206
  'onSeekable',
206
207
  'onSeeking',
@@ -238,51 +239,61 @@ const ALL_PLAYER_EVENTS: readonly PlayerEventName[] = [
238
239
  * | `seekable` | `onSeekable` | `seekable` = false |
239
240
  * | `seeking` | `onSeeking` | `isSeeking` = false |
240
241
  * | `paused-for-cache` | `onBuffering` | `isBuffering` = false |
241
- * | `cache-buffering-state`| `onBuffering` | `isBuffering` = false |
242
+ * | `cache-buffering-state`| `onCacheFill` | `cacheFill` = 0 |
242
243
  * | `demuxer-cache-state` | `onCacheState` | `cacheRanges` = [] |
243
- * | `time-pos` | `onPositionChanged` | (polled as a fallback) |
244
- * | `duration` | `onDurationChanged` | (polled as a fallback) |
245
- * | `volume` | `onVolumeChanged` | (polled as a fallback) |
246
- * | `speed` | `onSpeedChanged` | (polled as a fallback) |
247
- * | `pause` | `onPlaybackStateChanged` | (polled as a fallback) |
248
- * | `idle-active` / `eof-reached` | `onPlaybackStateChanged` | (polled as a fallback) |
249
- *
250
- * The difference between the two groups is the whole point: position,
251
- * duration, volume, speed and play state also arrive through the 1 Hz
252
- * poll in step 3, so they look fine. `seekable`, `isSeeking`,
253
- * `isBuffering` and `cacheRanges` have **no polling fallback**, so with
254
- * nothing observing them the scrub bar renders permanently disabled, the
255
- * buffering spinner never appears, and the buffered-range fill is never
256
- * painted — while every test in this repo still passes, because the
257
- * defaults are valid-looking values.
244
+ * | `time-pos` | `onPositionChanged` | `positionMs` = 0 |
245
+ * | `duration` | `onDurationChanged` | `durationMs` = 0 |
246
+ * | `volume` | `onVolumeChanged` | `volume` = 100 |
247
+ * | `speed` | `onSpeedChanged` | `speed` = 1 |
248
+ * | `pause` | `onPlaybackStateChanged` | `isPlaying` = false |
249
+ * | `idle-active` / `eof-reached` | `onPlaybackStateChanged` | `isPlaying` = false |
250
+ *
251
+ * Every property in that table is delivered by the event stream. There is
252
+ * no polling fallback for any of them, and there has not been one since
253
+ * v1.10.0. That is why the list is the load-bearing part: a property that
254
+ * is missing from it keeps its `DEFAULT_PROGRESS` value forever, and the
255
+ * default is a valid-looking value, so nothing fails and nothing looks
256
+ * broken. The scrub bar renders permanently disabled, the buffering
257
+ * spinner never appears, and the buffered-range fill is never painted.
258
258
  *
259
259
  * `demuxer-cache-state` is deliberately observed too: it is the only
260
260
  * source for the buffered ranges that the seek bar paints behind the
261
261
  * played fill.
262
262
  *
263
263
  * ---------------------------------------------------------------------------
264
- * OPEN NATIVE DEFECT (1.8.4) — registration is fixed, delivery is not
264
+ * MEASURED 2026-10-19 — the property path works
265
265
  * ---------------------------------------------------------------------------
266
- * This list is necessary but NOT sufficient. Measured on emulator-5554
267
- * (API 37) with the 1.8.3 code running and a file actively playing
268
- * (`time-pos` advancing, `pause=false`):
269
- *
270
- * - `mpv_observe_property(...)` returns `result=0` for all twelve —
271
- * registration genuinely succeeds.
272
- * - `onPlaybackRestart` arrives 7,418 times; `onFileLoaded` arrives.
273
- * So the native event loop IS pumping and IS dispatching to JS.
274
- * - `onSeekable` / `onPositionChanged` / `onDurationChanged` /
275
- * `onCacheState` / `onPlaybackStateChanged` arrive **0 times**.
276
- *
277
- * `MPV_EVENT_PROPERTY_CHANGE` is therefore never delivered to this
278
- * handle even though the property is observed on it. The next release
279
- * must fix the native property-event path (observe handle vs. pumped
280
- * handle in `android/src/main/cpp/event.cpp` / `property.cpp`).
281
- *
282
- * Until that lands, the observable symptom is unchanged: the scrub bar
283
- * still renders disabled ("Live stream — not seekable") because
284
- * `seekable` never leaves `DEFAULT_PROGRESS`. Do not read a green test
285
- * suite as evidence this works — the whole suite mocks the emitter.
266
+ * An earlier version of this comment claimed the opposite, under the
267
+ * heading "OPEN NATIVE DEFECT (1.8.4)": that `MPV_EVENT_PROPERTY_CHANGE`
268
+ * was never delivered, so the scrub bar was permanently disabled and the
269
+ * buffering spinner never appeared.
270
+ *
271
+ * That measurement was real, but it was taken against a build whose
272
+ * native event loop drained ONE event per blocking wait. The drain was
273
+ * fixed afterwards, and the claim was never re-measured — because the
274
+ * per-value property log was made a compile-time constant in v1.10.0
275
+ * (`TRACE_PROPERTY_EVENTS = false`), which left the whole property path
276
+ * UNOBSERVABLE in every build. A defect could sit here for a release
277
+ * cycle with nothing able to contradict it.
278
+ *
279
+ * The path works. Measured on emulator-5554 with a file actively playing:
280
+ *
281
+ * - The consumer's elapsed time advanced 0:00 -> 2:28. Position can
282
+ * only change if `time-pos` PROPERTY_CHANGE events arrive, because
283
+ * the only other source is a one-shot hydration read at mount.
284
+ * - `seekable` flipped to true once the stream was parsed — the
285
+ * "Live stream — not seekable" -> "Playback position" change on the
286
+ * seek bar. That arrives as `onSeekable`, which is a property event.
287
+ * - The lib's own test notes record `onCacheState` arriving 827 times
288
+ * over the same window.
289
+ *
290
+ * The native bridge now logs the FIRST arrival of each property, once
291
+ * per session, so "does this property ever arrive?" is answerable from a
292
+ * device log without a rebuild. Keep that log: it is what makes the next
293
+ * claim of this kind checkable.
294
+ *
295
+ * Do not read a green test suite as evidence the delivery path works —
296
+ * the whole suite mocks the emitter. The evidence is a device log.
286
297
  */
287
298
  const OBSERVED_PROPERTIES: readonly string[] = [
288
299
  'time-pos',
@@ -0,0 +1,121 @@
1
+ import React, { useMemo } from 'react';
2
+ import { StyleSheet } from 'react-native';
3
+
4
+ import { getMpvPlayerModule } from '../bridge/MpvPlayerModule';
5
+ import NativeSimbaVideoView from '../specs/SimbaVideoViewNativeComponent';
6
+ import type { NativeProps as NativeSimbaVideoViewProps } from '../specs/SimbaVideoViewNativeComponent';
7
+
8
+ export type SimbaVideoResizeMode = 'contain' | 'cover' | 'stretch';
9
+
10
+ export interface SimbaVideoProps extends NativeSimbaVideoViewProps {
11
+ /**
12
+ * How the picture fills this view. Maps onto mpv's `video-zoom`
13
+ * (0 / 1 / 2) rather than being reimplemented.
14
+ *
15
+ * @default 'contain'
16
+ */
17
+ resizeMode?: SimbaVideoResizeMode;
18
+ }
19
+
20
+ /**
21
+ * The video picture, as an ordinary React Native view.
22
+ *
23
+ * This is the whole point of the component: the surface is a **child of the
24
+ * React tree**, not a sibling of the React root. Everything that made video
25
+ * awkward follows from that one fact being fixed — React Native owns the
26
+ * layout, the z-order and the lifecycle, so no screen has to blank itself
27
+ * around the player and no code has to hand window coordinates to the engine.
28
+ *
29
+ * ```tsx
30
+ * <SafeAreaView style={{ flex: 1, backgroundColor: '#000' }}>
31
+ * <Header title={state.title} onBack={commands.pause} />
32
+ * <SimbaVideo style={StyleSheet.absoluteFill} />
33
+ * <Controls onPlay={commands.togglePlayPause} onPip={commands.enterPip} />
34
+ * </SafeAreaView>
35
+ * ```
36
+ *
37
+ * ## Controlling it
38
+ *
39
+ * There is deliberately no ref. Playback and Picture-in-Picture are properties
40
+ * of the **engine** and the **Activity**, not of this view, so they already
41
+ * live on `usePlayer().commands` and work from any component, anywhere:
42
+ *
43
+ * ```tsx
44
+ * const { commands } = usePlayer();
45
+ * commands.play(); commands.pause(); commands.setVolume(50);
46
+ * commands.seek(30_000); commands.enterPip(); commands.next();
47
+ * ```
48
+ *
49
+ * A view-addressed `enterPictureInPicture()` would be strictly worse: PiP is
50
+ * requested exactly when the fullscreen view is about to unmount, so an
51
+ * implementation that needed a live view would fail at the one moment it
52
+ * matters.
53
+ *
54
+ * ## Audio needs none of this
55
+ *
56
+ * Audio-only playback renders no view at all. The engine runs with no render
57
+ * target, which is mpv's correct configuration for audio, and every command
58
+ * above keeps working.
59
+ */
60
+ export function SimbaVideo(props: SimbaVideoProps): React.ReactElement {
61
+ const { nativePtr, resizeMode = 'contain', paused, muted, volume, style, ...rest } = props;
62
+
63
+ /**
64
+ * `PlayerProvider` calls `initPlayer()` on mount, and the native side
65
+ * short-circuits when a handle already exists, so inside a provider the
66
+ * handle is always available before any child renders. Resolving it during
67
+ * render rather than in an effect is deliberate: an effect would mount the
68
+ * surface unbound first and leave `MpvRenderView` waiting for a
69
+ * `setNativePtr` that only arrives on a later commit.
70
+ *
71
+ * Outside a provider, or when an app manages more than one engine, pass
72
+ * `nativePtr` explicitly.
73
+ */
74
+ const resolvedPtr = useMemo(
75
+ () => nativePtr ?? getMpvPlayerModule().getNativePtr(),
76
+ [nativePtr],
77
+ );
78
+
79
+ const videoZoom = useMemo(() => {
80
+ switch (resizeMode) {
81
+ case 'cover':
82
+ return '1';
83
+ case 'stretch':
84
+ return '2';
85
+ case 'contain':
86
+ default:
87
+ return '0';
88
+ }
89
+ }, [resizeMode]);
90
+
91
+ return (
92
+ <NativeSimbaVideoView
93
+ {...rest}
94
+ nativePtr={resolvedPtr}
95
+ paused={paused ?? false}
96
+ muted={muted ?? false}
97
+ volume={volume ?? 100}
98
+ resizeMode={videoZoom}
99
+ style={[styles.fill, style]}
100
+ />
101
+ );
102
+ }
103
+
104
+ const styles = StyleSheet.create({
105
+ /**
106
+ * Full-bleed by default, so a caller who forgets a style gets a sensible
107
+ * picture rather than a zero-height view. A zero-height surface renders no
108
+ * frames and reports no error anywhere, which is the worst possible failure
109
+ * mode for a video component.
110
+ *
111
+ * Written out rather than using `StyleSheet.absoluteFill*`, which is not
112
+ * declared on the `StyleSheet` type in React Native 0.86.
113
+ */
114
+ fill: {
115
+ position: 'absolute',
116
+ top: 0,
117
+ left: 0,
118
+ right: 0,
119
+ bottom: 0,
120
+ },
121
+ });
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Contract tests for `<SimbaVideo>`.
3
+ *
4
+ * These pin the promise the component makes to a consumer: it is an ordinary
5
+ * React Native view that React Native lays out, and every prop on it either
6
+ * reaches the native view or has a stated default.
7
+ *
8
+ * The native component is mocked as a host element ('SimbaVideoView') and
9
+ * located by testID. RNTL 14 has no `getByType` - only semantic queries - and
10
+ * a testID lookup that succeeds is itself the proof that matters: the view is
11
+ * reachable *through the React tree*. That is the whole regression this
12
+ * component exists to fix. The old picture was mounted by Kotlin at
13
+ * `android.R.id.content`, a sibling of the React root, so no React query could
14
+ * ever have found it.
15
+ */
16
+ import React from 'react';
17
+ import { render, screen } from '@testing-library/react-native';
18
+
19
+ import { SimbaVideo, type SimbaVideoProps } from '../SimbaVideo';
20
+
21
+ jest.mock('../../specs/SimbaVideoViewNativeComponent', () => ({
22
+ __esModule: true,
23
+ default: 'SimbaVideoView',
24
+ }));
25
+
26
+ const TEST_ID = 'native-video';
27
+
28
+ // `jest.setup.ts` already installs `getNativePtr: fn(() => 0)` on
29
+ // NativeModules.MpvPlayerModule.
30
+ const bridge = () =>
31
+ require('react-native').NativeModules.MpvPlayerModule as {
32
+ getNativePtr: jest.Mock;
33
+ };
34
+
35
+ /** Render and return the props that actually cross into the native view. */
36
+ async function renderNative(
37
+ props: Partial<SimbaVideoProps> = {},
38
+ ): Promise<Record<string, unknown>> {
39
+ await render(<SimbaVideo testID={TEST_ID} {...props} />);
40
+ return screen.getByTestId(TEST_ID).props as Record<string, unknown>;
41
+ }
42
+
43
+ describe('SimbaVideo', () => {
44
+ beforeEach(() => {
45
+ jest.clearAllMocks();
46
+ bridge().getNativePtr.mockReturnValue(0);
47
+ });
48
+
49
+ it('renders a real native view reachable through the React tree', async () => {
50
+ // If this test needs changing, the surface is no longer in the tree.
51
+ await render(<SimbaVideo testID={TEST_ID} />);
52
+
53
+ expect(screen.getByTestId(TEST_ID)).toBeTruthy();
54
+ });
55
+
56
+ describe('nativePtr', () => {
57
+ it('resolves the handle from the bridge when the prop is absent', async () => {
58
+ bridge().getNativePtr.mockReturnValue(4242);
59
+
60
+ const p = await renderNative();
61
+
62
+ expect(p.nativePtr).toBe(4242);
63
+ });
64
+
65
+ it('prefers an explicit prop and does not consult the bridge', async () => {
66
+ // An app managing more than one engine passes its own handle. Silently
67
+ // preferring the singleton would bind the wrong engine with no error.
68
+ const p = await renderNative({ nativePtr: 99 });
69
+
70
+ expect(p.nativePtr).toBe(99);
71
+ expect(bridge().getNativePtr).not.toHaveBeenCalled();
72
+ });
73
+
74
+ it('passes the handle through unrounded', async () => {
75
+ // mpv handles are 64-bit. An Int32 round-trip would hand mpv a pointer
76
+ // to nothing, and the symptom would be "video never appears" rather
77
+ // than a type error.
78
+ const big = 9007199254740991; // > Number.MAX_SAFE_INTEGER
79
+ const p = await renderNative({ nativePtr: big });
80
+
81
+ expect(p.nativePtr).toBe(big);
82
+ });
83
+ });
84
+
85
+ describe('resizeMode maps onto mpv video-zoom', () => {
86
+ it('contain is the default and maps to 0 (fit, letterboxed)', async () => {
87
+ expect((await renderNative()).resizeMode).toBe('0');
88
+ });
89
+
90
+ it('contain → 0 when asked for explicitly', async () => {
91
+ expect((await renderNative({ resizeMode: 'contain' })).resizeMode).toBe('0');
92
+ });
93
+
94
+ it('cover → 1 (fill, cropping, aspect preserved)', async () => {
95
+ expect((await renderNative({ resizeMode: 'cover' })).resizeMode).toBe('1');
96
+ });
97
+
98
+ it('stretch → 2 (fill, aspect ignored)', async () => {
99
+ expect((await renderNative({ resizeMode: 'stretch' })).resizeMode).toBe('2');
100
+ });
101
+
102
+ it('falls back to fit for an unrecognised mode', async () => {
103
+ // mpv would reject an unknown video-zoom value; a wrong-but-valid
104
+ // letterbox is recoverable, a rejected property is not.
105
+ const p = await renderNative({ resizeMode: 'bogus' as never });
106
+ expect(p.resizeMode).toBe('0');
107
+ });
108
+ });
109
+
110
+ describe('defaults', () => {
111
+ it('applies stated defaults for every prop that reaches native', async () => {
112
+ // A native view defaulting to "unset" while Kotlin defaults to
113
+ // something else is how a prop ends up looking accepted while doing
114
+ // nothing.
115
+ const p = await renderNative();
116
+
117
+ expect(p.paused).toBe(false);
118
+ expect(p.muted).toBe(false);
119
+ expect(p.volume).toBe(100);
120
+ });
121
+
122
+ it('honours explicit values over defaults', async () => {
123
+ const p = await renderNative({ paused: true, muted: true, volume: 35 });
124
+
125
+ expect(p.paused).toBe(true);
126
+ expect(p.muted).toBe(true);
127
+ expect(p.volume).toBe(35);
128
+ });
129
+ });
130
+
131
+ describe('layout', () => {
132
+ it('carries a full-bleed default style', async () => {
133
+ // A caller who forgets a style must not get a zero-height surface.
134
+ // That renders no frames and reports no error anywhere - the exact
135
+ // failure this project keeps having to chase.
136
+ const style = (await renderNative()).style as Array<
137
+ Record<string, unknown>
138
+ >;
139
+
140
+ expect(style[0]).toMatchObject({
141
+ position: 'absolute',
142
+ top: 0,
143
+ left: 0,
144
+ right: 0,
145
+ bottom: 0,
146
+ });
147
+ });
148
+
149
+ it('lets the caller override the default style', async () => {
150
+ const style = (await renderNative({ style: { flex: 1 } }))
151
+ .style as Array<Record<string, unknown>>;
152
+
153
+ expect(style[1]).toEqual({ flex: 1 });
154
+ });
155
+ });
156
+
157
+ it('forwards unknown props through to the native view', async () => {
158
+ await render(
159
+ <SimbaVideo testID={TEST_ID} accessibilityLabel="Video" />,
160
+ );
161
+
162
+ expect(screen.getByTestId(TEST_ID).props.accessibilityLabel).toBe('Video');
163
+ });
164
+ });
package/src/index.ts CHANGED
@@ -26,6 +26,12 @@ export {
26
26
 
27
27
  export { PlayerRoot } from './components/PlayerRoot';
28
28
 
29
+ export {
30
+ SimbaVideo,
31
+ type SimbaVideoProps,
32
+ type SimbaVideoResizeMode,
33
+ } from './components/SimbaVideo';
34
+
29
35
  export { PlayerSurface, type PlayerSurfaceProps } from './components/PlayerSurface';
30
36
 
31
37
  export {
@@ -0,0 +1,84 @@
1
+ import type { ViewProps } from 'react-native';
2
+ import type {
3
+ Double,
4
+ Float,
5
+ WithDefault,
6
+ } from 'react-native/Libraries/Types/CodegenTypes';
7
+ import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';
8
+
9
+ /**
10
+ * Codegen spec for the native mpv video surface.
11
+ *
12
+ * This is the component that makes the picture an ordinary child of the React
13
+ * tree instead of a sibling of the React root. Everything else about SIMBA's
14
+ * video lane follows from that:
15
+ *
16
+ * - React Native owns layout, so the surface gets a real Yoga measure/layout
17
+ * pass. The old path mutated `LayoutParams` straight from Kotlin, which
18
+ * `react-native-video` documents as a hazard - see its `ExoPlayerView`
19
+ * `requestLayout()` override: "React Native (Yoga) can sometimes defer
20
+ * layout passes that are required by ... surface view".
21
+ * - React Native owns z-order, so the video no longer sits behind an opaque
22
+ * React root and no screen has to blank itself around it.
23
+ * - React Native owns the lifecycle, so mount/unmount is the same event for
24
+ * the surface as for any other view.
25
+ *
26
+ * No events are declared in this first revision, deliberately. `MPVLib`
27
+ * forwards decoded mpv events through `onMpvEvent(event, jsonPayload)`, but
28
+ * which event names the C++ layer actually emits has not been verified against
29
+ * a running instance. Shipping an `onReadyForDisplay` prop that never fires
30
+ * would be worse than not shipping it: it would look like a working
31
+ * first-frame signal while being decorative. Events get added once they can be
32
+ * observed.
33
+ */
34
+ export interface NativeProps extends ViewProps {
35
+ /**
36
+ * The mpv handle to bind this surface to, from `getNativePtr()`.
37
+ *
38
+ * `Double`, not `Int32`: mpv handles are 64-bit pointers and an `Int32`
39
+ * prop would truncate them to 32 bits. Codegen maps `Double` to a Kotlin
40
+ * `double`, which carries the full range.
41
+ *
42
+ * May be omitted before the player is initialised. `MpvRenderView` treats a
43
+ * zero handle as "not bindable yet" and re-attaches from `onAttachedToWindow`
44
+ * once a real handle arrives, so an app that renders the view on first paint
45
+ * does not have to wait for the bridge.
46
+ */
47
+ nativePtr?: Double;
48
+
49
+ /**
50
+ * Pause playback. Declarative: set it and the surface pauses, exactly like
51
+ * `react-native-video`'s `paused` prop.
52
+ *
53
+ * Audio-only playback is the case where no view is rendered at all - the
54
+ * engine keeps running with no render target, which is the correct
55
+ * configuration for mpv.
56
+ */
57
+ paused?: WithDefault<boolean, false>;
58
+
59
+ /** Mute. Mirrors `PlayerCommands.setMuted`. */
60
+ muted?: WithDefault<boolean, false>;
61
+
62
+ /**
63
+ * Playback volume, 0..100 - mpv's native range, matching the range
64
+ * `PlayerCommands.setVolume` already exposes. No 0..1 rescaling: one unit
65
+ * system end to end, so a value read from the engine is a value you can hand
66
+ * straight back to it.
67
+ */
68
+ volume?: WithDefault<Float, 100>;
69
+
70
+ /**
71
+ * How the picture fills this view.
72
+ *
73
+ * - `contain` - fit inside, letterboxed. Default, and what every shipping
74
+ * media app uses for fullscreen video.
75
+ * - `cover` - fill the view, cropping the overflow, aspect preserved.
76
+ * - `stretch` - fill the view, aspect ignored.
77
+ *
78
+ * Maps onto mpv's `video-zoom` (0 / 1 / 2) rather than being reimplemented,
79
+ * so it inherits mpv's own scaling and rounding behaviour.
80
+ */
81
+ resizeMode?: WithDefault<string, 'contain'>;
82
+ }
83
+
84
+ export default codegenNativeComponent<NativeProps>('SimbaVideoView');
@@ -434,6 +434,7 @@ describe('usePlayer (inside PlayerProvider)', () => {
434
434
  'onVideoParamsChanged',
435
435
  'onError',
436
436
  'onBuffering',
437
+ 'onCacheFill',
437
438
  'onCacheState',
438
439
  'onSeekable',
439
440
  'onSeeking',
@@ -473,6 +474,128 @@ describe('usePlayer (inside PlayerProvider)', () => {
473
474
  expect(result.current.state.isPlaying).toBe(true);
474
475
  });
475
476
 
477
+ // ── The buffering contract: one fact, one owner ────────────────────────
478
+ //
479
+ // Three mpv properties, three facts, and they were tangled into two
480
+ // events with contradictory rules:
481
+ //
482
+ // `paused-for-cache` -> is the player STALLED? (a boolean)
483
+ // `cache-buffering-state` -> how full is the cache? (a percentage)
484
+ // `demuxer-cache-state` -> what is the TIMELINE? (ranges)
485
+ //
486
+ // `cache-buffering-state` used to write `isBuffering` as
487
+ // "percent < 100", which is true for most of a stream's life — a
488
+ // partially-filled cache is the NORMAL state during playback — so the
489
+ // spinner could latch on during perfectly healthy playback. And
490
+ // `paused-for-cache` invented a percentage (0 when stalled, 100 when
491
+ // not) that overwrote the real fill with a fabricated number.
492
+ //
493
+ // Each fact now has exactly one owner, and each event touches exactly
494
+ // one field. These tests are what keeps it that way.
495
+ describe('the buffering contract', () => {
496
+ let subs: ReturnType<typeof captureSubscribes>;
497
+
498
+ beforeEach(() => {
499
+ clearBridgeMocks();
500
+ subs = captureSubscribes();
501
+ });
502
+
503
+ afterEach(() => {
504
+ subs.restore();
505
+ });
506
+
507
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
508
+ <PlayerProvider>{children}</PlayerProvider>
509
+ );
510
+
511
+ async function fire(event: string, payload: Record<string, unknown>) {
512
+ const listeners = subs.handlers.get(event) ?? [];
513
+ expect(listeners.length).toBeGreaterThan(0);
514
+ await act(async () => {
515
+ for (const l of listeners) l(payload);
516
+ });
517
+ }
518
+
519
+ it('onBuffering sets the stall flag and nothing else', async () => {
520
+ const { result } = await renderHook(() => usePlayerProgress(), {
521
+ wrapper,
522
+ });
523
+
524
+ await fire('onBuffering', { isBuffering: true });
525
+
526
+ expect(result.current.isBuffering).toBe(true);
527
+ // The stall signal does not know the fill, so it must not invent
528
+ // one. It used to write 0/100, which destroyed the real fill.
529
+ expect(result.current.cacheFill).toBe(0);
530
+ });
531
+
532
+ it('onBuffering clears the stall flag when the stall ends', async () => {
533
+ const { result } = await renderHook(() => usePlayerProgress(), {
534
+ wrapper,
535
+ });
536
+
537
+ await fire('onBuffering', { isBuffering: true });
538
+ expect(result.current.isBuffering).toBe(true);
539
+
540
+ // The `false` case is the one that matters: `paused-for-cache` goes
541
+ // false the moment the cache recovers, and a consumer that cannot see
542
+ // that transition keeps a spinner on a player that is running.
543
+ await fire('onBuffering', { isBuffering: false });
544
+ expect(result.current.isBuffering).toBe(false);
545
+ });
546
+
547
+ it('onCacheFill sets the fill and never the stall flag', async () => {
548
+ const { result } = await renderHook(() => usePlayerProgress(), {
549
+ wrapper,
550
+ });
551
+
552
+ await fire('onCacheFill', { percent: 37 });
553
+
554
+ expect(result.current.cacheFill).toBe(37);
555
+ // A partially-filled cache is the NORMAL state during playback. It
556
+ // is not a stall, and reading it as one pinned the spinner on.
557
+ expect(result.current.isBuffering).toBe(false);
558
+ });
559
+
560
+ it('onCacheState sets the buffered ranges and never the fill', async () => {
561
+ const { result } = await renderHook(() => usePlayerProgress(), {
562
+ wrapper,
563
+ });
564
+
565
+ // The ranges arrive in MILLISECONDS: the native bridge converts,
566
+ // because it is the only layer that knows the payload's unit.
567
+ await fire('onCacheState', { ranges: [{ start: 0, end: 60000 }] });
568
+
569
+ expect(result.current.cacheRanges).toEqual([{ start: 0, end: 60000 }]);
570
+ expect(result.current.cacheFill).toBe(0);
571
+ });
572
+
573
+ it('onCacheState keeps the last known ranges when the payload carries none', async () => {
574
+ const { result } = await renderHook(() => usePlayerProgress(), {
575
+ wrapper,
576
+ });
577
+
578
+ await fire('onCacheState', { ranges: [{ start: 0, end: 60000 }] });
579
+ await fire('onCacheState', {});
580
+
581
+ expect(result.current.cacheRanges).toEqual([{ start: 0, end: 60000 }]);
582
+ });
583
+
584
+ it('onCacheState with an explicit empty array clears the ranges', async () => {
585
+ const { result } = await renderHook(() => usePlayerProgress(), {
586
+ wrapper,
587
+ });
588
+
589
+ await fire('onCacheState', { ranges: [{ start: 0, end: 60000 }] });
590
+ await fire('onCacheState', { ranges: [] });
591
+
592
+ // mpv saying "the cache is empty" is different from saying nothing,
593
+ // and the difference is the difference between an honest bar and a
594
+ // stale one.
595
+ expect(result.current.cacheRanges).toEqual([]);
596
+ });
597
+ });
598
+
476
599
  // ── The mute flag arrives as a STRING ─────────────────────────────────
477
600
  //
478
601
  // `applyPlayerEvent`'s `mute` case used to be