@simba-dev/react-native-media-player 3.3.6 → 3.4.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.
package/CHANGELOG.md CHANGED
@@ -1,4 +1,118 @@
1
1
 
2
+
3
+ ## [3.4.0] - 2026-11-21
4
+
5
+ ### Added
6
+
7
+ - **Per-file request headers — `openPlayer({headers})`.**
8
+ A stream can be told how to FETCH it, not only what to play. An IPTV playlist declares a
9
+ `User-Agent` and a `Referer` for the providers that check them, and until now the app
10
+ dropped them and asked for the stream without.
11
+
12
+ ```ts
13
+ await openPlayer({
14
+ uri: 'https://provider.example/stream.m3u8',
15
+ title: 'A channel',
16
+ type: 'video',
17
+ headers: {'User-Agent': 'Mozilla/5.0 ...', Referer: 'https://provider.example/'},
18
+ });
19
+ ```
20
+
21
+ The headers are PER FILE. mpv has no "send these headers with this one file" API; what it
22
+ has is `loadfile` per-file options, and that is what this uses — mpv applies every pair as
23
+ a file-local option (`M_SET_OPTION_FLAG_FILE_LOCAL`), so the headers apply to that load and
24
+ to no other. A global mpv option would have leaked the User-Agent onto every later file —
25
+ the app's own music, a podcast, anything.
26
+
27
+ Two parsers sit between the option string and mpv and they do not agree: the key/value list
28
+ takes a quoted value verbatim, while `http-header-fields` is a string LIST whose separator is
29
+ a comma. The format has ONE owner (`MpvFileOptions`), and the unit tests pin both layers.
30
+
31
+ The values are untrusted input if they came from a playlist a third party publishes, and they
32
+ end up in an HTTP request: the control characters are dropped next to the sink, so a value
33
+ cannot end a header and start another.
34
+
35
+ Both lanes carry them — the video lane through `loadFileWithHeaders`, the audio lane through
36
+ `startAudioPlayback({headersJson})` — and the headers ride the LOAD, not a property set
37
+ before it.
38
+
39
+ ### Changed
40
+
41
+ - `openPlayer`'s `headers` is optional. A launch without one loads exactly as it did before:
42
+ the native side builds no options and issues the same `loadfile` it always did.
43
+
44
+ ## [3.3.7] - 2026-11-19
45
+
46
+ ### Fixed
47
+
48
+ - **The media notification could abort the process — the framework was handed the same bitmap twice.**
49
+ Playing a radio station on API 37 killed the app with an abort from the platform's own
50
+ file-descriptor sanitizer:
51
+
52
+ ```
53
+ Abort message: 'fdsan: failed to exchange ownership of file descriptor:
54
+ fd 223 is owned by unique_fd 0x79cc1c6e311c, was expected to be unowned'
55
+ ```
56
+
57
+ The stack is the notification build, not the player:
58
+
59
+ ```
60
+ MediaPlaybackService.buildNotification
61
+ MediaPlaybackService.handleStart
62
+ Notification$Builder.build
63
+ Notification.reduceImageSizes
64
+ Icon.scaleDownToAshmem
65
+ BitmapCache.getShared
66
+ Bitmap.asShared
67
+ Bitmap.createAshmemBitmap
68
+ ...
69
+ ashmem_create_region
70
+ ```
71
+
72
+ The fd table in the same tombstone holds TWO descriptors on the SAME ashmem region — fd 145
73
+ (unowned) and fd 223 (owned by unique_fd) — which is the framework in the middle of making a
74
+ shared copy of an icon bitmap whose pixels already lived in a shared region.
75
+
76
+ **⇒ THE CAUSE: the notification handed the framework a bitmap it had already been handed.** The
77
+ framework SHARES the icon bitmap it is given — `Icon.scaleDownToAshmem` turns it into an
78
+ ashmem-backed bitmap so the system UI can read it. The notification was rebuilt once a second, and
79
+ on every start it was built TWICE back to back — once inside `applyMetadata()` and once for
80
+ `startForeground()` — and BOTH builds handed over the SAME instance whenever the artwork could
81
+ not be loaded: the radio rows pass a REMOTE image URL, that fetch failed ("Failed to load
82
+ artwork" appeared once per second in logcat), and both builds fell back to
83
+ `BitmapFactory.decodeResource(resources, android.R.drawable.ic_media_play)` — the
84
+ RESOURCES-CACHED bitmap, one instance shared with every other user of that drawable.
85
+
86
+ **The fix:**
87
+ - a new owner, `NotificationArtwork`, hands the notification a FRESH copy on every build. The
88
+ bitmap it owns is never handed to the framework — only copies of it are — so the framework's
89
+ sharing can never touch the source;
90
+ - the fallback is now OUR copy of the drawable, not the Resources-cached instance;
91
+ - the artwork is fetched OFF the notification thread, once per artwork path. It used to be
92
+ fetched while the notification was being built — once a second, with a 3 s connect and a 5 s
93
+ read timeout, on the main thread.
94
+
95
+ The notification now shows the artwork a beat after the track starts (the fetch is asynchronous),
96
+ and the fallback path — the one the radio rows always took — is the one that is now safe.
97
+
98
+ ### Not claimed
99
+
100
+ - This release does **not** claim the crash is gone. It was **intermittent**: the same station
101
+ played for the whole observation window on the re-test, with the process alive and the position
102
+ advancing (21947 → 22946 → 23850 → 24939 ms). What this release removes is the **mechanism**
103
+ that was measured — the framework being handed the same bitmap instance twice, and being handed
104
+ the Resources-cached bitmap at all. A platform `fdsan` abort is not something this library can
105
+ reproduce on demand, so the claim is about the construction, not about a reproduced crash.
106
+
107
+ - This release does **not** fix the radio artwork FETCH. The radio rows pass a REMOTE image URL and
108
+ that fetch failed on device. The log line is now written once per artwork path instead of once
109
+ per second, but the image still may not arrive.
110
+
111
+ - The artwork is fetched on a background thread, so the FIRST notification after a track starts
112
+ shows the fallback for up to one ticker tick (1 s) before the real artwork arrives.
113
+
114
+ - iOS is untouched — this library ships Android only.
115
+
2
116
  ## [3.3.6] - 2026-11-06
3
117
 
4
118
  ### Fixed
package/README.md CHANGED
@@ -570,8 +570,12 @@ const theme = useTheme();
570
570
  | `usePlaybackHistory()` / `usePlaybackHistoryAs()` | The playback history. |
571
571
  | `useQueueSelection()` / `useQueueSelectedIndices()` | The selection store. |
572
572
 
573
- `openPlayer` accepts `{uri, title, type, startPositionMs?, artworkPath?, artist?, album?}`. The
574
- artwork, artist and album fields apply to the audio lane only.
573
+ `openPlayer` accepts `{uri, title, type, startPositionMs?, artworkPath?, artist?, album?,
574
+ headers?}`. The artwork, artist and album fields apply to the audio lane only.
575
+
576
+ `headers` is a map of HTTP request headers to send when fetching THAT file — a `User-Agent`
577
+ or a `Referer` that the source declared for the stream. They are per file: they apply to
578
+ that launch and to no later one.
575
579
 
576
580
  The queue store's actions are `addToQueue`, `prependToQueue`, `removeFromQueue`,
577
581
  `removeFromQueueByIndex`, `reorderQueue`, `clearQueue`, `shuffleQueue`, `addToPlaybackHistory` and
@@ -215,6 +215,11 @@ dependencies {
215
215
  // pieces Robolectric can't simulate (ReactContext, DeviceEventManager
216
216
  // module, etc.).
217
217
  testImplementation("junit:junit:4.13.2")
218
+ // A REAL org.json for the JVM unit tests. Android ships one, but the
219
+ // mockable android.jar the unit tests run against has stubs for it, and
220
+ // `returnDefaultValues = true` would turn a parse into a silently empty
221
+ // result. The production code uses the org.json Android provides.
222
+ testImplementation("org.json:json:20231013")
218
223
  testImplementation("org.robolectric:robolectric:4.11.1")
219
224
  testImplementation("org.mockito:mockito-core:5.7.0")
220
225
  testImplementation("org.mockito.kotlin:mockito-kotlin:5.1.0")
@@ -548,7 +548,30 @@ Java_com_simba_player_mpv_MPVLib_nativeSurfaceChanged(
548
548
 
549
549
  // ── Playback Control ────────────────────────────────────────────────────────
550
550
 
551
- static void nativeLoadFileInternal(JNIEnv *env, jlong nativePtr, jstring path, jstring requestId) {
551
+ // The PER-FILE options argument.
552
+ //
553
+ // mpv 0.41's `loadfile` command is
554
+ //
555
+ // loadfile <url> [<flags> [<index> [<options>]]]
556
+ //
557
+ // and `<options>` is a key/value list that mpv turns into FILE-LOCAL
558
+ // options: mpv's `player/command.c` (`cmd_loadfile`) turns every pair
559
+ // into a playlist-entry param, and `player/loadfile.c`
560
+ // (`load_per_file_options`) applies every param with
561
+ // `M_SET_OPTION_FLAG_FILE_LOCAL`.
562
+ //
563
+ // That is the whole reason the options exist. A GLOBAL
564
+ // `mpv_set_option_string("user-agent", ...)` would leak the header onto
565
+ // every LATER file - the app's own music, a podcast, anything - and it
566
+ // would be read when the NEXT stream opens, not the one it was set for.
567
+ // The per-file form is the only one that means "this file".
568
+ //
569
+ // `flags` and `index` are passed explicitly because the options argument
570
+ // is positional: they are mpv's own defaults ("replace" is the first
571
+ // choice of the flags enum, and the index default is -1), so naming them
572
+ // changes nothing and leaves the argument order unambiguous.
573
+ static void nativeLoadFileInternal(JNIEnv *env, jlong nativePtr, jstring path,
574
+ jstring requestId, jstring options) {
552
575
  if (!path) {
553
576
  LOGE("nativeLoadFile rejected: path is null");
554
577
  return;
@@ -562,32 +585,47 @@ static void nativeLoadFileInternal(JNIEnv *env, jlong nativePtr, jstring path, j
562
585
  mpv_handle *mpv = lease.get();
563
586
  const char *utfPath = env->GetStringUTFChars(path, nullptr);
564
587
  const char *utfRequestId = requestId ? env->GetStringUTFChars(requestId, nullptr) : nullptr;
588
+ const char *utfOptions = options ? env->GetStringUTFChars(options, nullptr) : nullptr;
565
589
  if (utfRequestId && utfRequestId[0] != '\0') {
566
590
  enqueueLoadRequest({utfRequestId, utfPath});
567
591
  } else {
568
592
  clearActiveLoadRequest();
569
593
  }
570
- const char *cmd[] = {"loadfile", utfPath, nullptr};
571
- const int result = mpv_command(mpv, cmd);
594
+ int result;
595
+ if (utfOptions && utfOptions[0] != '\0') {
596
+ const char *cmd[] = {"loadfile", utfPath, "replace", "-1", utfOptions, nullptr};
597
+ result = mpv_command(mpv, cmd);
598
+ } else {
599
+ const char *cmd[] = {"loadfile", utfPath, nullptr};
600
+ result = mpv_command(mpv, cmd);
601
+ }
572
602
  if (result < 0 && utfRequestId && utfRequestId[0] != '\0') {
573
603
  dropLoadRequest(utfRequestId);
574
604
  }
575
- LOGI("[PlaybackTrace][Native][loadFile] result=%d pathLength=%zu token=%s",
576
- result, strlen(utfPath), utfRequestId && utfRequestId[0] != '\0' ? "present" : "none");
605
+ LOGI("[PlaybackTrace][Native][loadFile] result=%d pathLength=%zu token=%s options=%s",
606
+ result, strlen(utfPath), utfRequestId && utfRequestId[0] != '\0' ? "present" : "none",
607
+ utfOptions && utfOptions[0] != '\0' ? "present" : "none");
577
608
  if (utfRequestId) env->ReleaseStringUTFChars(requestId, utfRequestId);
609
+ if (utfOptions) env->ReleaseStringUTFChars(options, utfOptions);
578
610
  env->ReleaseStringUTFChars(path, utfPath);
579
611
  }
580
612
 
581
613
  extern "C" JNIEXPORT void JNICALL
582
614
  Java_com_simba_player_mpv_MPVLib_nativeLoadFile(
583
615
  JNIEnv *env, jclass, jlong nativePtr, jstring path) {
584
- nativeLoadFileInternal(env, nativePtr, path, nullptr);
616
+ nativeLoadFileInternal(env, nativePtr, path, nullptr, nullptr);
585
617
  }
586
618
 
587
619
  extern "C" JNIEXPORT void JNICALL
588
620
  Java_com_simba_player_mpv_MPVLib_nativeLoadFileWithRequestId(
589
621
  JNIEnv *env, jclass, jlong nativePtr, jstring path, jstring requestId) {
590
- nativeLoadFileInternal(env, nativePtr, path, requestId);
622
+ nativeLoadFileInternal(env, nativePtr, path, requestId, nullptr);
623
+ }
624
+
625
+ extern "C" JNIEXPORT void JNICALL
626
+ Java_com_simba_player_mpv_MPVLib_nativeLoadFileWithOptions(
627
+ JNIEnv *env, jclass, jlong nativePtr, jstring path, jstring options) {
628
+ nativeLoadFileInternal(env, nativePtr, path, nullptr, options);
591
629
  }
592
630
 
593
631
  extern "C" JNIEXPORT void JNICALL
@@ -8,8 +8,6 @@ import android.app.Service
8
8
  import android.content.Context
9
9
  import android.content.Intent
10
10
  import android.content.pm.PackageManager
11
- import android.graphics.Bitmap
12
- import android.graphics.BitmapFactory
13
11
  import android.os.Build
14
12
  import android.os.Handler
15
13
  import android.os.IBinder
@@ -20,8 +18,6 @@ import android.support.v4.media.session.PlaybackStateCompat
20
18
  import android.util.Log
21
19
  import androidx.core.app.NotificationCompat
22
20
  import com.simba.player.mpv.MPVLib
23
- import java.io.File
24
- import java.net.URL
25
21
 
26
22
  /**
27
23
  * V20 Phase B: the foreground service that owns playback.
@@ -297,6 +293,14 @@ class MediaPlaybackService : Service() {
297
293
  private var currentArtist: String = ""
298
294
  private var currentAlbum: String = ""
299
295
  private var currentArtworkPath: String = ""
296
+
297
+ /**
298
+ * The artwork for the media notification.
299
+ *
300
+ * It owns the rules that keep the notification from taking the process
301
+ * down - see `NotificationArtwork` for the measurement.
302
+ */
303
+ private lateinit var notificationArtwork: NotificationArtwork
300
304
  private var currentPosition: Long = 0L
301
305
  private var currentDuration: Long = 0L
302
306
  private var isCurrentlyPlaying: Boolean = true
@@ -377,6 +381,7 @@ class MediaPlaybackService : Service() {
377
381
  instance = this
378
382
  notificationManager = getSystemService(NotificationManager::class.java)
379
383
  createNotificationChannel()
384
+ notificationArtwork = NotificationArtwork(resources)
380
385
  createMediaSession()
381
386
  Log.i(TAG, "MediaPlaybackService created (session owned by service)")
382
387
  }
@@ -397,6 +402,7 @@ class MediaPlaybackService : Service() {
397
402
  // onDestroy. Doing it in an Activity's is what tied the session's
398
403
  // lifetime to a window.
399
404
  stopTicker("service destroyed")
405
+ if (::notificationArtwork.isInitialized) notificationArtwork.release()
400
406
  releaseMediaSession()
401
407
  isRunning = false
402
408
  instance = null
@@ -585,7 +591,7 @@ class MediaPlaybackService : Service() {
585
591
  if (title.isNotBlank()) currentTitle = title
586
592
  currentArtist = artist
587
593
  currentAlbum = album
588
- currentArtworkPath = artworkPath
594
+ setArtworkPath(artworkPath)
589
595
 
590
596
  val session = mediaSession ?: return
591
597
  val durationMs = enginePropertyMs("duration")
@@ -616,7 +622,7 @@ class MediaPlaybackService : Service() {
616
622
  currentTitle = extras?.getString(EXTRA_TITLE) ?: "Simba Player"
617
623
  currentArtist = extras?.getString(EXTRA_ARTIST) ?: ""
618
624
  currentAlbum = extras?.getString(EXTRA_ALBUM) ?: ""
619
- currentArtworkPath = extras?.getString(EXTRA_ARTWORK_PATH) ?: ""
625
+ setArtworkPath(extras?.getString(EXTRA_ARTWORK_PATH) ?: "")
620
626
  currentPosition = extras?.getLong(EXTRA_POSITION_MS, 0L) ?: 0L
621
627
  currentDuration = extras?.getLong(EXTRA_DURATION_MS, 0L) ?: 0L
622
628
  isCurrentlyPlaying = extras?.getBoolean(EXTRA_IS_PLAYING, true) ?: true
@@ -638,7 +644,7 @@ class MediaPlaybackService : Service() {
638
644
  extras.getString(EXTRA_TITLE)?.let { currentTitle = it }
639
645
  extras.getString(EXTRA_ARTIST)?.let { currentArtist = it }
640
646
  extras.getString(EXTRA_ALBUM)?.let { currentAlbum = it }
641
- extras.getString(EXTRA_ARTWORK_PATH)?.let { currentArtworkPath = it }
647
+ extras.getString(EXTRA_ARTWORK_PATH)?.let { setArtworkPath(it) }
642
648
  extras.getLong(EXTRA_POSITION_MS, -1L).let { if (it >= 0L) currentPosition = it }
643
649
  extras.getLong(EXTRA_DURATION_MS, -1L).let { if (it >= 0L) currentDuration = it }
644
650
  extras.getBoolean(EXTRA_IS_PLAYING, isCurrentlyPlaying)?.also { isCurrentlyPlaying = it }
@@ -691,14 +697,14 @@ class MediaPlaybackService : Service() {
691
697
  else -> ""
692
698
  }
693
699
 
694
- val artwork: Bitmap? = loadArtworkBitmap(currentArtworkPath) ?: BitmapFactory.decodeResource(
695
- resources,
696
- android.R.drawable.ic_media_play,
697
- )
700
+ // A FRESH bitmap for this build. The framework shares the icon
701
+ // bitmap it is handed, so handing it the same instance twice is
702
+ // what aborted the process - see `NotificationArtwork`.
703
+ val artworkBitmap = notificationArtwork.bitmapForNotification()
698
704
 
699
705
  val builder = NotificationCompat.Builder(this, CHANNEL_ID)
700
706
  .setSmallIcon(android.R.drawable.ic_media_play)
701
- .setLargeIcon(artwork)
707
+ .setLargeIcon(artworkBitmap)
702
708
  .setContentTitle(currentTitle)
703
709
  .setContentText(subtitle)
704
710
  .setContentIntent(buildContentIntent(this))
@@ -750,29 +756,18 @@ class MediaPlaybackService : Service() {
750
756
  return builder.build()
751
757
  }
752
758
 
753
- // ── Artwork Loading ────────────────────────────────────────────────────
759
+ // ── Artwork ────────────────────────────────────────────────────────────
754
760
 
755
- private fun loadArtworkBitmap(path: String): Bitmap? {
756
- if (path.isBlank()) return null
757
- return try {
758
- if (path.startsWith("http://") || path.startsWith("https://")) {
759
- val url = URL(path)
760
- val connection = url.openConnection()
761
- connection.connectTimeout = 3000
762
- connection.readTimeout = 5000
763
- val inputStream = connection.getInputStream()
764
- BitmapFactory.decodeStream(inputStream)
765
- } else {
766
- val file = File(path)
767
- if (file.exists()) {
768
- BitmapFactory.decodeFile(file.absolutePath)
769
- } else {
770
- null
771
- }
772
- }
773
- } catch (e: Exception) {
774
- Log.w(TAG, "Failed to load artwork: ${e.message}")
775
- null
776
- }
761
+ /**
762
+ * Point the notification at an artwork path.
763
+ *
764
+ * The artwork is told about the path HERE, in one place, so it can be
765
+ * fetched OFF the notification thread. Telling it in the notification
766
+ * builder instead would fetch the image while the notification is being
767
+ * built - once a second.
768
+ */
769
+ private fun setArtworkPath(path: String) {
770
+ currentArtworkPath = path
771
+ notificationArtwork.request(path)
777
772
  }
778
773
  }
@@ -0,0 +1,268 @@
1
+ package com.simba.player
2
+
3
+ import android.content.res.Resources
4
+ import android.graphics.Bitmap
5
+ import android.graphics.BitmapFactory
6
+ import android.os.Handler
7
+ import android.os.Looper
8
+ import android.util.Log
9
+ import java.io.File
10
+ import java.net.URL
11
+ import java.util.concurrent.Executors
12
+ import kotlin.math.max
13
+ import kotlin.math.roundToInt
14
+
15
+ /**
16
+ * The artwork that goes into the media notification.
17
+ *
18
+ * ## Why this class exists
19
+ *
20
+ * The notification was rebuilt once a second, and every rebuild re-fetched
21
+ * the artwork over the network ON THE NOTIFICATION THREAD and then handed
22
+ * the framework a bitmap the framework had already been handed before.
23
+ *
24
+ * That second half is what killed the app. Measured on emulator-5554
25
+ * (API 37) on 2026-11-19, from the tombstone of the crash:
26
+ *
27
+ * ```
28
+ * Abort message: 'fdsan: failed to exchange ownership of file descriptor:
29
+ * fd 223 is owned by unique_fd 0x79cc1c6e311c, was expected to be unowned'
30
+ *
31
+ * MediaPlaybackService.buildNotification
32
+ * MediaPlaybackService.handleStart
33
+ * Notification$Builder.build
34
+ * Notification.reduceImageSizes
35
+ * Icon.scaleDownToAshmem
36
+ * BitmapCache.getShared
37
+ * Bitmap.asShared
38
+ * Bitmap.createAshmemBitmap
39
+ * ashmem_create_region
40
+ * ```
41
+ *
42
+ * The fd table in that same tombstone holds TWO descriptors on the SAME
43
+ * ashmem region - fd 145 (unowned) and fd 223 (owned by unique_fd) - which
44
+ * is the framework in the middle of making a shared copy of an icon bitmap
45
+ * whose pixels already lived in a shared region.
46
+ *
47
+ * The framework SHARES the icon bitmap it is handed: `Icon.scaleDownToAshmem`
48
+ * turns it into an ashmem-backed bitmap so the system UI can read it. Hand
49
+ * the framework the same instance twice and the second handover operates on
50
+ * a bitmap that is already shared.
51
+ *
52
+ * And the same instance WAS handed twice, back to back, on every start:
53
+ *
54
+ * - `handleStart` builds the notification twice - once inside
55
+ * `applyMetadata` and once for `startForeground`;
56
+ * - when the artwork could not be loaded (the radio rows pass a REMOTE
57
+ * image URL, and that fetch failed - "Failed to load artwork" appeared
58
+ * once per second in logcat) BOTH builds fell back to
59
+ * `BitmapFactory.decodeResource(resources, android.R.drawable.ic_media_play)`,
60
+ * which is the RESOURCES-CACHED bitmap: one instance, shared with every
61
+ * other user of that drawable, handed to the framework twice.
62
+ *
63
+ * ## The three rules this class enforces
64
+ *
65
+ * 1. The framework is handed a FRESH bitmap on every notification build.
66
+ * The bitmap this class owns is never handed over - only copies of it
67
+ * are.
68
+ * 2. The fallback is OUR copy of the drawable, not the Resources-cached
69
+ * instance.
70
+ * 3. The artwork is fetched OFF the notification thread, once per artwork
71
+ * path - not once per notification build.
72
+ */
73
+ class NotificationArtwork(private val resources: Resources) {
74
+
75
+ companion object {
76
+ private const val TAG = "NotificationArtwork"
77
+
78
+ private const val CONNECT_TIMEOUT_MS = 3000
79
+ private const val READ_TIMEOUT_MS = 5000
80
+ }
81
+
82
+ /** The path the notification is currently meant to show. */
83
+ private var requestedPath: String = ""
84
+
85
+ /**
86
+ * Our own copy of the drawable fallback.
87
+ *
88
+ * `BitmapFactory.decodeResource` hands back the RESOURCES-CACHED
89
+ * bitmap - one instance, shared with every other user of that drawable.
90
+ * Handing that to the framework would let the framework share a bitmap
91
+ * the whole Resources cache still points at.
92
+ */
93
+ private val fallback: Bitmap? =
94
+ privateCopy(BitmapFactory.decodeResource(resources, android.R.drawable.ic_media_play))
95
+
96
+ /**
97
+ * The source bitmap.
98
+ *
99
+ * NEVER handed to the framework: only copies of it are. The framework
100
+ * shares the bitmap it is given, so a bitmap that has been handed over
101
+ * once must never be handed over again.
102
+ */
103
+ private var source: Bitmap? = fallback
104
+
105
+ /** The loader thread posts its results back to the main looper. */
106
+ private val mainHandler = Handler(Looper.getMainLooper())
107
+
108
+ /**
109
+ * The thread the artwork is fetched on.
110
+ *
111
+ * The fetch is network I/O with a 3 s connect and a 5 s read timeout.
112
+ * Doing it on the notification thread meant every notification build
113
+ * could block the main thread for seconds - and it happened once a
114
+ * second.
115
+ */
116
+ private val loader = Executors.newSingleThreadExecutor { runnable ->
117
+ Thread(runnable, "simba-artwork").apply { isDaemon = true }
118
+ }
119
+
120
+ /**
121
+ * Tell the artwork what the notification should show.
122
+ *
123
+ * Safe to call as often as the service hears about a path: the fetch
124
+ * only starts when the path actually changed.
125
+ */
126
+ fun request(path: String) {
127
+ val wanted = ArtworkPath.normalize(path)
128
+ if (wanted == requestedPath) return
129
+ requestedPath = wanted
130
+
131
+ if (wanted.isEmpty()) {
132
+ source = fallback
133
+ return
134
+ }
135
+
136
+ // The previous artwork must not keep showing while the new one
137
+ // loads - and the fallback is safer than the last track's artwork.
138
+ source = fallback
139
+
140
+ loader.execute {
141
+ val decoded = decode(wanted)
142
+ mainHandler.post {
143
+ // The path may have changed while the fetch was in flight.
144
+ if (wanted == requestedPath) source = decoded ?: fallback
145
+ }
146
+ }
147
+ }
148
+
149
+ /**
150
+ * The bitmap for ONE notification build.
151
+ *
152
+ * Always a fresh instance - see the class docblock. A null means the
153
+ * caller should show no large icon at all.
154
+ */
155
+ fun bitmapForNotification(): Bitmap? = privateCopy(source)
156
+
157
+ /**
158
+ * Stop the loader.
159
+ *
160
+ * The bitmaps are NOT recycled: the copies the framework holds are its
161
+ * own, and recycling a bitmap that a pending copy might still be
162
+ * reading is a crash waiting to happen. They are small, and the
163
+ * service dies with the app.
164
+ */
165
+ fun release() {
166
+ loader.shutdownNow()
167
+ }
168
+
169
+ /**
170
+ * Fetch and shrink the artwork.
171
+ *
172
+ * Runs on the loader thread, never on the notification thread.
173
+ */
174
+ private fun decode(path: String): Bitmap? {
175
+ return try {
176
+ val decoded = if (ArtworkPath.isRemote(path)) {
177
+ val connection = URL(path).openConnection()
178
+ connection.connectTimeout = CONNECT_TIMEOUT_MS
179
+ connection.readTimeout = READ_TIMEOUT_MS
180
+ connection.getInputStream().use { input ->
181
+ BitmapFactory.decodeStream(input)
182
+ }
183
+ } else {
184
+ val file = File(path)
185
+ if (file.exists()) BitmapFactory.decodeFile(file.absolutePath) else null
186
+ }
187
+ decoded?.let { shrink(it) }
188
+ } catch (e: Exception) {
189
+ Log.w(TAG, "Failed to load artwork: ${e.message}")
190
+ null
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Shrink a decoded bitmap to [ArtworkSizing.MAX_SOURCE_EDGE].
196
+ *
197
+ * The copy the framework receives is a copy of THIS bitmap, so the
198
+ * smaller it is, the cheaper every notification build is.
199
+ */
200
+ private fun shrink(bitmap: Bitmap): Bitmap {
201
+ val (width, height) = ArtworkSizing.shrunkSize(bitmap.width, bitmap.height)
202
+ if (width == bitmap.width && height == bitmap.height) return bitmap
203
+ val scaled = Bitmap.createScaledBitmap(bitmap, width, height, true)
204
+ // The bitmap was ours alone - it was decoded here and nothing else
205
+ // holds it - so it can be released once the smaller copy exists.
206
+ if (scaled !== bitmap) bitmap.recycle()
207
+ return scaled
208
+ }
209
+
210
+ /**
211
+ * A bitmap this class owns.
212
+ *
213
+ * `Bitmap.copy` returns a bitmap with its OWN pixels, which is what
214
+ * makes it safe to hand to the framework: the framework's sharing
215
+ * (ashmem) touches the copy, never the source.
216
+ */
217
+ private fun privateCopy(bitmap: Bitmap?): Bitmap? =
218
+ try {
219
+ bitmap?.copy(Bitmap.Config.ARGB_8888, false)
220
+ } catch (e: Exception) {
221
+ Log.w(TAG, "Could not copy a bitmap for the notification: ${e.message}")
222
+ null
223
+ }
224
+ }
225
+
226
+ /**
227
+ * The artwork's path rules - pure, with no Android in them.
228
+ */
229
+ object ArtworkPath {
230
+
231
+ /** The path as the notification should key it. */
232
+ fun normalize(path: String): String = path.trim()
233
+
234
+ /**
235
+ * Whether the path is a REMOTE image the loader has to fetch.
236
+ */
237
+ fun isRemote(path: String): Boolean {
238
+ val normalized = normalize(path)
239
+ return normalized.startsWith("http://") || normalized.startsWith("https://")
240
+ }
241
+ }
242
+
243
+ /**
244
+ * The artwork's sizing arithmetic - pure, with no Android in them.
245
+ */
246
+ object ArtworkSizing {
247
+
248
+ /**
249
+ * The longest edge the private source keeps.
250
+ *
251
+ * The notification's large icon is rendered at a few hundred pixels at
252
+ * most, so keeping more than this costs memory and makes the
253
+ * per-build copy bigger for no visible gain.
254
+ */
255
+ const val MAX_SOURCE_EDGE = 256
256
+
257
+ /**
258
+ * The size a source of [width] x [height] is shrunk to.
259
+ *
260
+ * A source that already fits is left alone.
261
+ */
262
+ fun shrunkSize(width: Int, height: Int, maxEdge: Int = MAX_SOURCE_EDGE): Pair<Int, Int> {
263
+ val longest = max(width, height)
264
+ if (longest <= maxEdge) return width to height
265
+ val scale = maxEdge.toDouble() / longest.toDouble()
266
+ return max(1, (width * scale).roundToInt()) to max(1, (height * scale).roundToInt())
267
+ }
268
+ }
@@ -36,6 +36,20 @@ object MPVLib {
36
36
 
37
37
  external fun nativeLoadFile(nativePtr: Long, path: String)
38
38
  external fun nativeLoadFileWithRequestId(nativePtr: Long, path: String, requestId: String)
39
+
40
+ /**
41
+ * Load a file with mpv PER-FILE options.
42
+ *
43
+ * `options` is mpv's `loadfile` options argument: a key/value list
44
+ * that mpv turns into file-local options, so the values apply to THIS
45
+ * file and to no other. It is the only way to send a request header
46
+ * with one stream without leaking it onto every later file.
47
+ *
48
+ * The string is built by `MpvFileOptions` - the format is mpv's, and
49
+ * mpv's two parsers do not agree on how a comma is escaped, so the
50
+ * format has exactly one owner.
51
+ */
52
+ external fun nativeLoadFileWithOptions(nativePtr: Long, path: String, options: String)
39
53
  external fun nativePlay(nativePtr: Long)
40
54
  external fun nativePause(nativePtr: Long)
41
55
  external fun nativeStop(nativePtr: Long)
@@ -1976,6 +1976,44 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1976
1976
  }
1977
1977
  }
1978
1978
 
1979
+ /**
1980
+ * Load a file with HTTP request headers that apply to THIS file only.
1981
+ *
1982
+ * The headers arrive as JSON (`{"User-Agent": "...", "Referer": "..."}`)
1983
+ * so the JS->native boundary stays a plain string on both sides and
1984
+ * neither side has to agree on a bespoke wire format.
1985
+ *
1986
+ * `MpvFileOptions` owns the mpv format: mpv's `loadfile` options
1987
+ * argument is a key/value list, and mpv parses it in two layers with
1988
+ * different escaping rules, so the format has one owner rather than
1989
+ * one per layer.
1990
+ */
1991
+ @ReactMethod
1992
+ @Override
1993
+ override fun loadFileWithHeaders(path: String, headersJson: String) {
1994
+ ensurePtr()
1995
+ applyCacheWindow(baseCacheWindowSecs, "new load")
1996
+ val resolvedPath = normalizeMpvInput(resolveContentUri(path))
1997
+ val options = MpvFileOptions.buildLoadFileOptions(MpvFileOptions.parseHeaders(headersJson))
1998
+ Log.i(
1999
+ TAG,
2000
+ "[PlaybackTrace][Bridge][loadFileWithHeaders] requested=$path resolved=$resolvedPath " +
2001
+ "ptr=$nativePtr options=${if (options == null) "none" else "present"}"
2002
+ )
2003
+ emitLoadRequested(path)
2004
+ try {
2005
+ if (options == null) {
2006
+ MPVLib.nativeLoadFile(nativePtr, resolvedPath)
2007
+ } else {
2008
+ MPVLib.nativeLoadFileWithOptions(nativePtr, resolvedPath, options)
2009
+ }
2010
+ Log.i(TAG, "[PlaybackTrace][Bridge][loadFileWithHeaders] native load returned")
2011
+ } catch (e: Exception) {
2012
+ Log.e(TAG, "[PlaybackTrace][Bridge][loadFileWithHeaders] native load threw: ${e.message}", e)
2013
+ throw e
2014
+ }
2015
+ }
2016
+
1979
2017
  @ReactMethod
1980
2018
  @Override
1981
2019
  override fun loadFileWithRequestId(path: String, requestId: String) {
@@ -2829,8 +2867,18 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2829
2867
  }
2830
2868
 
2831
2869
  val resolvedPath = normalizeMpvInput(resolveContentUri(uri))
2870
+ // The same per-file header path as the video lane: mpv applies the
2871
+ // options to THIS file only, so a stream that needs a User-Agent
2872
+ // gets one without the next file inheriting it.
2873
+ val fileOptions = MpvFileOptions.buildLoadFileOptions(
2874
+ MpvFileOptions.parseHeaders(optString(options, "headersJson"))
2875
+ )
2832
2876
  try {
2833
- MPVLib.nativeLoadFile(handle, resolvedPath)
2877
+ if (fileOptions == null) {
2878
+ MPVLib.nativeLoadFile(handle, resolvedPath)
2879
+ } else {
2880
+ MPVLib.nativeLoadFileWithOptions(handle, resolvedPath, fileOptions)
2881
+ }
2834
2882
  } catch (e: Throwable) {
2835
2883
  Log.e(TAG, "[PlaybackTrace][Bridge][startAudioPlayback] nativeLoadFile failed for '$resolvedPath'", e)
2836
2884
  promise.reject("E_LOAD_FAILED", e.message ?: "mpv refused '$uri'", e)
@@ -0,0 +1,154 @@
1
+ package com.simba.player.mpv
2
+
3
+ import org.json.JSONObject
4
+
5
+ /**
6
+ * Turns a set of HTTP request headers into mpv's PER-FILE option list.
7
+ *
8
+ * WHY A HELPER, AND WHY IT LIVES HERE
9
+ * -----------------------------------
10
+ * mpv has no "send these headers with this one file" API. What it has is
11
+ * `loadfile`'s per-file options. mpv 0.41's `loadfile` command is
12
+ *
13
+ * loadfile <url> [<flags> [<index> [<options>]]]
14
+ *
15
+ * and `<options>` is a key/value list that mpv turns into FILE-LOCAL
16
+ * options: mpv's `player/command.c` (`cmd_loadfile`) turns every pair into
17
+ * a playlist-entry param, and `player/loadfile.c` (`load_per_file_options`)
18
+ * applies every param with `M_SET_OPTION_FLAG_FILE_LOCAL`.
19
+ *
20
+ * That is the whole point. A GLOBAL `mpv_set_option_string("user-agent", ...)`
21
+ * would leak the header onto every LATER file - the app's own music, a
22
+ * podcast, anything - and the value would be read when the NEXT stream opens,
23
+ * not the one it was set for. The per-file form is the only one that means
24
+ * "this file".
25
+ *
26
+ * THE FORMAT, AND WHY IT IS THIS FLAKY
27
+ * -------------------------------------
28
+ * Two parsers sit between this string and mpv, and they are not the same:
29
+ *
30
+ * 1. mpv parses `<options>` as a KEY/VALUE LIST (`options/m_option.c`,
31
+ * `parse_keyvalue_list`): `key=value` pairs separated by commas. A value
32
+ * may be QUOTED, and a quoted value is taken verbatim (`read_subparam`) -
33
+ * that is how a value with a comma in it survives this layer.
34
+ * 2. mpv then parses each option's own VALUE with that option's type.
35
+ * `user-agent` is a string (verbatim), but `http-header-fields` is a
36
+ * STRING LIST, and a list is split on commas (`separate_input_param` ->
37
+ * `get_nextsep`), with `\,` as the escape for a literal comma.
38
+ *
39
+ * So: quote the value for layer 1, and escape the commas for layer 2.
40
+ *
41
+ * THE USER-AGENT GETS ITS OWN OPTION
42
+ * -----------------------------------
43
+ * mpv's `user-agent` is a plain string option, so a User-Agent needs no
44
+ * comma escaping at all. It also avoids ffmpeg sending the header TWICE:
45
+ * `http-header-fields` is ffmpeg's "extra headers" list, and a
46
+ * "User-Agent:" line in it would be added ALONGSIDE ffmpeg's own User-Agent
47
+ * rather than replacing it.
48
+ *
49
+ * THE VALUES ARE UNTRUSTED
50
+ * ------------------------
51
+ * These headers come from a playlist a third party publishes, and they end
52
+ * up in an HTTP request. CR and LF are the dangerous ones: a value carrying
53
+ * one would end the header and start another. The sink is a network
54
+ * request, so the control characters are dropped here, next to the sink,
55
+ * rather than trusted to have been checked upstream.
56
+ */
57
+ internal object MpvFileOptions {
58
+
59
+ /** mpv's own User-Agent option. A plain string - no list escaping. */
60
+ private const val OPTION_USER_AGENT = "user-agent"
61
+
62
+ /** mpv's extra-header option. A string LIST - commas need escaping. */
63
+ private const val OPTION_HEADER_FIELDS = "http-header-fields"
64
+
65
+ /**
66
+ * Parse the JSON the JS side sends into a header map.
67
+ *
68
+ * A blank or malformed payload is NOT an error: it means "no headers",
69
+ * and a load with no headers is exactly what happened before this option
70
+ * existed. Anything that is not a string is dropped.
71
+ */
72
+ fun parseHeaders(json: String?): Map<String, String> {
73
+ if (json.isNullOrBlank()) return emptyMap()
74
+ val out = LinkedHashMap<String, String>()
75
+ try {
76
+ val obj = JSONObject(json)
77
+ val keys = obj.keys()
78
+ while (keys.hasNext()) {
79
+ val name = keys.next()
80
+ if (!obj.isNull(name)) {
81
+ val value = obj.optString(name, "")
82
+ if (value.isNotEmpty()) out[name] = value
83
+ }
84
+ }
85
+ } catch (e: Exception) {
86
+ return emptyMap()
87
+ }
88
+ return out
89
+ }
90
+
91
+ /**
92
+ * Build mpv's `loadfile` options string for a set of headers.
93
+ *
94
+ * Returns null when there is nothing to send - the caller then loads the
95
+ * file the way it always did, with no options at all.
96
+ */
97
+ fun buildLoadFileOptions(headers: Map<String, String>): String? {
98
+ if (headers.isEmpty()) return null
99
+ val pairs = mutableListOf<String>()
100
+ val extraFields = mutableListOf<String>()
101
+ for ((rawName, rawValue) in headers) {
102
+ val name = sanitize(rawName)
103
+ val value = sanitize(rawValue)
104
+ if (name.isEmpty() || value.isEmpty()) continue
105
+ if (name.equals("User-Agent", ignoreCase = true)) {
106
+ pairs.add("$OPTION_USER_AGENT=${quote(value)}")
107
+ } else {
108
+ extraFields.add(escapeListItem("$name: $value"))
109
+ }
110
+ }
111
+ if (extraFields.isNotEmpty()) {
112
+ pairs.add("$OPTION_HEADER_FIELDS=${quote(extraFields.joinToString(","))}")
113
+ }
114
+ if (pairs.isEmpty()) return null
115
+ return pairs.joinToString(",")
116
+ }
117
+
118
+ /**
119
+ * Strip everything that could break the format or inject a header.
120
+ *
121
+ * CR and LF are the dangerous ones: a value carrying one would end the
122
+ * header and start another. NUL and the other C0 controls are dropped
123
+ * for the same reason. A double quote is dropped because it would end
124
+ * mpv's quoted value early.
125
+ */
126
+ private fun sanitize(value: String): String {
127
+ val sb = StringBuilder(value.length)
128
+ for (ch in value) {
129
+ val code = ch.code
130
+ if (code == 0x22) continue // the double quote
131
+ if (code < 0x20 || code == 0x7F) continue // C0 controls and DEL
132
+ sb.append(ch)
133
+ }
134
+ return sb.toString().trim()
135
+ }
136
+
137
+ /**
138
+ * Quote a value for mpv's key/value list.
139
+ *
140
+ * The quotes are what let the value hold commas and spaces: mpv's
141
+ * `read_subparam` takes a quoted value verbatim.
142
+ */
143
+ private fun quote(value: String): String = "\"" + value + "\""
144
+
145
+ /**
146
+ * Escape a value for mpv's STRING LIST parser.
147
+ *
148
+ * The list parser splits on commas and treats `\,` as a literal comma,
149
+ * so both the comma and the backslash itself have to be escaped - the
150
+ * backslash first, or the escape would be escaped again.
151
+ */
152
+ private fun escapeListItem(value: String): String =
153
+ value.replace("\\", "\\\\").replace(",", "\\,")
154
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "3.3.6",
3
+ "version": "3.4.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",
@@ -297,6 +297,17 @@ export interface MpvPlayerModuleBridge {
297
297
  // ── File loading ───────────────────────────────────────────────────────
298
298
  /** Load a media file by path / URI. */
299
299
  loadFile(path: string): void;
300
+ /**
301
+ * Load a media file with HTTP request headers that apply to THIS file
302
+ * only.
303
+ *
304
+ * `headersJson` is a JSON object of header name to value, e.g.
305
+ * `{"User-Agent": "...", "Referer": "..."}`. The native side turns it
306
+ * into mpv's per-file option list, so the headers apply to this load
307
+ * and to no other - which is the whole point: a global mpv option
308
+ * would leak the header onto every later file.
309
+ */
310
+ loadFileWithHeaders(path: string, headersJson: string): void;
300
311
  /** Load a media file with an attached request ID for traceability. */
301
312
  loadFileWithRequestId(path: string, requestId: string): void;
302
313
  /** Load a playlist of paths, starting at `startIndex` (default 0). */
@@ -464,6 +475,7 @@ export interface MpvPlayerModuleBridge {
464
475
  artworkPath?: string;
465
476
  startPositionMs?: number;
466
477
  autoPlay?: boolean;
478
+ headersJson?: string;
467
479
  }): Promise<boolean>;
468
480
  /** Stop playback and tear the foreground service down. Both lanes. */
469
481
  stopPlayback(): void;
@@ -619,6 +631,10 @@ const NOOP_BRIDGE: MpvPlayerModuleBridge = {
619
631
  loadFile: (_path: string) => {
620
632
  void _path;
621
633
  },
634
+ loadFileWithHeaders: (_path: string, _headersJson: string) => {
635
+ void _path;
636
+ void _headersJson;
637
+ },
622
638
  loadFileWithRequestId: (_path: string, _requestId: string) => {
623
639
  void _path;
624
640
  void _requestId;
@@ -68,6 +68,15 @@ export interface Spec extends TurboModule {
68
68
 
69
69
  // ── File loading ───────────────────────────────────────────────────────
70
70
  loadFile(path: string): void;
71
+ /**
72
+ * Load a file with HTTP request headers that apply to THIS file only.
73
+ *
74
+ * `headersJson` is a JSON object of header name to value, e.g.
75
+ * `{"User-Agent": "...", "Referer": "..."}`. The native side turns it
76
+ * into mpv's per-file option list, so the headers apply to this load
77
+ * and to no other.
78
+ */
79
+ loadFileWithHeaders(path: string, headersJson: string): void;
71
80
  loadFileWithRequestId(path: string, requestId: string): void;
72
81
  loadPlaylist(paths: ReadonlyArray<string>, startIndex: number): void;
73
82
  getFileInfo(): string;
@@ -223,6 +232,12 @@ export interface Spec extends TurboModule {
223
232
  startPositionMs?: number;
224
233
  /** Default true. Seek is applied regardless of `autoPlay`. */
225
234
  autoPlay?: boolean;
235
+ /**
236
+ * HTTP request headers for THIS file only, as a JSON object of
237
+ * header name to value. Same encoding as
238
+ * `loadFileWithHeaders`.
239
+ */
240
+ headersJson?: string;
226
241
  }): Promise<boolean>;
227
242
 
228
243
  /**
@@ -3,6 +3,7 @@ import {
3
3
  applyStartPosition,
4
4
  type MpvPlayerModuleBridge,
5
5
  } from './MpvPlayerModule';
6
+ import {encodeRequestHeaders} from './requestHeaders';
6
7
 
7
8
  /**
8
9
  * Feed a launch payload to mpv: title, file, resume position, play.
@@ -57,13 +58,31 @@ import {
57
58
  */
58
59
  export function loadAndPlay(
59
60
  bridge: MpvPlayerModuleBridge,
60
- payload: { uri: string; title?: string; startPositionMs?: number },
61
+ payload: {
62
+ uri: string;
63
+ title?: string;
64
+ startPositionMs?: number;
65
+ /**
66
+ * HTTP request headers for THIS file only. They become mpv's
67
+ * per-file options, so they apply to this load and to no other.
68
+ */
69
+ headers?: Record<string, string>;
70
+ },
61
71
  ): void {
62
- const {uri, title, startPositionMs = 0} = payload;
72
+ const {uri, title, startPositionMs = 0, headers} = payload;
63
73
  const startPositionSec = startPositionMs > 0 ? startPositionMs / 1000 : 0;
64
74
 
65
75
  applyForceMediaTitle(bridge, title);
66
76
  applyStartPosition(bridge, startPositionSec);
67
- bridge.loadFile(uri);
77
+ // The headers ride the LOAD, not a property set before it. mpv applies
78
+ // per-file options to the file being loaded, and a global option would
79
+ // be read by the NEXT stream instead - so the header would land on the
80
+ // wrong file, or on every file after this one.
81
+ const headersJson = encodeRequestHeaders(headers);
82
+ if (headersJson) {
83
+ bridge.loadFileWithHeaders(uri, headersJson);
84
+ } else {
85
+ bridge.loadFile(uri);
86
+ }
68
87
  bridge.play();
69
88
  }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The JS->native encoding of a request-header map.
3
+ *
4
+ * WHY A JSON STRING
5
+ * ---------------
6
+ * The native side needs a header map, and the two lanes reach it by two
7
+ * different routes: the video lane through a positional method argument,
8
+ * the audio lane through the options object `startAudioPlayback` already
9
+ * takes. A JSON string is the one shape that fits both without either side
10
+ * having to agree on a bespoke wire format, and it is the same shape the
11
+ * native side already speaks everywhere else in this module (the file info,
12
+ * the video params and the playlist are all JSON strings).
13
+ *
14
+ * The values are UNTRUSTED: they come from a playlist a third party
15
+ * publishes. The native side drops the control characters next to the
16
+ * sink, and this side drops the entries that carry nothing.
17
+ */
18
+ export function encodeRequestHeaders(
19
+ headers?: Record<string, string>,
20
+ ): string | undefined {
21
+ if (!headers) return undefined;
22
+ const out: Record<string, string> = {};
23
+ for (const name of Object.keys(headers)) {
24
+ const value = headers[name];
25
+ if (typeof value !== 'string' || value.length === 0) continue;
26
+ if (!name) continue;
27
+ out[name] = value;
28
+ }
29
+ const names = Object.keys(out);
30
+ if (names.length === 0) return undefined;
31
+ return JSON.stringify(out);
32
+ }
@@ -1,6 +1,7 @@
1
1
  import { useMemo } from 'react';
2
2
  import { getMpvPlayerModule } from '../bridge/MpvPlayerModule';
3
3
  import { loadAndPlay } from '../bridge/loadAndPlay';
4
+ import { encodeRequestHeaders } from '../bridge/requestHeaders';
4
5
 
5
6
  /**
6
7
  * Options accepted by `usePlayerActivity().openPlayer(opts)`. This is
@@ -46,6 +47,19 @@ export interface OpenPlayerOptions {
46
47
  */
47
48
  artist?: string;
48
49
  album?: string;
50
+ /**
51
+ * HTTP request headers to send when fetching THIS file.
52
+ *
53
+ * They are per-file: the native side turns them into mpv's per-file
54
+ * options, so they apply to this launch and to no later one. A stream
55
+ * that needs a `User-Agent` or a `Referer` gets one, and the app's own
56
+ * music is unaffected.
57
+ *
58
+ * The values are untrusted input if they came from a playlist a third
59
+ * party publishes; the native side drops the control characters next
60
+ * to the network request.
61
+ */
62
+ headers?: Record<string, string>;
49
63
  }
50
64
 
51
65
  /**
@@ -113,6 +127,7 @@ export function usePlayerActivity(): UsePlayerActivityResult {
113
127
 
114
128
  // Audio never touches a surface. See `OpenPlayerOptions.type`.
115
129
  if (opts.type === 'audio') {
130
+ const headersJson = encodeRequestHeaders(opts.headers);
116
131
  return bridge.startAudioPlayback({
117
132
  uri: opts.uri,
118
133
  title: opts.title,
@@ -126,6 +141,7 @@ export function usePlayerActivity(): UsePlayerActivityResult {
126
141
  ...(opts.artworkPath ? {artworkPath: opts.artworkPath} : {}),
127
142
  ...(opts.artist ? {artist: opts.artist} : {}),
128
143
  ...(opts.album ? {album: opts.album} : {}),
144
+ ...(headersJson ? {headersJson} : {}),
129
145
  });
130
146
  }
131
147
 
@@ -140,6 +156,7 @@ export function usePlayerActivity(): UsePlayerActivityResult {
140
156
  uri: opts.uri,
141
157
  title: opts.title,
142
158
  startPositionMs,
159
+ ...(opts.headers ? {headers: opts.headers} : {}),
143
160
  });
144
161
  return Promise.resolve(true);
145
162
  },