@simba-dev/react-native-media-player 1.0.8 → 1.2.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.
@@ -1,15 +1,51 @@
1
- import { useMemo } from 'react';
2
- import { getMpvPlayerModule, dlog } from '../bridge/MpvPlayerModule';
1
+ import React, { createContext, useContext, useMemo } from 'react';
2
+ import {
3
+ getMpvPlayerModule,
4
+ dlog,
5
+ MpvLoopMode,
6
+ MpvTrack,
7
+ MpvChapter,
8
+ MpvVideoParams,
9
+ MpvPlaybackState,
10
+ MpvFileInfo,
11
+ } from '../bridge/MpvPlayerModule';
3
12
 
4
13
  /**
5
- * Snapshot of the player's runtime state. Phase 24 entry point —
6
- * `state.title / artist / album / isPlaying` come from mpv events
7
- * (Phase 24 still ships defaults — the mpv-event subscription lands
8
- * in Phase 25 when the activity swap happens); `positionMs` /
9
- * `durationMs` come from `usePlayerProgress()` so they update
10
- * independently of the rest of the state.
14
+ * V13 Phase 51: expanded `PlayerState`. The V12 surface (4 fields)
15
+ * is preserved; the new fields populate from `subscribePlayerEvent`
16
+ * callbacks dispatched by `PlayerProvider`.
17
+ *
18
+ * Field sources (who writes each field):
19
+ * - `title` — `onFileLoaded.file.title`, `onPropertyChanged('media-title')`, hydration
20
+ * - `artist` — `onPropertyChanged('metadata')` (parsed), hydration
21
+ * - `album` — `onPropertyChanged('metadata')` (parsed), hydration
22
+ * - `isPlaying` — `onPlaybackStateChanged`, `onEndFile`, `onPlaybackRestart`
23
+ * - `positionMs` — 1Hz `bridge.getPosition()` poll + `onPositionChanged`
24
+ * - `durationMs` — `onDurationChanged` + `onFileLoaded.file.duration` + hydration
25
+ * - `isBuffering` — `onBuffering`
26
+ * - `isSeeking` — `onSeeking`
27
+ * - `seekable` — `onSeekable`
28
+ * - `volume` — `onVolumeChanged` + `onPropertyChanged('volume')` + hydration
29
+ * - `isMuted` — `onPropertyChanged('mute')` + hydration
30
+ * - `speed` — `onSpeedChanged` + hydration
31
+ * - `loopMode` — hydration from `bridge.getLoopMode()` (no event for it)
32
+ * - `playlist` — `onPropertyChanged('playlist')` (parsed) + hydration
33
+ * - `currentIndex` — `onPropertyChanged('playlist-playing-pos')` + hydration
34
+ * - `tracks` — `onTracksChanged` + hydration
35
+ * - `chapters` — hydration from `bridge.getChapters()` (no event for the full list)
36
+ * - `currentChapter` — `onChapterChanged` + hydration
37
+ * - `videoParams` — `onVideoParamsChanged` + hydration
38
+ * - `error` — `onError`; cleared on the next `onFileLoaded`
39
+ *
40
+ * All fields default to a documented baseline (see `DEFAULT_STATE`).
41
+ * Consumers that need a single source of truth for player state
42
+ * should rely on `usePlayer()` inside a `<PlayerProvider>`; consumers
43
+ * that need to render outside a provider (e.g. a top bar that
44
+ * always exists) can still call `usePlayer()` and get the baseline
45
+ * defaults (no throw, unlike `usePlayerConfig`).
11
46
  */
