@simba-dev/react-native-media-player 3.4.1 → 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.
@@ -1,39 +1,291 @@
1
1
  #include "native_state.h"
2
2
 
3
+ #include <algorithm>
4
+ #include <cmath>
5
+ #include <cstdio>
3
6
  #include <mutex>
7
+ #include <unistd.h>
8
+ #include <android/log.h>
9
+
10
+ #define HW_LOG_TAG "MpvHardware"
11
+ #define HW_LOGI(...) __android_log_print(ANDROID_LOG_INFO, HW_LOG_TAG, __VA_ARGS__)
4
12
 
5
13
  namespace {
6
14
  std::mutex g_loadQueueMutex;
7
15
  std::deque<PendingLoadRequest> g_pendingLoads;
8
16
  PendingLoadRequest g_activeLoad{};
9
17
 
18
+ void setMpvConfig(mpv_handle *mpv, const char *name, const char *value, bool isPreInit) {
19
+ if (!mpv || !name || !value) return;
20
+ if (isPreInit) {
21
+ mpv_set_option_string(mpv, name, value);
22
+ } else {
23
+ mpv_set_property_string(mpv, name, value);
24
+ }
25
+ }
26
+ } // namespace
27
+
28
+ // ── Shared hardened JSON serializer ────────────────────────────────────────
29
+
30
+ std::string jsonQuote(const char *value) {
31
+ std::string out;
32
+ out.push_back('"');
33
+ if (value) {
34
+ for (const unsigned char *p = reinterpret_cast<const unsigned char *>(value); *p; ++p) {
35
+ switch (*p) {
36
+ case '\\': out += "\\\\"; break;
37
+ case '"': out += "\\\""; break;
38
+ case '\b': out += "\\b"; break;
39
+ case '\f': out += "\\f"; break;
40
+ case '\n': out += "\\n"; break;
41
+ case '\r': out += "\\r"; break;
42
+ case '\t': out += "\\t"; break;
43
+ default:
44
+ if (*p < 0x20) {
45
+ char escaped[8];
46
+ snprintf(escaped, sizeof(escaped), "\\u%04x", *p);
47
+ out += escaped;
48
+ } else {
49
+ out.push_back(static_cast<char>(*p));
50
+ }
51
+ break;
52
+ }
53
+ }
54
+ }
55
+ out.push_back('"');
56
+ return out;
57
+ }
58
+
10
59
  std::string jsonQuote(const std::string &value) {
11
- std::string result;
12
- result.reserve(value.size() + 2);
13
- result.push_back('"');
14
- for (const unsigned char character : value) {
15
- switch (character) {
16
- case '\\': result += "\\\\"; break;
17
- case '"': result += "\\\""; break;
18
- case '\n': result += "\\n"; break;
19
- case '\r': result += "\\r"; break;
20
- case '\t': result += "\\t"; break;
21
- default: result.push_back(static_cast<char>(character)); break;
60
+ return jsonQuote(value.c_str());
61
+ }
62
+
63
+ std::string jsonNode(const mpv_node *node) {
64
+ if (!node) return "null";
65
+
66
+ switch (node->format) {
67
+ case MPV_FORMAT_NONE:
68
+ return "null";
69
+ case MPV_FORMAT_STRING:
70
+ return jsonQuote(node->u.string);
71
+ case MPV_FORMAT_FLAG:
72
+ return node->u.flag ? "true" : "false";
73
+ case MPV_FORMAT_INT64: {
74
+ char buf[32];
75
+ snprintf(buf, sizeof(buf), "%lld", static_cast<long long>(node->u.int64));
76
+ return buf;
77
+ }
78
+ case MPV_FORMAT_DOUBLE: {
79
+ if (!std::isfinite(node->u.double_)) {
80
+ return "null";
81
+ }
82
+ char buf[64];
83
+ snprintf(buf, sizeof(buf), "%.6f", node->u.double_);
84
+ return buf;
85
+ }
86
+ case MPV_FORMAT_BYTE_ARRAY:
87
+ return "null";
88
+ case MPV_FORMAT_NODE_ARRAY: {
89
+ std::string out = "[";
90
+ const mpv_node_list *list = node->u.list;
91
+ if (list && list->values) {
92
+ for (int i = 0; i < list->num; ++i) {
93
+ if (i > 0) out += ",";
94
+ out += jsonNode(&list->values[i]);
95
+ }
96
+ }
97
+ out += "]";
98
+ return out;
99
+ }
100
+ case MPV_FORMAT_NODE_MAP: {
101
+ std::string out = "{";
102
+ const mpv_node_list *list = node->u.list;
103
+ if (list && list->values) {
104
+ for (int i = 0; i < list->num; ++i) {
105
+ if (i > 0) out += ",";
106
+ out += jsonQuote(list->keys && list->keys[i] ? list->keys[i] : "");
107
+ out += ":";
108
+ out += jsonNode(&list->values[i]);
109
+ }
110
+ }
111
+ out += "}";
112
+ return out;
22
113
  }
114
+ default:
115
+ return "null";
23
116
  }
24
- result.push_back('"');
25
- return result;
26
117
  }
118
+
119
+ // ── Hardware-adaptive libmpv tuning ────────────────────────────────────────
120
+
121
+ const char *deviceTierName(DeviceTier tier) {
122
+ switch (tier) {
123
+ case DeviceTier::Low: return "low";
124
+ case DeviceTier::Mid: return "mid";
125
+ case DeviceTier::High: return "high";
126
+ default: return "mid";
127
+ }
27
128
  }
28
129
 
130
+ HardwareProfile detectHardwareProfile(
131
+ int64_t totalRamMbHint,
132
+ int cpuCoresHint,
133
+ int screenWidthPx,
134
+ int screenHeightPx,
135
+ int glEsMajor,
136
+ bool isLowRamHint) {
137
+ HardwareProfile p{};
138
+
139
+ // Query OS physical RAM directly in C++ when hint is absent.
140
+ int64_t ramMb = totalRamMbHint;
141
+ if (ramMb <= 0) {
142
+ const long pages = sysconf(_SC_PHYS_PAGES);
143
+ const long pageSize = sysconf(_SC_PAGE_SIZE);
144
+ if (pages > 0 && pageSize > 0) {
145
+ ramMb = (static_cast<int64_t>(pages) * static_cast<int64_t>(pageSize)) / (1024 * 1024);
146
+ }
147
+ }
148
+
149
+ int cores = cpuCoresHint;
150
+ if (cores <= 0) {
151
+ const long online = sysconf(_SC_NPROCESSORS_ONLN);
152
+ cores = online > 0 ? static_cast<int>(online) : 4;
153
+ }
154
+
155
+ p.totalRamMb = ramMb;
156
+ p.cpuCores = cores;
157
+ p.screenWidthPx = screenWidthPx > 0 ? screenWidthPx : 0;
158
+ p.screenHeightPx = screenHeightPx > 0 ? screenHeightPx : 0;
159
+ p.glEsMajor = glEsMajor > 0 ? glEsMajor : 3;
160
+ p.isLowRam = isLowRamHint || (ramMb > 0 && ramMb <= 3200);
161
+
162
+ const int shortEdge = (p.screenWidthPx > 0 && p.screenHeightPx > 0)
163
+ ? std::min(p.screenWidthPx, p.screenHeightPx)
164
+ : 1080;
165
+
166
+ if (p.isLowRam || p.glEsMajor < 3 || (ramMb > 0 && ramMb <= 3500) ||
167
+ (shortEdge <= 720 && ramMb > 0 && ramMb <= 4500) || cores <= 4) {
168
+ p.tier = DeviceTier::Low;
169
+ } else if ((ramMb > 0 && ramMb <= 6500) || shortEdge < 1080) {
170
+ p.tier = DeviceTier::Mid;
171
+ } else {
172
+ p.tier = DeviceTier::High;
173
+ }
174
+
175
+ return p;
176
+ }
177
+
178
+ void applyHardwareTuning(mpv_handle *mpv, const HardwareProfile &profile, bool isPreInit) {
179
+ if (!mpv) return;
180
+
181
+ // Resilient hardware decoding: prefer zero-copy MediaCodec Surface,
182
+ // automatically fall back to mediacodec-copy on quirky OEM drivers or when
183
+ // video filters (vf) are active, before ever dropping to CPU decode.
184
+ setMpvConfig(mpv, "hwdec", "mediacodec,mediacodec-copy", isPreInit);
185
+ setMpvConfig(mpv, "framedrop", "vo", isPreInit);
186
+ setMpvConfig(mpv, "video-output-levels", "auto", isPreInit);
187
+ setMpvConfig(mpv, "deband", "no", isPreInit);
188
+
189
+ const int safeCores = profile.cpuCores > 0 ? profile.cpuCores : 4;
190
+ char threadsBuf[16];
191
+
192
+ switch (profile.tier) {
193
+ case DeviceTier::Low: {
194
+ // Budget / low-RAM / <=720p / weak GPU:
195
+ // Minimize GPU fragment shader cost and native heap footprint.
196
+ setMpvConfig(mpv, "scale", "bilinear", isPreInit);
197
+ setMpvConfig(mpv, "dscale", "bilinear", isPreInit);
198
+ setMpvConfig(mpv, "cscale", "bilinear", isPreInit);
199
+ setMpvConfig(mpv, "correct-downscaling", "no", isPreInit);
200
+ setMpvConfig(mpv, "dither-depth", "no", isPreInit);
201
+ setMpvConfig(mpv, "fbo-format", "rgba8", isPreInit);
202
+ setMpvConfig(mpv, "target-colorspace-hint", "no", isPreInit);
203
+ snprintf(threadsBuf, sizeof(threadsBuf), "%d", std::max(1, std::min(safeCores, 4)));
204
+ setMpvConfig(mpv, "vd-lavc-threads", threadsBuf, isPreInit);
205
+ setMpvConfig(mpv, "vd-lavc-fast", "yes", isPreInit);
206
+ setMpvConfig(mpv, "vd-lavc-skiploopfilter", "nonref", isPreInit);
207
+ setMpvConfig(mpv, "cache", "yes", isPreInit);
208
+ setMpvConfig(mpv, "cache-secs", "60", isPreInit);
209
+ setMpvConfig(mpv, "demuxer-readahead-secs", "60", isPreInit);
210
+ setMpvConfig(mpv, "demuxer-max-bytes", "32MiB", isPreInit);
211
+ setMpvConfig(mpv, "demuxer-max-back-bytes", "16MiB", isPreInit);
212
+ break;
213
+ }
214
+ case DeviceTier::Mid: {
215
+ // Mid-range 4-6 GB RAM / 1080p:
216
+ // Crisp downscaling with 8-bit FBOs and balanced RAM cache.
217
+ setMpvConfig(mpv, "scale", "bilinear", isPreInit);
218
+ setMpvConfig(mpv, "dscale", "mitchell", isPreInit);
219
+ setMpvConfig(mpv, "cscale", "bilinear", isPreInit);
220
+ setMpvConfig(mpv, "correct-downscaling", "no", isPreInit);
221
+ setMpvConfig(mpv, "dither-depth", "auto", isPreInit);
222
+ setMpvConfig(mpv, "fbo-format", "rgba8", isPreInit);
223
+ setMpvConfig(mpv, "target-colorspace-hint", "yes", isPreInit);
224
+ snprintf(threadsBuf, sizeof(threadsBuf), "%d", std::max(2, std::min(safeCores, 6)));
225
+ setMpvConfig(mpv, "vd-lavc-threads", threadsBuf, isPreInit);
226
+ setMpvConfig(mpv, "vd-lavc-fast", "no", isPreInit);
227
+ setMpvConfig(mpv, "vd-lavc-skiploopfilter", "default", isPreInit);
228
+ setMpvConfig(mpv, "cache", "yes", isPreInit);
229
+ setMpvConfig(mpv, "cache-secs", "180", isPreInit);
230
+ setMpvConfig(mpv, "demuxer-readahead-secs", "180", isPreInit);
231
+ setMpvConfig(mpv, "demuxer-max-bytes", "80MiB", isPreInit);
232
+ setMpvConfig(mpv, "demuxer-max-back-bytes", "40MiB", isPreInit);
233
+ break;
234
+ }
235
+ case DeviceTier::High: {
236
+ // Flagship >=8 GB RAM / >=1080p-1440p / GLES 3+:
237
+ // Full cinema-grade scaling, HDR colorspace hint, and 300s buffer.
238
+ setMpvConfig(mpv, "scale", "spline36", isPreInit);
239
+ setMpvConfig(mpv, "dscale", "mitchell", isPreInit);
240
+ setMpvConfig(mpv, "cscale", "bilinear", isPreInit);
241
+ setMpvConfig(mpv, "correct-downscaling", "yes", isPreInit);
242
+ setMpvConfig(mpv, "dither-depth", "auto", isPreInit);
243
+ setMpvConfig(mpv, "fbo-format", "rgba16f", isPreInit);
244
+ setMpvConfig(mpv, "target-colorspace-hint", "yes", isPreInit);
245
+ setMpvConfig(mpv, "vd-lavc-threads", "0", isPreInit);
246
+ setMpvConfig(mpv, "vd-lavc-fast", "no", isPreInit);
247
+ setMpvConfig(mpv, "vd-lavc-skiploopfilter", "default", isPreInit);
248
+ setMpvConfig(mpv, "cache", "yes", isPreInit);
249
+ setMpvConfig(mpv, "cache-secs", "300", isPreInit);
250
+ setMpvConfig(mpv, "demuxer-readahead-secs", "300", isPreInit);
251
+ setMpvConfig(mpv, "demuxer-max-bytes", "150MiB", isPreInit);
252
+ setMpvConfig(mpv, "demuxer-max-back-bytes", "75MiB", isPreInit);
253
+ break;
254
+ }
255
+ }
256
+
257
+ HW_LOGI(
258
+ "Applied libmpv hardware profile tier=%s (ramMb=%lld cores=%d screen=%dx%d gles=%d lowRam=%d preInit=%d)",
259
+ deviceTierName(profile.tier),
260
+ static_cast<long long>(profile.totalRamMb),
261
+ profile.cpuCores,
262
+ profile.screenWidthPx,
263
+ profile.screenHeightPx,
264
+ profile.glEsMajor,
265
+ profile.isLowRam ? 1 : 0,
266
+ isPreInit ? 1 : 0);
267
+ }
268
+
269
+ std::string hardwareProfileToJson(const HardwareProfile &profile) {
270
+ char buf[256];
271
+ snprintf(
272
+ buf,
273
+ sizeof(buf),
274
+ "{\"tier\":\"%s\",\"totalRamMb\":%lld,\"cpuCores\":%d,\"screenWidthPx\":%d,\"screenHeightPx\":%d,\"glEsMajor\":%d,\"isLowRam\":%s}",
275
+ deviceTierName(profile.tier),
276
+ static_cast<long long>(profile.totalRamMb),
277
+ profile.cpuCores,
278
+ profile.screenWidthPx,
279
+ profile.screenHeightPx,
280
+ profile.glEsMajor,
281
+ profile.isLowRam ? "true" : "false");
282
+ return std::string(buf);
283
+ }
284
+
285
+ // ── Load request correlation queue ─────────────────────────────────────────
286
+
29
287
  void enqueueLoadRequest(PendingLoadRequest request) {
30
288
  std::lock_guard<std::mutex> guard(g_loadQueueMutex);
31
- // L3: reap the previously-active request if it's been superseded.
32
- // Without this, a user navigating between files before FILE_LOADED
33
- // fires for the first one leaves the old entry in the queue
34
- // forever (it never matches the new file's resolvedPath and
35
- // consumeFileLoadedPayload never pops it). Drop it here so the
36
- // queue never holds more than one in-flight request at a time.
37
289
  if (!g_activeLoad.requestId.empty() && g_activeLoad.requestId != request.requestId) {
38
290
  for (auto iterator = g_pendingLoads.begin(); iterator != g_pendingLoads.end();) {
39
291
  if (iterator->requestId == g_activeLoad.requestId) {
@@ -88,9 +340,6 @@ std::string consumeFileLoadedPayload(const std::string &resolvedPath) {
88
340
 
89
341
  auto selected = g_pendingLoads.end();
90
342
  if (resolvedPath.empty()) {
91
- // MPV can report FILE_LOADED before its `path` property becomes
92
- // readable. With exactly one pending V3 request, the event is still
93
- // unambiguous; preserve its token and let V3 correlate by request ID.
94
343
  if (g_pendingLoads.size() == 1) selected = g_pendingLoads.begin();
95
344
  } else {
96
345
  for (auto iterator = g_pendingLoads.begin(); iterator != g_pendingLoads.end(); ++iterator) {
@@ -99,9 +348,6 @@ std::string consumeFileLoadedPayload(const std::string &resolvedPath) {
99
348
  break;
100
349
  }
101
350
  }
102
- // Some mpv backends normalize a path (for example by changing a
103
- // document-provider fd representation). If there is only one pending
104
- // request, the FILE_LOADED event is still unambiguous by event order.
105
351
  if (selected == g_pendingLoads.end() && g_pendingLoads.size() == 1) {
106
352
  selected = g_pendingLoads.begin();
107
353
  }
@@ -32,6 +32,45 @@ private:
32
32
  mpv_handle *handle_;
33
33
  };
34
34
 
35
+ // ── Hardware-adaptive libmpv tuning (v3.5.0) ───────────────────────────────
36
+
37
+ enum class DeviceTier : int {
38
+ Low = 0,
39
+ Mid = 1,
40
+ High = 2,
41
+ };
42
+
43
+ struct HardwareProfile {
44
+ int64_t totalRamMb = 0;
45
+ int cpuCores = 0;
46
+ int screenWidthPx = 0;
47
+ int screenHeightPx = 0;
48
+ int glEsMajor = 3;
49
+ bool isLowRam = false;
50
+ DeviceTier tier = DeviceTier::Mid;
51
+ };
52
+
53
+ const char *deviceTierName(DeviceTier tier);
54
+
55
+ HardwareProfile detectHardwareProfile(
56
+ int64_t totalRamMbHint,
57
+ int cpuCoresHint,
58
+ int screenWidthPx,
59
+ int screenHeightPx,
60
+ int glEsMajor,
61
+ bool isLowRamHint);
62
+
63
+ void applyHardwareTuning(mpv_handle *mpv, const HardwareProfile &profile, bool isPreInit);
64
+ std::string hardwareProfileToJson(const HardwareProfile &profile);
65
+
66
+ // ── Shared hardened JSON serializer ────────────────────────────────────────
67
+
68
+ std::string jsonQuote(const char *value);
69
+ std::string jsonQuote(const std::string &value);
70
+ std::string jsonNode(const mpv_node *node);
71
+
72
+ // ── Load request correlation queue ─────────────────────────────────────────
73
+
35
74
  struct PendingLoadRequest {
36
75
  std::string requestId;
37
76
  std::string resolvedPath;
@@ -9,70 +9,6 @@
9
9
  #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
10
10
  #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
11
11
 
12
- // ── mpv_node → JSON string ──────────────────────────────────────────────────
13
- // Simple recursive conversion; production code should use a proper JSON lib.
14
-
15
- static void appendNode(std::string &out, const mpv_node *node) {
16
- switch (node->format) {
17
- case MPV_FORMAT_NONE:
18
- out += "null";
19
- break;
20
- case MPV_FORMAT_STRING:
21
- out += "\"";
22
- for (const char *p = node->u.string; *p; p++) {
23
- switch (*p) {
24
- case '"': out += "\\\""; break;
25
- case '\\': out += "\\\\"; break;
26
- case '\n': out += "\\n"; break;
27
- case '\r': out += "\\r"; break;
28
- case '\t': out += "\\t"; break;
29
- default: out += *p; break;
30
- }
31
- }
32
- out += "\"";
33
- break;
34
- case MPV_FORMAT_FLAG:
35
- out += node->u.flag ? "true" : "false";
36
- break;
37
- case MPV_FORMAT_INT64: {
38
- char buf[32];
39
- snprintf(buf, sizeof(buf), "%lld", (long long)node->u.int64);
40
- out += buf;
41
- break;
42
- }
43
- case MPV_FORMAT_DOUBLE: {
44
- char buf[64];
45
- snprintf(buf, sizeof(buf), "%.6f", node->u.double_);
46
- out += buf;
47
- break;
48
- }
49
- case MPV_FORMAT_NODE_ARRAY: {
50
- out += "[";
51
- for (int i = 0; i < node->u.list->num; i++) {
52
- if (i > 0) out += ",";
53
- appendNode(out, &node->u.list->values[i]);
54
- }
55
- out += "]";
56
- break;
57
- }
58
- case MPV_FORMAT_NODE_MAP: {
59
- out += "{";
60
- for (int i = 0; i < node->u.list->num; i++) {
61
- if (i > 0) out += ",";
62
- out += "\"";
63
- out += node->u.list->keys[i];
64
- out += "\":";
65
- appendNode(out, &node->u.list->values[i]);
66
- }
67
- out += "}";
68
- break;
69
- }
70
- default:
71
- out += "null";
72
- break;
73
- }
74
- }
75
-
76
12
  extern "C" JNIEXPORT jstring JNICALL
77
13
  Java_com_simba_player_mpv_MPVLib_nativeGetProperty(
78
14
  JNIEnv *env, jclass, jlong nativePtr, jstring name) {
@@ -81,17 +17,17 @@ Java_com_simba_player_mpv_MPVLib_nativeGetProperty(
81
17
  if (!lease.valid()) return env->NewStringUTF("null");
82
18
  mpv_handle *mpv = lease.get();
83
19
  const char *propName = env->GetStringUTFChars(name, nullptr);
20
+ if (!propName) return env->NewStringUTF("null");
84
21
 
85
- mpv_node node;
86
- int err = mpv_get_property(mpv, propName, MPV_FORMAT_NODE, &node);
22
+ mpv_node node{};
23
+ const int err = mpv_get_property(mpv, propName, MPV_FORMAT_NODE, &node);
87
24
  env->ReleaseStringUTFChars(name, propName);
88
25
 
89
26
  if (err < 0) {
90
27
  return env->NewStringUTF("null");
91
28
  }
92
29
 
93
- std::string json;
94
- appendNode(json, &node);
30
+ const std::string json = jsonNode(&node);
95
31
  mpv_free_node_contents(&node);
96
32
  return env->NewStringUTF(json.c_str());
97
33
  }
@@ -104,12 +40,14 @@ Java_com_simba_player_mpv_MPVLib_nativeSetProperty(
104
40
  if (!lease.valid()) return;
105
41
  mpv_handle *mpv = lease.get();
106
42
  const char *propName = env->GetStringUTFChars(name, nullptr);
43
+ if (!propName) return;
107
44
  const char *json = valueJson ? env->GetStringUTFChars(valueJson, nullptr) : "null";
108
45
 
109
- // For simple types, use string form for simplicity
110
- mpv_set_property_string(mpv, propName, json);
46
+ if (json) {
47
+ mpv_set_property_string(mpv, propName, json);
48
+ }
111
49
 
112
- if (valueJson) env->ReleaseStringUTFChars(valueJson, json);
50
+ if (valueJson && json) env->ReleaseStringUTFChars(valueJson, json);
113
51
  env->ReleaseStringUTFChars(name, propName);
114
52
  }
115
53
 
@@ -121,10 +59,10 @@ Java_com_simba_player_mpv_MPVLib_nativeObserveProperty(
121
59
  if (!lease.valid()) return;
122
60
  mpv_handle *mpv = lease.get();
123
61
  const char *propName = env->GetStringUTFChars(name, nullptr);
124
- // Use a hash of the property name as the reply_userdata
62
+ if (!propName) return;
125
63
  uint64_t hash = 0;
126
64
  for (const char *p = propName; *p; p++)
127
- hash = hash * 31 + *p;
65
+ hash = hash * 31 + static_cast<unsigned char>(*p);
128
66
  enum mpv_format format = MPV_FORMAT_NODE;
129
67
  if (strcmp(propName, "paused-for-cache") == 0 ||
130
68
  strcmp(propName, "seekable") == 0 ||
@@ -142,7 +80,7 @@ Java_com_simba_player_mpv_MPVLib_nativeObserveProperty(
142
80
  }
143
81
  const int err = mpv_observe_property(mpv, hash, propName, format);
144
82
  LOGI("[PlaybackTrace][Native][observe] property=%s id=%llu format=%d result=%d",
145
- propName, (unsigned long long)hash, format, err);
83
+ propName, static_cast<unsigned long long>(hash), format, err);
146
84
 
147
85
  env->ReleaseStringUTFChars(name, propName);
148
86
  }
@@ -155,9 +93,10 @@ Java_com_simba_player_mpv_MPVLib_nativeUnobserveProperty(
155
93
  if (!lease.valid()) return;
156
94
  mpv_handle *mpv = lease.get();
157
95
  const char *propName = env->GetStringUTFChars(name, nullptr);
96
+ if (!propName) return;
158
97
  uint64_t hash = 0;
159
98
  for (const char *p = propName; *p; p++)
160
- hash = hash * 31 + *p;
99
+ hash = hash * 31 + static_cast<unsigned char>(*p);
161
100
  mpv_unobserve_property(mpv, hash);
162
101
  LOGI("Unobserving property: %s", propName);
163
102
  env->ReleaseStringUTFChars(name, propName);
@@ -23,6 +23,31 @@ object MPVLib {
23
23
  /** Create mpv instance. Returns native pointer as Long. */
24
24
  external fun nativeCreate(caFilePath: String): Long
25
25
 
26
+ /**
27
+ * Create mpv instance with real Android hardware metrics (RAM, CPU cores,
28
+ * display resolution, GLES major version, low-RAM flag) so C++ applies the
29
+ * optimal libmpv scaling, FBO, decode-thread, and demuxer cache tier before
30
+ * `mpv_initialize`.
31
+ */
32
+ external fun nativeCreateWithHardwareInfo(
33
+ caFilePath: String,
34
+ totalRamMb: Long,
35
+ cpuCores: Int,
36
+ screenWidthPx: Int,
37
+ screenHeightPx: Int,
38
+ glEsMajor: Int,
39
+ isLowRam: Boolean,
40
+ ): Long
41
+
42
+ /** Dynamically switch the libmpv hardware performance profile ("auto" | "low" | "mid" | "high" | "battery-saver" | "balanced" | "high-quality"). */
43
+ external fun nativeSetPerformanceProfile(nativePtr: Long, profileName: String)
44
+
45
+ /** Return the active hardware profile as a JSON string. */
46
+ external fun nativeGetHardwareProfile(nativePtr: Long): String
47
+
48
+ /** Dynamically update libmpv log level ("error" | "warn" | "info" | "v"). */
49
+ external fun nativeSetLogLevel(nativePtr: Long, level: String)
50
+
26
51
  /** Destroy mpv instance. */
27
52
  external fun nativeDestroy()
28
53
 
@@ -2555,8 +2555,44 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2555
2555
  return true
2556
2556
  }
2557
2557
  val caFilePath = prepareMpvCaBundle()
2558
- nativePtr = MPVLib.nativeCreate(caFilePath)
2559
- Log.i(TAG, "[PlaybackTrace][Bridge][initPlayer] nativeCreate returned ptr=$nativePtr")
2558
+ val am = reactApplicationContext.getSystemService(android.content.Context.ACTIVITY_SERVICE) as? android.app.ActivityManager
2559
+ val memInfo = android.app.ActivityManager.MemoryInfo()
2560
+ val totalRamMb = try {
2561
+ if (am != null) {
2562
+ am.getMemoryInfo(memInfo)
2563
+ memInfo.totalMem / (1024L * 1024L)
2564
+ } else {
2565
+ 0L
2566
+ }
2567
+ } catch (_: Exception) {
2568
+ 0L
2569
+ }
2570
+ val isLowRam = try {
2571
+ am?.isLowRamDevice == true
2572
+ } catch (_: Exception) {
2573
+ false
2574
+ }
2575
+ val glEsMajor = try {
2576
+ val req = am?.deviceConfigurationInfo?.reqGlEsVersion ?: 0x30000
2577
+ (req ushr 16).coerceAtLeast(2)
2578
+ } catch (_: Exception) {
2579
+ 3
2580
+ }
2581
+ val cpuCores = Runtime.getRuntime().availableProcessors().coerceAtLeast(1)
2582
+ val dm = reactApplicationContext.resources?.displayMetrics
2583
+ val screenWidthPx = dm?.widthPixels ?: 0
2584
+ val screenHeightPx = dm?.heightPixels ?: 0
2585
+
2586
+ nativePtr = MPVLib.nativeCreateWithHardwareInfo(
2587
+ caFilePath,
2588
+ totalRamMb,
2589
+ cpuCores,
2590
+ screenWidthPx,
2591
+ screenHeightPx,
2592
+ glEsMajor,
2593
+ isLowRam,
2594
+ )
2595
+ Log.i(TAG, "[PlaybackTrace][Bridge][initPlayer] nativeCreateWithHardwareInfo returned ptr=$nativePtr ramMb=$totalRamMb cores=$cpuCores screen=${screenWidthPx}x${screenHeightPx} gles=$glEsMajor lowRam=$isLowRam")
2560
2596
  if (nativePtr == 0L) {
2561
2597
  Log.e(TAG, "Failed to create mpv instance")
2562
2598
  return false
@@ -2602,6 +2638,7 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2602
2638
  debugLoggingEnabled = enabled
2603
2639
  if (nativePtr != 0L) {
2604
2640
  try {
2641
+ MPVLib.nativeSetLogLevel(nativePtr, if (enabled) "v" else "error")
2605
2642
  MPVLib.setPropertyString(nativePtr, "msg-level", if (enabled) "all" else "info")
2606
2643
  Log.i(TAG, "[PlaybackTrace][Bridge][setDebugLogging] enabled=$enabled (mpv msg-level=${if (enabled) "all" else "info"})")
2607
2644
  } catch (e: Exception) {
@@ -2610,6 +2647,31 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
2610
2647
  }
2611
2648
  }
2612
2649
 
2650
+ @ReactMethod
2651
+ @Override
2652
+ override fun setPerformanceProfile(profile: String) {
2653
+ if (nativePtr == 0L) {
2654
+ Log.w(TAG, "[PlaybackTrace][Bridge][setPerformanceProfile] ignored (not initialized)")
2655
+ return
2656
+ }
2657
+ try {
2658
+ MPVLib.nativeSetPerformanceProfile(nativePtr, profile)
2659
+ } catch (e: Exception) {
2660
+ Log.w(TAG, "[PlaybackTrace][Bridge][setPerformanceProfile] failed: ${e.message}", e)
2661
+ }
2662
+ }
2663
+
2664
+ @ReactMethod(isBlockingSynchronousMethod = true)
2665
+ @Override
2666
+ override fun getHardwareProfile(): String {
2667
+ return try {
2668
+ MPVLib.nativeGetHardwareProfile(nativePtr)
2669
+ } catch (e: Exception) {
2670
+ Log.w(TAG, "[PlaybackTrace][Bridge][getHardwareProfile] failed: ${e.message}", e)
2671
+ "{\"tier\":\"mid\"}"
2672
+ }
2673
+ }
2674
+
2613
2675
  /**
2614
2676
  * Phase 39: dump all currently-observed mpv properties to logcat.
2615
2677
  * Returns the count of properties dumped (for test verification).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "3.4.1",
3
+ "version": "3.5.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",