@simba-dev/react-native-media-player 1.10.0 → 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.
- package/android/src/main/java/com/simba/player/mpv/MpvBridgeModule.kt +354 -0
- package/package.json +1 -1
- package/src/bridge/MpvPlayerModule.ts +68 -1
- package/src/bridge/NativeMpvPlayer.ts +30 -0
- package/src/hooks/__tests__/useResumeThumbnail.test.ts +154 -0
- package/src/hooks/useResumeThumbnail.ts +153 -0
- package/src/index.ts +12 -0
|
@@ -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,35 @@ 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
|
+
|
|
38
73
|
// v1.10.0 — hot-path property tracing.
|
|
39
74
|
//
|
|
40
75
|
// `time-pos` is mpv's per-frame property, so tracing every property
|
|
@@ -266,6 +301,31 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
|
|
|
266
301
|
*/
|
|
267
302
|
private val pendingObservedProperties = linkedSetOf<String>()
|
|
268
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
|
+
|
|
269
329
|
// ── MPVLib Listener → JS Event Bridge ──────────────────────────────────
|
|
270
330
|
|
|
271
331
|
private val mpvListener = object : MPVLib.MpvEventListener {
|
|
@@ -694,6 +754,22 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
|
|
|
694
754
|
*
|
|
695
755
|
* The thumbnail persists in cache and is used by the recent-files list to
|
|
696
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.
|
|
697
773
|
*/
|
|
698
774
|
@ReactMethod(isBlockingSynchronousMethod = true)
|
|
699
775
|
@Override
|
|
@@ -705,6 +781,277 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
|
|
|
705
781
|
return MPVLib.nativeScreenshot(nativePtr, thumbFile.absolutePath)
|
|
706
782
|
}
|
|
707
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
|
+
|
|
708
1055
|
// ── File Loading ───────────────────────────────────────────────────────
|
|
709
1056
|
|
|
710
1057
|
@ReactMethod
|
|
@@ -1445,6 +1792,13 @@ class MpvBridgeModule(reactContext: ReactApplicationContext) :
|
|
|
1445
1792
|
// apart during dev reload, or never on release builds).
|
|
1446
1793
|
instance = null
|
|
1447
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()
|
|
1448
1802
|
super.onCatalystInstanceDestroy()
|
|
1449
1803
|
}
|
|
1450
1804
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simba-dev/react-native-media-player",
|
|
3
|
-
"version": "1.
|
|
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",
|
|
@@ -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
|
-
/**
|
|
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
|
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unit tests for the public `captureFrame` wrapper
|
|
3
|
+
* (`src/hooks/useResumeThumbnail.ts`).
|
|
4
|
+
*
|
|
5
|
+
* What is testable at the JS level is the wrapper's own contract,
|
|
6
|
+
* not the extraction itself — the pixels come from
|
|
7
|
+
* `MediaMetadataRetriever` on a native background thread and are
|
|
8
|
+
* exercised on-device:
|
|
9
|
+
*
|
|
10
|
+
* - `null` (never a rejection) is passed through for "no frame
|
|
11
|
+
* available" — the live stream / unsupported container /
|
|
12
|
+
* unreachable URL / past-the-end cases,
|
|
13
|
+
* - a resolved absolute path is passed through unchanged,
|
|
14
|
+
* - programmer error rejects with the documented `E_*` codes
|
|
15
|
+
* BEFORE any bridge call happens,
|
|
16
|
+
* - omitted options are filled in with the poster-sized defaults,
|
|
17
|
+
* and the options object is ALWAYS sent (the codegen'd TurboModule
|
|
18
|
+
* signature is positional, so an absent 3rd argument is an arity
|
|
19
|
+
* hazard rather than a clean null),
|
|
20
|
+
* - a partial options object only overrides what it names.
|
|
21
|
+
*
|
|
22
|
+
* The bridge itself is the global `NativeModules.MpvPlayerModule`
|
|
23
|
+
* mock installed in `jest.setup.ts`; `getMpvPlayerModule()` returns
|
|
24
|
+
* that instance because the mock satisfies `resolveBridge()`.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { NativeModules } from 'react-native';
|
|
28
|
+
import {
|
|
29
|
+
captureFrame,
|
|
30
|
+
DEFAULT_FRAME_WIDTH,
|
|
31
|
+
DEFAULT_FRAME_HEIGHT,
|
|
32
|
+
DEFAULT_FRAME_QUALITY,
|
|
33
|
+
} from '../useResumeThumbnail';
|
|
34
|
+
|
|
35
|
+
const nativeCaptureFrame = NativeModules.MpvPlayerModule
|
|
36
|
+
.captureFrame as jest.Mock;
|
|
37
|
+
|
|
38
|
+
describe('captureFrame', () => {
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
nativeCaptureFrame.mockClear();
|
|
41
|
+
nativeCaptureFrame.mockResolvedValue(null);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
describe('the null contract', () => {
|
|
45
|
+
it('resolves null without throwing when no frame is available', async () => {
|
|
46
|
+
await expect(captureFrame('https://cdn.test/a.mkv', 42_000)).resolves.toBeNull();
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('does not reject — null is the documented fallback signal', async () => {
|
|
50
|
+
// A rejection here would force every consumer into a try/catch
|
|
51
|
+
// and would break the no-op bridge hosts (jest / web preview),
|
|
52
|
+
// which resolve null rather than throw.
|
|
53
|
+
const result = await captureFrame('file:///movies/a.mp4', 0).catch(
|
|
54
|
+
(e: unknown) => `rejected: ${String(e)}`,
|
|
55
|
+
);
|
|
56
|
+
expect(result).toBeNull();
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('passes a resolved absolute path through unchanged', async () => {
|
|
60
|
+
const path = '/data/user/0/com.simba/files/simba-resume-thumbs/frame_1_30000.jpg';
|
|
61
|
+
nativeCaptureFrame.mockResolvedValue(path);
|
|
62
|
+
await expect(captureFrame('file:///movies/a.mp4', 31_000)).resolves.toBe(path);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
describe('programmer errors', () => {
|
|
67
|
+
it('rejects a blank uri with E_INVALID_URI and never touches the bridge', async () => {
|
|
68
|
+
await expect(captureFrame(' ', 1000)).rejects.toMatchObject({
|
|
69
|
+
code: 'E_INVALID_URI',
|
|
70
|
+
});
|
|
71
|
+
expect(nativeCaptureFrame).not.toHaveBeenCalled();
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('rejects a negative positionMs with E_INVALID_POSITION', async () => {
|
|
75
|
+
await expect(captureFrame('file:///a.mp4', -1)).rejects.toMatchObject({
|
|
76
|
+
code: 'E_INVALID_POSITION',
|
|
77
|
+
});
|
|
78
|
+
expect(nativeCaptureFrame).not.toHaveBeenCalled();
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it.each([Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY])(
|
|
82
|
+
'rejects the non-finite positionMs %p',
|
|
83
|
+
async (bad) => {
|
|
84
|
+
await expect(captureFrame('file:///a.mp4', bad)).rejects.toMatchObject({
|
|
85
|
+
code: 'E_INVALID_POSITION',
|
|
86
|
+
});
|
|
87
|
+
},
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
it('accepts positionMs === 0 (start of media is a valid frame)', async () => {
|
|
91
|
+
await expect(captureFrame('file:///a.mp4', 0)).resolves.toBeNull();
|
|
92
|
+
expect(nativeCaptureFrame).toHaveBeenCalledTimes(1);
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
describe('options', () => {
|
|
97
|
+
it('applies the poster-sized defaults when options are omitted', async () => {
|
|
98
|
+
await captureFrame('file:///a.mp4', 5000);
|
|
99
|
+
expect(nativeCaptureFrame).toHaveBeenCalledWith('file:///a.mp4', 5000, {
|
|
100
|
+
width: DEFAULT_FRAME_WIDTH,
|
|
101
|
+
height: DEFAULT_FRAME_HEIGHT,
|
|
102
|
+
quality: DEFAULT_FRAME_QUALITY,
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('always sends an options object, even when none were supplied', async () => {
|
|
107
|
+
await captureFrame('file:///a.mp4', 5000);
|
|
108
|
+
const args = nativeCaptureFrame.mock.calls[0] as unknown[];
|
|
109
|
+
// The codegen'd TurboModule signature is
|
|
110
|
+
// (uri, positionMs, options, promise) — a missing 3rd argument is
|
|
111
|
+
// an arity mismatch on some RN versions, not a clean null.
|
|
112
|
+
expect(args).toHaveLength(3);
|
|
113
|
+
expect(args[2]).toEqual(expect.any(Object));
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('only overrides the fields the caller actually names', async () => {
|
|
117
|
+
await captureFrame('file:///a.mp4', 5000, { height: 720 });
|
|
118
|
+
expect(nativeCaptureFrame).toHaveBeenCalledWith('file:///a.mp4', 5000, {
|
|
119
|
+
width: DEFAULT_FRAME_WIDTH,
|
|
120
|
+
height: 720,
|
|
121
|
+
quality: DEFAULT_FRAME_QUALITY,
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it('forwards an explicit width of 0 (the aspect-preserving escape hatch)', async () => {
|
|
126
|
+
await captureFrame('file:///portrait.mp4', 5000, { width: 0 });
|
|
127
|
+
expect(nativeCaptureFrame).toHaveBeenCalledWith(
|
|
128
|
+
'file:///portrait.mp4',
|
|
129
|
+
5000,
|
|
130
|
+
expect.objectContaining({ width: 0 }),
|
|
131
|
+
);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it('floors a fractional positionMs before crossing the bridge', async () => {
|
|
135
|
+
await captureFrame('file:///a.mp4', 1234.99);
|
|
136
|
+
expect(nativeCaptureFrame).toHaveBeenCalledWith(
|
|
137
|
+
'file:///a.mp4',
|
|
138
|
+
1234,
|
|
139
|
+
expect.any(Object),
|
|
140
|
+
);
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
describe('the defaults themselves', () => {
|
|
145
|
+
it('uses a 16:9 box and a sane JPEG quality', () => {
|
|
146
|
+
// 640x360 is exactly 16:9, so landscape sources scale without
|
|
147
|
+
// distortion; quality 80 keeps a rail-sized frame in the tens of
|
|
148
|
+
// kB rather than the hundreds.
|
|
149
|
+
expect(DEFAULT_FRAME_WIDTH / DEFAULT_FRAME_HEIGHT).toBeCloseTo(16 / 9, 5);
|
|
150
|
+
expect(DEFAULT_FRAME_HEIGHT).toBe(360);
|
|
151
|
+
expect(DEFAULT_FRAME_QUALITY).toBe(80);
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
});
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getMpvPlayerModule,
|
|
3
|
+
type CaptureFrameOptions,
|
|
4
|
+
} from '../bridge/MpvPlayerModule';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Default output geometry for [captureFrame].
|
|
8
|
+
*
|
|
9
|
+
* These are the values the NATIVE side substitutes when a field is
|
|
10
|
+
* omitted (`MpvBridgeModule.kt`, `DEFAULT_FRAME_WIDTH` /
|
|
11
|
+
* `DEFAULT_FRAME_HEIGHT` / `DEFAULT_FRAME_QUALITY`). They are
|
|
12
|
+
* mirrored here so a consumer can display or assert on them without
|
|
13
|
+
* hardcoding the same literals twice — if you change one, change
|
|
14
|
+
* both.
|
|
15
|
+
*
|
|
16
|
+
* Why 640×360:
|
|
17
|
+
* - It is exactly 16:9, so the common case (film / TV / YouTube
|
|
18
|
+
* landscape video) is scaled without any aspect distortion.
|
|
19
|
+
* - 360 px tall is ~2.5× a 144 dp rail card at xxhdpi, so the
|
|
20
|
+
* JPEG stays crisp when the rail is scaled or cached by the
|
|
21
|
+
* image loader, without paying for full-HD frames.
|
|
22
|
+
* - ~230 kpx ≈ 25–40 kB at quality 80. A 50-item resume rail is
|
|
23
|
+
* ~2 MB on disk, which is why this is cheap enough to keep
|
|
24
|
+
* writing instead of evicting.
|
|
25
|
+
*
|
|
26
|
+
* Portrait (9:16) sources: pass `width: 0` to leave the width
|
|
27
|
+
* unconstrained and let the platform keep the source aspect ratio,
|
|
28
|
+
* rather than squashing the frame into a 16:9 box.
|
|
29
|
+
*/
|
|
30
|
+
export const DEFAULT_FRAME_WIDTH = 640;
|
|
31
|
+
export const DEFAULT_FRAME_HEIGHT = 360;
|
|
32
|
+
export const DEFAULT_FRAME_QUALITY = 80;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Re-exported so a consumer only needs one import:
|
|
36
|
+
*
|
|
37
|
+
* ```ts
|
|
38
|
+
* import {captureFrame, type CaptureFrameOptions} from '@simba-dev/react-native-media-player';
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
export type {CaptureFrameOptions};
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Error codes the wrapper and the native bridge both use. Kept in
|
|
45
|
+
* sync with `MpvBridgeModule.captureFrame`'s `promise.reject`
|
|
46
|
+
* calls — these are programmer errors, not media errors.
|
|
47
|
+
*/
|
|
48
|
+
const E_INVALID_URI = 'E_INVALID_URI';
|
|
49
|
+
const E_INVALID_POSITION = 'E_INVALID_POSITION';
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Extract a single video frame at `positionMs` and resolve the
|
|
53
|
+
* absolute path of the JPEG written for it.
|
|
54
|
+
*
|
|
55
|
+
* ## What it is for
|
|
56
|
+
*
|
|
57
|
+
* The "frame at the position you left off" thumbnail — Continue
|
|
58
|
+
* Watching rails, resume cards, scrub previews. It is deliberately
|
|
59
|
+
* NOT built on the module's existing `captureThumbnail(uri)`:
|
|
60
|
+
* that one only uses the URI to hash a filename and grabs whatever
|
|
61
|
+
* mpv is displaying *right now*, so it needs an initialised player,
|
|
62
|
+
* a loaded file, and it cannot target a position at all.
|
|
63
|
+
* [captureFrame] needs none of that.
|
|
64
|
+
*
|
|
65
|
+
* ## Why it works without a player
|
|
66
|
+
*
|
|
67
|
+
* Natively this is
|
|
68
|
+
* `MediaMetadataRetriever.getScaledFrameAtTime(timeUs, option,
|
|
69
|
+
* dstWidth, dstHeight)` — Android's standard "make a thumbnail from
|
|
70
|
+
* a data source" API. It opens the source itself (local path,
|
|
71
|
+
* `file://`, or `http(s)` via range requests), so no decoder
|
|
72
|
+
* instance, no playback, and no surface is involved. All the work
|
|
73
|
+
* happens on a native background executor, never on the JS or UI
|
|
74
|
+
* thread.
|
|
75
|
+
*
|
|
76
|
+
* ## `null` is a normal answer, not a failure
|
|
77
|
+
*
|
|
78
|
+
* The promise resolves `null` — it does NOT reject — for every
|
|
79
|
+
* "there is no frame here" case: a live stream, an unsupported
|
|
80
|
+
* container, an unreachable URL, a position past the end of the
|
|
81
|
+
* file. That is the documented signal for "no thumbnail, fall back
|
|
82
|
+
* to poster art", so a consumer can render a placeholder without a
|
|
83
|
+
* `try`/`catch` and without a blank `<Image>`.
|
|
84
|
+
*
|
|
85
|
+
* Rejection is reserved for programmer error:
|
|
86
|
+
* - `E_INVALID_URI` — blank/whitespace-only `uri`
|
|
87
|
+
* - `E_INVALID_POSITION` — `positionMs` is `NaN`, `±Infinity`, or
|
|
88
|
+
* negative
|
|
89
|
+
*
|
|
90
|
+
* Both are checked here in JS before the bridge call (so the
|
|
91
|
+
* contract also holds on a jest / Storybook / web host, where the
|
|
92
|
+
* bridge is the no-op fallback) and again natively (so a caller
|
|
93
|
+
* going straight at the bridge gets the same codes).
|
|
94
|
+
*
|
|
95
|
+
* ## Caching / output
|
|
96
|
+
*
|
|
97
|
+
* The JPEG lands in the app's **files** dir under
|
|
98
|
+
* `simba-resume-thumbs/`, named from a hash of the URI plus the
|
|
99
|
+
* position bucketed to 30 s. The URI is never used verbatim, so
|
|
100
|
+
* `?`, `/` and `%` in a signed URL cannot break the path; the bucket
|
|
101
|
+
* means repeated calls for "roughly where the user stopped"
|
|
102
|
+
* overwrite one file instead of accumulating a new one.
|
|
103
|
+
*
|
|
104
|
+
* `filesDir` (not the cache dir) is deliberate: a cache-dir
|
|
105
|
+
* thumbnail can be evicted at any moment, which would silently
|
|
106
|
+
* blank a rail cell on the next cold start.
|
|
107
|
+
*
|
|
108
|
+
* @param uri `file://`, an absolute path, a `content://` URI, or an
|
|
109
|
+
* `http(s)` URL.
|
|
110
|
+
* @param positionMs Position to grab, in milliseconds from the
|
|
111
|
+
* start of the media.
|
|
112
|
+
* @param options Output geometry / JPEG quality. Every field is
|
|
113
|
+
* optional; omitted fields use the defaults above.
|
|
114
|
+
* @returns Absolute path to the written JPEG, or `null` when no
|
|
115
|
+
* frame could be produced.
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* ```ts
|
|
119
|
+
* const path = await captureFrame(episode.uri, resumePositionMs);
|
|
120
|
+
* return path !== null ? {uri: `file://${path}`} : {uri: episode.poster};
|
|
121
|
+
* ```
|
|
122
|
+
*/
|
|
123
|
+
export async function captureFrame(
|
|
124
|
+
uri: string,
|
|
125
|
+
positionMs: number,
|
|
126
|
+
options?: CaptureFrameOptions,
|
|
127
|
+
): Promise<string | null> {
|
|
128
|
+
if (typeof uri !== 'string' || uri.trim().length === 0) {
|
|
129
|
+
throw Object.assign(new Error('captureFrame: uri must be a non-empty string'), {
|
|
130
|
+
code: E_INVALID_URI,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
if (!Number.isFinite(positionMs) || positionMs < 0) {
|
|
134
|
+
throw Object.assign(
|
|
135
|
+
new Error(
|
|
136
|
+
`captureFrame: positionMs must be a finite, non-negative number (got ${String(positionMs)})`,
|
|
137
|
+
),
|
|
138
|
+
{code: E_INVALID_POSITION},
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const bridge = getMpvPlayerModule();
|
|
143
|
+
// The options object is always sent, never omitted: the codegen'd
|
|
144
|
+
// TurboModule signature is `(uri, positionMs, options, promise)`,
|
|
145
|
+
// so an absent third argument is an arity mismatch on some RN
|
|
146
|
+
// versions rather than a clean `null`. An empty object is free and
|
|
147
|
+
// lets the native side apply the defaults.
|
|
148
|
+
return bridge.captureFrame(uri, Math.floor(positionMs), {
|
|
149
|
+
width: options?.width ?? DEFAULT_FRAME_WIDTH,
|
|
150
|
+
height: options?.height ?? DEFAULT_FRAME_HEIGHT,
|
|
151
|
+
quality: options?.quality ?? DEFAULT_FRAME_QUALITY,
|
|
152
|
+
});
|
|
153
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -100,6 +100,18 @@ export {
|
|
|
100
100
|
type PlayerQueueSelectionStore,
|
|
101
101
|
} from './hooks/useQueueSelection';
|
|
102
102
|
export {useLaunchParams} from './hooks/useLaunchParams';
|
|
103
|
+
// v1.10.0 — the "frame at the position you left off" thumbnail. The
|
|
104
|
+
// first genuinely PUBLIC frame API: `screenshot` / `captureThumbnail`
|
|
105
|
+
// live in the bridge but were never exported here, so a consumer had
|
|
106
|
+
// no supported way to reach them. `captureFrame` needs no player
|
|
107
|
+
// instance — see the wrapper's docblock for the `null` contract.
|
|
108
|
+
export {
|
|
109
|
+
captureFrame,
|
|
110
|
+
DEFAULT_FRAME_WIDTH,
|
|
111
|
+
DEFAULT_FRAME_HEIGHT,
|
|
112
|
+
DEFAULT_FRAME_QUALITY,
|
|
113
|
+
type CaptureFrameOptions,
|
|
114
|
+
} from './hooks/useResumeThumbnail';
|
|
103
115
|
// 1.8.0 — the load half of `<PlayerRoot>`, exposed so a consumer using
|
|
104
116
|
// `<SimbaPlayerRoot headless>` (which delegates the player UI) can call
|
|
105
117
|
// it directly for a payload the module did not originate. See
|