@simba-dev/react-native-media-player 1.15.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.
@@ -233,6 +233,21 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
233
233
  * Property observers requested by JS before native initialization completes.
234
234
  * Keep them until the handle exists instead of silently dropping them.
235
235
  */
236
+ /**
237
+ * Property names this module has already logged, so each one is
238
+ * announced exactly once per session.
239
+ *
240
+ * The per-value property log was made a compile-time constant in
241
+ * v1.10.0 (it fired 30-60x/second for `time-pos`). That made the
242
+ * whole property path UNOBSERVABLE: no build could answer "does this
243
+ * property ever arrive?", which is why a delivery defect could sit
244
+ * here for a release cycle with nothing to contradict it.
245
+ *
246
+ * One line per property per session answers that question at no
247
+ * ongoing cost, so this stays unconditional.
248
+ */
249
+ private val announcedProperties = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
250
+
236
251
  private val pendingObservedProperties = linkedSetOf<String>()
237
252
 
238
253
  /**
@@ -292,6 +307,12 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
292
307
  // to discard them) and performing a synchronous write to logd.
293
308
  // Gate it behind the same debug switch as the JS dlog(); the
294
309
  // property value is still delivered to JS regardless.
310
+ // First arrival of each property, once per session. This is the
311
+ // observable that was missing: with it, a device log answers
312
+ // "does this property ever arrive?" without a rebuild.
313
+ if (announcedProperties.add(name)) {
314
+ Log.i(TAG, "[PlaybackTrace][Bridge][property:first] name=$name")
315
+ }
295
316
  if (TRACE_PROPERTY_EVENTS) {
296
317
  Log.d(TAG, "[PlaybackTrace][Bridge][listener:property] name=$name value=$jsonValue")
297
318
  }
@@ -331,25 +352,44 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
331
352
  // `percent > 0 && percent < 100` correctly drops the spinner.
332
353
  when (name) {
333
354
  "cache-buffering-state" -> {
355
+ // The cache FILL LEVEL. It is NOT a stall signal.
356
+ //
357
+ // mpv reports `cache-buffering-state` as the percentage
358
+ // of the cache that is filled, and a partially-filled
359
+ // cache is the NORMAL state during playback. The old
360
+ // code read it as "isBuffering = percent < 100", which
361
+ // is true for most of a stream's life — so the flag
362
+ // flickered with every refill and the spinner could
363
+ // latch on during perfectly healthy playback.
364
+ //
365
+ // The stall signal is `paused-for-cache`, which is a
366
+ // different property with a different owner. One fact,
367
+ // one owner: this one owns the fill, that one owns the
368
+ // stall.
334
369
  val percent = parseBufferingPercent(jsonValue)
335
370
  try {
336
- val bufPayload = Arguments.createMap().apply {
371
+ val fillPayload = Arguments.createMap().apply {
337
372
  putDouble("percent", percent)
338
- putBoolean("isBuffering", percent < 100.0)
339
373
  }
340
- eventEmitter.emit("onBuffering", bufPayload)
374
+ eventEmitter.emit("onCacheFill", fillPayload)
341
375
  } catch (e: Exception) {
342
- Log.w(TAG, "onBuffering emit failed: ${e.message}")
376
+ Log.w(TAG, "onCacheFill emit failed: ${e.message}")
343
377
  }
344
378
  }
345
- // `paused-for-cache` is the universal stall signal. Do not
346
- // encode it as a fabricated fill percentage; the JS layer gets
347
- // the explicit boolean and preserves the last honest cache fill.
379
+ // `paused-for-cache` is the universal stall signal: mpv sets
380
+ // it exactly while playback is paused because the cache
381
+ // underran. It is a BOOLEAN, and it is the only thing that
382
+ // may drive `isBuffering`.
383
+ //
384
+ // It carries no percentage. It does not know the fill, and
385
+ // the old code invented one (0 when stalled, 100 when not)
386
+ // which then overwrote the real fill with a fabricated
387
+ // number — the same "one fact, two owners" failure as
388
+ // above, in the other direction.
348
389
  "paused-for-cache" -> {
349
390
  val isBuffering = jsonValue.trim().equals("true", ignoreCase = true)
350
391
  try {
351
392
  val bufPayload = Arguments.createMap().apply {
352
- putDouble("percent", if (isBuffering) 0.0 else 100.0)
353
393
  putBoolean("isBuffering", isBuffering)
354
394
  }
355
395
  eventEmitter.emit("onBuffering", bufPayload)
@@ -360,8 +400,17 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
360
400
  // `demuxer-cache-state` carries the buffered ranges — the
361
401
  // grey overlay on the seek bar. Each range is
362
402
  // `{start, end, flags}` in MPV; we extract `start`/`end`
363
- // (in seconds, relative to the stream start) and forward
364
- // them as a list so JS can paint the buffered region.
403
+ // and forward them as a list so JS can paint the buffered
404
+ // region.
405
+ //
406
+ // The ranges leave this bridge in MILLISECONDS. mpv reports
407
+ // `seekable-ranges` in seconds, and the bridge is the only
408
+ // place that knows which unit a payload carried — so the
409
+ // bridge is the only place that converts it. Every other
410
+ // time value on this API (positionMs, durationMs) is
411
+ // milliseconds, and a consumer that had to guess the unit
412
+ // of one field among them is a consumer that will get it
413
+ // wrong.
365
414
  "demuxer-cache-state" -> {
366
415
  try {
367
416
  val parsed = parseCacheState(jsonValue)
@@ -375,7 +424,6 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
375
424
  }
376
425
  val cachePayload = Arguments.createMap().apply {
377
426
  putArray("ranges", rangesArray)
378
- putDouble("fill", parsed.fill)
379
427
  }
380
428
  eventEmitter.emit("onCacheState", cachePayload)
381
429
  } catch (e: Exception) {
@@ -2439,50 +2487,76 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2439
2487
  }
2440
2488
 
2441
2489
  /**
2442
- * Parse a `demuxer-cache-state` payload into buffered ranges + fill.
2490
+ * Parse a `demuxer-cache-state` payload into buffered ranges.
2443
2491
  *
2444
- * MPV serialises this property as a node map whose documented fields
2492
+ * MPV serialises this property as a node map whose documented fields
2445
2493
  * include `seekable-ranges`, `bof-cached`, `eof-cached`, `fw-bytes`,
2446
2494
  * `file-cache-bytes`, `cache-end`, `reader-pts`, and `cache-duration`.
2447
2495
  * The seekable ranges are the authoritative buffered timeline ranges.
2448
2496
  *
2449
- * We extract only those ranges here. Cache fill is intentionally not
2450
- * fabricated from byte counts: mpv exposes the user-facing fill percentage
2451
- * through the separate `cache-buffering-state` property, which is mapped
2452
- * to `onBuffering` and consumed by TransportContext.
2453
-
2497
+ * ## The unit
2498
+ *
2499
+ * `seekable-ranges` is in SECONDS, relative to the stream start. The
2500
+ * ranges leave this bridge in MILLISECONDS, because the bridge is the
2501
+ * only layer that knows which unit a payload carried.
2502
+ *
2503
+ * The legacy `ranges` field is BYTE OFFSETS, and a byte offset is not
2504
+ * a time: there is no constant bytes-per-second to divide by, because
2505
+ * the bitrate varies and a VBR stream has no single one. The old code
2506
+ * read `ranges` as if it were `seekable-ranges` and forwarded it
2507
+ * unlabelled, and the consumer read the numbers as milliseconds. So a
2508
+ * 60-second range arrived as 60 ms, and a byte range was clamped to
2509
+ * the duration and painted as a full-width "100% buffered" bar — a bar
2510
+ * claiming that data is buffered when it is not.
2511
+ *
2512
+ * So the byte field is read, logged, and NOT forwarded as a time
2513
+ * range. A seek bar that shows nothing is honest; a seek bar that
2514
+ * shows a false 100% is not.
2515
+ *
2516
+ * Cache fill is intentionally not derived from byte counts: mpv
2517
+ * exposes the user-facing fill percentage through the separate
2518
+ * `cache-buffering-state` property, which is mapped to `onCacheFill`.
2454
2519
  */
