@simba-dev/react-native-media-player 3.4.0 → 3.5.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,5 +1,38 @@
1
1
 
2
2
 
3
+ ## [3.5.0] - 2026-11-27
4
+
5
+ ### Added
6
+
7
+ - **Hardware-Adaptive C++ Libmpv Tuning Engine (`LOW` / `MID` / `HIGH` tiers).**
8
+ `MPVLib.nativeCreateWithHardwareInfo()` probes real Android hardware capabilities (physical RAM via `ActivityManager` + `sysconf(_SC_PHYS_PAGES)`, CPU core count, display resolution, OpenGL ES version, and `isLowRamDevice`) and tunes libmpv scalers (`scale`/`dscale`/`cscale`), `correct-downscaling`, `fbo-format` (`rgba8` vs `rgba16f`), `target-colorspace-hint`, `vd-lavc-threads`/`vd-lavc-fast`/`vd-lavc-skiploopfilter`, `framedrop=vo`, and demuxer RAM budgets (`32MiB`/`80MiB`/`150MiB`) automatically for each device class.
9
+ - **Resilient Hardware Decoder Fallback (`hwdec=mediacodec,mediacodec-copy`).**
10
+ Prefers zero-copy MediaCodec Surface decoding and falls back cleanly to `mediacodec-copy` on devices/filters where zero-copy fails before ever dropping to CPU decode.
11
+ - **Runtime Performance Profile API (`setPerformanceProfile` / `getHardwareProfile`).**
12
+ Exposed through the TurboModule spec (`NativeMpvPlayer.ts`) and `MpvPlayerModule` so apps can switch between `'auto' | 'battery-saver' | 'balanced' | 'high-quality'` at runtime.
13
+
14
+ ### Fixed
15
+
16
+ - **Undefined Behavior in `nativeLoadPlaylist`:** Fixed `mpv_set_property("playlist-pos", MPV_FORMAT_INT64, &startIndex)` passing a 32-bit `jint*` instead of a 64-bit `int64_t*`.
17
+ - **JNI Local Reference Table Overflow in `nativeLoadPlaylist`:** Added `env->DeleteLocalRef(jpath)` and null checks inside the playlist loop so loading 500+ item playlists never aborts ART.
18
+ - **Uninitialized `pause` variable in `nativeTogglePlayPause`:** Initialized `int pause = 0;` and checked `mpv_get_property` return value.
19
+ - **Unified Hardened JSON Serializer:** Consolidated duplicate JSON serializers across `property.cpp`, `event.cpp`, and `native_state.cpp` into one null-safe, control-character-escaping, `std::isfinite`-guarded implementation in `native_state.cpp`.
20
+ - **Release Verbose Log Flood:** Changed default `mpv_request_log_messages` from `"v"` to `"error"` in release builds (dynamically toggleable via `setDebugLogging(true/false)` -> `nativeSetLogLevel`).
21
+ - **JNI Thread-Attachment Leak & Handle Safety:** Replaced raw `getEnv()` in `main.cpp` with RAII `ScopedJniEnv` (auto-detaching attached threads), passed `mpv_handle*` explicitly to `eventLoop(mpv)`, added `GetStringUTFChars` null checks, and removed unconditional `LOGI` spam from `nativeGetPosition`/`nativeGetDuration`.
22
+
23
+ ## [3.4.1] - 2026-11-21
24
+
25
+ ### Added
26
+
27
+ - **`LaunchParams.headers` — the in-window launch path can carry the request headers too.**
28
+
29
+ `useLaunchPlayback` is the library's own load half, and it is what a consumer that loads
30
+ into an already-open window uses. It had no way to say "fetch this file with these
31
+ headers", so a consumer whose video lane needed them could not pass them at all.
32
+
33
+ The headers ride the LOAD, like every other launch parameter: they are part of the file
34
+ being opened, not a property set before it.
35
+
3
36
  ## [3.4.0] - 2026-11-21
4
37
 
5
38
  ### Added
@@ -57,113 +57,6 @@ extern jmethodID g_mid_onError;
57
57
  static int64_t g_lastPositionForwardUs = 0;
58
58
  static int64_t g_lastCacheForwardUs = 0;
59
59
 
