@simba-dev/react-native-media-player 1.10.0 → 1.12.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,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
@@ -13,8 +19,8 @@ import com.facebook.react.module.annotations.ReactModule
13
19
  import com.facebook.react.modules.core.DeviceEventManagerModule
14
20
  import com.facebook.fbreact.specs.NativeMpvPlayerSpec
15
21
  import com.simba.player.IMpvConfigProvider
16
- import com.simba.player.IMpvNativePtrProvider
17
22
  import com.simba.player.IPipModeChangeEmitter
23
+ import com.simba.player.PlaybackHost
18
24
  import org.json.JSONArray
19
25
  import org.json.JSONObject
20
26
 
@@ -28,13 +34,41 @@ import org.json.JSONObject
28
34
  class MpvBridgeModule(reactContext: ReactApplicationContext) :
29
35
  NativeMpvPlayerSpec(reactContext),
30
36
  IMpvConfigProvider,
31
- IMpvNativePtrProvider,
32
37
  IPipModeChangeEmitter {
33
38
 
34
39
  companion object {
35
40
  const val NAME = "MpvPlayerModule"
36
41
  private const val TAG = "MpvBridgeModule"
37
42
 
43
+ // ── captureFrame: resume-rail thumbnails ──────────────────────────
44
+ // `MediaMetadataRetriever` needs a real filesystem path for its
45
+ // output. `filesDir` (NOT cacheDir) is deliberate: the platform
46
+ // is free to evict cacheDir at any moment, and a thumbnail that
47
+ // disappears silently blanks a Continue-Watching cell on the
48
+ // next cold start with no error anywhere.
49
+ private const val RESUME_THUMB_DIR = "simba-resume-thumbs"
50
+
51
+ // Poster-sized defaults, mirrored in TS as
52
+ // `DEFAULT_FRAME_WIDTH` / `DEFAULT_FRAME_HEIGHT` /
53
+ // `DEFAULT_FRAME_QUALITY` (src/hooks/useResumeThumbnail.ts).
54
+ //
55
+ // 640x360 is exactly 16:9, so the dominant case (film / TV /
56
+ // YouTube landscape video) scales without distortion, and
57
+ // ~230 kpx lands around 25-40 kB per JPEG at quality 80.
58
+ // Portrait sources should pass `width = 0`, which the platform
59
+ // reads as "leave the width unconstrained" so the source
60
+ // aspect ratio survives.
61
+ private const val DEFAULT_FRAME_WIDTH = 640
62
+ private const val DEFAULT_FRAME_HEIGHT = 360
63
+ private const val DEFAULT_FRAME_QUALITY = 80
64
+
65
+ // Position granularity for the output filename. A resume
66
+ // position drifts by seconds between renders (and the user may
67
+ // stop anywhere), so bucketing to 30s means repeated calls for
68
+ // "roughly where they left off" overwrite ONE file instead of
69
+ // re-encoding a near-duplicate JPEG on every scroll/re-render.
70
+ private const val FRAME_POSITION_BUCKET_MS = 30_000L
71
+
38
72
  // v1.10.0 — hot-path property tracing.
39
73
  //
40
74
  // `time-pos` is mpv's per-frame property, so tracing every property
@@ -251,8 +285,24 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
251
285
 
252
286
  // ── State ──────────────────────────────────────────────────────────────
253
287
 
254
- /** Native mpv_handle* stored as Long (0 = uninitialized). */
255
- private var nativePtr: Long = 0
288
+ /**
289
+ * V20 Phase A: the libmpv handle, *delegated* to [PlaybackHost].
290
+ *
291
+ * This is deliberately a property, not a field. It holds no state of
292
+ * its own — [PlaybackHost] is the single owner, because the handle is
293
+ * a process-global in C++ (`g_mpv`) and a React Native TurboModule
294
+ * dies with its React context, which would leave the handle owned by
295
+ * something that is not alive when playback still needs it.
296
+ *
297
+ * Keeping the name means the ~30 existing read sites are unchanged;
298
+ * what changed is that a read can no longer return a stale copy,
299
+ * because there is no longer a copy to be stale.
300
+ */
301
+ private var nativePtr: Long
302
+ get() = PlaybackHost.handle()
303
+ set(value) {
304
+ if (value == 0L) PlaybackHost.clearHandle() else PlaybackHost.publishHandle(value)
305
+ }
256
306
 
257
307
  /** Event emitter for JS-side event listeners. */
258
308
  private val eventEmitter: DeviceEventManagerModule.RCTDeviceEventEmitter by lazy {
@@ -266,6 +316,31 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
266
316
  */
267
317
  private val pendingObservedProperties = linkedSetOf<String>()
268
318
 
319
+ /**
320
+ * Serial executor for [captureFrame].
321
+ *
322
+ * Two things force it to exist at all:
323
+ * 1. `MediaMetadataRetriever.getScaledFrameAtTime()` does real
324
+ * I/O — opening a (possibly remote, range-requested) source,
325
+ * seeking a decoder, and JPEG-encoding the result. On a cold
326
+ * Continue-Watching rail that is tens of ms PER ITEM, which on
327
+ * the JS or UI thread is a dropped-frame stall (and on the UI
328
+ * thread, an ANR if the source is remote). The existing
329
+ * `screenshot()` is a blocking-sync `@ReactMethod` and must NOT
330
+ * be used as a template for this.
331
+ * 2. `MediaMetadataRetriever` holds native codec handles. Two
332
+ * concurrent retrievers on the same source multiply peak
333
+ * memory, so requests are queued on ONE thread and the
334
+ * in-flight count stays at exactly 1.
335
+ *
336
+ * Shut down in `onCatalystInstanceDestroy` so a dev reload does
337
+ * not leave an idle thread behind per module instance.
338
+ */
339
+ private val frameExecutor: ExecutorService =
340
+ Executors.newSingleThreadExecutor { runnable ->
341
+ Thread(runnable, "simba-frame-extractor")
342
+ }
343
+
269
344
  // ── MPVLib Listener → JS Event Bridge ──────────────────────────────────
270
345
 
271
346
  private val mpvListener = object : MPVLib.MpvEventListener {
@@ -694,6 +769,22 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
694
769
  *
695
770
  * The thumbnail persists in cache and is used by the recent-files list to
696
771
  * show a preview of where the user left off.
772
+ *
773
+ * ## NAME WARNING — this is the LIVE-frame capture
774
+ *
775
+ * `captureThumbnail` reads as "thumbnail for this uri", but the `uri`
776
+ * is used for NOTHING except hashing the output filename. The pixels
777
+ * come from `MPVLib.nativeScreenshot(nativePtr, ...)`, i.e. whatever
778
+ * the one initialised mpv handle is showing right now. So it:
779
+ * - requires `initPlayer()` to have run (`ensurePtr()`),
780
+ * - requires that something is actually loaded (pause counts, an
781
+ * empty player yields mpv's "no video" error string),
782
+ * - CANNOT target a position — there is no time argument.
783
+ *
784
+ * It is kept exactly as-is for backwards compatibility. Callers that
785
+ * want "the frame at position X" — resume rails, scrub previews,
786
+ * bookmark art — must use [captureFrame], which takes a timestamp
787
+ * and needs no player instance at all.
697
788
  */
698
789
  @ReactMethod(isBlockingSynchronousMethod = true)
699
790
  @Override
@@ -705,6 +796,277 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
705
796
  return MPVLib.nativeScreenshot(nativePtr, thumbFile.absolutePath)
706
797
  }
707
798
 
799
+ /**
800
+ * Extract ONE frame at [positionMs] from [uri] and write it as a JPEG.
801
+ * Resolves the absolute file path, or `null` when no frame exists.
802
+ *
803
+ * ## Why a separate method (not `captureThumbnail`)
804
+ *
805
+ * The "frame where the user left off" thumbnail cannot come from mpv:
806
+ * `captureThumbnail` has no time argument, needs a live player, and
807
+ * grabs the current surface (see its NAME WARNING above). Android's
808
+ * standard API for "make a thumbnail from a data source" is
809
+ * [MediaMetadataRetriever.getScaledFrameAtTime] — AOSP documents it as
810
+ * "useful for generating a thumbnail for an input data source", it
811
+ * accepts a local path or an http(s) URL (via range requests), and it
812
+ * needs no decoder instance, no playback, and no surface. That is
813
+ * exactly the Continue-Watching rail's requirement: many sources, no
814
+ * player, one image each.
815
+ *
816
+ * ## Contract
817
+ *
818
+ * - Resolves `null` — NEVER rejects — for every "no frame here" case:
819
+ * live/non-seekable stream, unsupported container, unreachable URL,
820
+ * position past the end of the media, no video track. `null` is the
821
+ * documented "no thumbnail, fall back to poster art" signal, so a
822
+ * consumer can render a placeholder with no `try`/`catch` and no
823
+ * blank `<Image>`.
824
+ * - Rejects ONLY on programmer error: `E_INVALID_URI` (blank uri) and
825
+ * `E_INVALID_POSITION` (NaN / Infinity / negative positionMs).
826
+ *
827
+ * ## Threading
828
+ *
829
+ * Validates synchronously (cheap, so the error reaches JS with the
830
+ * same stack the caller wrote), then hands the real work to
831
+ * [frameExecutor] — a single background thread. Opening a remote
832
+ * source, seeking and JPEG-encoding is tens of ms; doing it inline
833
+ * would stall the JS thread per rail item and risk an ANR when the
834
+ * source is on the network.
835
+ *
836
+ * ## Output
837
+ *
838
+ * `filesDir/simba-resume-thumbs/frame_<hash>_<bucketMs>.jpg`. The
839
+ * filename never contains the raw URI (a signed URL's `?`, `/` and `%`
840
+ * would break the path), and the position is bucketed to 30s so a
841
+ * drifting resume position overwrites one file instead of
842
+ * accumulating near-duplicates.
843
+ */
844
+ @ReactMethod
845
+ @Override
846
+ override fun captureFrame(
847
+ uri: String,
848
+ positionMs: Double,
849
+ options: ReadableMap?,
850
+ promise: Promise,
851
+ ) {
852
+ if (uri.isBlank()) {
853
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] blank uri, rejecting with E_INVALID_URI")
854
+ promise.reject("E_INVALID_URI", "captureFrame requires a non-empty uri")
855
+ return
856
+ }
857
+ if (positionMs.isNaN() || positionMs.isInfinite() || positionMs < 0) {
858
+ Log.w(
859
+ TAG,
860
+ "[PlaybackTrace][Bridge][captureFrame] invalid positionMs=$positionMs, rejecting with E_INVALID_POSITION",
861
+ )
862
+ promise.reject(
863
+ "E_INVALID_POSITION",
864
+ "captureFrame requires a finite, non-negative positionMs (got $positionMs)",
865
+ )
866
+ return
867
+ }
868
+
869
+ val width = readFrameOption(options, "width", DEFAULT_FRAME_WIDTH)
870
+ val height = readFrameOption(options, "height", DEFAULT_FRAME_HEIGHT)
871
+ val quality = readFrameOption(options, "quality", DEFAULT_FRAME_QUALITY).coerceIn(0, 100)
872
+ val timeUs = (positionMs * 1000.0).toLong()
873
+
874
+ try {
875
+ frameExecutor.execute {
876
+ promise.resolve(extractFrameToFile(uri, timeUs, width, height, quality))
877
+ }
878
+ } catch (e: RejectedExecutionException) {
879
+ // The module was torn down between the JS call and this
880
+ // dispatch. That is a lifecycle event, not a media error, so
881
+ // it answers with the same "no thumbnail" result every
882
+ // unavailable-frame case produces.
883
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] executor rejected: ${e.message}")
884
+ promise.resolve(null)
885
+ }
886
+ }
887
+
888
+ /**
889
+ * The actual frame extraction, always on [frameExecutor]'s thread.
890
+ * Returns the written JPEG's absolute path, or `null`.
891
+ *
892
+ * `release()` is in the `finally` and is NOT optional: an
893
+ * unreleased `MediaMetadataRetriever` pins native codec/OMX handles
894
+ * for the lifetime of the process, and a rail that extracts a frame
895
+ * per item would leak one per item until the app died.
896
+ */
897
+ private fun extractFrameToFile(
898
+ uri: String,
899
+ timeUs: Long,
900
+ width: Int,
901
+ height: Int,
902
+ quality: Int,
903
+ ): String? {
904
+ val retriever = MediaMetadataRetriever()
905
+ var bitmap: Bitmap? = null
906
+ try {
907
+ applyFrameDataSource(retriever, uri)
908
+
909
+ // A still frame needs a video track. This checks
910
+ // `METADATA_KEY_HAS_VIDEO` ("yes"/"no"), NOT
911
+ // `retriever.hasVideoTrack()` — that method does not exist on
912
+ // MediaMetadataRetriever and the Kotlin compile gate (via the
913
+ // example app) is what catches it. Audio-only and unsupported
914
+ // containers answer "no" or throw; both land on the `null`
915
+ // answer via the return below or the catch.
916
+ val hasVideo =
917
+ retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO)
918
+ if (hasVideo != null && hasVideo != "yes") {
919
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] no video track in $uri, no frame")
920
+ return null
921
+ }
922
+
923
+ // Duration guard. A live stream reports no duration, in which
924
+ // case we let the frame call below decide (it fails, and we
925
+ // return null) rather than guessing.
926
+ val durationMs =
927
+ retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L
928
+ if (durationMs > 0 && timeUs > durationMs * 1000) {
929
+ Log.w(
930
+ TAG,
931
+ "[PlaybackTrace][Bridge][captureFrame] position ${timeUs / 1000}ms is past " +
932
+ "duration ${durationMs}ms, no frame",
933
+ )
934
+ return null
935
+ }
936
+
937
+ val frame = scaledFrameAt(retriever, timeUs, width, height)
938
+ ?: run {
939
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] no frame at ${timeUs / 1000}ms in $uri")
940
+ return null
941
+ }
942
+ bitmap = frame
943
+
944
+ val dir = File(reactApplicationContext.filesDir, RESUME_THUMB_DIR)
945
+ if (!dir.exists() && !dir.mkdirs()) {
946
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] could not create $dir")
947
+ return null
948
+ }
949
+ val outFile = File(dir, frameFileName(uri, timeUs / 1000))
950
+ FileOutputStream(outFile).use { stream ->
951
+ if (!frame.compress(Bitmap.CompressFormat.JPEG, quality, stream)) {
952
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] JPEG encode failed for $outFile")
953
+ return null
954
+ }
955
+ }
956
+ Log.i(
957
+ TAG,
958
+ "[PlaybackTrace][Bridge][captureFrame] wrote $outFile (${width}x$height q=$quality)",
959
+ )
960
+ return outFile.absolutePath
961
+ } catch (e: Exception) {
962
+ // Every media failure lands here: unreachable URL, malformed
963
+ // container, decoder refusal on a non-seekable stream. All of
964
+ // them are "no thumbnail", not an error the caller should see.
965
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] extraction failed for $uri: ${e.message}", e)
966
+ return null
967
+ } finally {
968
+ bitmap?.recycle()
969
+ retriever.release()
970
+ }
971
+ }
972
+
973
+ /**
974
+ * Point [retriever] at the right data source for [uri].
975
+ *
976
+ * Which overload is correct depends on the scheme, and picking the
977
+ * wrong one fails at runtime rather than at compile time:
978
+ *
979
+ * - `content://` needs `(Context, Uri)`, which resolves through the
980
+ * ContentResolver. Nothing else can open it.
981
+ * - `http(s)://` needs the plain `String` overload — THAT is the
982
+ * one that issues byte-range requests, which is what makes
983
+ * extracting a frame from a remote file feasible at all. The
984
+ * `(Context, Uri)` overload would route a network URL through the
985
+ * ContentResolver and fail.
986
+ *
987
+ * There is deliberately no `(Context, Uri, Map<String, String>)` call.
988
+ * That overload's only purpose is to carry HTTP headers, and this
989
+ * caller has none to send; adding it meant a bare `emptyMap()` whose
990
+ * type argument could not be inferred, which made overload resolution
991
+ * fall through to `setDataSource(FileDescriptor, long, long)` and
992
+ * report three type mismatches about arguments that were never wrong.
993
+ */
994
+ private fun applyFrameDataSource(retriever: MediaMetadataRetriever, uri: String) {
995
+ if (uri.startsWith("content://")) {
996
+ retriever.setDataSource(reactApplicationContext, android.net.Uri.parse(uri))
997
+ return
998
+ }
999
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
1000
+ retriever.setDataSource(uri)
1001
+ return
1002
+ }
1003
+ val path = if (uri.startsWith("file://")) android.net.Uri.parse(uri).path ?: uri else uri
1004
+ retriever.setDataSource(path)
1005
+ }
1006
+
1007
+ /**
1008
+ * Frame grab with the platform's scaling API on API 27+, and an
1009
+ * explicit decode-then-scale below it (minSdk here is 24).
1010
+ *
1011
+ * `width`/`height` of 0 mean "unconstrained" — the platform then
1012
+ * keeps the source aspect ratio instead of forcing the frame into
1013
+ * the requested box, which is what a portrait source in a 16:9
1014
+ * default box needs.
1015
+ */
1016
+ private fun scaledFrameAt(
1017
+ retriever: MediaMetadataRetriever,
1018
+ timeUs: Long,
1019
+ width: Int,
1020
+ height: Int,
1021
+ ): Bitmap? {
1022
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O_MR1) {
1023
+ return retriever.getScaledFrameAtTime(
1024
+ timeUs,
1025
+ MediaMetadataRetriever.OPTION_CLOSEST_SYNC,
1026
+ width,
1027
+ height,
1028
+ )
1029
+ }
1030
+ val full = retriever.getFrameAtTime(timeUs, MediaMetadataRetriever.OPTION_CLOSEST_SYNC)
1031
+ ?: return null
1032
+ if (width <= 0 && height <= 0) return full
1033
+ val targetH = if (height > 0) height else full.height
1034
+ val targetW = if (width > 0) {
1035
+ width
1036
+ } else {
1037
+ (full.width.toDouble() * targetH / full.height).toInt().coerceAtLeast(1)
1038
+ }
1039
+ if (targetW == full.width && targetH == full.height) return full
1040
+ return Bitmap.createScaledBitmap(full, targetW, targetH, true)
1041
+ }
1042
+
1043
+ /**
1044
+ * `frame_<hash>_<bucketMs>.jpg` — same `hashCode() and 0x7FFFFFFF`
1045
+ * idiom [captureThumbnail] uses, so the two stay visually
1046
+ * consistent, plus the coarse position bucket.
1047
+ */
1048
+ private fun frameFileName(uri: String, positionMs: Long): String {
1049
+ val hash = uri.hashCode().toLong() and 0x7FFFFFFF
1050
+ val bucket = (positionMs / FRAME_POSITION_BUCKET_MS) * FRAME_POSITION_BUCKET_MS
1051
+ return "frame_${hash}_${bucket}.jpg"
1052
+ }
1053
+
1054
+ /**
1055
+ * Read one integer-ish option out of the JS options map, falling back
1056
+ * to the default when the key is absent, null, not a number, or
1057
+ * negative. Never throws — a malformed option is a missing option.
1058
+ */
1059
+ private fun readFrameOption(options: ReadableMap?, key: String, fallback: Int): Int {
1060
+ if (options == null || !options.hasKey(key) || options.isNull(key)) return fallback
1061
+ return try {
1062
+ val value = options.getDouble(key)
1063
+ if (value.isNaN() || value.isInfinite() || value < 0) fallback else value.toInt()
1064
+ } catch (e: Exception) {
1065
+ Log.w(TAG, "[PlaybackTrace][Bridge][captureFrame] option '$key' is not a number: ${e.message}")
1066
+ fallback
1067
+ }
1068
+ }
1069
+
708
1070
  // ── File Loading ───────────────────────────────────────────────────────
