@simba-dev/react-native-media-player 1.9.4 → 1.11.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.
@@ -3,6 +3,7 @@
3
3
  #include <string>
4
4
  #include <cstring>
5
5
  #include <cstdio>
6
+ #include <ctime>
6
7
  #include <client.h>
7
8
  #include <native_state.h>
8
9
 
@@ -11,6 +12,34 @@
11
12
  #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
12
13
  #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
13
14
 
15
+ // ── Hot-path logging gate (v1.10.0) ────────────────────────────────────────
16
+ //
17
+ // `MPV_EVENT_PROPERTY_CHANGE` fires for `time-pos` roughly ONCE PER VIDEO
18
+ // FRAME (mpv's own manual documents `time-pos` as the per-frame position
19
+ // property). `MPV_EVENT_LOG_MESSAGE` fires once per mpv/FFmpeg log line,
20
+ // which during network playback is dozens per second.
21
+ //
22
+ // So this loop is the single hottest thread in the app, and writing to
23
+ // logcat from it is not free: `__android_log_print` is a synchronous write
24
+ // into logd's ring buffer, and the string is formatted by snprintf BEFORE
25
+ // any level filtering is considered. Android's own `Log` documentation
26
+ // warns that building the message already costs "at least three
27
+ // allocations"; measured Android studies (FDroid EMSE 2019) report up to
28
+ // ~3x response-time overhead when logging is hot, and droidcon's 2025
29
+ // benchmark shows the cost is paid even when the log is filtered out.
30
+ //
31
+ // A player cannot ship that. `SIMBA_MPV_TRACE` compiles the hot-path logs
32
+ // to nothing; flip it locally when debugging a property/event path.
33
+ // It is OFF by default and is intentionally NOT runtime-configurable:
34
+ // a runtime flag would still evaluate the arguments at every call site.
35
+ #ifdef SIMBA_MPV_TRACE
36
+ #define TRACE_PROPERTY(...) __android_log_print(ANDROID_LOG_DEBUG, "MpvProperty", __VA_ARGS__)
37
+ #define TRACE_MPVLOG(...) __android_log_print(ANDROID_LOG_DEBUG, "mpv", __VA_ARGS__)
38
+ #else
39
+ #define TRACE_PROPERTY(...) do { } while (0)
40
+ #define TRACE_MPVLOG(...) do { } while (0)
41
+ #endif
42
+
14
43
  // ── External globals set by main.cpp ────────────────────────────────────────
15
44
 
16
45
  extern JavaVM *g_vm;
@@ -20,6 +49,14 @@ extern jmethodID g_mid_onEvent;
20
49
  extern jmethodID g_mid_onPropertyChanged;
21
50
  extern jmethodID g_mid_onError;
22
51
 
52
+ // ── Coalescing state (v1.10.0) ─────────────────────────────────────────────
53
+ //
54
+ // Only touched by the mpv event thread (mpvEventLoop), so plain int64_t is
55
+ // sufficient — no atomics or locks on the hottest path in the app. 0 means
56
+ // "nothing forwarded yet", so the first event of each property always passes.
57
+ static int64_t g_lastPositionForwardUs = 0;
58
+ static int64_t g_lastCacheForwardUs = 0;
59
+
23
60
  // ── Helper: attach current thread to JVM and call static void method ────────
24
61
 