2455
2520
  private data class CacheStatePayload(
2521
+ /** Buffered ranges in MILLISECONDS, relative to the stream start. */
2456
2522
  val ranges: List<Pair<Double, Double>>,
2457
- val fill: Double,
2458
2523
  )
2459
2524
 
2460
2525
  private fun parseCacheState(jsonValue: String): CacheStatePayload {
2461
2526
  val trimmed = jsonValue.trim()
2462
2527
  if (trimmed.isEmpty() || trimmed == "null") {
2463
- return CacheStatePayload(emptyList(), 0.0)
2528
+ return CacheStatePayload(emptyList())
2464
2529
  }
2465
2530
  return try {
2466
2531
  val obj = JSONObject(trimmed)
2467
- val rangesJson = obj.optJSONArray("seekable-ranges")
2468
- ?: obj.optJSONArray("ranges") // compatibility with older native payloads
2532
+ val seekableJson = obj.optJSONArray("seekable-ranges")
2533
+ val legacyByteJson = obj.optJSONArray("ranges")
2469
2534
 
2470
2535
  val ranges = mutableListOf<Pair<Double, Double>>()
2471
- if (rangesJson != null) {
2472
- for (i in 0 until rangesJson.length()) {
2473
- val r = rangesJson.optJSONObject(i) ?: continue
2536
+ if (seekableJson != null) {
2537
+ for (i in 0 until seekableJson.length()) {
2538
+ val r = seekableJson.optJSONObject(i) ?: continue
2474
2539
  val start = r.optDouble("start", Double.NaN)
2475
2540
  val end = r.optDouble("end", Double.NaN)
2476
2541
  if (!start.isNaN() && !end.isNaN() && end > start) {
2477
- ranges.add(start to end)
2542
+ // seconds -> milliseconds
2543
+ ranges.add(start * 1000.0 to end * 1000.0)
2478
2544
  }
2479
2545
  }
2546
+ } else if (legacyByteJson != null) {
2547
+ Log.w(
2548
+ TAG,
2549
+ "parseCacheState: payload carries byte-offset 'ranges' and no " +
2550
+ "'seekable-ranges'. Byte offsets are not time positions, so no " +
2551
+ "buffered range is forwarded — painting them on a seek bar " +
2552
+ "would claim unbuffered data is buffered.",
2553
+ )
2480
2554
  }
2481
- CacheStatePayload(ranges, 0.0)
2555
+ CacheStatePayload(ranges)
2482
2556
 
2483
2557
  } catch (e: Exception) {
2484
2558
  Log.w(TAG, "parseCacheState: bad json '$jsonValue': ${e.message}")
2485
- CacheStatePayload(emptyList(), 0.0)
2559
+ CacheStatePayload(emptyList())
2486
2560
  }
2487
2561
  }
2488
2562
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.15.0",
3
+ "version": "1.16.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",
@@ -122,6 +122,7 @@ export type PlayerEventName =
122
122
  | 'onVideoParamsChanged'
123
123
  | 'onError'
124
124
  | 'onBuffering'
125
+ | 'onCacheFill'
125
126
  | 'onCacheState'
126
127
  | 'onSeekable'
127
128
  | 'onSeeking'
@@ -154,8 +155,23 @@ export interface PlayerEventPayloads {
154
155
  message: string;
155
156
  requestId?: string;
156
157
  };
157
- onBuffering: { percent: number; isBuffering?: boolean };
158
- onCacheState: { ranges: Array<{ start: number; end: number }>; fill: number };
158
+ /**
159
+ * The STALL signal. True exactly while playback is paused because the
160
+ * cache underran. It carries no percentage: the property does not know
161
+ * the fill, and an invented one destroys the real fill.
162
+ */
163
+ onBuffering: { isBuffering: boolean };
164
+ /**
165
+ * The cache FILL LEVEL, 0..100. A level, not a stall — a partially
166
+ * filled cache is the normal state during playback.
167
+ */
168
+ onCacheFill: { percent: number };
169
+ /**
170
+ * The buffered timeline ranges, in MILLISECONDS, relative to the stream
171
+ * start. Byte offsets are never reported here: a byte offset is not a
172
+ * time.
173
+ */
174
+ onCacheState: { ranges: Array<{ start: number; end: number }> };
159
175
  onSeekable: { seekable: boolean };
160
176
  onSeeking: { seeking: boolean };
161
177
  onEndFile: { reason: number; error: number; requestId?: string };
@@ -968,6 +984,7 @@ const ALL_PLAYER_EVENTS: readonly PlayerEventName[] = [
968
984
  'onVideoParamsChanged',
969
985
  'onError',
970
986
  'onBuffering',
987
+ 'onCacheFill',
971
988
  'onCacheState',
972
989
  'onSeekable',
973
990
  'onSeeking',
@@ -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',
@@ -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
@@ -128,9 +128,20 @@ export interface PlayerProgress {
128
128
  isSeeking: boolean;
129
129
  /** True when the current file is seekable. */
130
130
  seekable: boolean;
131
- /** Cached byte ranges. Empty for non-network sources. */
131
+ /**
132
+ * Buffered timeline ranges, in MILLISECONDS, relative to the stream start.
133
+ *
134
+ * The same unit as `positionMs` and `durationMs`, so a consumer never
135
+ * has to know that mpv's own `seekable-ranges` is in seconds — the
136
+ * native bridge converts, because it is the only layer that knows which
137
+ * unit a payload carried.
138
+ *
139
+ * Empty when the source exposes no time-space cache information. A byte
140
+ * offset is NOT a time and is never reported here: a range painted from
141
+ * byte offsets would claim that unbuffered data is buffered.
142
+ */
132
143
  cacheRanges: Array<{ start: number; end: number }>;
133
- /** Cache fill percent (0..100). 0 for non-network sources. */
144
+ /** Cache fill percent (0..100), from mpv's `cache-buffering-state`. */
134
145
  cacheFill: number;
135
146
  }
136
147
 
@@ -1231,29 +1242,66 @@ export function applyPlayerEvent(
1231
1242
  progress,
1232
1243
  };
1233
1244
  case 'onBuffering': {
1234
- // `isBuffering` is the more useful consumer signal than `percent`;
1235
- // honor the explicit flag if present, otherwise treat any
1236
- // non-zero percent as buffering.
1237
- const isBuffering =
1238
- typeof p.isBuffering === 'boolean'
1239
- ? p.isBuffering
1240
- : ((p.percent as number) > 0 && (p.percent as number) < 100);
1245
+ // The STALL signal, and the only thing that may set `isBuffering`.
1246
+ //
1247
+ // It comes from mpv's `paused-for-cache`, which is true exactly while
1248
+ // playback is paused because the cache underran. The payload carries
1249
+ // no percentage: the property does not know the fill, and the old
1250
+ // code invented one (0 when stalled, 100 when not) which overwrote
1251
+ // the real fill with a fabricated number.
1252
+ //
1253
+ // The percent-based inference is gone with the percent. A partially
1254
+ // filled cache is the NORMAL state during playback, so
1255
+ // "percent < 100" is true for most of a stream's life — reading it
1256
+ // as "buffering" latched the spinner on during healthy playback.
1257
+ const isBuffering = Boolean(p.isBuffering);
1241
1258
  return {
1242
1259
  state: { ...state, isBuffering },
1243
1260
  progress: { ...progress, isBuffering },
1244
1261
  };
1245
1262
  }
1246
- case 'onCacheState':
1247
- // Cache state is progress-only — no state field, just progress
1248
- // updates for consumers that render a cache indicator.
1263
+ case 'onCacheFill': {
1264
+ // The cache FILL LEVEL — a percentage, not a stall. It comes from
1265
+ // mpv's `cache-buffering-state`, which changes continuously as the
1266
+ // cache refills, so it is a level and nothing else.
1267
+ //
1268
+ // It owns `cacheFill` and nothing else. `isBuffering` belongs to
1269
+ // `onBuffering`, and `cacheRanges` belongs to `onCacheState`. One
1270
+ // fact, one owner — the old code had two properties writing one
1271
+ // field with contradictory rules, and they disagreed.
1272
+ const percent = Number(p.percent ?? 0);
1249
1273
  return {
1250
1274
  state,
1251
1275
  progress: {
1252
1276
  ...progress,
1253
- cacheRanges: (p.ranges as Array<{ start: number; end: number }>) ?? [],
1254
- cacheFill: Number(p.fill ?? 0),
1277
+ cacheFill: Number.isFinite(percent) ? percent : 0,
1255
1278
  },
1256
1279
  };
1280
+ }
1281
+ case 'onCacheState': {
1282
+ // The buffered TIMELINE ranges, in MILLISECONDS.
1283
+ //
1284
+ // They come from mpv's `demuxer-cache-state.seekable-ranges`, which is
1285
+ // in seconds; the native bridge converts to milliseconds because it
1286
+ // is the only layer that knows which unit the payload carried. The
1287
+ // consumer receives one unit — the same one `positionMs` and
1288
+ // `durationMs` use — and never has to guess.
1289
+ //
1290
+ // A payload that carries no `ranges` at all leaves the previous value
1291
+ // alone. A payload that carries an EMPTY array is authoritative and
1292
+ // clears: that is mpv saying the cache is empty, which is different
1293
+ // from saying nothing.
1294
+ const ranges = p.ranges as
1295
+ | Array<{ start: number; end: number }>
1296
+ | undefined;
1297
+ return {
1298
+ state,
1299
+ progress: {
1300
+ ...progress,
1301
+ cacheRanges: Array.isArray(ranges) ? ranges : progress.cacheRanges,
1302
+ },
1303
+ };
1304
+ }
1257
1305
  case 'onSeekable':
1258
1306
  return {
1259
1307
  state: { ...state, seekable: Boolean(p.seekable) },