709
1071
 
710
1072
  @ReactMethod
@@ -1445,6 +1807,13 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1445
1807
  // apart during dev reload, or never on release builds).
1446
1808
  instance = null
1447
1809
  pendingObservedProperties.clear()
1810
+ // `frameExecutor` (captureFrame) is per-instance, so without this
1811
+ // a debug reload leaves an idle "simba-frame-extractor" thread
1812
+ // behind for every module instance the app has ever built.
1813
+ // Queued-but-unstarted tasks are dropped; an in-flight
1814
+ // extraction finishes and its (now-unused) retriever releases
1815
+ // itself in its own `finally`.
1816
+ frameExecutor.shutdown()
1448
1817
  super.onCatalystInstanceDestroy()
1449
1818
  }
1450
1819
 
@@ -1867,21 +2236,23 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
1867
2236
  // ── Native Pointer (for MpvRenderView) ─────────────────────────────────
1868
2237
 
1869
2238
  /**
1870
- * Phase 7: module-side accessor (Long) used by `PlayerActivity` (which
1871
- * lives in the `@simba/react-native-media-player` module and therefore
1872
- * cannot reference `MpvBridgeModule` directly) to obtain the active
1873
- * libmpv handle without crossing the Gradle module boundary.
2239
+ * The JS-facing pointer accessor.
2240
+ *
2241
+ * V20 Phase A removed its `IMpvNativePtrProvider` sibling. That
2242
+ * interface existed so `PlayerActivity` could fetch the handle across
2243
+ * a Gradle module boundary — a boundary Phase 6 had already removed
2244
+ * (see `MPVLib`'s own header). `PlayerActivity` now reads
2245
+ * `PlaybackHost` directly and registers with `whenAvailable`, so the
2246
+ * interface had no remaining consumer and was deleted rather than
2247
+ * left in place as fiction.
1874
2248
  *
1875
- * The JS-facing @ReactMethod below stays as-is to keep the public
1876
- * TurboModule API stable. The two methods share the same private
1877
- * `nativePtr` field, so they can never disagree.
2249
+ * This method stays because it is part of the published TurboModule
2250
+ * spec and removing it would be a breaking change for consumers.
1878
2251
  */
