@simba-dev/react-native-media-player 1.17.0 → 1.19.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.
@@ -241,28 +241,76 @@ Java_com_simba_player_mpv_MPVLib_nativeCreate(JNIEnv *env, jclass, jstring caFil
241
241
  //
242
242
  // • cache=yes : enable a RAM cache even for non-network
243
243
  // sources (so seek-back is instant).
244
- // • cache-secs=120 : keep ~2 minutes of stream ahead of the
244
+ // • cache-secs=300 : keep ~5 minutes of stream ahead of the
245
245
  // playhead in RAM. Big enough to absorb a
246
246
  // brief re-buffer without a spinner, small
247
247
  // enough to stay under mobile RAM limits.
248
+ //
249
+ // This was 120 s, and 120 s is not enough to
250
+ // SEE. The buffered range a consumer draws
251
+ // is the span between the playhead and the
252
+ // end of the buffer, and the seek bar's thumb
253
+ // covers 3.04 % of the track (a 14 dp thumb on
254
+ // a 230 dp rail). On a feature-length film
255
+ // 120 s is 2.44 % of the file — LESS than
256
+ // the thumb — so the thumb covered the whole
257
+ // visible band and the buffered indicator
258
+ // could not be seen at all. Measured on
259
+ // device (2026-10-20): track 690 px, band
260
+ // 16 px, thumb half-width 21 px. 300 s is
261
+ // 6.1 % of the same film, so the band
262
+ // clears the thumb.
248
263
  // • demuxer-max-bytes : hard upper bound on the cache size in
249
264
  // bytes (≈150 MB). Prevents OOM on large
250
265
  // VOD files over HTTP.
266
+ //
267
+ // This is the SECOND bound on how far
268
+ // the buffered band can reach: 300 s of
269
+ // video only fits in 150 MB at ≤4 Mbit/s,
270
+ // so above that bitrate the byte cap
271
+ // binds first and the band is shorter
272
+ // than 300 s. The band was measured on
273
+ // device rather than assumed.
251
274
  // • demuxer-max-back-bytes : how far backwards the cache retains
252
275
  // data (~75 MB). This is what makes
253
276
  // "seek back 30 s" instantaneous.
254
277
  // • demuxer-readahead-secs : how many seconds of stream to prefetch
255
278
  // ahead of the playhead.
279
+ //
280
+ // It is NOT independent of `cache-secs`.
281
+ // mpv computes the demuxer's read-ahead
282
+ // target as the MAXIMUM of the two —
283
+ // mpv `demux/demux.c`, `update_opts()`:
284
+ //
285
+ // in->min_secs = opts->min_secs; // readahead
286
+ // if (use_cache)
287
+ // in->min_secs = MPMAX(in->min_secs,
288
+ // opts->min_secs_cache);
289
+ // // cache-secs
290
+ //
291
+ // `update_opts()` re-runs on EVERY config
292
+ // change, so the two must be raised AND
293
+ // lowered together. That is why the runtime
294
+ // memory-pressure trim in
295
+ // `MpvBridgeModule.onTrimMemory` writes
296
+ // BOTH — trimming only `cache-secs` would
297
+ // leave the read-ahead pinned and the trim
298
+ // would have no effect at all.
299
+ //
300
+ // The span between the playhead and the end
301
+ // of the buffer is exactly what a consumer
302
+ // paints as its buffered range, so this
303
+ // value is what makes that span visible.
256
304
  // • demuxer-termination-timeout : if a network read stalls, fail
257
305
  // the demuxer so the player can recover
258
306
  // instead of hanging forever.
259
307
  // • prefetch-playlist=yes : proactively fetch the next playlist
260
308
  // entry (HLS / DASH) to enable gapless.
261
309
  mpv_set_option_string(mpv, "cache", "yes");
262
- mpv_set_option_string(mpv, "cache-secs", "120");
310
+ mpv_set_option_string(mpv, "cache-secs", "300");
263
311
  mpv_set_option_string(mpv, "demuxer-max-bytes", "150MiB");
264
312
  mpv_set_option_string(mpv, "demuxer-max-back-bytes", "75MiB");
265
- mpv_set_option_string(mpv, "demuxer-readahead-secs", "120");
313
+ mpv_set_option_string(mpv, "demuxer-readahead-secs", "300");
266
314
  mpv_set_option_string(mpv, "demuxer-termination-timeout", "10");
267
315
  mpv_set_option_string(mpv, "prefetch-playlist", "yes");
268
316
 
@@ -31,7 +31,8 @@ import org.json.JSONObject
31
31
  */
32
32
  @ReactModule(name = MpvBridgeModule.NAME)
33
33
  class MpvBridgeModule(reactContext: ReactApplicationContext) :
34
- NativeMpvPlayerSpec(reactContext) {
34
+ NativeMpvPlayerSpec(reactContext),
35
+ android.content.ComponentCallbacks2 {
35
36
 
36
37
  companion object {
37
38
  const val NAME = "MpvPlayerModule"
@@ -1105,6 +1106,12 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1105
1106
  @Override
1106
1107
  override fun loadFile(path: String) {
1107
1108
  ensurePtr()
1109
+ // A new file gets the FULL prefetch window. A previous
1110
+ // memory-pressure trim reduced it, and without this the
1111
+ // reduction would persist for the rest of the process, leaving
1112
+ // every later playback with a 10 s buffer — and therefore an
1113
+ // invisible buffered band.
1114
+ applyCacheWindow(baseCacheWindowSecs, "new load")
1108
1115
  val resolvedPath = normalizeMpvInput(resolveContentUri(path))
1109
1116
  Log.i(TAG, "[PlaybackTrace][Bridge][loadFile] requested=$path resolved=$resolvedPath ptr=$nativePtr")
1110
1117
  emitLoadRequested(path)
@@ -1121,6 +1128,9 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1121
1128
  @Override
1122
1129
  override fun loadFileWithRequestId(path: String, requestId: String) {
1123
1130
  ensurePtr()
1131
+ // Same reasoning as `loadFile`: a new file restores the full
1132
+ // prefetch window after any memory-pressure trim.
1133
+ applyCacheWindow(baseCacheWindowSecs, "new load")
1124
1134
  if (requestId.isBlank()) {
1125
1135
  loadFile(path)
1126
1136
  return
@@ -1748,23 +1758,87 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1748
1758
  }
1749
1759
 
1750
1760
  /**
1751
- * Phase 39 + Phase 38.7: react to system memory pressure by reducing
1752
- * mpv's cache. Registered as a ComponentCallbacks2 listener in
1753
- * PlayerActivity.onCreate; called by the system when the process
1754
- * is at a trim level.
1761
+ * The prefetch / cache window, in seconds, used when the system is
1762
+ * NOT under memory pressure.
1755
1763
  *
1756
- * Levels:
1757
- * - TRIM_MEMORY_RUNNING_MODERATE (5) → cache-secs=10
1758
- * - TRIM_MEMORY_RUNNING_LOW (10) → cache-secs=5
1759
- * - TRIM_MEMORY_RUNNING_CRITICAL (15) → cache-secs=2
1760
- * - TRIM_MEMORY_BACKGROUND (40) → cache-secs=10
1761
- * - TRIM_MEMORY_COMPLETE (80) → cache-secs=0
1762
- *
1763
- * Public so PlayerActivity can register the listener (it has the
1764
- * Application context for ComponentCallbacks2 registration).
1764
+ * MUST match `cache-secs` and `demuxer-readahead-secs` in
1765
+ * `android/src/main/cpp/main.cpp` — the two places that set the
1766
+ * same policy, kept in step deliberately.
1767
+ *
1768
+ * 300 s is chosen so the buffered band a seek bar paints is
1769
+ * WIDER than the scrub thumb that sits on top of it. A 14 dp
1770
+ * thumb covers 3.04 % of a 230 dp rail; 300 s is 6.1 % of a
1771
+ * feature-length film and 120 s was only 2.44 %, so at 120 s the
1772
+ * thumb covered the entire visible band and the buffered
1773
+ * indicator could not be seen at all (measured on device
1774
+ * 2026-10-20: track 690 px, band 16 px, thumb half-width 21 px).
1765
1775
  */
1766
- fun onTrimMemory(level: Int) {
1776
+ private val baseCacheWindowSecs = 300
1777
+
1778
+ /**
1779
+ * Apply a cache / prefetch window to BOTH mpv options that govern it.
1780
+ *
1781
+ * mpv computes the demuxer's read-ahead target as the MAXIMUM of
1782
+ * the two options, not as one overriding the other:
1783
+ *
1784
+ * mpv `demux/demux.c`, `update_opts()`:
1785
+ * in->min_secs = opts->min_secs; // demuxer-readahead-secs
1786
+ * if (use_cache)
1787
+ * in->min_secs = MPMAX(in->min_secs, opts->min_secs_cache);
1788
+ * // cache-secs
1789
+ *
1790
+ * `update_opts()` re-runs on EVERY config change, so trimming only
1791
+ * `cache-secs` would leave `in->min_secs` pinned at the readahead
1792
+ * value and the trim would have NO effect at all. Both options
1793
+ * therefore always move together. That is a property of mpv, not a
1794
+ * style choice.
1795
+ */
1796
+ private fun applyCacheWindow(seconds: Int, reason: String) {
1767
1797
  if (nativePtr == 0L) return
1798
+ try {
1799
+ MPVLib.setPropertyString(nativePtr, "cache-secs", seconds.toString())
1800
+ MPVLib.setPropertyString(nativePtr, "demuxer-readahead-secs", seconds.toString())
1801
+ Log.w(
1802
+ TAG,
1803
+ "[PlaybackTrace][Bridge][cacheWindow] $reason → cache-secs=$seconds " +
1804
+ "demuxer-readahead-secs=$seconds",
1805
+ )
1806
+ } catch (e: Exception) {
1807
+ Log.w(TAG, "[PlaybackTrace][Bridge][cacheWindow] $reason failed: ${e.message}", e)
1808
+ }
1809
+ }
1810
+
1811
+ /**
1812
+ * System memory pressure: shrink the prefetch window.
1813
+ *
1814
+ * This module implements `ComponentCallbacks2` and is registered
1815
+ * with the application context in `initialize()` (and unregistered
1816
+ * in `onCatalystInstanceDestroy()`), so the system actually
1817
+ * reaches this. An earlier version of this file documented a
1818
+ * `PlayerActivity.onCreate` registration that did not exist, so the
1819
+ * handler was DEAD: the buffer was never reduced, and the
1820
+ * documented policy was fiction.
1821
+ *
1822
+ * Levels:
1823
+ * - TRIM_MEMORY_RUNNING_MODERATE (5) → 10 s
1824
+ * - TRIM_MEMORY_RUNNING_LOW (10) → 5 s
1825
+ * - TRIM_MEMORY_RUNNING_CRITICAL (15) → 2 s
1826
+ * - TRIM_MEMORY_BACKGROUND (40) → 10 s
1827
+ * - TRIM_MEMORY_COMPLETE (80) → 0 s
1828
+ *
1829
+ * A trim is a REACTION to pressure, not a new setting: loading a
1830
+ * file restores the base window, so the reduction is not a
1831
+ * permanent ratchet that leaves every later playback with a 10 s
1832
+ * buffer — and therefore an invisible buffered band.
1833
+ */
1834
+ // `ComponentCallbacks2.onTrimMemory(int)` and the `TRIM_MEMORY_*`
1835
+ // constants carry `@Deprecated` from API 35, but this 1-arg method
1836
+ // is the ONLY trim callback the platform exposes — checked against
1837
+ // the installed android-34 / 35 / 36 / 36.1 jars, none of them has a
1838
+ // 2-arg overload. Implementing it is therefore the only way a
1839
+ // memory-pressure policy can run at all.
1840
+ @Suppress("DEPRECATION", "OVERRIDE_DEPRECATION")
1841
+ override fun onTrimMemory(level: Int) {
1768
1842
  val cacheSecs: Int = when (level) {
1769
1843
  android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE -> 10
1770
1844
  android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW -> 5
@@ -1773,12 +1847,25 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1773
1847
  android.content.ComponentCallbacks2.TRIM_MEMORY_COMPLETE -> 0
1774
1848
  else -> return // unknown level — no change
1775
1849
  }
1776
- try {
1777
- MPVLib.setPropertyString(nativePtr, "cache-secs", cacheSecs.toString())
1778
- Log.w(TAG, "[PlaybackTrace][Bridge][onTrimMemory] level=$level → cache-secs=$cacheSecs")
1779
- } catch (e: Exception) {
1780
- Log.w(TAG, "[PlaybackTrace][Bridge][onTrimMemory] setPropertyString failed: ${e.message}", e)
1781
- }
1850
+ applyCacheWindow(cacheSecs, "trim level=$level")
1851
+ }
1852
+
1853
+ /**
1854
+ * `ComponentCallbacks2` also requires `onLowMemory` — the
1855
+ * platform's "you are about to be killed" signal. The window goes
1856
+ * to zero.
1857
+ */
1858
+ @Suppress("DEPRECATION", "OVERRIDE_DEPRECATION")
1859
+ override fun onLowMemory() {
1860
+ applyCacheWindow(0, "low memory")
1861
+ }
1862
+
1863
+ /**
1864
+ * Required by `ComponentCallbacks2`. The cache window does not
1865
+ * depend on the configuration, so there is nothing to do.
1866
+ */
1867
+ override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
1868
+ // no-op by design
1782
1869
  }
1783
1870
 
1784
1871
  @ReactMethod
@@ -1796,6 +1883,9 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1796
1883
  override fun initialize() {
1797
1884
  super.initialize()
1798
1885
  MPVLib.addListener(mpvListener)
1886
+ // Register the memory-pressure callback so `onTrimMemory` /
1887
+ // `onLowMemory` are actually reached by the platform.
1888
+ reactApplicationContext.registerComponentCallbacks(this)
1799
1889
  // Phase 39: native module init logging. Logs the key
1800
1890
  // properties of the bridge on init so dev tools can confirm
1801
1891
  // the module is wired + report version/build info. Use
@@ -1811,6 +1901,7 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1811
1901
  override fun onCatalystInstanceDestroy() {
1812
1902
  destroy()
1813
1903
  MPVLib.removeListener(mpvListener)
1904
+ reactApplicationContext.unregisterComponentCallbacks(this)
1814
1905
  // Phase 36: clear the static ReactApplicationContext reference so the
1815
1906
  // bridge context can be reclaimed. Companion-level static fields hold
1816
1907
  // the only strong reference to the React context across reloads;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.17.0",
3
+ "version": "1.19.0",
4
4
  "description": "React Native video & audio player powered by libmpv — Picture-in-Picture, MediaSession, foreground service, and a customizable TypeScript UI. Built for Android. Designed as a drop-in replacement for react-native-video / react-native-track-player / expo-av. See CHANGELOG.md for per-version notes.",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -682,9 +682,33 @@ export function PlayerProvider({
682
682
  setState(nextState);
683
683
  }
684
684
  // Progress: apply the patch via the functional setState
685
- // form so we can compare against the previous value (the
686
- // ref may have been updated by another event handler in
687
- // the same batch).
685
+ // form so we can compare against the COMMITTED value and
686
+ // skip the update when no field changed.
687
+ //
688
+ // The ref MUST be written HERE, synchronously, for the same
689
+ // reason `stateRef.current` is written above: `applyPlayerEvent`
690
+ // reads the CURRENT progress to compute the next one, and React
691
+ // DEFERS the updater function to the render phase. A ref written
692
+ // only inside the updater is therefore out of step with the state
693
+ // ref by one flush, and any event arriving before that flush
694
+ // computes its nextProgress from a STALE progress — silently
695
+ // dropping fields an earlier event had already delivered.
696
+ //
697
+ // MEASURED on device (2026-10-20, lib 1.17.0): mpv delivered
698
+ // `duration` and `time-pos` inside one batch. The duration event
699
+ // wrote `state.durationMs = 7673792` correctly, but the PROGRESS
700
+ // context kept `durationMs = 0`, because the position event —
701
+ // computed from the stale progress — replaced it with 0.
702
+ //
703
+ // The visible effect was a seek bar with no played fill, NO
704
+ // buffered range at all (the consumer gates the buffered window
705
+ // on `durationMs > 0`), and "--:--" for the remaining time — on a
706
+ // video that was demonstrably playing.
707
+ //
708
+ // Writing the ref here also makes the updater PURE: it used to
709
+ // write `progressRef.current` from inside the updater, which is a
710
+ // side effect in a function React may invoke more than once.
711
+ progressRef.current = nextProgress;
688
712
  setProgress((prev) => {
689
713
  // Cheap reference + field equality check.
690
714
  if (
@@ -698,7 +722,6 @@ export function PlayerProvider({
698
722
  ) {
699
723
  return prev;
700
724
  }
701
- progressRef.current = nextProgress;
702
725
  return nextProgress;
703
726
  });
704
727
 
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Regression tests: the PROGRESS context must not lose a field that the
3
+ * STATE context already holds.
4
+ *
5
+ * THE DEFECT (found on device, emulator-5554, 2026-10-20, lib 1.17.0):
6
+ *
7
+ * mpv delivers `duration` and `time-pos` inside ONE batch, ~3 ms apart
8
+ * (measured: `fileLoaded` 19:29:59.615, `time-pos` 19:29:59.616,
9
+ * `duration` 19:29:59.619). The provider handled each event with
10
+ * `applyPlayerEvent(stateRef.current, progressRef.current, ...)` and then
11
+ * wrote the two refs:
12
+ *
13
+ * - `stateRef.current` was written SYNCHRONOUSLY, in the event handler.
14
+ * - `progressRef.current` was written INSIDE the `setProgress` updater,
15
+ * which React DEFERS to the render phase.
16
+ *
17
+ * So the progress ref was one flush behind the state ref. The second event
18
+ * of the batch therefore computed its `nextProgress` from a STALE progress
19
+ * — one that did not yet contain the duration the first event had just
20
+ * delivered — and overwrote it with 0.
21
+ *
22
+ * MEASURED on device:
23
+ *
24
+ * state.durationMs = 7673792 (correct)
25
+ * progress.durationMs = 0 (WRONG)
26
+ *
27
+ * The visible damage was a seek bar with no played fill, NO buffered range
28
+ * at all (the consumer gates the buffered window on `durationMs > 0`), and
29
+ * "--:--" for the remaining time — on a video that was demonstrably
30
+ * playing.
31
+ *
32
+ * These tests pin the fix: the progress ref is written synchronously, in
33
+ * lockstep with the state ref.
34
+ *
35
+ * Test surface:
36
+ * - duration survives in the progress context when duration and position
37
+ * arrive in one batch (the exact device order)
38
+ * - duration survives when the order is reversed
39
+ * - duration survives across a longer run of interleaved events
40
+ * - the buffered ranges survive the same interleaving
41
+ * - the two contexts agree on the duration — the invariant the seek bar
42
+ * depends on
43
+ *
44
+ * The MpvPlayerModule bridge mock is installed globally in
45
+ * `jest.setup.ts`; its `getDuration` returns 0, so the hydrated baseline
46
+ * duration is 0 and every value asserted here arrives through the EVENT
47
+ * path. A test that passed on the hydrated baseline would prove nothing.
48
+ */
49
+
50
+ import React from 'react';
51
+ import { act, renderHook } from '@testing-library/react-native';
52
+ import { PlayerProvider } from '../PlayerProvider';
53
+ import { usePlayer, usePlayerProgress } from '../../types/player';
54
+
55
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
56
+ <PlayerProvider>{children}</PlayerProvider>
57
+ );
58
+
59
+ /**
60
+ * Deliver an event through the SAME emitter production uses.
61
+ *
62
+ * The bridge's `resolveEmitter()` builds a `NativeEventEmitter` over
63
+ * `NativeModules.MpvPlayerModule`, and on the native side the events are
64
+ * published through `RCTDeviceEventEmitter`. RN's own jest preset mocks
65
+ * `DeviceEventEmitter`, and `NativeEventEmitter` delegates to it, so
66
+ * emitting there drives the real subscription the provider registered.
67
+ */
68
+ function emit(eventName: string, payload: Record<string, unknown>): void {
69
+ const {
70
+ DeviceEventEmitter,
71
+ } = require('react-native') as typeof import('react-native');
72
+ DeviceEventEmitter.emit(eventName, payload);
73
+ }
74
+
75
+ /** The real movie length from the device session: 7673.792 seconds. */
76
+ const DURATION_S = 7673.792;
77
+ const DURATION_MS = 7673792;
78
+
79
+ describe('PlayerProvider progress context keeps the duration', () => {
80
+ it('keeps the duration when duration and position arrive in ONE batch', async () => {
81
+ // The exact device scenario: two events, one batch, duration FIRST.
82
+ const { result, unmount } = await renderHook(
83
+ () => ({ state: usePlayer().state, progress: usePlayerProgress() }),
84
+ { wrapper },
85
+ );
86
+
87
+ // The hydrated baseline is 0 (the bridge mock's getDuration returns 0),
88
+ // so anything asserted below arrived through the event path.
89
+ expect(result.current.state.durationMs).toBe(0);
90
+ expect(result.current.progress.durationMs).toBe(0);
91
+
92
+ await act(async () => {
93
+ emit('onDurationChanged', { duration: DURATION_S });
94
+ emit('onPositionChanged', { position: 12.5 });
95
+ });
96
+
97
+ expect(result.current.state.durationMs).toBe(DURATION_MS);
98
+ // THE assertion this file exists for. Before the fix this was 0:
99
+ // the position event was computed from a stale progress and replaced
100
+ // the duration with the stale 0.
101
+ expect(result.current.progress.durationMs).toBe(DURATION_MS);
102
+ // The position must not be the casualty of the fix.
103
+ expect(result.current.progress.positionMs).toBe(12500);
104
+
105
+ await unmount();
106
+ });
107
+
108
+ it('keeps the duration when the position arrives FIRST in the batch', async () => {
109
+ // The mirror order. A fix that only special-cased "duration first"
110
+ // would pass the test above and fail this one.
111
+ const { result, unmount } = await renderHook(
112
+ () => ({ state: usePlayer().state, progress: usePlayerProgress() }),
113
+ { wrapper },
114
+ );
115
+
116
+ await act(async () => {
117
+ emit('onPositionChanged', { position: 12.5 });
118
+ emit('onDurationChanged', { duration: DURATION_S });
119
+ });
120
+
121
+ expect(result.current.progress.durationMs).toBe(DURATION_MS);
122
+ expect(result.current.progress.positionMs).toBe(12500);
123
+
124
+ await unmount();
125
+ });
126
+
127
+ it('keeps the duration across a long run of interleaved events', async () => {
128
+ // The real event stream is not two events: mpv keeps sending
129
+ // `time-pos` for the whole session. Every one of them used to carry a
130
+ // stale duration into the progress context.
131
+ const { result, unmount } = await renderHook(
132
+ () => ({ state: usePlayer().state, progress: usePlayerProgress() }),
133
+ { wrapper },
134
+ );
135
+
136
+ await act(async () => {
137
+ emit('onDurationChanged', { duration: DURATION_S });
138
+ for (let i = 1; i <= 25; i++) {
139
+ emit('onPositionChanged', { position: i * 0.5 });
140
+ }
141
+ });
142
+
143
+ expect(result.current.progress.durationMs).toBe(DURATION_MS);
144
+ expect(result.current.progress.positionMs).toBe(12500);
145
+
146
+ await unmount();
147
+ });
148
+
149
+ it('keeps the buffered ranges through the same interleaving', async () => {
150
+ // The buffered ranges are the other half of the damage: the consumer
151
+ // gates the buffered window on `durationMs > 0`, so a lost duration
152
+ // silently removed the buffered indicator from the seek bar.
153
+ const { result, unmount } = await renderHook(
154
+ () => ({ state: usePlayer().state, progress: usePlayerProgress() }),
155
+ { wrapper },
156
+ );
157
+
158
+ await act(async () => {
159
+ emit('onDurationChanged', { duration: DURATION_S });
160
+ emit('onCacheState', { ranges: [{ start: 0, end: 130713.917 }] });
161
+ emit('onPositionChanged', { position: 12.5 });
162
+ });
163
+
164
+ expect(result.current.progress.durationMs).toBe(DURATION_MS);
165
+ expect(result.current.progress.cacheRanges).toEqual([
166
+ { start: 0, end: 130713.917 },
167
+ ]);
168
+
169
+ await unmount();
170
+ });
171
+
172
+ it('keeps the state context and the progress context in agreement', async () => {
173
+ // The invariant the seek bar depends on: it reads the duration from
174
+ // the progress context and the play state from the state context, so
175
+ // the two must never disagree about the length of the file.
176
+ const { result, unmount } = await renderHook(
177
+ () => ({ state: usePlayer().state, progress: usePlayerProgress() }),
178
+ { wrapper },
179
+ );
180
+
181
+ await act(async () => {
182
+ emit('onDurationChanged', { duration: DURATION_S });
183
+ emit('onPositionChanged', { position: 12.5 });
184
+ emit('onCacheState', { ranges: [{ start: 0, end: 130713.917 }] });
185
+ });
186
+
187
+ expect(result.current.progress.durationMs).toBe(
188
+ result.current.state.durationMs,
189
+ );
190
+ expect(result.current.progress.durationMs).toBe(DURATION_MS);
191
+
192
+ await unmount();
193
+ });
194
+ });