@simba-dev/react-native-media-player 1.13.3 → 1.13.5

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.
@@ -7,6 +7,7 @@ import android.app.PendingIntent
7
7
  import android.app.Service
8
8
  import android.content.Context
9
9
  import android.content.Intent
10
+ import android.content.pm.PackageManager
10
11
  import android.graphics.Bitmap
11
12
  import android.graphics.BitmapFactory
12
13
  import android.os.Build
@@ -196,16 +197,79 @@ class MediaPlaybackService : Service() {
196
197
  }
197
198
 
198
199
  /**
199
- * Build a [PendingIntent] that opens `PlayerActivity`. Used
200
- * when the user taps the notification body — returns them
201
- * to the player if its task is still alive, or launches a fresh
202
- * instance otherwise.
200
+ * The intent that surfaces the player UI.
201
+ *
202
+ * ## Why this is resolved and not written down
203
+ *
204
+ * Both this and the session-activity [PendingIntent] used to name
205
+ * their target as the string literal `"com.simba.player.PlayerActivity"`.
206
+ * A hardcoded component name is the one kind of dependency that
207
+ * survives every gate: it typechecks, it compiles, it packages, and
208
+ * the only failure is at runtime — `ActivityNotFoundException` when
209
+ * the user taps the notification or PiP resumes. Nothing tells you
210
+ * at build time, which is exactly why it has to not exist.
211
+ *
212
+ * It also made the V21 collapse unsafe *by construction*: the
213
+ * library was naming a class the application is about to delete, so
214
+ * deleting it would have shipped a green build with two dead
215
+ * notification paths in it.
216
+ *
217
+ * The player host IS the application entry point once playback lives
218
+ * in a single Activity — so rather than assert a name and keep it in
219
+ * sync, ask Android which component the launcher icon resolves to.
220
+ * `CATEGORY_LAUNCHER` + `setPackage` is the platform's own answer to
221
+ * "what does launching this app do", scoped to this package so it
222
+ * cannot pick up another app's activity.
223
+ *
224
+ * Returns null when the package declares no launchable activity.
225
+ * Callers must degrade rather than invent a component — a
226
+ * [PendingIntent] aimed at a class that may not exist is precisely
227
+ * the bug this replaces.
203
228
  */