60
- // ── Helper: attach current thread to JVM and call static void method ────────
61
-
62
- static std::string jsonQuote(const char *value) {
63
- std::string out;
64
- out.push_back(34);
65
- if (value) {
66
- for (const unsigned char *p = reinterpret_cast<const unsigned char *>(value); *p; ++p) {
67
- switch (*p) {
68
- case 92:
69
- out.push_back(92);
70
- out.push_back(92);
71
- break;
72
- case 34:
73
- out.push_back(92);
74
- out.push_back(34);
75
- break;
76
- case 8:
77
- out.push_back(92);
78
- out.push_back('b');
79
- break;
80
- case 12:
81
- out.push_back(92);
82
- out.push_back('f');
83
- break;
84
- case 10:
85
- out.push_back(92);
86
- out.push_back('n');
87
- break;
88
- case 13:
89
- out.push_back(92);
90
- out.push_back('r');
91
- break;
92
- case 9:
93
- out.push_back(92);
94
- out.push_back('t');
95
- break;
96
- default:
97
- if (*p < 0x20) {
98
- char escaped[7];
99
- out.push_back(92);
100
- snprintf(escaped, sizeof(escaped), "u%04x", *p);
101
- out += escaped;
102
- } else {
103
- out += static_cast<char>(*p);
104
- }
105
- }
106
- }
107
- }
108
- out.push_back(34);
109
- return out;
110
- }
111
-
112
- static std::string jsonNode(const mpv_node *node) {
113
- if (!node) return "null";
114
-
115
- switch (node->format) {
116
- case MPV_FORMAT_NONE:
117
- return "null";
118
- case MPV_FORMAT_STRING:
119
- return jsonQuote(node->u.string);
120
- case MPV_FORMAT_FLAG:
121
- return node->u.flag ? "true" : "false";
122
- case MPV_FORMAT_INT64: {
123
- char buf[32];
124
- snprintf(buf, sizeof(buf), "%lld", static_cast<long long>(node->u.int64));
125
- return buf;
126
- }
127
- case MPV_FORMAT_DOUBLE: {
128
- char buf[64];
129
- snprintf(buf, sizeof(buf), "%.6f", node->u.double_);
130
- return buf;
131
- }
132
- case MPV_FORMAT_BYTE_ARRAY:
133
- // Buffering properties are node/string/number values. Do not
134
- // expose arbitrary binary data as malformed JSON.
135
- return "null";
136
- case MPV_FORMAT_NODE_ARRAY: {
137
- std::string out = "[";
138
- const mpv_node_list *list = node->u.list;
139
- if (list) {
140
- for (int i = 0; i < list->num; ++i) {
141
- if (i > 0) out += ",";
142
- out += jsonNode(&list->values[i]);
143
- }
144
- }
145
- out += "]";
146
- return out;
147
- }
148
- case MPV_FORMAT_NODE_MAP: {
149
- std::string out = "{";
150
- const mpv_node_list *list = node->u.list;
151
- if (list) {
152
- for (int i = 0; i < list->num; ++i) {
153
- if (i > 0) out += ",";
154
- out += jsonQuote(list->keys && list->keys[i] ? list->keys[i] : "");
155
- out += ":";
156
- out += jsonNode(&list->values[i]);
157
- }
158
- }
159
- out += "}";
160
- return out;
161
- }
162
- default:
163
- return "null";
164
- }
165
- }
166
-
167
60
  static thread_local JNIEnv *g_eventEnv = nullptr;
168
61
  static thread_local bool g_eventThreadAttached = false;
169
62
 
@@ -296,11 +189,11 @@ static void callJavaError(int code, const char *message, const char *requestId,
296
189
  if (jRequestId) env->DeleteLocalRef(jRequestId);
297
190
  }
298
191
 