1879
- override fun fetchNativePtr(): Long = nativePtr
1880
-
1881
2252
  @ReactMethod(isBlockingSynchronousMethod = true)
1882
2253
  @Override
1883
2254
  override fun getNativePtr(): Double {
1884
- return nativePtr.toDouble()
2255
+ return PlaybackHost.handle().toDouble()
1885
2256
  }
1886
2257
 
1887
2258
  // ── Helpers ────────────────────────────────────────────────────────────
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simba-dev/react-native-media-player",
3
- "version": "1.10.0",
3
+ "version": "1.12.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",
@@ -153,6 +153,27 @@ export interface PlayerEventPayloads {
153
153
  // Bridge surface (V13 Phase 50a — 78 methods)
154
154
  // ═══════════════════════════════════════════════════════════════════════════
155
155
 
156
+ /**
157
+ * Output geometry + JPEG quality for `captureFrame`.
158
+ *
159
+ * Every field is optional; an omitted field falls back to the
160
+ * poster-sized default the native side applies (mirrored in TS as
161
+ * `DEFAULT_FRAME_WIDTH` / `DEFAULT_FRAME_HEIGHT` /
162
+ * `DEFAULT_FRAME_QUALITY`, exported from `hooks/useResumeThumbnail`).
163
+ */
164
+ export interface CaptureFrameOptions {
165
+ /**
166
+ * Target width in pixels. `0` means "do not constrain width" —
167
+ * the platform then keeps the source aspect ratio instead of
168
+ * squashing the frame into the requested box.
169
+ */
170
+ readonly width?: number;
171
+ /** Target height in pixels. `0` means "leave the frame unscaled". */
172
+ readonly height?: number;
173
+ /** JPEG quality, 0–100. Out-of-range values are clamped natively. */
174
+ readonly quality?: number;
175
+ }
176
+
156
177
  /**
157
178
  * Typed shape of the `MpvPlayerModule` native bridge as exposed by
158
179
  * `MpvBridgeModule.kt`. V13 Phase 50 expands the Phase 24 entry point
@@ -225,8 +246,39 @@ export interface MpvPlayerModuleBridge {
225
246
  getFileInfo(): string;
226
247
  /** Get the currently-loaded video params as a JSON string. */
227
248
  getVideoParams(): string;
228
- /** Capture a thumbnail screenshot for the given URI; returns the file path. */
249
+ /**
250
+ * LIVE-FRAME capture — the name is misleading, read this first.
251
+ *
252
+ * The `uri` argument is used ONLY to derive the output filename
253
+ * (`thumb_${hash}.png`); the pixels come from the currently
254
+ * initialised mpv handle. It therefore needs a live player AND a
255
+ * loaded file, and it cannot target a position.
256
+ *
257
+ * For a "thumbnail at position X" (resume rails, scrub previews,
258
+ * bookmark art) use `captureFrame` instead — that one takes a
259
+ * timestamp and needs no player at all.
260
+ */
229
261
  captureThumbnail(uri: string): string;
262
+ /**
263
+ * Extract one frame at `positionMs` from `uri` — WITHOUT a player
264
+ * instance, without playback, and without the mpv surface.
265
+ *
266
+ * The native implementation is
267
+ * `MediaMetadataRetriever.getScaledFrameAtTime()`, so it accepts a
268
+ * local path, `file://`, or an `http(s)` URL (fetched with range
269
+ * requests).
270
+ *
271
+ * **Resolves `null` — never rejects — when no frame exists:**
272
+ * live stream, unsupported container, unreachable URL, position
273
+ * past the end. `null` is the "no thumbnail, show poster art"
274
+ * signal, not a failure. Rejection is reserved for programmer
275
+ * error (blank `uri`, non-finite or negative `positionMs`).
276
+ */
277
+ captureFrame(
278
+ uri: string,
279
+ positionMs: number,
280
+ options?: CaptureFrameOptions,
281
+ ): Promise<string | null>;
230
282
  /** Take a persistable read URI permission for a content:// URI. */
231
283
  grantPersistablePermission(uri: string): void;
232
284
  /** Returns true when the URI is still readable (content:// or file://). */
@@ -473,6 +525,21 @@ const NOOP_BRIDGE: MpvPlayerModuleBridge = {
473
525
  void _uri;
474
526
  return '';
475
527
  },
528
+ // No-op fallback resolves `null` — the same "no frame available,
529
+ // use poster art" answer the real native path returns for a live
530
+ // stream or an unreachable URL. It must NOT reject, or every
531
+ // jest/Storybook/web host would see a red screen where a consumer
532
+ // sees a placeholder image.
533
+ captureFrame: (
534
+ _uri: string,
535
+ _positionMs: number,
536
+ _options?: CaptureFrameOptions,
537
+ ) => {
538
+ void _uri;
539
+ void _positionMs;
540
+ void _options;
541
+ return Promise.resolve(null);
542
+ },
476
543
  grantPersistablePermission: (_uri: string) => {
477
544
  void _uri;
478
545
  },
@@ -72,7 +72,37 @@ export interface Spec extends TurboModule {
72
72
  loadPlaylist(paths: ReadonlyArray<string>, startIndex: number): void;
73
73
  getFileInfo(): string;
74
74
  getVideoParams(): string;
75
+ /**
76
+ * LIVE-FRAME capture. `uri` is used ONLY to derive the output
77
+ * filename (`thumb_${hash}.png`) — the pixels come from whatever
78
+ * mpv is playing right now, so this requires an initialised
79
+ * player AND a running/paused playback session. Do NOT use it
80
+ * for a "thumbnail at position X"; see `captureFrame` below.
81
+ */
75
82
  captureThumbnail(uri: string): string;
83
+ /**
84
+ * Extract a single frame at `positionMs` from `uri` WITHOUT a
85
+ * player instance, via `MediaMetadataRetriever
86
+ * .getScaledFrameAtTime()`. Works on a local path, `file://`, or
87
+ * an `http(s)` URL (range requests) — no mpv handle, no
88
+ * playback, no surface.
89
+ *
90
+ * Rejects ONLY for programmer error (blank `uri`, non-finite or
91
+ * negative `positionMs`). Every "cannot get a frame" outcome —
92
+ * live stream, unsupported container, unreachable URL, position
93
+ * past the end of the file — resolves `null`, which is the
94
+ * documented "no thumbnail, fall back to poster art" signal and
95
+ * NOT an error.
96
+ *
97
+ * Options are all optional; the Kotlin side substitutes a
98
+ * poster-sized default. `width: 0` means "do not constrain width"
99
+ * (the platform then preserves the source aspect ratio).
100
+ */
101
+ captureFrame(
102
+ uri: string,
103
+ positionMs: number,
104
+ options?: {width: number; height: number; quality: number},
105
+ ): Promise<string | null>;
76
106
  grantPersistablePermission(uri: string): void;
77
107
  verifyContentUri(uri: string): boolean;
78
108