@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.
@@ -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
@@ -1,30 +0,0 @@
1
- package com.simba.player
2
-
3
- /**
4
- * Module-side contract that lets non-RN consumers (e.g. `PlayerActivity`)
5
- * fetch the active libmpv native pointer without crossing the Gradle
6
- * module boundary into the consumer app's bridge code.
7
- *
8
- * Why this exists:
9
- * - `MpvBridgeModule` lives in the consumer app at
10
- * `com.simba.player.mpv.MpvBridgeModule`. The module cannot import
11
- * it directly (Gradle does not let a library depend on its consumer).
12
- * - But `PlayerActivity` (which lives in the module) needs to call
13
- * `mpvRenderView.setNativePtr(ptr)` so the SurfaceView can attach
14
- * to mpv's `wid`. That ptr is owned by `MpvBridgeModule`.
15
- * - Solution: `MpvBridgeModule` implements this interface; module
16
- * code looks it up via `reactContext.getNativeModule("MpvPlayerModule")`
17
- * and casts to `IMpvNativePtrProvider`. The cast is safe because
18
- * we control both sides of the boundary.
19
- *
20
- * Phase 7 deliverable. The bridge-side ReactMethod `getNativePtr(): Double`
21
- * remains unchanged (keeps the JS-facing API stable) — this interface is
22
- * the native-only accessor used by the module's own activity code.
23
- */
24
- interface IMpvNativePtrProvider {
25
- /**
26
- * @return the active libmpv handle as a `Long`, or `0L` if mpv has
27
- * not been initialized yet (or has been destroyed).
28
- */
29
- fun fetchNativePtr(): Long
30
- }