12
47
  export interface PlayerState {
48
+ // ── V12 surface (preserved) ───────────────────────────────────────────
13
49
  /** True when mpv is actively playing (not paused, not stopped). */
14
50
  isPlaying: boolean;
15
51
  /** Track title (from mpv `media-title` → launch title → "Simba Player"). */
@@ -18,29 +54,94 @@ export interface PlayerState {
18
54
  artist: string;
19
55
  /** Track album (from mpv `metadata/by-key/album`). Empty when untagged. */
20
56
  album: string;
57
+
58
+ // ── V13 Phase 51 additions ────────────────────────────────────────────
59
+ /** Current playback position in milliseconds. 0 when no file is loaded. */
60
+ positionMs: number;
61
+ /** Total duration in milliseconds. 0 when unknown (mpv hasn't parsed yet). */
62
+ durationMs: number;
63
+ /** True while mpv is buffering. Drives the center loading spinner. */
64
+ isBuffering: boolean;
65
+ /** True while a seek is in flight. Suppresses redundant seek commands. */
66
+ isSeeking: boolean;
67
+ /** True when the current file is seekable (false for live streams). */
68
+ seekable: boolean;
69
+ /** Playback volume (0..100). mpv-native range. */
70
+ volume: number;
71
+ /** Mute state. Decoupled from volume (volume stays at last value). */
72
+ isMuted: boolean;
73
+ /** Playback speed (1.0 = normal). */
74
+ speed: number;
75
+ /** Loop mode: 'none' | 'file' | 'playlist'. */
76
+ loopMode: MpvLoopMode;
77
+ /** Current playlist entries (filename + title, as returned by mpv). */
78
+ playlist: PlaylistEntry[];
79
+ /** Index into `playlist` of the currently-playing entry. -1 when empty. */
80
+ currentIndex: number;
81
+ /** Available tracks (video / audio / sub) for the current file. */
82
+ tracks: MpvTrack[];
83
+ /** Chapter list for the current file. */
84
+ chapters: MpvChapter[];
85
+ /** Currently-active chapter (or null at file start). */
86
+ currentChapter: MpvChapter | null;
87
+ /** Video stream params (resolution, fps, codec). null for audio-only files. */
88
+ videoParams: MpvVideoParams | null;
89
+ /** Last error reported by mpv. Cleared on the next `onFileLoaded`. */
90
+ error: { code: number; recoverable: boolean; message: string } | null;
21
91
  }
22
92
 
23
93
  /**
24
- * Position + duration. Returned by `usePlayerProgress()` so it can
25
- * update at a different cadence than `usePlayer()` (1Hz for
26
- * progress vs once-per-event for the rest of the state). Consumers
27
- * that don't render a scrubber / time labels can opt out of the
28
- * 1Hz re-render storm by NOT calling `usePlayerProgress()`.
94
+ * mpv playlist entry. Mirrors the Kotlin `MpvPlaylistEntry` shape.
95
+ */
96
+ export interface PlaylistEntry {
97
+ readonly filename: string;
98
+ readonly title?: string;
99
+ readonly current?: boolean;
100
+ }
101
+
102
+ /**
103
+ * V13 Phase 51: expanded `PlayerProgress`. The V12 surface (2 fields)
104
+ * is preserved; the new fields populate from mpv events.
105
+ *
106
+ * `usePlayerProgress()` is separate from `usePlayer()` so consumers
107
+ * that only need position/duration don't re-render on every
108
+ * `onPropertyChanged('volume')` etc. The provider updates the
109
+ * progress context ONLY on 1Hz ticks + the dedicated event updates
110
+ * (`isBuffering`, `isSeeking`, `seekable`, `cacheRanges`, `cacheFill`).
29
111
  */
30
112
  export interface PlayerProgress {
113
+ // ── V12 surface (preserved) ───────────────────────────────────────────
31
114
  /** Current playback position in milliseconds. 0 when no file is loaded. */
32
115
  positionMs: number;
33
116
  /** Total duration in milliseconds. 0 when unknown (mpv hasn't parsed yet). */
34
117
  durationMs: number;
118
+
119
+ // ── V13 Phase 51 additions ────────────────────────────────────────────
120
+ /** True while mpv is buffering. */
121
+ isBuffering: boolean;
122
+ /** True while a seek is in flight. */
123
+ isSeeking: boolean;
124
+ /** True when the current file is seekable. */
125
+ seekable: boolean;
126
+ /** Cached byte ranges. Empty for non-network sources. */
127
+ cacheRanges: Array<{ start: number; end: number }>;
128
+ /** Cache fill percent (0..100). 0 for non-network sources. */
129
+ cacheFill: number;
35
130
  }
36
131
 
37
132
  /**
38
- * Player commands. Phase 24 wires the play / pause / seek methods
39
- * to `MpvPlayerModule` bridge calls — the methods are no longer
40
- * stub no-ops, they call `MPVLib.nativePlay / nativePause /
41
- * nativeSeek` via the React Native bridge.
133
+ * V13 Phase 51: expanded `PlayerCommands`. The V12 surface (5 methods)
134
+ * is preserved; the new methods map to the additional 73 native bridge
135
+ * methods that consumers use (volume, mute, speed, loop, tracks, PiP,
136
+ * brightness, openPlayer, etc.).
137
+ *
138
+ * All methods resolve the bridge lazily at call time, so a stable
139
+ * command object is built once at module load. The 1Hz-poll progress
140
+ * context and the heavy event-subscription state context are
141
+ * separate from the commands.
42
142
  */
43
143
  export interface PlayerCommands {
144
+ // ── V12 surface (preserved) ───────────────────────────────────────────
44
145
  /** Resume playback (or start playback of the current file). */
45
146
  play(): void;
46
147
  /** Pause playback (mpv remains at the current position). */
@@ -51,6 +152,110 @@ export interface PlayerCommands {
51
152
  skipBackward(seconds: number): void;
52
153
  /** Skip forward by N seconds. */
53
154
  skipForward(seconds: number): void;
155
+
156
+ // ── V13 Phase 51 additions ────────────────────────────────────────────
157
+ /** Toggle between play and pause. */
158
+ togglePlayPause(): void;
159
+ /** Stop playback entirely. */
160
+ stop(): void;
161
+ /** Relative seek in milliseconds. Negative seeks backward. */
162
+ seekBy(deltaMs: number): void;
163
+ /** Seek to the chapter at `index` (via mpv `setProperty('chapter', index)`). */
164
+ seekToChapter(index: number): void;
165
+ /** Skip to the next playlist entry. */
166
+ next(): void;
167
+ /** Skip to the previous playlist entry. */
168
+ previous(): void;
169
+
170
+ // Volume / audio
171
+ /** Set the playback volume (0..100). */
172
+ setVolume(volume: number): void;
173
+ /** Set the muted state. */
174
+ setMuted(muted: boolean): void;
175
+ /** Toggle the muted state. */
176
+ toggleMute(): void;
177
+
178
+ // Speed / loop
179
+ /** Set the playback speed (1.0 = normal). */
180
+ setSpeed(speed: number): void;
181
+ /** Set the loop mode (`'none' | 'file' | 'playlist'`). */
182
+ setLoopMode(mode: MpvLoopMode): void;
183
+
184
+ // File loading
185
+ /** Load a single media file. */
186
+ loadFile(uri: string): void;
187
+ /** Load a playlist of media files, starting at `startIndex` (default 0). */
188
+ loadPlaylist(uris: string[], startIndex?: number): void;
189
+
190
+ // Playlist manipulation
191
+ /** Remove the playlist entry at `index`. */
192
+ playlistRemove(index: number): void;
193
+ /** Shuffle the current playlist. */
194
+ shuffle(): void;
195
+ /** Clear the current playlist. */
196
+ clear(): void;
197
+
198
+ // Tracks
199
+ /** Select a track by ID. */
200
+ selectTrack(trackId: number): void;
201
+ /** Cycle to the next/previous track of the given type. */
202
+ cycleTrack(type: 'video' | 'audio' | 'sub'): void;
203
+ /** Set the active track for a type (trackId < 0 means "no track"). */
204
+ setTrack(type: 'video' | 'audio' | 'sub', trackId: number): void;
205
+
206
+ // PiP
207
+ /** Enter Picture-in-Picture mode. */
208
+ enterPip(): void;
209
+ /** Exit PiP by bringing the activity to the front. */
210
+ exitPip(): void;
211
+ /** Exit PiP and finish the activity. */
212
+ exitPipAndFinish(): void;
213
+
214
+ // Screen
215
+ /** Toggle `FLAG_KEEP_SCREEN_ON` on the current activity window. */
216
+ setKeepScreenOn(enabled: boolean): void;
217
+ /** Pin the activity to a fixed orientation. */
218
+ setOrientation(mode: 'portrait' | 'landscape' | 'sensor'): void;
219
+ /** Toggle system bars visibility (immersive mode). */
220
+ setImmersive(enabled: boolean): void;
221
+ /** Set the window screen brightness (0..1). */
222
+ setScreenBrightness(value: number): void;
223
+
224
+ // Notification
225
+ /** Request the `POST_NOTIFICATIONS` permission on Android 13+. */
226
+ requestNotificationPermission(): void;
227
+
228
+ // Activity launch (Phase 52 hooks wrap these for consumer ergonomics)
229
+ /**
230
+ * Hand off to the dedicated `PlayerActivity`. Resolves with `true`
231
+ * on a successful `startActivity`. The new signature is the V13
232
+ * module signature (no `duration` / `source` / `mediaType` — those
233
+ * were V11 Redux-dispatch concerns that V13 drops).
234
+ */
235
+ openPlayer(opts: {
236
+ uri: string;
237
+ title: string;
238
+ type: 'video' | 'audio';
239
+ startPositionMs?: number;
240
+ }): Promise<boolean>;
241
+ /** One-shot accessor for the launch params the most recent `openPlayer` handed to `PlayerActivity`. */
242
+ getLaunchParams(): { uri: string; title: string; type: 'video' | 'audio'; startPositionMs: number } | null;
243
+
244
+ // Generic property access (used by audioSettingsService, metadataService)
245
+ /** Get the value of an mpv property as a string. */
246
+ getProperty(name: string): string;
247
+ /** Set the value of an mpv property. Value is stringified before sending. */
248
+ setProperty(name: string, value: unknown): void;
249
+ /** Begin observing an mpv property (emits `onPropertyChanged` events). */
250
+ observeProperty(name: string): void;
251
+ /** Stop observing an mpv property. */
252
+ unobserveProperty(name: string): void;
253
+
254
+ // File persistence (used by fileService for content:// URI permissions)
255
+ /** Take a persistable read URI permission for a content:// URI. */
256
+ grantPersistablePermission(uri: string): void;
257
+ /** Returns true when the URI is still readable (content:// or file://). */
258
+ verifyContentUri(uri: string): boolean;
54
259
  }
55
260
 
56
261
  /** Combined result from `usePlayer()`. */
@@ -59,83 +264,753 @@ export interface UsePlayerResult {
59
264
  commands: PlayerCommands;
60
265
  }
61
266
 
267
+ // ═══════════════════════════════════════════════════════════════════════════
268
+ // Context plumbing
269
+ // ═══════════════════════════════════════════════════════════════════════════
270
+
62
271
  /**
63
- * Phase 24 default state used until mpv events wire in (Phase 25).
64
- * `title` falls back to "Simba Player" so the top bar shows
65
- * something rather than an empty string during the cold-start
66
- * window before the first `onFileLoaded` event fires.
272
+ * V13 Phase 51: React context for the live player state. `null`
273
+ * means "no provider in scope — fall back to `DEFAULT_STATE`".
274
+ *
275
+ * The provider holds the state in a `useState` (rendered) +
276
+ * `useRef` (read-by-event-handlers) pair; both contexts are exposed
277
+ * for the provider to write, and the public hooks (`usePlayer`,
278
+ * `usePlayerProgress`) read from them with the null-fallback to
279
+ * the default constants.
280
+ *
281
+ * Exported (not module-local) so `<PlayerStateProvider>` in
282
+ * `PlayerProvider.tsx` can wrap children with the context.
67
283
  */
68
- const DEFAULT_STATE: PlayerState = {
284
+ export const PlayerStateContext = createContext<PlayerState | null>(null);
285
+ export const PlayerProgressContext = createContext<PlayerProgress | null>(null);
286
+
287
+ // ═══════════════════════════════════════════════════════════════════════════
288
+ // Defaults
289
+ // ═══════════════════════════════════════════════════════════════════════════
290
+
291
+ /**
292
+ * V13 Phase 51 default state. The four V12 fields keep their
293
+ * documented baseline (`title: 'Simba Player'`, `artist: ''`,
294
+ * `album: ''`, `isPlaying: false`); the new fields default to
295
+ * their "no media loaded" / "no event received" values.
296
+ *
297
+ * Used by:
298
+ * - The provider's initial `useState` (the first frame before
299
+ * hydration runs)
300
+ * - `usePlayer()` when called outside any `<PlayerProvider>` —
301
+ * returns the default state instead of throwing
302
+ * - Tests asserting the documented baseline
303
+ */
304
+ export const DEFAULT_STATE: PlayerState = {
305
+ // V12
69
306
  isPlaying: false,
70
307
  title: 'Simba Player',
71
308
  artist: '',
72
309
  album: '',
310
+
311
+ // V13
312
+ positionMs: 0,
313
+ durationMs: 0,
314
+ isBuffering: false,
315
+ isSeeking: false,
316
+ seekable: false,
317
+ volume: 100,
318
+ isMuted: false,
319
+ speed: 1,
320
+ loopMode: 'none',
321
+ playlist: [],
322
+ currentIndex: -1,
323
+ tracks: [],
324
+ chapters: [],
325
+ currentChapter: null,
326
+ videoParams: null,
327
+ error: null,
73
328
  };
74
329
 
75
- /** Phase 24 default progress (Phase 25 wires to 1Hz bridge poll). */
76
- const DEFAULT_PROGRESS: PlayerProgress = {
330
+ /** V13 default progress (2 V12 + 5 V13 fields). */
331
+ export const DEFAULT_PROGRESS: PlayerProgress = {
77
332
  positionMs: 0,
78
333
  durationMs: 0,
334
+ isBuffering: false,
335
+ isSeeking: false,
336
+ seekable: false,
337
+ cacheRanges: [],
338
+ cacheFill: 0,
79
339
  };
80
340
 
341
+ // ═══════════════════════════════════════════════════════════════════════════
342
+ // Commands (built once, stable across renders)
343
+ // ═══════════════════════════════════════════════════════════════════════════
344
+
345
+ /**
346
+ * V13 Phase 51: build the full commands object. The bridge is
347
+ * resolved lazily on every invocation, so we can build the
348
+ * commands at module load without forcing a native module to be
349
+ * present (the no-op fallback kicks in for jest / web previews).
350
+ *
351
+ * The returned object is memoized at module scope and reused for
352
+ * every `usePlayer()` call — `expect(result.current.commands).toBe(firstCommands)`
353
+ * holds across re-renders (per the Phase 24 stable-reference contract).
354
+ */
355
+ function buildCommands(): PlayerCommands {
356
+ return {
357
+ // V12 surface
358
+ play: () => {
359
+ dlog('commands.play()');
360
+ getMpvPlayerModule().play();
361
+ },
362
+ pause: () => {
363
+ dlog('commands.pause()');
364
+ getMpvPlayerModule().pause();
365
+ },
366
+ seek: (positionMs: number) => {
367
+ dlog('commands.seek(positionMs=', positionMs, ')');
368
+ getMpvPlayerModule().seekAbsolute(positionMs / 1000);
369
+ },
370
+ skipBackward: (seconds: number) => {
371
+ dlog('commands.skipBackward(', seconds, ')');
372
+ getMpvPlayerModule().seekBackward(seconds);
373
+ },
374
+ skipForward: (seconds: number) => {
375
+ dlog('commands.skipForward(', seconds, ')');
376
+ getMpvPlayerModule().seekForward(seconds);
377
+ },
378
+
379
+ // V13 additions
380
+ togglePlayPause: () => {
381
+ dlog('commands.togglePlayPause()');
382
+ getMpvPlayerModule().togglePlayPause();
383
+ },
384
+ stop: () => {
385
+ dlog('commands.stop()');
386
+ getMpvPlayerModule().stop();
387
+ },
388
+ seekBy: (deltaMs: number) => {
389
+ dlog('commands.seekBy(', deltaMs, ')');
390
+ const deltaSec = Math.abs(deltaMs / 1000);
391
+ if (deltaMs >= 0) {
392
+ getMpvPlayerModule().seekForward(deltaSec);
393
+ } else {
394
+ getMpvPlayerModule().seekBackward(deltaSec);
395
+ }
396
+ },
397
+ seekToChapter: (index: number) => {
398
+ dlog('commands.seekToChapter(', index, ')');
399
+ // mpv supports `setProperty('chapter', N)` to jump to a specific
400
+ // chapter index. The bridge has `seekChapter(direction)` for
401
+ // next/previous but not direct index access; use the property
402
+ // setter so we get a single round-trip.
403
+ getMpvPlayerModule().setProperty('chapter', index);
404
+ },
405
+ next: () => {
406
+ dlog('commands.next()');
407
+ getMpvPlayerModule().playlistNext();
408
+ },
409
+ previous: () => {
410
+ dlog('commands.previous()');
411
+ getMpvPlayerModule().playlistPrev();
412
+ },
413
+
414
+ setVolume: (volume: number) => {
415
+ dlog('commands.setVolume(', volume, ')');
416
+ getMpvPlayerModule().setVolume(volume);
417
+ },
418
+ setMuted: (muted: boolean) => {
419
+ dlog('commands.setMuted(', muted, ')');
420
+ getMpvPlayerModule().setMuted(muted);
421
+ },
422
+ toggleMute: () => {
423
+ dlog('commands.toggleMute()');
424
+ getMpvPlayerModule().toggleMute();
425
+ },
426
+
427
+ setSpeed: (speed: number) => {
428
+ dlog('commands.setSpeed(', speed, ')');
429
+ getMpvPlayerModule().setSpeed(speed);
430
+ },
431
+ setLoopMode: (mode: MpvLoopMode) => {
432
+ dlog('commands.setLoopMode(', mode, ')');
433
+ getMpvPlayerModule().setLoopMode(mode);
434
+ },
435
+
436
+ loadFile: (uri: string) => {
437
+ dlog('commands.loadFile(', uri, ')');
438
+ getMpvPlayerModule().loadFile(uri);
439
+ },
440
+ loadPlaylist: (uris: string[], startIndex?: number) => {
441
+ dlog('commands.loadPlaylist(len=', uris.length, ', start=', startIndex, ')');
442
+ getMpvPlayerModule().loadPlaylist(uris, startIndex);
443
+ },
444
+
445
+ playlistRemove: (index: number) => {
446
+ dlog('commands.playlistRemove(', index, ')');
447
+ getMpvPlayerModule().playlistRemove(index);
448
+ },
449
+ shuffle: () => {
450
+ dlog('commands.shuffle()');
451
+ getMpvPlayerModule().playlistShuffle();
452
+ },
453
+ clear: () => {
454
+ dlog('commands.clear()');
455
+ getMpvPlayerModule().playlistClear();
456
+ },
457
+
458
+ selectTrack: (trackId: number) => {
459
+ dlog('commands.selectTrack(', trackId, ')');
460
+ getMpvPlayerModule().selectTrack(trackId);
461
+ },
462
+ cycleTrack: (type: 'video' | 'audio' | 'sub') => {
463
+ dlog('commands.cycleTrack(', type, ')');
464
+ getMpvPlayerModule().cycleTrack(type);
465
+ },
466
+ setTrack: (type: 'video' | 'audio' | 'sub', trackId: number) => {
467
+ dlog('commands.setTrack(', type, ',', trackId, ')');
468
+ getMpvPlayerModule().setTrack(type, trackId);
469
+ },
470
+
471
+ enterPip: () => {
472
+ dlog('commands.enterPip()');
473
+ getMpvPlayerModule().enterPip();
474
+ },
475
+ exitPip: () => {
476
+ dlog('commands.exitPip()');
477
+ getMpvPlayerModule().exitPip();
478
+ },
479
+ exitPipAndFinish: () => {
480
+ dlog('commands.exitPipAndFinish()');
481
+ getMpvPlayerModule().exitPipAndFinish();
482
+ },
483
+
484
+ setKeepScreenOn: (enabled: boolean) => {
485
+ dlog('commands.setKeepScreenOn(', enabled, ')');
486
+ getMpvPlayerModule().setKeepScreenOn(enabled);
487
+ },
488
+ setOrientation: (mode) => {
489
+ dlog('commands.setOrientation(', mode, ')');
490
+ getMpvPlayerModule().setOrientation(mode);
491
+ },
492
+ setImmersive: (enabled: boolean) => {
493
+ dlog('commands.setImmersive(', enabled, ')');
494
+ getMpvPlayerModule().setImmersive(enabled);
495
+ },
496
+ setScreenBrightness: (value: number) => {
497
+ dlog('commands.setScreenBrightness(', value, ')');
498
+ getMpvPlayerModule().setScreenBrightness(value);
499
+ },
500
+
501
+ requestNotificationPermission: () => {
502
+ dlog('commands.requestNotificationPermission()');
503
+ getMpvPlayerModule().requestNotificationPermission();
504
+ },
505
+
506
+ openPlayer: async (opts) => {
507
+ dlog('commands.openPlayer(', opts, ')');
508
+ return getMpvPlayerModule().openPlayer(
509
+ opts.uri,
510
+ opts.title,
511
+ opts.type,
512
+ opts.startPositionMs ?? 0,
513
+ );
514
+ },
515
+ getLaunchParams: () => {
516
+ dlog('commands.getLaunchParams()');
517
+ return getMpvPlayerModule().getLaunchParams();
518
+ },
519
+
520
+ getProperty: (name: string) => {
521
+ dlog('commands.getProperty(', name, ')');
522
+ return getMpvPlayerModule().getProperty(name);
523
+ },
524
+ setProperty: (name: string, value: unknown) => {
525
+ dlog('commands.setProperty(', name, ',', value, ')');
526
+ getMpvPlayerModule().setProperty(name, value);
527
+ },
528
+ observeProperty: (name: string) => {
529
+ dlog('commands.observeProperty(', name, ')');
530
+ getMpvPlayerModule().observeProperty(name);
531
+ },
532
+ unobserveProperty: (name: string) => {
533
+ dlog('commands.unobserveProperty(', name, ')');
534
+ getMpvPlayerModule().unobserveProperty(name);
535
+ },
536
+
537
+ grantPersistablePermission: (uri: string) => {
538
+ dlog('commands.grantPersistablePermission(', uri, ')');
539
+ getMpvPlayerModule().grantPersistablePermission(uri);
540
+ },
541
+ verifyContentUri: (uri: string) => {
542
+ dlog('commands.verifyContentUri(', uri, ')');
543
+ return getMpvPlayerModule().verifyContentUri(uri);
544
+ },
545
+ };
546
+ }
547
+
548
+ /** Module-scope singleton: built once, shared by every `usePlayer()` call. */
549
+ const BUILT_COMMANDS: PlayerCommands = buildCommands();
550
+
551
+ // ═══════════════════════════════════════════════════════════════════════════
552
+ // Public hooks
553
+ // ═══════════════════════════════════════════════════════════════════════════
554
+
81
555
  /**
82
- * Hook returning the player's current state + commands.
83
- *
84
- * Phase 24 wires the commands to `MpvPlayerModule` (so play / pause /
85
- * seek actually drive mpv when the native side is wired) but keeps
86
- * `state` at the defaults. Phase 25 adds the mpv-event
87
- * subscription that updates `state.title / artist / album /
88
- * isPlaying` from `onFileLoaded`, `onEndFile`, `onPlaybackRestart`
89
- * events.
556
+ * V13 Phase 51: hook returning the player's current state + commands.
557
+ *
558
+ * When called inside a `<PlayerProvider>`, the `state` object is
559
+ * driven by mpv events (via `subscribePlayerEvent`) and the 1Hz
560
+ * position/duration poll. Outside a provider, `state` is
561
+ * `DEFAULT_STATE` (no throw — see Phase 24 design notes: this
562
+ * hook is non-throwing so DefaultControls can render in any
563
+ * environment, including web previews and tests).
564
+ *
565
+ * The `commands` object is a module-singleton: the same reference
566
+ * is returned for every `usePlayer()` call, so `useMemo`-wrapped
567
+ * consumers don't re-create handlers on every render.
568
+ *
569
+ * @example
570
+ * ```tsx
571
+ * function MyControls() {
572
+ * const { state, commands } = usePlayer();
573
+ * return (
574
+ * <Pressable onPress={state.isPlaying ? commands.pause : commands.play}>
575
+ * <Text>{state.isPlaying ? 'Pause' : 'Play'} {state.title}</Text>
576
+ * </Pressable>
577
+ * );
578
+ * }
579
+ * ```
90
580
  */
91
581
  export function usePlayer(): UsePlayerResult {
92
- const bridge = useMemo(getMpvPlayerModule, []);
582
+ const state = useContext(PlayerStateContext);
93
583
  return useMemo<UsePlayerResult>(
94
584
  () => ({
95
- state: DEFAULT_STATE,
96
- commands: {
97
- play: () => {
98
- // Phase 39: log bridge calls when verbose logging is on.
99
- // Helps debug "play button doesn't do anything" by showing
100
- // whether the bridge call is being made at all + what arg.
101
- dlog('commands.play()');
102
- bridge.play();
103
- },
104
- pause: () => {
105
- dlog('commands.pause()');
106
- bridge.pause();
107
- },
108
- seek: (positionMs: number) => {
109
- dlog('commands.seek(positionMs=', positionMs, ')');
110
- // Convert ms → seconds for the bridge (mpv's nativeSeek
111
- // takes a Double in seconds; PlayerCommands uses ms for
112
- // ergonomic JS-side arithmetic).
113
- bridge.seekAbsolute(positionMs / 1000);
114
- },
115
- skipBackward: (seconds: number) => {
116
- dlog('commands.skipBackward(', seconds, ')');
117
- bridge.seekBackward(seconds);
118
- },
119
- skipForward: (seconds: number) => {
120
- dlog('commands.skipForward(', seconds, ')');
121
- bridge.seekForward(seconds);
122
- },
123
- },
585
+ state: state ?? DEFAULT_STATE,
586
+ commands: BUILT_COMMANDS,
124
587
  }),
125
- [bridge],
588
+ [state],
126
589
  );
127
590
  }
128
591
 
129
592
  /**
130
- * Phase 24 hook: returns position + duration. Separate from
131
- * `usePlayer()` so consumers that don't render a scrubber (just
132
- * play/pause buttons) don't pay the 1Hz re-render cost.
133
- *
134
- * Phase 24 returns the defaults (0 / 0). Phase 25 wires to a
135
- * 1Hz poll of `MpvBridgeModule.getTimePos` + `getDuration` (both
136
- * `@ReactMethod(isBlockingSynchronousMethod = true)`) or a
137
- * property-observer subscription on `time-pos` / `duration`.
593
+ * V13 Phase 51: hook returning position + duration + a few related
594
+ * progress fields. Separate from `usePlayer()` so consumers that
595
+ * only render a scrubber / time labels don't re-render on every
596
+ * volume / track / chapter change.
597
+ *
598
+ * The provider updates the progress context only on:
599
+ * - 1Hz `bridge.getPosition()` / `getDuration()` ticks
600
+ * - `onBuffering` / `onSeeking` / `onSeekable` / `onCacheState`
601
+ * events
602
+ *
603
+ * Outside a provider, returns `DEFAULT_PROGRESS` (`0/0` + falsy
604
+ * progress fields).
138
605
  */
139
606
  export function usePlayerProgress(): PlayerProgress {
140
- return DEFAULT_PROGRESS;
607
+ const progress = useContext(PlayerProgressContext);
608
+ return progress ?? DEFAULT_PROGRESS;
609
+ }
610
+
611
+ // ═══════════════════════════════════════════════════════════════════════════
612
+ // Internal: state hydrate + event dispatch (used by PlayerProvider)
613
+ // ═══════════════════════════════════════════════════════════════════════════
614
+
615
+ /**
616
+ * Internal: hydrate `PlayerState` from synchronous bridge getters.
617
+ * Called once on `<PlayerProvider>` mount to seed the state before
618
+ * any mpv events have had a chance to fire.
619
+ *
620
+ * Each getter is wrapped in its own try/catch — a partially-wired
621
+ * bridge (jest, web preview) should not throw out of hydration.
622
+ * On the no-op fallback bridge, every getter returns its
623
+ * documented zero value, so the resulting state equals
624
+ * `DEFAULT_STATE`.
625
+ */
626
+ export function hydratePlayerState(
627
+ bridge: ReturnType<typeof getMpvPlayerModule>,
628
+ ): PlayerState {
629
+ const state: PlayerState = { ...DEFAULT_STATE };
630
+
631
+ // Position + duration + playback state
632
+ try {
633
+ const pos = bridge.getPosition();
634
+ if (Number.isFinite(pos) && pos >= 0) {
635
+ state.positionMs = Math.round(pos * 1000);
636
+ }
637
+ } catch {
638
+ // bridge not fully wired; leave default
639
+ }
640
+ try {
641
+ const dur = bridge.getDuration();
642
+ if (Number.isFinite(dur) && dur >= 0) {
643
+ state.durationMs = Math.round(dur * 1000);
644
+ }
645
+ } catch {
646
+ // ignore
647
+ }
648
+ try {
649
+ const ps: MpvPlaybackState = bridge.getPlaybackState();
650
+ state.isPlaying = ps === 'playing';
651
+ } catch {
652
+ // ignore
653
+ }
654
+
655
+ // Volume / mute / speed / loop
656
+ try {
657
+ state.volume = bridge.getVolume();
658
+ } catch {
659
+ // ignore
660
+ }
661
+ try {
662
+ state.isMuted = bridge.getMuted();
663
+ } catch {
664
+ // ignore
665
+ }
666
+ try {
667
+ state.speed = bridge.getSpeed();
668
+ } catch {
669
+ // ignore
670
+ }
671
+ try {
672
+ state.loopMode = bridge.getLoopMode();
673
+ } catch {
674
+ // ignore
675
+ }
676
+
677
+ // Title + artist + album (via media-title + metadata property)
678
+ try {
679
+ const title = bridge.getProperty('media-title');
680
+ if (title) {
681
+ state.title = title;
682
+ }
683
+ } catch {
684
+ // ignore
685
+ }
686
+ try {
687
+ const metadataJson = bridge.getProperty('metadata');
688
+ const meta = parseMetadata(metadataJson);
689
+ if (meta.title && state.title === 'Simba Player') {
690
+ state.title = meta.title;
691
+ }
692
+ if (meta.artist) {
693
+ state.artist = meta.artist;
694
+ }
695
+ if (meta.album) {
696
+ state.album = meta.album;
697
+ }
698
+ } catch {
699
+ // ignore
700
+ }
701
+
702
+ // Playlist + current index
703
+ try {
704
+ const playlistJson = bridge.getPlaylist();
705
+ const parsed = JSON.parse(playlistJson);
706
+ if (Array.isArray(parsed)) {
707
+ state.playlist = parsed as PlaylistEntry[];
708
+ }
709
+ } catch {
710
+ // ignore
711
+ }
712
+ try {
713
+ const pos = Number(bridge.getProperty('playlist-playing-pos'));
714
+ if (Number.isFinite(pos) && pos >= 0) {
715
+ state.currentIndex = pos;
716
+ }
717
+ } catch {
718
+ // ignore
719
+ }
720
+
721
+ // Tracks
722
+ try {
723
+ const tracksJson = bridge.getTracks();
724
+ const parsed = JSON.parse(tracksJson);
725
+ if (Array.isArray(parsed)) {
726
+ state.tracks = parsed as MpvTrack[];
727
+ }
728
+ } catch {
729
+ // ignore
730
+ }
731
+
732
+ // Chapters + current chapter
733
+ try {
734
+ const chaptersJson = bridge.getChapters();
735
+ const parsed = JSON.parse(chaptersJson);
736
+ if (Array.isArray(parsed)) {
737
+ state.chapters = parsed as MpvChapter[];
738
+ }
739
+ } catch {
740
+ // ignore
741
+ }
742
+ try {
743
+ const chapterJson = bridge.getCurrentChapter();
744
+ if (chapterJson && chapterJson !== '{}') {
745
+ const parsed = JSON.parse(chapterJson);
746
+ state.currentChapter = parsed as MpvChapter;
747
+ }
748
+ } catch {
749
+ // ignore
750
+ }
751
+
752
+ // Video params
753
+ try {
754
+ const vpJson = bridge.getVideoParams();
755
+ if (vpJson && vpJson !== '{}') {
756
+ const parsed = JSON.parse(vpJson);
757
+ state.videoParams = parsed as MpvVideoParams;
758
+ }
759
+ } catch {
760
+ // ignore
761
+ }
762
+
763
+ return state;
141
764
  }
765
+
766
+ /**
767
+ * Internal: parse an mpv `metadata` property value (a JSON array of
768
+ * `{key, value}` entries) into a flat `{title, artist, album}`
769
+ * object. Unknown keys are ignored. Returns an empty object for
770
+ * any input that fails to parse.
771
+ */
772
+ export function parseMetadata(
773
+ metadataJson: string,
774
+ ): { title?: string; artist?: string; album?: string } {
775
+ if (!metadataJson) return {};
776
+ let parsed: unknown;
777
+ try {
778
+ parsed = JSON.parse(metadataJson);
779
+ } catch {
780
+ return {};
781
+ }
782
+ if (!Array.isArray(parsed)) return {};
783
+ const result: { title?: string; artist?: string; album?: string } = {};
784
+ for (const entry of parsed) {
785
+ if (entry == null || typeof entry !== 'object') continue;
786
+ const key = (entry as { key?: unknown }).key;
787
+ const value = (entry as { value?: unknown }).value;
788
+ if (typeof key !== 'string' || value == null) continue;
789
+ const str = String(value);
790
+ switch (key) {
791
+ case 'title':
792
+ result.title = str;
793
+ break;
794
+ case 'artist':
795
+ result.artist = str;
796
+ break;
797
+ case 'album':
798
+ result.album = str;
799
+ break;
800
+ }
801
+ }
802
+ return result;
803
+ }
804
+
805
+ /**
806
+ * Internal: apply a single mpv event to a `(state, progress)` pair
807
+ * and return the next pair. Pure function — no React, no bridge calls.
808
+ *
809
+ * `state` carries the "static-ish" player state (title, isPlaying,
810
+ * volume, tracks, etc.) and `progress` carries the "1Hz-pollable"
811
+ * fields (position, duration, isBuffering, isSeeking, seekable,
812
+ * cacheRanges, cacheFill). The two are kept separate so consumers
813
+ * that only render a scrubber (using `usePlayerProgress`) don't
814
+ * re-render on every volume/track change.
815
+ *
816
+ * For events that only touch one of the two, the other is returned
817
+ * unchanged. For events that touch both, both are updated. This is
818
+ * the canonical V13 "split-context" pattern.
819
+ */
820
+ export function applyPlayerEvent(
821
+ state: PlayerState,
822
+ progress: PlayerProgress,
823
+ event: string,
824
+ payload: unknown,
825
+ ): { state: PlayerState; progress: PlayerProgress } {
826
+ const p = (payload ?? {}) as Record<string, unknown>;
827
+
828
+ switch (event) {
829
+ case 'onFileLoaded': {
830
+ const file = (p.file ?? undefined) as MpvFileInfo | undefined;
831
+ return {
832
+ state: {
833
+ ...state,
834
+ title: file?.title ?? state.title,
835
+ durationMs: file?.duration
836
+ ? Math.round(file.duration * 1000)
837
+ : state.durationMs,
838
+ isPlaying: true,
839
+ positionMs: 0,
840
+ error: null, // clear any prior error
841
+ },
842
+ progress: {
843
+ ...progress,
844
+ positionMs: 0,
845
+ durationMs: file?.duration
846
+ ? Math.round(file.duration * 1000)
847
+ : progress.durationMs,
848
+ },
849
+ };
850
+ }
851
+ case 'onPlaybackStateChanged':
852
+ return { state: { ...state, isPlaying: (p.state as MpvPlaybackState) === 'playing' }, progress };
853
+ case 'onPositionChanged': {
854
+ const positionMs = Math.round(((p.position as number) ?? 0) * 1000);
855
+ return {
856
+ state: { ...state, positionMs },
857
+ progress: { ...progress, positionMs },
858
+ };
859
+ }
860
+ case 'onDurationChanged': {
861
+ const durationMs = Math.round(((p.duration as number) ?? 0) * 1000);
862
+ return {
863
+ state: { ...state, durationMs },
864
+ progress: { ...progress, durationMs },
865
+ };
866
+ }
867
+ case 'onPropertyChanged': {
868
+ const property = String(p.property ?? '');
869
+ const value = p.value;
870
+ switch (property) {
871
+ case 'media-title':
872
+ return { state: { ...state, title: String(value ?? '') }, progress };
873
+ case 'volume':
874
+ return { state: { ...state, volume: Number(value) }, progress };
875
+ case 'mute':
876
+ return { state: { ...state, isMuted: Boolean(value) }, progress };
877
+ case 'speed':
878
+ return { state: { ...state, speed: Number(value) }, progress };
879
+ case 'loop-file':
880
+ // mpv's loop-file is a boolean; the unified loopMode combines
881
+ // it with loop-playlist. We only mutate when this property
882
+ // turns ON — turning OFF defers to loop-playlist (if it's
883
+ // also off, the next hydration will reset to 'none').
884
+ if (value) return { state: { ...state, loopMode: 'file' }, progress };
885
+ return { state, progress };
886
+ case 'loop-playlist':
887
+ if (value) return { state: { ...state, loopMode: 'playlist' }, progress };
888
+ return { state, progress };
889
+ case 'metadata': {
890
+ const meta = parseMetadata(String(value ?? ''));
891
+ return {
892
+ state: {
893
+ ...state,
894
+ ...(meta.title ? { title: meta.title } : {}),
895
+ ...(meta.artist ? { artist: meta.artist } : {}),
896
+ ...(meta.album ? { album: meta.album } : {}),
897
+ },
898
+ progress,
899
+ };
900
+ }
901
+ case 'playlist': {
902
+ try {
903
+ const parsed = JSON.parse(String(value ?? '[]'));
904
+ if (Array.isArray(parsed)) {
905
+ return { state: { ...state, playlist: parsed as PlaylistEntry[] }, progress };
906
+ }
907
+ } catch {
908
+ // ignore — bad payload
909
+ }
910
+ return { state, progress };
911
+ }
912
+ case 'playlist-playing-pos':
913
+ return { state: { ...state, currentIndex: Number(value) }, progress };
914
+ default:
915
+ return { state, progress };
916
+ }
917
+ }
918
+ case 'onTracksChanged':
919
+ return { state: { ...state, tracks: (p.tracks as MpvTrack[]) ?? [] }, progress };
920
+ case 'onChapterChanged':
921
+ return { state: { ...state, currentChapter: (p.chapter as MpvChapter | null) ?? null }, progress };
922
+ case 'onVideoParamsChanged':
923
+ return { state: { ...state, videoParams: (p.params as MpvVideoParams) ?? null }, progress };
924
+ case 'onError':
925
+ return {
926
+ state: {
927
+ ...state,
928
+ error: {
929
+ code: Number(p.code ?? 0),
930
+ recoverable: Boolean(p.recoverable ?? false),
931
+ message: String(p.message ?? ''),
932
+ },
933
+ },
934
+ progress,
935
+ };
936
+ case 'onBuffering': {
937
+ // `isBuffering` is the more useful consumer signal than `percent`;
938
+ // honor the explicit flag if present, otherwise treat any
939
+ // non-zero percent as buffering.
940
+ const isBuffering =
941
+ typeof p.isBuffering === 'boolean'
942
+ ? p.isBuffering
943
+ : ((p.percent as number) > 0 && (p.percent as number) < 100);
944
+ return {
945
+ state: { ...state, isBuffering },
946
+ progress: { ...progress, isBuffering },
947
+ };
948
+ }
949
+ case 'onCacheState':
950
+ // Cache state is progress-only — no state field, just progress
951
+ // updates for consumers that render a cache indicator.
952
+ return {
953
+ state,
954
+ progress: {
955
+ ...progress,
956
+ cacheRanges: (p.ranges as Array<{ start: number; end: number }>) ?? [],
957
+ cacheFill: Number(p.fill ?? 0),
958
+ },
959
+ };
960
+ case 'onSeekable':
961
+ return {
962
+ state: { ...state, seekable: Boolean(p.seekable) },
963
+ progress: { ...progress, seekable: Boolean(p.seekable) },
964
+ };
965
+ case 'onSeeking':
966
+ return {
967
+ state: { ...state, isSeeking: Boolean(p.seeking) },
968
+ progress: { ...progress, isSeeking: Boolean(p.seeking) },
969
+ };
970
+ case 'onEndFile':
971
+ return { state: { ...state, isPlaying: false }, progress };
972
+ case 'onPlaybackRestart':
973
+ return {
974
+ state: { ...state, isPlaying: true, positionMs: 0 },
975
+ progress: { ...progress, positionMs: 0 },
976
+ };
977
+ case 'onEndReached':
978
+ return { state: { ...state, isPlaying: false }, progress };
979
+ case 'onAudioDeviceChanged':
980
+ case 'onVolumeChanged':
981
+ return {
982
+ state: { ...state, volume: Number(p.volume ?? state.volume) },
983
+ progress,
984
+ };
985
+ case 'onSpeedChanged':
986
+ return {
987
+ state: { ...state, speed: Number(p.speed ?? state.speed) },
988
+ progress,
989
+ };
990
+ case 'videoReconfig':
991
+ case 'onPipModeChanged':
992
+ case 'onPipPlayPause':
993
+ case 'onPipExpand':
994
+ case 'onPipClose':
995
+ // No state-field mapping for these in the V13 surface (PiP state
996
+ // is owned by the activity; reconfig signals a video-parameter
997
+ // change that's already covered by onVideoParamsChanged).
998
+ return { state, progress };
999
+ default:
1000
+ return { state, progress };
1001
+ }
1002
+ }
1003
+
1004
+ // ═══════════════════════════════════════════════════════════════════════════
1005
+ // Internal: context providers
1006
+ // ═══════════════════════════════════════════════════════════════════════════
1007
+
1008
+ /**
1009
+ * The state + progress contexts are exported here so the
1010
+ * `<PlayerStateProvider>` component (in `PlayerProvider.tsx`)
1011
+ * can import them. The component itself is a JSX component, so
1012
+ * it has to live in a `.tsx` file — we keep the contexts in
1013
+ * this `.ts` file so non-JSX consumers (DefaultControls,
1014
+ * `usePlayer`, etc.) can import them without forcing the JSX
1015
+ * transform on the whole module.
1016
+ */