204
- private fun buildContentIntent(context: Context): PendingIntent {
205
- val intent = Intent().apply {
206
- setClassName(context, "com.simba.player.PlayerActivity")
229
+ private fun hostPlayerActivityIntent(context: Context): Intent? {
230
+ val pm = context.packageManager
231
+ val launchIntent = Intent(Intent.ACTION_MAIN)
232
+ .addCategory(Intent.CATEGORY_LAUNCHER)
233
+ .setPackage(context.packageName)
234
+ val className = try {
235
+ pm.resolveActivity(launchIntent, PackageManager.MATCH_DEFAULT_ONLY)
236
+ ?.activityInfo?.name
237
+ } catch (e: Exception) {
238
+ // PackageManager can throw on a package that is mid-update
239
+ // or being read cross-process. Naming the cause beats a
240
+ // silent null: this is a real, reportable failure.
241
+ Log.w(TAG, "resolveActivity($launchIntent) failed: ${e.message}")
242
+ null
243
+ }
244
+
245
+ if (className.isNullOrBlank()) {
246
+ Log.e(
247
+ TAG,
248
+ "No launchable activity for ${context.packageName}. The notification " +
249
+ "body and the lock-screen widget will have no way to surface the " +
250
+ "player, so they are being built without a target rather than " +
251
+ "with one that would throw when tapped.",
252
+ )
253
+ return null
254
+ }
255
+
256
+ return Intent().apply {
257
+ setClassName(context, className)
207
258
  flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
208
259
  }
260
+ }
261
+
262
+ /**
263
+ * Build a [PendingIntent] that surfaces the player. Used when the
264
+ * user taps the notification body — returns them to the player if
265
+ * its task is still alive, or launches a fresh instance otherwise.
266
+ *
267
+ * Null when the package declares no launchable activity; see
268
+ * [hostPlayerActivityIntent] for why that degrades instead of
269
+ * guessing a component.
270
+ */
271
+ private fun buildContentIntent(context: Context): PendingIntent? {
272
+ val intent = hostPlayerActivityIntent(context) ?: return null
209
273
  return PendingIntent.getActivity(
210
274
  context,
211
275
  0,
@@ -391,18 +455,22 @@ class MediaPlaybackService : Service() {
391
455
  )
392
456
  setCallback(callback)
393
457
  // Tapping the lock-screen widget should surface the player.
394
- val activityIntent = Intent().apply {
395
- setClassName(this@MediaPlaybackService, "com.simba.player.PlayerActivity")
396
- flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
458
+ //
459
+ // Resolved from the manifest rather than hardcoded — see
460
+ // `hostPlayerActivityIntent`. `setSessionActivity(null)` is the
461
+ // documented "this session has no UI target" value, so an
462
+ // unresolvable host degrades to a widget that simply does not
463
+ // offer a tap target instead of one that throws when tapped.
464
+ hostPlayerActivityIntent(this@MediaPlaybackService)?.let { hostIntent ->
465
+ setSessionActivity(
466
+ PendingIntent.getActivity(
467
+ this@MediaPlaybackService,
468
+ 0,
469
+ hostIntent,
470
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
471
+ ),
472
+ )
397
473
  }
398
- setSessionActivity(
399
- PendingIntent.getActivity(
400
- this@MediaPlaybackService,
401
- 0,
402
- activityIntent,
403
- PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
404
- ),
405
- )
406
474
  isActive = true
407
475
  }
408
476
  mediaSession = session
@@ -25,6 +25,7 @@ import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnable
25
25
  import com.facebook.react.defaults.DefaultReactActivityDelegate
26
26
  import com.simba.player.mpv.MPVLib
27
27
  import com.simba.player.mpv.MpvRenderView
28
+ import com.simba.player.mpv.PlayerSurface
28
29
 
29
30
  /**
30
31
  * Dedicated ReactActivity that hosts the SIMBA video/audio player.
@@ -454,48 +455,39 @@ class PlayerActivity : ReactActivity() {
454
455
  Log.i(TAG, "Audio mode entered: MpvRenderView will be hidden in Phase 12; mpv engine will run without video output")
455
456
  }
456
457
 
457
- // ── Phase 6: Mount MpvRenderView at content root index 0 ────────
458
- // Step 6.1.1 + 6.1.2: get root via android.R.id.content (the
459
- // standard FrameLayout that AppCompat installs as the activity's
460
- // content view). super.onCreate has populated it; ReactRootView is
461
- // already added at index 1 by super, so we add the SurfaceView at
462
- // index 0 to sit BENEATH the React tree (PiP-friendly layering).
463
- val rootView = findViewById<ViewGroup>(android.R.id.content)
464
- if (rootView !is FrameLayout) {
465
- Log.w(
466
- TAG,
467
- "content root is not FrameLayout (got ${rootView?.javaClass?.simpleName}); MpvRenderView may not layer correctly",
468
- )
469
- }
470
- // Step 6.2: create MpvRenderView (constructor widened to Context
471
- // in Phase 6 — see MpvRenderView.kt docblock).
472
- // Step 6.3: layout params. We use FrameLayout.LayoutParams so we
473
- // can later set gravity / insets via additional Phase 8 work;
474
- // MATCH_PARENT x MATCH_PARENT keeps the surface full-bleed.
475
- val renderView = MpvRenderView(this).apply {
476
- layoutParams = FrameLayout.LayoutParams(
477
- FrameLayout.LayoutParams.MATCH_PARENT,
478
- FrameLayout.LayoutParams.MATCH_PARENT,
479
- )
480
- }
481
- // Step 6.4: add at index 0 so it sits below the ReactRootView that
482
- // super.onCreate installed. The React UI will float on top with a
483
- // transparent background (Phase 8) so the surface shows through.
484
- rootView.addView(renderView, 0)
485
- mpvRenderView = renderView
486
- // Step 6.5: log.
487
- Log.i(TAG, "MpvRenderView mounted at content root, index=0")
488
- // Phase 12.1.1: for audio files, hide the MpvRenderView. The
489
- // SurfaceView is still created and the mpv engine still runs (so
490
- // audio plays) — the view is just visually absent. View.GONE
491
- // collapses the layout slot AND skips drawing; we use GONE (not
492
- // INVISIBLE) because INVISIBLE would still take layout space
493
- // which would push the future audio UI (Phase 13) below the
494
- // fold on first render. Phase 12.2's MpvRenderView guard makes
495
- // the surface attach path robust to this state.
496
- if (launchType == TYPE_AUDIO) {
497
- renderView.visibility = android.view.View.GONE
498
- Log.i(TAG, "MpvRenderView hidden for audio mode (visibility=GONE)")
458
+ // ── Mount the render surface (V21) ─────────────────────────────────
459
+ // This block used to create the MpvRenderView inline, size it
460
+ // MATCH_PARENT, add it at index 0, and hide it only for audio. That
461
+ // duplicated the one piece of knowledge the bridge also needs — "is
462
+ // there a surface, and where is it" — inside an Activity, while
463
+ // `PlayerSurface` (the registry the bridge reads) was never populated by
464
+ // anyone. `isSurfaceMounted()` therefore answered `false` and all four
465
+ // surface mutators refused, on a fully working video path.
466
+ //
467
+ // Mounting is now the library's job, through `PlayerSurface.mount`,
468
+ // which is the single implementation of "create it, put it under the
469
+ // React root, register it". The Activity supplies an Activity and
470
+ // nothing else; `MainActivity` will do exactly the same after the
471
+ // collapse.
472
+ //
473
+ // mount() deliberately leaves the view GONE at 0x0, so showing video is
474
+ // always two explicit acts — give it size, then show it — and no host can
475
+ // end up with an accidental full-bleed surface over its own UI.
476
+ val renderView = PlayerSurface.mount(this)
477
+ if (renderView == null) {
478
+ // mount() has already logged the concrete reason. Carrying on with a
479
+ // null view is safe (onEngineAvailable returns early, onDestroy is
480
+ // null-safe) and it means audio still plays if only video cannot.
481
+ Log.e(TAG, "no render surface mounted; this window cannot present video")
482
+ } else {
483
+ mpvRenderView = renderView
484
+ if (launchType != TYPE_AUDIO) {
485
+ PlayerSurface.fillBounds()
486
+ PlayerSurface.setVisible(true)
487
+ Log.i(TAG, "render surface sized to fill and shown for video")
488
+ } else {
489
+ Log.i(TAG, "render surface left hidden for audio mode")
490
+ }
499
491
  }
500
492
 
501
493
  // ── Wire the libmpv handle into MpvRenderView (V20 Phase A) ─────────
@@ -1570,16 +1562,15 @@ class PlayerActivity : ReactActivity() {
1570
1562
  // and zero the native pointer so any late native callback becomes
1571
1563
  // a no-op).
1572
1564
  mpvRenderView?.cleanup()
1573
- // Step 6.6.2: remove from the content root. Guard against the
1574
- // view having already been detached by the framework (defensive
1575
- // but cheap; indexOfChildById-style call would be heavier).
1576
- mpvRenderView?.let { view ->
1577
- val parent = view.parent as? ViewGroup
1578
- parent?.removeView(view)
1579
- }
1565
+ // Step 6.6.2: unmount through the library, which both removes the view
1566
+ // from the content root and withdraws it from the registry in one
1567
+ // identity-checked step. Removing it here without withdrawing it would
1568
+ // leave `PlayerSurface` publishing a detached view, and the surface
1569
+ // mutators would keep reporting success against a surface with no window.
1570
+ mpvRenderView?.let { view -> PlayerSurface.unmount(view) }
1580
1571
  // Step 6.6.3: null the reference.
1581
1572
  mpvRenderView = null
1582
- Log.i(TAG, "onDestroy: MpvRenderView cleaned up and removed")
1573
+ Log.i(TAG, "onDestroy: MpvRenderView cleaned up and unmounted")
1583
1574
  // V22.0.0 / 1.5.10 (D-034): clear the player-host flag. We set
1584
1575
  // the flag in onCreate before RN mounts; we clear it here so
1585
1576
  // the next time JS asks `isCurrentActivityPlayer()` it sees
@@ -242,10 +242,19 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
242
242
  // Do NOT cycle the surface binding here. Cycling detaches →
243
243
  // re-attaches → triggers a mpv VO reinit → kills MediaCodec
244
244
  // (decoder falls back to software, ~1s render gap, PiP
245
- // shows black). Instead, the SurfaceView with
246
- // setZOrderMediaOverlay(true) and force-window=yes keeps the
247
- // gpu video output rendering into the attached surface, and
248
- // the PiP compositor samples that surface layer directly.
245
+ // shows black).
246
+ //
247
+ // The surface keeps rendering because it is an ordinary
248
+ // SurfaceView at DEFAULT z-order (below the window). An
249
+ // earlier version of this comment claimed the opposite —
250
+ // that "the SurfaceView with setZOrderMediaOverlay(true)
251
+ // and force-window=yes" keeps the GPU output alive and the
252
+ // PiP compositor samples that layer. Neither call is made
253
+ // anywhere: `MpvRenderView` explicitly forbids them, because
254
+ // a media-overlay surface is not composited into PiP by the
255
+ // platform. The comment outlived the implementation and made
256
+ // the next reader believe the z-order was doing work it
257
+ // never did.
249
258
  val params = Arguments.createMap().apply {
250
259
  putBoolean("isInPip", isInPictureInPictureMode)
251
260
  }
@@ -662,10 +671,16 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
662
671
  "sensor" -> android.content.pm.ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
663
672
  else -> android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
664
673
  }
674
+ // Read the previous value BEFORE the write. Reading it after
675
+ // would log the new value as "was", so every rotation would
676
+ // print as though nothing changed — which is exactly the
677
+ // symptom this log exists to diagnose, and it made the
678
+ // orientation lock look broken for the wrong reason.
679
+ val previous = activity.requestedOrientation
665
680
  activity.requestedOrientation = requested
666
681
  android.util.Log.d(
667
682
  TAG,
668
- "setOrientation('$mode') -> requestedOrientation=$requested (was ${activity.requestedOrientation})",
683
+ "setOrientation('$mode') -> requestedOrientation=$requested (was $previous)",
669
684
  )
670
685
  }
671
686
  }
@@ -1883,12 +1898,20 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1883
1898
  }
1884
1899
  // 3.5: build the intent. Title falls back to the URI when blank
1885
1900
  // so the notification / lock-screen widget always has a display
1886
- // string. We use FLAG_ACTIVITY_NEW_TASK because we are launching
1887
- // from a non-Activity context (the bridge runs in the React
1888
- // context's main looper; the startActivity call is technically
1889
- // from the activity, but the flag is harmless and makes the
1890
- // intent correct if the activity is ever swapped for a
1891
- // background-launched one).
1901
+ // string.
1902
+ //
1903
+ // No intent flags are set, deliberately. An earlier version of this
1904
+ // comment said "we use FLAG_ACTIVITY_NEW_TASK because we are
1905
+ // launching from a non-Activity context ... the flag is harmless".
1906
+ // Both halves were wrong: we launch from `activity`, and the flag is
1907
+ // NOT harmless — it starts the target in a new task, which breaks
1908
+ // the `singleTask` reuse that keeps a second `openPlayer` from
1909
+ // stacking a duplicate player window, and leaves the video in a task
1910
+ // the user's back gesture does not return from.
1911
+ //
1912
+ // If this ever does need to launch without an Activity, the flag
1913
+ // belongs there — and the task-affinity consequences need dealing
1914
+ // with, not waving through as "harmless".
1892
1915
  val resolvedTitle = title.takeIf { it.isNotBlank() } ?: uri
1893
1916
  val intent = android.content.Intent(
1894
1917
  activity,
@@ -1,8 +1,11 @@
1
1
  package com.simba.player.mpv
2
2
 
3
- import android.os.Handler
3
+ import android.app.Activity
4
4
  import android.os.Looper
5
5
  import android.util.Log
6
+ import android.view.View
7
+ import android.view.ViewGroup
8
+ import android.widget.FrameLayout
6
9
  import java.lang.ref.WeakReference
7
10
 
8
11
  /**
@@ -35,30 +38,115 @@ import java.lang.ref.WeakReference
35
38
  *
36
39
  * ## Threading
37
40
  *
38
- * View mutation is main-thread only. Every public method here marshals to the
39
- * main looper and reports success through a synchronous result when called
40
- * from the main thread, so JS gets an honest "did this take effect" answer.
41
+ * View mutation is main-thread only. Every public method here refuses off the
42
+ * main thread rather than posting, because a posted mutation has no caller left
43
+ * to report success to, and a `Promise<boolean>` that resolves before the work
44
+ * happens is a lie. JS therefore gets a synchronous, honest answer.
41
45
  *
42
46
  * ## No silent no-ops
43
47
  *
44
48
  * Each mutator returns `false` and logs when there is no surface to act on.
45
49
  * Callers are expected to surface that to JS so a control whose handler could
46
50
  * not run renders disabled rather than inert.
51
+ *
52
+ * ## The surface is always mounted hidden
53
+ *
54
+ * [mount] creates the view `GONE` and `0x0`. That is deliberate and is the
55
+ * reason no host can accidentally end up with a full-bleed surface covering its
56
+ * own UI: making the surface visible is always an explicit, separate act, via
57
+ * [setVisible], and giving it size is always an explicit act, via [fillBounds]
58
+ * or [setBounds]. "Playing video" is therefore always two deliberate calls
59
+ * rather than an emergent property of having constructed the view.
47
60
  */
48
61
  object PlayerSurface {
49
62
 
50
63
  private const val TAG = "PlayerSurface"
51
64
 
52
- private val mainHandler = Handler(Looper.getMainLooper())
53
-
54
65
  private var viewRef: WeakReference<MpvRenderView> = WeakReference(null)
55
66
 
56
67
  /** The live surface, or `null` when nothing is mounted. Never cache the result. */
57
68
  fun current(): MpvRenderView? = viewRef.get()
58
69
 
59
70
  /**
60
- * Publish the process's surface. Called by the hosting Activity once the
61
- * view is mounted and bound to a window.
71
+ * Create, position and register the process's single [MpvRenderView] inside
72
+ * [activity], beneath its React root.
73
+ *
74
+ * This is the only sanctioned way to put a render surface on screen. The
75
+ * hosting Activity hands over an Activity; it never constructs, lays out or
76
+ * registers the view itself. That keeps exactly one implementation of
77
+ * "where does the surface go and what layer is it on" — previously that
78
+ * knowledge was duplicated per-Activity, which is how a host and the
79
+ * bridge ended up disagreeing about whether a surface existed at all.
80
+ *
81
+ * The view is added at index 0 of `android.R.id.content` so it sits below
82
+ * the React tree, and is left `GONE` at `0x0`; see the class docblock.
83
+ *
84
+ * @return the mounted view, or `null` when mounting was refused. Refusal is
85
+ * always logged with the reason — never swallowed.
86
+ */
87
+ @JvmStatic
88
+ fun mount(activity: Activity): MpvRenderView? {
89
+ if (Looper.myLooper() != Looper.getMainLooper()) {
90
+ Log.e(TAG, "mount refused: must be called from the main thread")
91
+ return null
92
+ }
93
+
94
+ // Idempotent: a configuration change recreates the Activity, and the
95
+ // outgoing instance's onDestroy can run after the incoming one has
96
+ // already mounted. Reuse rather than orphan the first surface.
97
+ val existing = viewRef.get()
98
+ if (existing != null && existing.parent != null) {
99
+ Log.i(TAG, "mount reused the already-mounted surface ${System.identityHashCode(existing)}")
100
+ return existing
101
+ }
102
+
103
+ val root = activity.findViewById<ViewGroup>(android.R.id.content)
104
+ ?: run {
105
+ Log.e(TAG, "mount refused: ${activity.javaClass.simpleName} has no android.R.id.content")
106
+ return null
107
+ }
108
+ if (root !is FrameLayout) {
109
+ // Not fatal — a non-FrameLayout container cannot take FrameLayout
110
+ // params, and setVideoBounds() then no-ops via frameParams(). Say so
111
+ // loudly rather than layering wrongly and shipping a black screen.
112
+ Log.e(
113
+ TAG,
114
+ "mount: content root is ${root.javaClass.simpleName}, not FrameLayout; " +
115
+ "explicit video bounds will not be applied",
116
+ )
117
+ return null
118
+ }
119
+
120
+ val view = MpvRenderView(activity).apply {
121
+ layoutParams = FrameLayout.LayoutParams(0, 0)
122
+ visibility = View.GONE
123
+ }
124
+ root.addView(view, 0)
125
+ attach(view)
126
+ Log.i(TAG, "surface mounted beneath the React root, hidden and 0x0")
127
+ return view
128
+ }
129
+
130
+ /**
131
+ * Remove [view] from its container and withdraw it from the registry.
132
+ *
133
+ * Identity-safe: passing a view that is not the registered one only removes
134
+ * that view and leaves the live registration alone, so an outgoing
135
+ * Activity's teardown cannot unregister its replacement's surface.
136
+ */
137
+ @JvmStatic
138
+ fun unmount(view: MpvRenderView) {
139
+ if (Looper.myLooper() != Looper.getMainLooper()) {
140
+ Log.e(TAG, "unmount refused: must be called from the main thread")
141
+ return
142
+ }
143
+ detach(view)
144
+ (view.parent as? ViewGroup)?.removeView(view)
145
+ Log.i(TAG, "surface unmounted and withdrawn from the registry")
146
+ }
147
+
148
+ /**
149
+ * Publish the process's surface. Called by [mount].
62
150
  */
63
151
  fun attach(view: MpvRenderView) {
64
152
  viewRef = WeakReference(view)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.13.3",
3
+ "version": "1.13.5",
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",
@@ -336,7 +336,21 @@ export interface Spec extends TurboModule {
336
336
  setConfig(configJson: string): Promise<number>;
337
337
 
338
338
  // ── Picture-in-Picture ─────────────────────────────────────────────────
339
- enterPip(chapterTitle: string, progressPct: string): void;
339
+ // Both params are OPTIONAL, and this spec is the one that matters.
340
+ //
341
+ // TurboModule codegen reads *this* file, not the `MpvPlayerModule`
342
+ // facade — so a facade that declares them optional is not enough. This
343
+ // signature said `string` (required) while the Kotlin impl says
344
+ // `String?` and `commands.enterPip()` (src/types/player.ts) calls it
345
+ // with zero arguments. Codegen therefore advertised an arity the JS
346
+ // side never uses and the native side never required, and the Kotlin
347
+ // fix that made them nullable could not take effect through a spec
348
+ // still promising two required arguments.
349
+ //
350
+ // Two declarations of one method, disagreeing, is the same class of
351
+ // defect as the MediaKind/MediaLane confusion: the real bug is that
352
+ // there are two sources of truth, not that either value was wrong.
353
+ enterPip(chapterTitle?: string, progressPct?: string): void;
340
354
  exitPip(): void;
341
355
  exitPipAndFinish(): void;
342
356
 
@@ -0,0 +1,159 @@
1
+ /**
2
+ * `resolveStreamType` decides which lane a launch opens, and therefore
3
+ * which PLAYER WINDOW opens — not just which badge renders.
4
+ *
5
+ * ## The defect this pins
6
+ *
7
+ * Two tabulation errors in the same switch:
8
+ *
9
+ * - `'episode'` sat in the video list. A podcast episode is an AUDIO
10
+ * lane in this app; the seam maps `bridgeOpts.type` straight to the
11
+ * lane, so a podcast episode opened the video window.
12
+ * - `'archive-video'` was absent entirely, so it fell through to the
13
+ * default and opened the AUDIO player.
14
+ *
15
+ * The second is the worse of the two, and the reason the fallback needs
16
+ * its own scrutiny: a RECOGNISED kind falling into the default is worse
17
+ * than an unrecognised one, because the default reads as a deliberate
18
+ * choice rather than a gap in a table.
19
+ *
20
+ * `MediaKind` in the consumer is the authority here; this table is a
21
+ * hand-maintained mirror of it and drifts silently when either side moves.
22
+ * These tests are what make the drift visible.
23
+ */
24
+
25
+ import {
26
+ resolveStreamType,
27
+ CONTENT_KIND_LANES,
28
+ type ContentKind,
29
+ } from '../useOpenWithResume';
30
+
31
+ /** Mirrors the consumer's `MediaKind` union. */
32
+ const CONSUMER_MEDIA_KINDS = [
33
+ 'audio',
34
+ 'music',
35
+ 'podcast',
36
+ 'audiobook',
37
+ 'radio',
38
+ 'video',
39
+ 'movie',
40
+ 'live-tv',
41
+ 'archive-audio',
42
+ 'archive-video',
43
+ ] as const;
44
+
45
+ /** The kinds that must NOT open the video window. */
46
+ const AUDIO_LANES = [
47
+ 'audio',
48
+ 'music',
49
+ 'podcast',
50
+ 'audiobook',
51
+ 'radio',
52
+ 'episode',
53
+ 'archive-audio',
54
+ ] as const;
55
+
56
+ const VIDEO_LANES = [
57
+ 'video',
58
+ 'movie',
59
+ 'live-tv',
60
+ 'video-file',
61
+ 'archive-video',
62
+ ] as const;
63
+
64
+ describe('resolveStreamType', () => {
65
+ it.each(AUDIO_LANES)("routes '%s' to the audio lane", kind => {
66
+ expect(resolveStreamType(kind)).toBe('audio');
67
+ });
68
+
69
+ it.each(VIDEO_LANES)("routes '%s' to the video lane", kind => {
70
+ expect(resolveStreamType(kind)).toBe('video');
71
+ });
72
+
73
+ it('treats a podcast episode as audio, not video', () => {
74
+ // The regression. 'episode' was in the video list.
75
+ expect(resolveStreamType('episode')).toBe('audio');
76
+ });
77
+
78
+ it('routes archive-video to video rather than the audio default', () => {
79
+ // The worse regression: absent from the table entirely, so a known
80
+ // video kind opened the audio player.
81
+ expect(resolveStreamType('archive-video')).toBe('video');
82
+ });
83
+
84
+ it('falls back to audio for an unrecognised kind', () => {
85
+ // Deliberately unchanged: an unknown file is genuinely more likely to
86
+ // be audio-only, and the audio player still plays it.
87
+ expect(resolveStreamType('something-unknown')).toBe('audio');
88
+ expect(resolveStreamType('')).toBe('audio');
89
+ });
90
+
91
+ it('covers every MediaKind the consumer defines', () => {
92
+ // The mirror has to stay in step with the consumer's union. This is
93
+ // the assertion that fails when either side adds a kind.
94
+ const unclassified = CONSUMER_MEDIA_KINDS.filter(
95
+ kind =>
96
+ !AUDIO_LANES.includes(kind as never) && !VIDEO_LANES.includes(kind as never),
97
+ );
98
+ expect(unclassified).toEqual([]);
99
+ });
100
+
101
+ it('never returns the input for a lane spelling (passthrough is not a branch)', () => {
102
+ // 'video' and 'audio' are in both the passthrough and the table; the
103
+ // table is now authoritative, so there is no way for the two to drift.
104
+ for (const kind of CONSUMER_MEDIA_KINDS) {
105
+ expect(['audio', 'video']).toContain(resolveStreamType(kind as ContentKind));
106
+ }
107
+ });
108
+ });
109
+
110
+ /**
111
+ * These assert the TABLE, not the return value.
112
+ *
113
+ * A return-value test cannot see a kind dropped from the table when the
114
+ * fallback happens to agree with the expected answer: remove 'episode'
115
+ * from the audio entries and `resolveStreamType('episode')` still returns
116
+ * 'audio' via the default. That mutation was actually run, and it passed
117
+ * a value-only suite — which is why the map is exported and these
118
+ * assertions exist.
119
+ */
120
+ describe('CONTENT_KIND_LANES — the table itself', () => {
121
+ it("tabulates 'episode' as AUDIO explicitly", () => {
122
+ // Not merely "resolves to audio" — PRESENT in the table as audio.
123
+ expect(CONTENT_KIND_LANES.episode).toBe('audio');
124
+ });
125
+
126
+ it("tabulates 'archive-video' as VIDEO explicitly", () => {
127
+ // Absent before: it took the audio default and opened the audio player.
128
+ expect(CONTENT_KIND_LANES['archive-video']).toBe('video');
129
+ });
130
+
131
+ it('is not the "video list minus audio" accident it was', () => {
132
+ // Guards the specific regression shape: a kind present but in the
133
+ // wrong lane. Both of these are one character away from correct.
134
+ expect(CONTENT_KIND_LANES.episode).not.toBe('video');
135
+ expect(CONTENT_KIND_LANES['archive-audio']).toBe('audio');
136
+ });
137
+
138
+ it('covers every kind the lib claims to accept', () => {
139
+ const declared = [
140
+ ...AUDIO_LANES,
141
+ ...VIDEO_LANES,
142
+ ];
143
+ const missing = declared.filter(kind => !(kind in CONTENT_KIND_LANES));
144
+ expect(missing).toEqual([]);
145
+ });
146
+
147
+ it('assigns every table entry a real lane', () => {
148
+ for (const [kind, lane] of Object.entries(CONTENT_KIND_LANES)) {
149
+ expect(['audio', 'video']).toContain(lane);
150
+ expect(resolveStreamType(kind as ContentKind)).toBe(lane);
151
+ }
152
+ });
153
+
154
+ it('is frozen so a consumer cannot mutate the shared table', () => {
155
+ // A writable export would let one consumer's fix corrupt every other
156
+ // consumer's routing.
157
+ expect(Object.isFrozen(CONTENT_KIND_LANES)).toBe(true);
158
+ });
159
+ });
@@ -207,30 +207,59 @@ export { PlayerResumeContext };
207
207
  export type ContentKind =
208
208
  | 'video' | 'audio' // stream types (passthrough)
209
209
  | 'music' | 'audiobook' | 'podcast' | 'radio' | 'archive-audio' // audio content
210
- | 'movie' | 'episode' | 'live-tv' | 'video-file' // video content
210
+ | 'movie' | 'episode' | 'live-tv' | 'video-file' | 'archive-video' // video content
211
211
  | string; // unknown — falls back to 'audio'
212
212
 
213
+ /**
214
+ * Content kind → playback lane.
215
+ *
216
+ * ## Why a single map rather than two sets plus a default
217
+ *
218
+ * Two sets with an unknown-value fallback cannot be tested for
219
+ * correctness in the one case that matters. If a kind is dropped from
220
+ * both sets it falls through to the default, and for an AUDIO kind that
221
+ * default is also `'audio'` — so the mistake is invisible to any
222
+ * assertion on the return value. A kind only becomes visible once it has
223
+ * already been mis-tabulated *into* the other lane.
224
+ *
225
+ * That is not hypothetical: `'episode'` sat in the video list while the
226
+ * rest of the app treats a podcast episode as audio, and `'archive-video'`
227
+ * was absent entirely so it took the audio default. Both produced a file
228
+ * opening the wrong PLAYER WINDOW, and neither was reachable from a
229
+ * return-value test.
230
+ *
231
+ * Exported so a consumer can audit the table against its own `MediaKind`
232
+ * union instead of discovering a gap as a mis-routed file.
233
+ */
234
+ export const CONTENT_KIND_LANES: Readonly<Record<string, 'audio' | 'video'>> =
235
+ Object.freeze({
236
+ // Audio content kinds. A podcast episode belongs here, not in video.
237
+ audio: 'audio',
238
+ music: 'audio',
239
+ audiobook: 'audio',
240
+ podcast: 'audio',
241
+ radio: 'audio',
242
+ episode: 'audio',
243
+ 'archive-audio': 'audio',
244
+
245
+ // Video content kinds, listed explicitly rather than as "everything
246
+ // else" — a negative list would silently send any kind dropped from
247
+ // the audio table to video.
248
+ video: 'video',
249
+ movie: 'video',
250
+ 'live-tv': 'video',
251
+ 'video-file': 'video',
252
+ 'archive-video': 'video',
253
+ });
254
+
255
+ /**
256
+ * Map a content/media-kind string to a stream type (`'video' | 'audio'`).
257
+ *
258
+ * The fallback for an unrecognised kind is `'audio'`, unchanged: an
259
+ * unknown file is genuinely more likely to be audio-only, and the audio
260
+ * player still plays it. The defect this fixes was never the fallback —
261
+ * it was recognised kinds falling INTO it.
262
+ */
213
263
  export function resolveStreamType(input: ContentKind): 'video' | 'audio' {
214
- // Already a stream type — passthrough.
215
- if (input === 'video' || input === 'audio') return input;
216
- // Audio content kinds.
217
- switch (input) {
218
- case 'music':
219
- case 'audiobook':
220
- case 'podcast':
221
- case 'radio':
222
- case 'archive-audio':
223
- return 'audio';
224
- // Video content kinds.
225
- case 'movie':
226
- case 'episode':
227
- case 'live-tv':
228
- case 'video-file':
229
- return 'video';
230
- default:
231
- // Unknown kind — conservative default. Better to launch an
232
- // audio player on an unknown file than to crash on a video
233
- // mismatch.
234
- return 'audio';
235
- }
264
+ return CONTENT_KIND_LANES[input] ?? 'audio';
236
265
  }