@simba-dev/react-native-media-player 3.3.7 → 3.4.1

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,5 +1,59 @@
1
1
 
2
2
 
3
+ ## [3.4.1] - 2026-11-21
4
+
5
+ ### Added
6
+
7
+ - **`LaunchParams.headers` — the in-window launch path can carry the request headers too.**
8
+
9
+ `useLaunchPlayback` is the library's own load half, and it is what a consumer that loads
10
+ into an already-open window uses. It had no way to say "fetch this file with these
11
+ headers", so a consumer whose video lane needed them could not pass them at all.
12
+
13
+ The headers ride the LOAD, like every other launch parameter: they are part of the file
14
+ being opened, not a property set before it.
15
+
16
+ ## [3.4.0] - 2026-11-21
17
+
18
+ ### Added
19
+
20
+ - **Per-file request headers — `openPlayer({headers})`.**
21
+ A stream can be told how to FETCH it, not only what to play. An IPTV playlist declares a
22
+ `User-Agent` and a `Referer` for the providers that check them, and until now the app
23
+ dropped them and asked for the stream without.
24
+
25
+ ```ts
26
+ await openPlayer({
27
+ uri: 'https://provider.example/stream.m3u8',
28
+ title: 'A channel',
29
+ type: 'video',
30
+ headers: {'User-Agent': 'Mozilla/5.0 ...', Referer: 'https://provider.example/'},
31
+ });
32
+ ```
33
+
34
+ The headers are PER FILE. mpv has no "send these headers with this one file" API; what it
35
+ has is `loadfile` per-file options, and that is what this uses — mpv applies every pair as
36
+ a file-local option (`M_SET_OPTION_FLAG_FILE_LOCAL`), so the headers apply to that load and
37
+ to no other. A global mpv option would have leaked the User-Agent onto every later file —
38
+ the app's own music, a podcast, anything.
39
+
40
+ Two parsers sit between the option string and mpv and they do not agree: the key/value list
41
+ takes a quoted value verbatim, while `http-header-fields` is a string LIST whose separator is
42
+ a comma. The format has ONE owner (`MpvFileOptions`), and the unit tests pin both layers.
43
+
44
+ The values are untrusted input if they came from a playlist a third party publishes, and they
45
+ end up in an HTTP request: the control characters are dropped next to the sink, so a value
46
+ cannot end a header and start another.
47
+
48
+ Both lanes carry them — the video lane through `loadFileWithHeaders`, the audio lane through
49
+ `startAudioPlayback({headersJson})` — and the headers ride the LOAD, not a property set
50
+ before it.
51
+
52
+ ### Changed
53
+
54
+ - `openPlayer`'s `headers` is optional. A launch without one loads exactly as it did before:
55
+ the native side builds no options and issues the same `loadfile` it always did.
56
+
3
57
  ## [3.3.7] - 2026-11-19
4
58
 
5
59
  ### 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
@@ -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.7",
3
+ "version": "3.4.1",
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",
@@ -110,6 +110,13 @@ export interface LaunchParams {
110
110
  * `loadFileWithRequestId`, which already exists for the same reason.
111
111
  */
112
112
  readonly requestId?: string;
113
+ /**
114
+ * HTTP request headers to send when fetching THIS file.
115
+ *
116
+ * They are per file: the native side turns them into mpv¤s per-file
117
+ * options, so they apply to this launch and to no later one.
118
+ */
119
+ readonly headers?: Record<string, string>;
113
120
  }
114
121
 
115
122
  /**
@@ -297,6 +304,17 @@ export interface MpvPlayerModuleBridge {
297
304
  // ── File loading ───────────────────────────────────────────────────────
298
305
  /** Load a media file by path / URI. */
299
306
  loadFile(path: string): void;
307
+ /**
308
+ * Load a media file with HTTP request headers that apply to THIS file
309
+ * only.
310
+ *
311
+ * `headersJson` is a JSON object of header name to value, e.g.
312
+ * `{"User-Agent": "...", "Referer": "..."}`. The native side turns it
313
+ * into mpv's per-file option list, so the headers apply to this load
314
+ * and to no other - which is the whole point: a global mpv option
315
+ * would leak the header onto every later file.
316
+ */
317
+ loadFileWithHeaders(path: string, headersJson: string): void;
300
318
  /** Load a media file with an attached request ID for traceability. */
301
319
  loadFileWithRequestId(path: string, requestId: string): void;
302
320
  /** Load a playlist of paths, starting at `startIndex` (default 0). */
@@ -464,6 +482,7 @@ export interface MpvPlayerModuleBridge {
464
482
  artworkPath?: string;
465
483
  startPositionMs?: number;
466
484
  autoPlay?: boolean;
485
+ headersJson?: string;
467
486
  }): Promise<boolean>;
468
487
  /** Stop playback and tear the foreground service down. Both lanes. */
469
488
  stopPlayback(): void;
@@ -619,6 +638,10 @@ const NOOP_BRIDGE: MpvPlayerModuleBridge = {
619
638
  loadFile: (_path: string) => {
620
639
  void _path;
621
640
  },
641
+ loadFileWithHeaders: (_path: string, _headersJson: string) => {
642
+ void _path;
643
+ void _headersJson;
644
+ },
622
645
  loadFileWithRequestId: (_path: string, _requestId: string) => {
623
646
  void _path;
624
647
  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
+ }
@@ -90,7 +90,9 @@ export function useLaunchPlayback(
90
90
  // `loadAndPlay` owns the title-then-load ordering now, shared
91
91
  // with `usePlayerActivity.openPlayer` so the two entry points
92
92
  // cannot drift into loading a file under the wrong title.
93
- loadAndPlay(bridge, {uri, title, startPositionMs});
93
+ // The headers ride the LOAD. They are part of the file being
94
+ // opened, not a property set before it.
95
+ loadAndPlay(bridge, {uri, title, startPositionMs, headers: launchParams?.headers});
94
96
  } catch {
95
97
  // Bridge not present (jest/web) — ignore.
96
98
  }
@@ -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
  },