25
62
  static std::string jsonQuote(const char *value) {
@@ -187,6 +224,67 @@ static void callJavaPropertyChanged(const char *name, const char *jsonValue) {
187
224
  if (jValue) env->DeleteLocalRef(jValue);
188
225
  }
189
226
 
227
+ // ── High-frequency property coalescing (v1.10.0) ──────────────────────────
228
+ //
229
+ // `time-pos` is mpv's PER-FRAME position property (mpv manual, "Playback
230
+ // Control": `time-pos` "updates about once per frame"). `demuxer-cache-state`
231
+ // is a NODE map containing `seekable-ranges` (an array of maps) plus
232
+ // `fw-bytes`, `reader-pts`, `raw-input-rate` — a large payload that changes
233
+ // on essentially every cache tick.
234
+ //
235
+ // Forwarding both verbatim costs, per frame: a std::string build, two JNI
236
+ // local refs, a JNI static call, a WritableMap alloc on the Kotlin side, an
237
+ // RN event dispatch, and a React setState that re-renders the entire player
238
+ // chrome. Measured on-device: 1168 `demuxer-cache-state` events inside one
239
+ // short window, dominating every other event combined.
240
+ //
241
+ // Media3's own guidance for the reference Android player is the opposite of
242
+ // this: "the listener interface doesn't include any callbacks to track normal
243
+ // playback progression. To continuously monitor playback progress ... you
244
+ // should query the current position at proper intervals."
245
+ //
246
+ // So: drop frames we are not going to render. Dropping happens here, at the
247
+ // cheapest possible point — BEFORE jsonNode()/jsonQuote() serialization and
248
+ // before the JNI crossing, so a dropped frame costs one strcmp.
249
+ //
250
+ // This is a RATE LIMIT, not a filter: the most recent value always wins and
251
+ // is always delivered, so the UI stays truthful. It is only a trailing-edge
252
+ // rate limit, and it is deliberately NOT applied to properties whose value is
253
+ // itself the signal (pause, eof-reached, seekable, muted, speed, loop-mode,
254
+ // media-title, chapter, track-list): losing one of those is a lost event, not
255
+ // a dropped duplicate frame.
256
+ static const int64_t kPositionCoalesceUs = 250000; // 250 ms -> 4 Hz
257
+ static const int64_t kCacheCoalesceUs = 500000; // 500 ms -> 2 Hz
258
+
259
+ static int64_t nowMicros() {
260
+ struct timespec ts;
261
+ clock_gettime(CLOCK_MONOTONIC, &ts);
262
+ return static_cast<int64_t>(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000;
263
+ }
264
+
265
+ // Returns true when the property should be forwarded to the JVM.
266
+ // `nowUs` is passed in rather than sampled per call so a single iteration
267
+ // of the loop shares one clock read.
268
+ static bool shouldForwardProperty(const char *name, int64_t nowUs) {
269
+ if (!name) return true;
270
+
271
+ int64_t *lastUs = nullptr;
272
+ int64_t windowUs = 0;
273
+ if (strcmp(name, "time-pos") == 0) {
274
+ lastUs = &g_lastPositionForwardUs;
275
+ windowUs = kPositionCoalesceUs;
276
+ } else if (strcmp(name, "demuxer-cache-state") == 0) {
277
+ lastUs = &g_lastCacheForwardUs;
278
+ windowUs = kCacheCoalesceUs;
279
+ } else {
280
+ return true;
281
+ }
282
+
283
+ if (*lastUs != 0 && nowUs - *lastUs < windowUs) return false;
284
+ *lastUs = nowUs;
285
+ return true;
286
+ }
287
+
190
288
  static void callJavaError(int code, const char *message, const char *requestId, bool recoverable) {
191
289
  JNIEnv *env = getEventEnv();
192
290
  if (!env || !g_cls_MPVLib || !g_mid_onError) return;
@@ -237,6 +335,9 @@ void eventLoop() {
237
335
  // state in which mpv is obliged to release the coalesced property
238
336
  // changes. One queue-drained iteration costs one non-blocking call.
239
337
  while (g_running.load()) {
338
+ // Sampled once per iteration (not per property) so a drain batch that
339
+ // releases several coalesced property changes shares one clock read.
340
+ const int64_t nowUs = nowMicros();
240
341
  mpv_event *event = mpv_wait_event(g_mpv, 0);
241
342
  if (!event) {
242
343
  LOGE("[PlaybackTrace][Native][eventLoop] mpv_wait_event returned null");
@@ -338,6 +439,14 @@ void eventLoop() {
338
439
  TRACEI("[PlaybackTrace][Native][eventLoop] property=%s format=NONE", prop->name);
339
440
  break;
340
441
  }
442
+ // Coalesce BEFORE serializing. `demuxer-cache-state` is a
443
+ // NODE map (seekable-ranges array of maps + fw-bytes +
444
+ // reader-pts), so skipping it here skips the most expensive
445
+ // payload in the whole loop rather than just a scalar.
446
+ if (!shouldForwardProperty(prop->name, nowUs)) {
447
+ TRACEI("[PlaybackTrace][Native][property] coalesced name=%s", prop->name);
448
+ break;
449
+ }
341
450
  std::string json;
342
451
  if (prop->format == MPV_FORMAT_NODE && prop->data) {
343
452
  json = jsonNode(static_cast<const mpv_node *>(prop->data));
@@ -357,15 +466,21 @@ void eventLoop() {
357
466
  json = "null";
358
467
  }
359
468
  TRACEI("[PlaybackTrace][Native][property] name=%s format=%d value=%s", prop->name, prop->format, json.c_str());
360
- // DEBUG (not TRACEI) on purpose. TRACEI is compiled to a
361
- // no-op, which is why a broken property path was
362
- // completely invisible in logcat for as long as it
363
- // existed. This is the one line that makes
364
- // "properties are observed but events never arrive"
469
+ // This line deliberately existed as a VISIBLE DEBUG log
470
+ // rather than TRACEI: TRACEI compiles to a no-op, which is
471
+ // why a broken property path was completely invisible in
472
+ // logcat for as long as it existed. It is the one line that
473
+ // makes "properties are observed but events never arrive"
365
474
  // distinguishable from "the loop never saw them".
366
- __android_log_print(ANDROID_LOG_DEBUG, "MpvProperty",
367
- "[PlaybackTrace][Native][property] name=%s format=%d value=%s",
368
- prop->name, prop->format, json.c_str());
475
+ //
476
+ // v1.10.0: it is now behind the SIMBA_MPV_TRACE compile-time
477
+ // gate instead. Leaving it unconditional cost a synchronous
478
+ // logd write PER VIDEO FRAME (time-pos) on the hottest
479
+ // thread in the app, which is a shipping-performance defect,
480
+ // not a diagnostic. Build with -DSIMBA_MPV_TRACE to restore
481
+ // exactly this visibility while debugging.
482
+ TRACE_PROPERTY("[PlaybackTrace][Native][property] name=%s format=%d value=%s",
483
+ prop->name, prop->format, json.c_str());
369
484
  callJavaPropertyChanged(prop->name, json.c_str());
370
485
  break;
371
486
  }
@@ -373,8 +488,7 @@ void eventLoop() {
373
488
  case MPV_EVENT_LOG_MESSAGE: {
374
489
  auto *log = (mpv_event_log_message *)event->data;
375
490
  TRACEI("[PlaybackTrace][Native][mpv-log] prefix=%s level=%s text=%s", log && log->prefix ? log->prefix : "", log && log->level ? log->level : "", log && log->text ? log->text : "");
376
- __android_log_print(ANDROID_LOG_DEBUG, "mpv", "[%s] %s: %s",
377
- log->prefix, log->level, log->text);
491
+ TRACE_MPVLOG("[%s] %s: %s", log->prefix, log->level, log->text);
378
492
  // Do not promote every `error`-level mpv log to a playback
379
493
  // failure. Decoder warnings such as recoverable mjpeg overread
380
494
  // messages are common during network playback and previously
@@ -1,8 +1,14 @@
1
1
  package com.simba.player.mpv
2
2
 
3
3
  import android.content.Intent
4
+ import android.graphics.Bitmap
5
+ import android.media.MediaMetadataRetriever
4
6
  import android.util.Log
5
7
  import java.io.File
8
+ import java.io.FileOutputStream
9
+ import java.util.concurrent.ExecutorService
10
+ import java.util.concurrent.Executors
11
+ import java.util.concurrent.RejectedExecutionException
6
12
  import com.facebook.react.bridge.Arguments
7
13
  import com.facebook.react.bridge.Promise
8
14
  import com.facebook.react.bridge.ReadableArray
@@ -35,6 +41,48 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
35
41
  const val NAME = "MpvPlayerModule"
36
42
  private const val TAG = "MpvBridgeModule"
37
43
 
44
+ // ── captureFrame: resume-rail thumbnails ──────────────────────────
45
+ // `MediaMetadataRetriever` needs a real filesystem path for its
46
+ // output. `filesDir` (NOT cacheDir) is deliberate: the platform
47
+ // is free to evict cacheDir at any moment, and a thumbnail that
48
+ // disappears silently blanks a Continue-Watching cell on the
49
+ // next cold start with no error anywhere.
50
+ private const val RESUME_THUMB_DIR = "simba-resume-thumbs"
51
+
52
+ // Poster-sized defaults, mirrored in TS as
53
+ // `DEFAULT_FRAME_WIDTH` / `DEFAULT_FRAME_HEIGHT` /
54
+ // `DEFAULT_FRAME_QUALITY` (src/hooks/useResumeThumbnail.ts).
55
+ //
56
+ // 640x360 is exactly 16:9, so the dominant case (film / TV /
57
+ // YouTube landscape video) scales without distortion, and
58
+ // ~230 kpx lands around 25-40 kB per JPEG at quality 80.
59
+ // Portrait sources should pass `width = 0`, which the platform
60
+ // reads as "leave the width unconstrained" so the source
61
+ // aspect ratio survives.
62
+ private const val DEFAULT_FRAME_WIDTH = 640
63
+ private const val DEFAULT_FRAME_HEIGHT = 360
64
+ private const val DEFAULT_FRAME_QUALITY = 80
65
+
66
+ // Position granularity for the output filename. A resume
67
+ // position drifts by seconds between renders (and the user may
68
+ // stop anywhere), so bucketing to 30s means repeated calls for
69
+ // "roughly where they left off" overwrite ONE file instead of
70
+ // re-encoding a near-duplicate JPEG on every scroll/re-render.
71
+ private const val FRAME_POSITION_BUCKET_MS = 30_000L
72
+
73
+ // v1.10.0 — hot-path property tracing.
74
+ //
75
+ // `time-pos` is mpv's per-frame property, so tracing every property
76
+ // change costs a logd write 30-60x/second on the player event
77
+ // thread. Off in every build config; flip to `true` locally when
78
+ // diagnosing a property that is observed but never arrives.
79
+ //
80
+ // Deliberately a `const val`, not a system property or env lookup:
81
+ // a runtime lookup would itself run on the hot path, and
82
+ // `Log.isLoggable()` is not free either. A constant lets R8 inline
83
+ // the branch away in release entirely.
84
+ private const val TRACE_PROPERTY_EVENTS = false
85
+
38
86
  // V22.0.0 / 1.5.10 (D-034): activity-aware launchParams guard.
39
87
  //
40
88
  // Background: `lastLaunchParams` (declared further down) is the
@@ -253,6 +301,31 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
253
301
  */
254
302
  private val pendingObservedProperties = linkedSetOf<String>()
255
303
 
304
+ /**
305
+ * Serial executor for [captureFrame].
306
+ *
307
+ * Two things force it to exist at all:
308
+ * 1. `MediaMetadataRetriever.getScaledFrameAtTime()` does real
309
+ * I/O — opening a (possibly remote, range-requested) source,
310
+ * seeking a decoder, and JPEG-encoding the result. On a cold
311
+ * Continue-Watching rail that is tens of ms PER ITEM, which on
312
+ * the JS or UI thread is a dropped-frame stall (and on the UI
313
+ * thread, an ANR if the source is remote). The existing
314
+ * `screenshot()` is a blocking-sync `@ReactMethod` and must NOT
315
+ * be used as a template for this.
316
+ * 2. `MediaMetadataRetriever` holds native codec handles. Two
317
+ * concurrent retrievers on the same source multiply peak
318
+ * memory, so requests are queued on ONE thread and the
319
+ * in-flight count stays at exactly 1.
320
+ *
321
+ * Shut down in `onCatalystInstanceDestroy` so a dev reload does
322
+ * not leave an idle thread behind per module instance.
323
+ */
324
+ private val frameExecutor: ExecutorService =
325
+ Executors.newSingleThreadExecutor { runnable ->
326
+ Thread(runnable, "simba-frame-extractor")
327
+ }
328
+
256
329
  // ── MPVLib Listener → JS Event Bridge ──────────────────────────────────
257
330
 
258
331
  private val mpvListener = object : MPVLib.MpvEventListener {
@@ -277,15 +350,42 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
277
350
  }
278
351
 
279
352
  override fun onMpvPropertyChanged(name: String, jsonValue: String) {
280
- Log.i(TAG, "[PlaybackTrace][Bridge][listener:property] name=$name value=$jsonValue")
281
- try {
282
- val payload = Arguments.createMap().apply {
283
- putString("property", name)
284
- putString("value", jsonValue)
353
+ // v1.10.0: this was an unconditional Log.i carrying the full
354
+ // JSON payload of EVERY property change. `time-pos` changes once
355
+ // per video frame, so this fired 30-60x/second on the player's
356
+ // event thread, each call building the message string
357
+ // (Kotlin string templates are evaluated before Log.i can decide
358
+ // to discard them) and performing a synchronous write to logd.
359
+ // Gate it behind the same debug switch as the JS dlog(); the
360
+ // property value is still delivered to JS regardless.
361
+ if (TRACE_PROPERTY_EVENTS) {
362
+ Log.d(TAG, "[PlaybackTrace][Bridge][listener:property] name=$name value=$jsonValue")
363
+ }
364
+ // v1.10.0: dedupe the generic stream. Every property below already
365
+ // gets a dedicated, typed event (onPositionChanged, onBuffering,
366
+ // onCacheState, onSeekable, ...), and `onPropertyChanged` was
367
+ // emitted for all of them too — so `time-pos` crossed the bridge
368
+ // twice per frame and the JS reducer ran twice. Emitting the
369
+ // generic event ONLY for properties that have no dedicated event
370
+ // keeps the JS `onPropertyChanged` contract intact for anything
371
+ // that reads it while removing the double delivery.
372
+ val hasDedicatedEvent = when (name) {
373
+ "time-pos", "duration", "volume", "speed", "pause",
374
+ "idle-active", "eof-reached", "seekable", "seeking",
375
+ "cache-buffering-state", "paused-for-cache",
376
+ "demuxer-cache-state" -> true
377
+ else -> false
378
+ }
379
+ if (!hasDedicatedEvent) {
380
+ try {
381
+ val payload = Arguments.createMap().apply {
382
+ putString("property", name)
383
+ putString("value", jsonValue)
384
+ }
385
+ eventEmitter.emit("onPropertyChanged", payload)
386
+ } catch (e: Exception) {
387
+ Log.w(TAG, "Property change emit failed: ${e.message}")
285
388
  }
286
- eventEmitter.emit("onPropertyChanged", payload)
287
- } catch (e: Exception) {
288
- Log.w(TAG, "Property change emit failed: ${e.message}")
289
389
  }
290
390
  // P33.4: re-emit `cache-buffering-state` updates as `onBuffering`
291
391
  // so the JS UI can show a buffering spinner for slow streams
@@ -654,6 +754,22 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
654
754
  *
655
755
  * The thumbnail persists in cache and is used by the recent-files list to
656
756
  * show a preview of where the user left off.
757
+ *
758
+ * ## NAME WARNING — this is the LIVE-frame capture
759
+ *
760
+ * `captureThumbnail` reads as "thumbnail for this uri", but the `uri`
761
+ * is used for NOTHING except hashing the output filename. The pixels
762
+ * come from `MPVLib.nativeScreenshot(nativePtr, ...)`, i.e. whatever
763
+ * the one initialised mpv handle is showing right now. So it:
764
+ * - requires `initPlayer()` to have run (`ensurePtr()`),
765
+ * - requires that something is actually loaded (pause counts, an
766
+ * empty player yields mpv's "no video" error string),
767
+ * - CANNOT target a position — there is no time argument.
768
+ *
769
+ * It is kept exactly as-is for backwards compatibility. Callers that
770
+ * want "the frame at position X" — resume rails, scrub previews,
771
+ * bookmark art — must use [captureFrame], which takes a timestamp
772
+ * and needs no player instance at all.
657
773
  */
658
774
  @ReactMethod(isBlockingSynchronousMethod = true)
659
775
  @Override
@@ -665,6 +781,277 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
665
781
  return MPVLib.nativeScreenshot(nativePtr, thumbFile.absolutePath)
666
782
  }
667
783
 
784
+ /**
785
+ * Extract ONE frame at [positionMs] from [uri] and write it as a JPEG.
786
+ * Resolves the absolute file path, or `null` when no frame exists.
787
+ *
788
+ * ## Why a separate method (not `captureThumbnail`)
789
+ *
790
+ * The "frame where the user left off" thumbnail cannot come from mpv:
791
+ * `captureThumbnail` has no time argument, needs a live player, and
792
+ * grabs the current surface (see its NAME WARNING above). Android's
793
+ * standard API for "make a thumbnail from a data source" is
794
+ * [MediaMetadataRetriever.getScaledFrameAtTime] — AOSP documents it as
795
+ * "useful for generating a thumbnail for an input data source", it
796
+ * accepts a local path or an http(s) URL (via range requests), and it
797
+ * needs no decoder instance, no playback, and no surface. That is
798
+ * exactly the Continue-Watching rail's requirement: many sources, no
799
+ * player, one image each.
800
+ *
801
+ * ## Contract
802
+ *
803
+ * - Resolves `null` — NEVER rejects — for every "no frame here" case:
804
+ * live/non-seekable stream, unsupported container, unreachable URL,
805
+ * position past the end of the media, no video track. `null` is the
806
+ * documented "no thumbnail, fall back to poster art" signal, so a
807
+ * consumer can render a placeholder with no `try`/`catch` and no
808
+ * blank `<Image>`.
809
+ * - Rejects ONLY on programmer error: `E_INVALID_URI` (blank uri) and
810
+ * `E_INVALID_POSITION` (NaN / Infinity / negative positionMs).
811
+ *
812
+ * ## Threading
813
+ *
814
+ * Validates synchronously (cheap, so the error reaches JS with the
815
+ * same stack the caller wrote), then hands the real work to
816
+ * [frameExecutor] — a single background thread. Opening a remote
817
+ * source, seeking and JPEG-encoding is tens of ms; doing it inline
818
+ * would stall the JS thread per rail item and risk an ANR when the
819
+ * source is on the network.
820
+ *
821
+ * ## Output
822
+ *
823
+ * `filesDir/simba-resume-thumbs/frame_<hash>_<bucketMs>.jpg`. The
824
+ * filename never contains the raw URI (a signed URL's `?`, `/` and `%`
825
+ * would break the path), and the position is bucketed to 30s so a
826
+ * drifting resume position overwrites one file instead of
827
+ * accumulating near-duplicates.
828
+ */
829
+ @ReactMethod
830
+ @Override
831
+ override fun captureFrame(
832
+ uri: String,
833
+ positionMs: Double,
834
+ options: ReadableMap?,
835
+ promise: Promise,
836
+ ) {
837
+ if (uri.isBlank()) {
838
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] blank uri, rejecting with E_INVALID_URI")
839
+ promise.reject("E_INVALID_URI", "captureFrame requires a non-empty uri")
840
+ return
841
+ }
842
+ if (positionMs.isNaN() || positionMs.isInfinite() || positionMs < 0) {
843
+ Log.w(
844
+ TAG,
845
+ "[PlaybackTrace][Bridge][captureFrame] invalid positionMs=$positionMs, rejecting with E_INVALID_POSITION",
846
+ )
847
+ promise.reject(
848
+ "E_INVALID_POSITION",
849
+ "captureFrame requires a finite, non-negative positionMs (got $positionMs)",
850
+ )
851
+ return
852
+ }
853
+
854
+ val width = readFrameOption(options, "width", DEFAULT_FRAME_WIDTH)
855
+ val height = readFrameOption(options, "height", DEFAULT_FRAME_HEIGHT)
856
+ val quality = readFrameOption(options, "quality", DEFAULT_FRAME_QUALITY).coerceIn(0, 100)
857
+ val timeUs = (positionMs * 1000.0).toLong()
858
+
859
+ try {
860
+ frameExecutor.execute {
861
+ promise.resolve(extractFrameToFile(uri, timeUs, width, height, quality))
862
+ }
863
+ } catch (e: RejectedExecutionException) {
864
+ // The module was torn down between the JS call and this
865
+ // dispatch. That is a lifecycle event, not a media error, so
866
+ // it answers with the same "no thumbnail" result every
867
+ // unavailable-frame case produces.
868
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] executor rejected: ${e.message}")
869
+ promise.resolve(null)
870
+ }
871
+ }
872
+
873
+ /**
874
+ * The actual frame extraction, always on [frameExecutor]'s thread.
875
+ * Returns the written JPEG's absolute path, or `null`.
876
+ *
877
+ * `release()` is in the `finally` and is NOT optional: an
878
+ * unreleased `MediaMetadataRetriever` pins native codec/OMX handles
879
+ * for the lifetime of the process, and a rail that extracts a frame
880
+ * per item would leak one per item until the app died.
881
+ */
882
+ private fun extractFrameToFile(
883
+ uri: String,
884
+ timeUs: Long,
885
+ width: Int,
886
+ height: Int,
887
+ quality: Int,
888
+ ): String? {
889
+ val retriever = MediaMetadataRetriever()
890
+ var bitmap: Bitmap? = null
891
+ try {
892
+ applyFrameDataSource(retriever, uri)
893
+
894
+ // A still frame needs a video track. This checks
895
+ // `METADATA_KEY_HAS_VIDEO` ("yes"/"no"), NOT
896
+ // `retriever.hasVideoTrack()` — that method does not exist on
897
+ // MediaMetadataRetriever and the Kotlin compile gate (via the
898
+ // example app) is what catches it. Audio-only and unsupported
899
+ // containers answer "no" or throw; both land on the `null`
900
+ // answer via the return below or the catch.
901
+ val hasVideo =
902
+ retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO)
903
+ if (hasVideo != null && hasVideo != "yes") {
904
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] no video track in $uri, no frame")
905
+ return null
906
+ }
907
+
908
+ // Duration guard. A live stream reports no duration, in which
909
+ // case we let the frame call below decide (it fails, and we
910
+ // return null) rather than guessing.
911
+ val durationMs =
912
+ retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L
913
+ if (durationMs > 0 && timeUs > durationMs * 1000) {
914
+ Log.w(
915
+ TAG,
916
+ "[PlaybackTrace][Bridge][captureFrame] position ${timeUs / 1000}ms is past " +
917
+ "duration ${durationMs}ms, no frame",
918
+ )
919
+ return null
920
+ }
921
+
922
+ val frame = scaledFrameAt(retriever, timeUs, width, height)
923
+ ?: run {
924
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] no frame at ${timeUs / 1000}ms in $uri")
925
+ return null
926
+ }
927
+ bitmap = frame
928
+
929
+ val dir = File(reactApplicationContext.filesDir, RESUME_THUMB_DIR)
930
+ if (!dir.exists() && !dir.mkdirs()) {
931
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] could not create $dir")
932
+ return null
933
+ }
934
+ val outFile = File(dir, frameFileName(uri, timeUs / 1000))
935
+ FileOutputStream(outFile).use { stream ->
936
+ if (!frame.compress(Bitmap.CompressFormat.JPEG, quality, stream)) {
937
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] JPEG encode failed for $outFile")
938
+ return null
939
+ }
940
+ }
941
+ Log.i(
942
+ TAG,
943
+ "[PlaybackTrace][Bridge][captureFrame] wrote $outFile (${width}x$height q=$quality)",
944
+ )
945
+ return outFile.absolutePath
946
+ } catch (e: Exception) {
947
+ // Every media failure lands here: unreachable URL, malformed
948
+ // container, decoder refusal on a non-seekable stream. All of
949
+ // them are "no thumbnail", not an error the caller should see.
950
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] extraction failed for $uri: ${e.message}", e)
951
+ return null
952
+ } finally {
953
+ bitmap?.recycle()
954
+ retriever.release()
955
+ }
956
+ }
957
+
958
+ /**
959
+ * Point [retriever] at the right data source for [uri].
960
+ *
961
+ * Which overload is correct depends on the scheme, and picking the
962
+ * wrong one fails at runtime rather than at compile time:
963
+ *
964
+ * - `content://` needs `(Context, Uri)`, which resolves through the
965
+ * ContentResolver. Nothing else can open it.
966
+ * - `http(s)://` needs the plain `String` overload — THAT is the
967
+ * one that issues byte-range requests, which is what makes
968
+ * extracting a frame from a remote file feasible at all. The
969
+ * `(Context, Uri)` overload would route a network URL through the
970
+ * ContentResolver and fail.
971
+ *
972
+ * There is deliberately no `(Context, Uri, Map<String, String>)` call.
973
+ * That overload's only purpose is to carry HTTP headers, and this
974
+ * caller has none to send; adding it meant a bare `emptyMap()` whose
975
+ * type argument could not be inferred, which made overload resolution
976
+ * fall through to `setDataSource(FileDescriptor, long, long)` and
977
+ * report three type mismatches about arguments that were never wrong.
978
+ */
979
+ private fun applyFrameDataSource(retriever: MediaMetadataRetriever, uri: String) {
980
+ if (uri.startsWith("content://")) {
981
+ retriever.setDataSource(reactApplicationContext, android.net.Uri.parse(uri))
982
+ return
983
+ }
984
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
985
+ retriever.setDataSource(uri)
986
+ return
987
+ }
988
+ val path = if (uri.startsWith("file://")) android.net.Uri.parse(uri).path ?: uri else uri
989
+ retriever.setDataSource(path)
990
+ }
991
+
992
+ /**
993
+ * Frame grab with the platform's scaling API on API 27+, and an
994
+ * explicit decode-then-scale below it (minSdk here is 24).
995
+ *
996
+ * `width`/`height` of 0 mean "unconstrained" — the platform then
997
+ * keeps the source aspect ratio instead of forcing the frame into
998
+ * the requested box, which is what a portrait source in a 16:9
999
+ * default box needs.
1000
+ */
1001
+ private fun scaledFrameAt(
1002
+ retriever: MediaMetadataRetriever,
1003
+ timeUs: Long,
1004
+ width: Int,
1005
+ height: Int,
1006
+ ): Bitmap? {
1007
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O_MR1) {
1008
+ return retriever.getScaledFrameAtTime(
1009
+ timeUs,
1010
+ MediaMetadataRetriever.OPTION_CLOSEST_SYNC,
1011
+ width,
1012
+ height,
1013
+ )
1014
+ }
1015
+ val full = retriever.getFrameAtTime(timeUs, MediaMetadataRetriever.OPTION_CLOSEST_SYNC)
1016
+ ?: return null
1017
+ if (width <= 0 && height <= 0) return full
1018
+ val targetH = if (height > 0) height else full.height
1019
+ val targetW = if (width > 0) {
1020
+ width
1021
+ } else {
1022
+ (full.width.toDouble() * targetH / full.height).toInt().coerceAtLeast(1)
1023
+ }
1024
+ if (targetW == full.width && targetH == full.height) return full
1025
+ return Bitmap.createScaledBitmap(full, targetW, targetH, true)
1026
+ }
1027
+
1028
+ /**
1029
+ * `frame_<hash>_<bucketMs>.jpg` — same `hashCode() and 0x7FFFFFFF`
1030
+ * idiom [captureThumbnail] uses, so the two stay visually
1031
+ * consistent, plus the coarse position bucket.
1032
+ */
1033
+ private fun frameFileName(uri: String, positionMs: Long): String {
1034
+ val hash = uri.hashCode().toLong() and 0x7FFFFFFF
1035
+ val bucket = (positionMs / FRAME_POSITION_BUCKET_MS) * FRAME_POSITION_BUCKET_MS
1036
+ return "frame_${hash}_${bucket}.jpg"
1037
+ }
1038
+
1039
+ /**
1040
+ * Read one integer-ish option out of the JS options map, falling back
1041
+ * to the default when the key is absent, null, not a number, or
1042
+ * negative. Never throws — a malformed option is a missing option.
1043
+ */
1044
+ private fun readFrameOption(options: ReadableMap?, key: String, fallback: Int): Int {
1045
+ if (options == null || !options.hasKey(key) || options.isNull(key)) return fallback
1046
+ return try {
1047
+ val value = options.getDouble(key)
1048
+ if (value.isNaN() || value.isInfinite() || value < 0) fallback else value.toInt()
1049
+ } catch (e: Exception) {
1050
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] option '$key' is not a number: ${e.message}")
1051
+ fallback
1052
+ }
1053
+ }
1054
+
668
1055
  // ── File Loading ───────────────────────────────────────────────────────
669
1056
 
670
1057
  @ReactMethod
@@ -1405,6 +1792,13 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1405
1792
  // apart during dev reload, or never on release builds).
1406
1793
  instance = null
1407
1794
  pendingObservedProperties.clear()
1795
+ // `frameExecutor` (captureFrame) is per-instance, so without this
1796
+ // a debug reload leaves an idle "simba-frame-extractor" thread
1797
+ // behind for every module instance the app has ever built.
1798
+ // Queued-but-unstarted tasks are dropped; an in-flight
1799
+ // extraction finishes and its (now-unused) retriever releases
1800
+ // itself in its own `finally`.
1801
+ frameExecutor.shutdown()
1408
1802
  super.onCatalystInstanceDestroy()
1409
1803
  }
1410
1804
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.9.4",
3
+ "version": "1.11.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",