299
- static std::string currentMpvPath() {
300
- if (!g_mpv) return {};
192
+ static std::string currentMpvPath(mpv_handle *mpv) {
193
+ if (!mpv) return {};
301
194
  char *path = nullptr;
302
195
  std::string resolvedPath;
303
- if (mpv_get_property(g_mpv, "path", MPV_FORMAT_STRING, &path) >= 0 && path) {
196
+ if (mpv_get_property(mpv, "path", MPV_FORMAT_STRING, &path) >= 0 && path) {
304
197
  resolvedPath = path;
305
198
  mpv_free(path);
306
199
  }
@@ -309,7 +202,8 @@ static std::string currentMpvPath() {
309
202
 
310
203
  // ── Event Loop ──────────────────────────────────────────────────────────────
311
204
 
312
- void eventLoop() {
205
+ void eventLoop(mpv_handle *mpv) {
206
+ if (!mpv) return;
313
207
  TRACEI("Event loop started");
314
208
 
315
209
  // ── Why this drains instead of blocking ────────────────────────────────
@@ -338,7 +232,7 @@ void eventLoop() {
338
232
  // Sampled once per iteration (not per property) so a drain batch that
339
233
  // releases several coalesced property changes shares one clock read.
340
234
  const int64_t nowUs = nowMicros();
341
- mpv_event *event = mpv_wait_event(g_mpv, 0);
235
+ mpv_event *event = mpv_wait_event(mpv, 0);
342
236
  if (!event) {
343
237
  LOGE("[PlaybackTrace][Native][eventLoop] mpv_wait_event returned null");
344
238
  continue;
@@ -346,7 +240,7 @@ void eventLoop() {
346
240
  if (event->event_id == MPV_EVENT_NONE) {
347
241
  // Queue is empty. Block until mpv has something for us; the
348
242
  // wake-up will also flush any coalesced property changes.
349
- event = mpv_wait_event(g_mpv, -1);
243
+ event = mpv_wait_event(mpv, -1);
350
244
  if (!event) {
351
245
  LOGE("[PlaybackTrace][Native][eventLoop] mpv_wait_event returned null");
352
246
  continue;
@@ -365,12 +259,7 @@ void eventLoop() {
365
259
 
366
260
  case MPV_EVENT_FILE_LOADED: {
367
261
  TRACEI("MPV_EVENT_FILE_LOADED");
368
- char *path = nullptr;
369
- std::string resolvedPath;
370
- if (g_mpv && mpv_get_property(g_mpv, "path", MPV_FORMAT_STRING, &path) >= 0 && path) {
371
- resolvedPath = path;
372
- mpv_free(path);
373
- }
262
+ const std::string resolvedPath = currentMpvPath(mpv);
374
263
  const std::string payload = consumeFileLoadedPayload(resolvedPath);
375
264
  LOGI("[PlaybackTrace][Native][fileLoaded] pathLength=%zu token=%s payloadLength=%zu",
376
265
  resolvedPath.size(),
@@ -390,7 +279,7 @@ void eventLoop() {
390
279
  LOGE("[PlaybackTrace][Native][eventLoop] MPV_EVENT_END_FILE reason=%d error=%d", prop ? prop->reason : -1, prop ? prop->error : -1);
391
280
  const int reason = prop ? prop->reason : -1;
392
281
  const int error = prop ? prop->error : -1;
393
- const std::string resolvedPath = currentMpvPath();
282
+ const std::string resolvedPath = currentMpvPath(mpv);
394
283
  const std::string requestId = activeLoadRequestId(resolvedPath);
395
284
  const std::string payload = "{\"reason\":" + std::to_string(reason)
396
285
  + ",\"error\":" + std::to_string(error)
@@ -494,8 +383,8 @@ void eventLoop() {
494
383
  // messages are common during network playback and previously
495
384
  // caused the JS controller to reload the stream mid-playback.
496
385
  // Terminal failures are reported through MPV_EVENT_END_FILE.
497
- if (log->level && strcmp(log->level, "fatal") == 0) {
498
- const std::string requestId = activeLoadRequestId(currentMpvPath());
386
+ if (log && log->level && strcmp(log->level, "fatal") == 0) {
387
+ const std::string requestId = activeLoadRequestId(currentMpvPath(mpv));
499
388
  // M5: mpv only promotes "fatal"-level log lines to a JS
500
389
  // error. Fatal decoder/IO failures are not retryable
501
390
  // without a different source, so we mark them
@@ -42,7 +42,8 @@ jmethodID g_mid_onError = nullptr;
42
42
 
43
43
  // ── Forward declarations ──────────────────────────────────────────────────
44
44
 
45
- void eventLoop();
45
+ void eventLoop(mpv_handle *mpv);
46
+ static HardwareProfile g_hardwareProfile{};
46
47
 
47
48
  static bool initializeMpv(mpv_handle *mpv) {
48
49
  if (!mpv) {
@@ -62,14 +63,19 @@ static bool initializeMpv(mpv_handle *mpv) {
62
63
  }
63
64
 
64
65
  LOGI("[PlaybackTrace][Native][initialize] mpv_initialize succeeded");
66
+ #ifdef SIMBA_MPV_TRACE
65
67
  mpv_request_log_messages(mpv, "v");
66
- LOGI("[PlaybackTrace][Native][initialize] requested mpv verbose logs");
68
+ #else
69
+ // Avoid flooding mpv_wait_event with verbose log events in release builds.
70
+ // Runtime debugging can promote this via nativeSetLogLevel("v").
71
+ mpv_request_log_messages(mpv, "error");
72
+ #endif
67
73
  g_initialized.store(true);
68
74
  g_running.store(true);
69
- if (pthread_create(&g_eventThread, nullptr, [](void *) -> void * {
70
- eventLoop();
75
+ if (pthread_create(&g_eventThread, nullptr, [](void *arg) -> void * {
76
+ eventLoop(static_cast<mpv_handle *>(arg));
71
77
  return nullptr;
72
- }, nullptr) != 0) {
78
+ }, mpv) != 0) {
73
79
  LOGE("Failed to create mpv event thread");
74
80
  g_running.store(false);
75
81
  g_initialized.store(false);
@@ -96,6 +102,10 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) {
96
102
  }
97
103
  g_cls_MPVLib = static_cast<jclass>(env->NewGlobalRef(temp));
98
104
  env->DeleteLocalRef(temp);
105
+ if (!g_cls_MPVLib) {
106
+ LOGE("Failed to create GlobalRef for MPVLib");
107
+ return JNI_ERR;
108
+ }
99
109
 
100
110
  g_mid_onEvent = env->GetStaticMethodID(
101
111
  g_cls_MPVLib, "onNativeEvent",
@@ -149,15 +159,38 @@ static void callStaticJavaVoid(JNIEnv *env, jmethodID mid, ...) {
149
159
  va_end(args);
150
160
  }
151
161
 
152
- static JNIEnv *getEnv() {
153
- JNIEnv *env = nullptr;
154
- if (g_vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) == JNI_OK)
155
- return env;
156
- JavaVMAttachArgs args = {JNI_VERSION_1_6, nullptr, nullptr};
157
- if (g_vm->AttachCurrentThread(&env, &args) == JNI_OK)
158
- return env;
159
- return nullptr;
160
- }
162
+ // Scoped JNIEnv accessor that detaches automatically if it had to attach a
163
+ // native thread, preventing JVM thread-table leaks.
164
+ class ScopedJniEnv {
165
+ public:
166
+ ScopedJniEnv() {
167
+ if (!g_vm) return;
168
+ const jint status = g_vm->GetEnv(reinterpret_cast<void **>(&env_), JNI_VERSION_1_6);
169
+ if (status == JNI_OK) {
170
+ return;
171
+ }
172
+ if (status == JNI_EDETACHED) {
173
+ JavaVMAttachArgs args = {JNI_VERSION_1_6, "mpv-jni-call", nullptr};
174
+ if (g_vm->AttachCurrentThread(&env_, &args) == JNI_OK) {
175
+ attached_ = true;
176
+ } else {
177
+ env_ = nullptr;
178
+ }
179
+ }
180
+ }
181
+
182
+ ~ScopedJniEnv() {
183
+ if (attached_ && g_vm) {
184
+ g_vm->DetachCurrentThread();
185
+ }
186
+ }
187
+
188
+ JNIEnv *get() const { return env_; }
189
+
190
+ private:
191
+ JNIEnv *env_ = nullptr;
192
+ bool attached_ = false;
193
+ };
161
194
 
162
195
  // ── Helper: flush queued mpv core work ──────────────────────────────────
163
196
  // Property writes (vo=null / wid=...) from other threads are processed
@@ -217,7 +250,8 @@ static void reportCommandFailure(const char *command, int result, const char *de
217
250
  LOGE("[PlaybackTrace][Native][command] '%s' failed: %s (code=%d)%s%s",
218
251
  command, reason, result,
219
252
  (detail && detail[0]) ? " - " : "", (detail && detail[0]) ? detail : "");
220
- JNIEnv *env = getEnv();
253
+ ScopedJniEnv scopedEnv;
254
+ JNIEnv *env = scopedEnv.get();
221
255
  if (!env || !g_cls_MPVLib || !g_mid_onError) return;
222
256
  char message[192];
223
257
  snprintf(message, sizeof(message), "mpv command '%s' failed: %s%s%s",
@@ -257,8 +291,15 @@ static int runMpvCommand(mpv_handle *mpv, const char **args,
257
291
 
258
292
  // ── Lifecycle ─────────────────────────────────────────────────────────────
259
293
 
260
- extern "C" JNIEXPORT jlong JNICALL
261
- Java_com_simba_player_mpv_MPVLib_nativeCreate(JNIEnv *env, jclass, jstring caFilePath) {
294
+ static jlong nativeCreateInternal(
295
+ JNIEnv *env,
296
+ jstring caFilePath,
297
+ int64_t totalRamMbHint,
298
+ int cpuCoresHint,
299
+ int screenWidthPx,
300
+ int screenHeightPx,
301
+ int glEsMajor,
302
+ bool isLowRamHint) {
262
303
  std::unique_lock<std::shared_mutex> lifecycleLock(g_mpvLifecycleMutex);
263
304
  if (g_mpv) {
264
305
  LOGI("mpv instance already exists, returning existing");
@@ -273,24 +314,23 @@ Java_com_simba_player_mpv_MPVLib_nativeCreate(JNIEnv *env, jclass, jstring caFil
273
314
  return 0;
274
315
  }
275
316
 
276
- // Set pre-init options (NOT wid — that requires the Surface and will be
277
- // set in nativeAttachSurface before mpv_initialize).
278
317
  // Audio overlays do not mount a video surface. Keep video output disabled
279
318
  // until a surface is explicitly attached by MpvRenderView.
280
- int optionResult = mpv_set_option_string(mpv, "vo", "null");
281
- LOGI("[PlaybackTrace][Native][create] option vo=null result=%d", optionResult);
282
- optionResult = mpv_set_option_string(mpv, "gpu-api", "opengl");
283
- LOGI("[PlaybackTrace][Native][create] option gpu-api=opengl result=%d", optionResult);
284
- optionResult = mpv_set_option_string(mpv, "hwdec", "mediacodec");
285
- LOGI("[PlaybackTrace][Native][create] option hwdec=mediacodec result=%d", optionResult);
286
- // Let mpv preserve the source transfer function and range instead of
287
- // applying a blanket SDR conversion. This keeps SDR/HDR content neutral
288
- // on devices that expose the required display metadata.
289
- mpv_set_option_string(mpv, "video-output-levels", "auto");
290
- mpv_set_option_string(mpv, "target-colorspace-hint", "yes");
291
- mpv_set_option_string(mpv, "correct-downscaling", "yes");
292
- optionResult = mpv_set_option_string(mpv, "audio-device-auto", "yes");
293
- LOGI("[PlaybackTrace][Native][create] option audio-device-auto=yes result=%d", optionResult);
319
+ mpv_set_option_string(mpv, "vo", "null");
320
+ mpv_set_option_string(mpv, "gpu-api", "opengl");
321
+ mpv_set_option_string(mpv, "audio-device-auto", "yes");
322
+
323
+ // Hardware-adaptive tuning (v3.5.0): classify device by real RAM, CPU cores,
324
+ // display resolution, and GLES version so budget/low-GPU phones run smooth
325
+ // without OOM/throttling while flagship phones get cinema-grade shaders.
326
+ g_hardwareProfile = detectHardwareProfile(
327
+ totalRamMbHint,
328
+ cpuCoresHint,
329
+ screenWidthPx,
330
+ screenHeightPx,
331
+ glEsMajor,
332
+ isLowRamHint);
333
+ applyHardwareTuning(mpv, g_hardwareProfile, /*isPreInit=*/true);
294
334
 
295
335
  // Android libmpv builds do not consistently discover the platform trust
296
336
  // store. Supply the app-bundled Mozilla CA bundle while keeping TLS
@@ -298,7 +338,7 @@ Java_com_simba_player_mpv_MPVLib_nativeCreate(JNIEnv *env, jclass, jstring caFil
298
338
  if (caFilePath) {
299
339
  const char *caPath = env->GetStringUTFChars(caFilePath, nullptr);
300
340
  if (caPath && caPath[0] != '\0') {
301
- optionResult = mpv_set_option_string(mpv, "tls-ca-file", caPath);
341
+ int optionResult = mpv_set_option_string(mpv, "tls-ca-file", caPath);
302
342
  LOGI("[PlaybackTrace][Native][create] option tls-ca-file=%s result=%d", caPath, optionResult);
303
343
  env->ReleaseStringUTFChars(caFilePath, caPath);
304
344
  } else {
@@ -308,96 +348,12 @@ Java_com_simba_player_mpv_MPVLib_nativeCreate(JNIEnv *env, jclass, jstring caFil
308
348
  } else {
309
349
  LOGE("[PlaybackTrace][Native][create] null CA bundle path; HTTPS validation may fail");
310
350
  }
311
- optionResult = mpv_set_option_string(mpv, "tls-verify", "yes");
312
- LOGI("[PlaybackTrace][Native][create] option tls-verify=yes result=%d", optionResult);
313
- optionResult = mpv_set_option_string(mpv, "keep-open", "yes");
314
- LOGI("[PlaybackTrace][Native][create] option keep-open=yes result=%d", optionResult);
315
- optionResult = mpv_set_option_string(mpv, "pause", "no");
316
- LOGI("[PlaybackTrace][Native][create] option pause=no result=%d", optionResult);
317
-
318
- // ── Streaming / buffering tuning ────────────────────────────────────
319
- // These are the same options used by desktop MPV configs to get
320
- // YouTube/Netflix-class seek-bar buffered-range visualization and
321
- // snappy re-seeks on slow network streams (archive.org HLS, etc.).
322
- //
323
- // • cache=yes : enable a RAM cache even for non-network
324
- // sources (so seek-back is instant).
325
- // • cache-secs=300 : keep ~5 minutes of stream ahead of the
326
- // playhead in RAM. Big enough to absorb a
327
- // brief re-buffer without a spinner, small
328
- // enough to stay under mobile RAM limits.
329
- //
330
- // This was 120 s, and 120 s is not enough to
331
- // SEE. The buffered range a consumer draws
332
- // is the span between the playhead and the
333
- // end of the buffer, and the seek bar's thumb
334
- // covers 3.04 % of the track (a 14 dp thumb on
335
- // a 230 dp rail). On a feature-length film
336
- // 120 s is 2.44 % of the file — LESS than
337
- // the thumb — so the thumb covered the whole
338
- // visible band and the buffered indicator
339
- // could not be seen at all. Measured on
340
- // device (2026-10-20): track 690 px, band
341
- // 16 px, thumb half-width 21 px. 300 s is
342
- // 6.1 % of the same film, so the band
343
- // clears the thumb.
344
- // • demuxer-max-bytes : hard upper bound on the cache size in
345
- // bytes (≈150 MB). Prevents OOM on large
346
- // VOD files over HTTP.
347
- //
348
- // This is the SECOND bound on how far
349
- // the buffered band can reach: 300 s of
350
- // video only fits in 150 MB at ≤4 Mbit/s,
351
- // so above that bitrate the byte cap
352
- // binds first and the band is shorter
353
- // than 300 s. The band was measured on
354
- // device rather than assumed.
355
- // • demuxer-max-back-bytes : how far backwards the cache retains
356
- // data (~75 MB). This is what makes
357
- // "seek back 30 s" instantaneous.
358
- // • demuxer-readahead-secs : how many seconds of stream to prefetch
359
- // ahead of the playhead.
360
- //
361
- // It is NOT independent of `cache-secs`.
362
- // mpv computes the demuxer's read-ahead
363
- // target as the MAXIMUM of the two —
364
- // mpv `demux/demux.c`, `update_opts()`:
365
- //
366
- // in->min_secs = opts->min_secs; // readahead
367
- // if (use_cache)
368
- // in->min_secs = MPMAX(in->min_secs,
369
- // opts->min_secs_cache);
370
- // // cache-secs
371
- //
372
- // `update_opts()` re-runs on EVERY config
373
- // change, so the two must be raised AND
374
- // lowered together. That is why the runtime
375
- // memory-pressure trim in
376
- // `MpvBridgeModule.onTrimMemory` writes
377
- // BOTH — trimming only `cache-secs` would
378
- // leave the read-ahead pinned and the trim
379
- // would have no effect at all.
380
- //
381
- // The span between the playhead and the end
382
- // of the buffer is exactly what a consumer
383
- // paints as its buffered range, so this
384
- // value is what makes that span visible.
385
- // • demuxer-termination-timeout : if a network read stalls, fail
386
- // the demuxer so the player can recover
387
- // instead of hanging forever.
388
- // • prefetch-playlist=yes : proactively fetch the next playlist
389
- // entry (HLS / DASH) to enable gapless.
390
- mpv_set_option_string(mpv, "cache", "yes");
391
- mpv_set_option_string(mpv, "cache-secs", "300");
392
- mpv_set_option_string(mpv, "demuxer-max-bytes", "150MiB");
393
- mpv_set_option_string(mpv, "demuxer-max-back-bytes", "75MiB");
394
- mpv_set_option_string(mpv, "demuxer-readahead-secs", "300");
351
+ mpv_set_option_string(mpv, "tls-verify", "yes");
352
+ mpv_set_option_string(mpv, "keep-open", "yes");
353
+ mpv_set_option_string(mpv, "pause", "no");
395
354
  mpv_set_option_string(mpv, "demuxer-termination-timeout", "10");
396
355
  mpv_set_option_string(mpv, "prefetch-playlist", "yes");
397
356
 
398
- // Initialize immediately so audio-only playback can load streams without
399
- // waiting for a video surface. Video surfaces remain independently attachable.
400
-
401
357
  LOGI("[PlaybackTrace][Native][create] mpv_create succeeded handle=%p", mpv);
402
358
  g_mpv = mpv;
403
359
  if (!initializeMpv(mpv)) {
@@ -406,7 +362,90 @@ Java_com_simba_player_mpv_MPVLib_nativeCreate(JNIEnv *env, jclass, jstring caFil
406
362
  }
407
363
  LOGI("mpv instance created and initialized without a required surface");
408
364
  return reinterpret_cast<jlong>(mpv);
365
+ }
409
366
 
367
+ extern "C" JNIEXPORT jlong JNICALL
368
+ Java_com_simba_player_mpv_MPVLib_nativeCreate(JNIEnv *env, jclass, jstring caFilePath) {
369
+ return nativeCreateInternal(env, caFilePath, 0, 0, 0, 0, 3, false);
370
+ }
371
+
372
+ extern "C" JNIEXPORT jlong JNICALL
373
+ Java_com_simba_player_mpv_MPVLib_nativeCreateWithHardwareInfo(
374
+ JNIEnv *env,
375
+ jclass,
376
+ jstring caFilePath,
377
+ jlong totalRamMb,
378
+ jint cpuCores,
379
+ jint screenWidthPx,
380
+ jint screenHeightPx,
381
+ jint glEsMajor,
382
+ jboolean isLowRam) {
383
+ return nativeCreateInternal(
384
+ env,
385
+ caFilePath,
386
+ static_cast<int64_t>(totalRamMb),
387
+ static_cast<int>(cpuCores),
388
+ static_cast<int>(screenWidthPx),
389
+ static_cast<int>(screenHeightPx),
390
+ static_cast<int>(glEsMajor),
391
+ isLowRam == JNI_TRUE);
392
+ }
393
+
394
+ extern "C" JNIEXPORT void JNICALL
395
+ Java_com_simba_player_mpv_MPVLib_nativeSetPerformanceProfile(
396
+ JNIEnv *env, jclass, jlong nativePtr, jstring profileName) {
397
+ if (!profileName) return;
398
+ NativeMpvReadLease lease(nativePtr);
399
+ if (!lease.valid()) return;
400
+ mpv_handle *mpv = lease.get();
401
+ const char *utf = env->GetStringUTFChars(profileName, nullptr);
402
+ if (!utf) return;
403
+
404
+ HardwareProfile next = g_hardwareProfile;
405
+ if (strcmp(utf, "low") == 0 || strcmp(utf, "battery-saver") == 0) {
406
+ next.tier = DeviceTier::Low;
407
+ } else if (strcmp(utf, "mid") == 0 || strcmp(utf, "balanced") == 0) {
408
+ next.tier = DeviceTier::Mid;
409
+ } else if (strcmp(utf, "high") == 0 || strcmp(utf, "high-quality") == 0) {
410
+ next.tier = DeviceTier::High;
411
+ } else {
412
+ // "auto" — re-detect from hardware facts
413
+ next = detectHardwareProfile(
414
+ g_hardwareProfile.totalRamMb,
415
+ g_hardwareProfile.cpuCores,
416
+ g_hardwareProfile.screenWidthPx,
417
+ g_hardwareProfile.screenHeightPx,
418
+ g_hardwareProfile.glEsMajor,
419
+ g_hardwareProfile.isLowRam);
420
+ }
421
+ env->ReleaseStringUTFChars(profileName, utf);
422
+
423
+ g_hardwareProfile = next;
424
+ applyHardwareTuning(mpv, g_hardwareProfile, /*isPreInit=*/false);
425
+ }
426
+
427
+ extern "C" JNIEXPORT jstring JNICALL
428
+ Java_com_simba_player_mpv_MPVLib_nativeGetHardwareProfile(
429
+ JNIEnv *env, jclass, jlong nativePtr) {
430
+ NativeMpvReadLease lease(nativePtr);
431
+ if (!lease.valid()) {
432
+ const HardwareProfile fallback = detectHardwareProfile(0, 0, 0, 0, 3, false);
433
+ return env->NewStringUTF(hardwareProfileToJson(fallback).c_str());
434
+ }
435
+ return env->NewStringUTF(hardwareProfileToJson(g_hardwareProfile).c_str());
436
+ }
437
+
438
+ extern "C" JNIEXPORT void JNICALL
439
+ Java_com_simba_player_mpv_MPVLib_nativeSetLogLevel(
440
+ JNIEnv *env, jclass, jlong nativePtr, jstring level) {
441
+ if (!level) return;
442
+ NativeMpvReadLease lease(nativePtr);
443
+ if (!lease.valid()) return;
444
+ mpv_handle *mpv = lease.get();
445
+ const char *utf = env->GetStringUTFChars(level, nullptr);
446
+ if (!utf) return;
447
+ mpv_request_log_messages(mpv, utf);
448
+ env->ReleaseStringUTFChars(level, utf);
410
449
  }
411
450
 
412
451
  extern "C" JNIEXPORT void JNICALL
@@ -497,13 +536,13 @@ Java_com_simba_player_mpv_MPVLib_nativeAttachSurface(
497
536
  LOGI("Surface attached with global-ref wid");
498
537
 
499
538
  // Emit surfaceAttached event
500
- JNIEnv* jniEnv = getEnv();
501
- if (jniEnv && g_mid_onEvent) {
502
- jstring jName = jniEnv->NewStringUTF("surfaceAttached");
503
- jstring jPayload = jniEnv->NewStringUTF("{}");
504
- callStaticJavaVoid(jniEnv, g_mid_onEvent, jName, jPayload);
505
- jniEnv->DeleteLocalRef(jName);
506
- jniEnv->DeleteLocalRef(jPayload);
539
+ if (env && g_mid_onEvent) {
540
+ jstring jName = env->NewStringUTF("surfaceAttached");
541
+ jstring jPayload = env->NewStringUTF("{}");
542
+ callStaticJavaVoid(env, g_mid_onEvent, jName, jPayload);
543
+ if (env->ExceptionCheck()) env->ExceptionClear();
544
+ if (jName) env->DeleteLocalRef(jName);
545
+ if (jPayload) env->DeleteLocalRef(jPayload);
507
546
  }
508
547
  } else {
509
548
  // ── Detach surface ─────────────────────────────────────────────
@@ -669,8 +708,10 @@ Java_com_simba_player_mpv_MPVLib_nativeTogglePlayPause(
669
708
  NativeMpvReadLease lease(nativePtr);
670
709
  if (!lease.valid()) return;
671
710
  mpv_handle *mpv = lease.get();
672
- int pause;
673
- mpv_get_property(mpv, "pause", MPV_FORMAT_FLAG, &pause);
711
+ int pause = 0;
712
+ if (mpv_get_property(mpv, "pause", MPV_FORMAT_FLAG, &pause) < 0) {
713
+ return;
714
+ }
674
715
  mpv_set_property_string(mpv, "pause", pause ? "no" : "yes");
675
716
  }
676
717
 
@@ -870,17 +911,22 @@ Java_com_simba_player_mpv_MPVLib_nativeLoadPlaylist(
870
911
  runMpvCommand(mpv, clearArgs, "playlist-clear", nullptr);
871
912
  jsize count = env->GetArrayLength(paths);
872
913
  for (jsize i = 0; i < count; i++) {
873
- jstring jpath = (jstring)env->GetObjectArrayElement(paths, i);
914
+ jstring jpath = static_cast<jstring>(env->GetObjectArrayElement(paths, i));
915
+ if (!jpath) continue;
874
916
  const char *utfPath = env->GetStringUTFChars(jpath, nullptr);
875
- const char *cmd[] = {"loadfile", utfPath, i == 0 ? "replace" : "append", nullptr};
876
- int result = mpv_command(mpv, cmd);
877
- if (result < 0) {
878
- LOGE("playlist loadfile command failed at index %d: %s", static_cast<int>(i), mpv_error_string(result));
917
+ if (utfPath) {
918
+ const char *cmd[] = {"loadfile", utfPath, i == 0 ? "replace" : "append", nullptr};
919
+ int result = mpv_command(mpv, cmd);
920
+ if (result < 0) {
921
+ LOGE("playlist loadfile command failed at index %d: %s", static_cast<int>(i), mpv_error_string(result));
922
+ }
923
+ env->ReleaseStringUTFChars(jpath, utfPath);
879
924
  }
880
- env->ReleaseStringUTFChars(jpath, utfPath);
925
+ env->DeleteLocalRef(jpath);
881
926
  }
882
927
  if (startIndex > 0) {
883
- mpv_set_property(mpv, "playlist-pos", MPV_FORMAT_INT64, &startIndex);
928
+ int64_t pos = static_cast<int64_t>(startIndex);
929
+ mpv_set_property(mpv, "playlist-pos", MPV_FORMAT_INT64, &pos);
884
930
  }
885
931
  }
886
932
 
@@ -991,8 +1037,7 @@ Java_com_simba_player_mpv_MPVLib_nativeGetPosition(
991
1037
  if (!lease.valid()) return 0;
992
1038
  mpv_handle *mpv = lease.get();
993
1039
  double pos = 0;
994
- int result = mpv_get_property(mpv, "time-pos", MPV_FORMAT_DOUBLE, &pos);
995
- LOGI("[PlaybackTrace][Native][getPosition] result=%d position=%f", result, pos);
1040
+ mpv_get_property(mpv, "time-pos", MPV_FORMAT_DOUBLE, &pos);
996
1041
  return pos;
997
1042
  }
998
1043
 
@@ -1003,7 +1048,6 @@ Java_com_simba_player_mpv_MPVLib_nativeGetDuration(
1003
1048
  if (!lease.valid()) return 0;
1004
1049
  mpv_handle *mpv = lease.get();
1005
1050
  double dur = 0;
1006
- int result = mpv_get_property(mpv, "duration", MPV_FORMAT_DOUBLE, &dur);
1007
- LOGI("[PlaybackTrace][Native][getDuration] result=%d duration=%f", result, dur);
1051
+ mpv_get_property(mpv, "duration", MPV_FORMAT_DOUBLE, &dur);
1008
1052
  return dur;
1009
1053
  }