react-native-image-stitcher 0.7.1 → 0.9.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/CHANGELOG.md +241 -0
- package/android/build.gradle +35 -1
- package/android/src/main/cpp/CMakeLists.txt +64 -2
- package/android/src/main/cpp/stitcher_jsi_install_jni.cpp +227 -0
- package/android/src/main/java/io/imagestitcher/rn/IncrementalStitcher.kt +30 -11
- package/android/src/main/java/io/imagestitcher/rn/RNImageStitcherPackage.kt +21 -3
- package/android/src/main/java/io/imagestitcher/rn/RNSARCameraView.kt +78 -3
- package/android/src/main/java/io/imagestitcher/rn/SaveFrameAsJpegPlugin.kt +162 -0
- package/android/src/main/java/io/imagestitcher/rn/StitcherJsiInstallerModule.kt +103 -0
- package/android/src/main/java/io/imagestitcher/rn/StitcherWorkletRuntime.kt +256 -0
- package/android/src/main/java/io/imagestitcher/rn/TransferredNV21.kt +100 -0
- package/cpp/stitcher_frame_data.hpp +141 -0
- package/cpp/stitcher_frame_jsi.cpp +214 -0
- package/cpp/stitcher_frame_jsi.hpp +108 -0
- package/cpp/stitcher_proxy_jsi.cpp +109 -0
- package/cpp/stitcher_proxy_jsi.hpp +46 -0
- package/cpp/stitcher_worklet_dispatch.cpp +103 -0
- package/cpp/stitcher_worklet_dispatch.hpp +71 -0
- package/cpp/stitcher_worklet_registry.cpp +81 -0
- package/cpp/stitcher_worklet_registry.hpp +136 -0
- package/dist/camera/Camera.d.ts +62 -12
- package/dist/camera/Camera.js +30 -15
- package/dist/index.d.ts +6 -0
- package/dist/index.js +30 -1
- package/dist/stitching/StitcherFrame.d.ts +170 -0
- package/dist/stitching/StitcherFrame.js +4 -0
- package/dist/stitching/StitcherWorkletRegistry.d.ts +117 -0
- package/dist/stitching/StitcherWorkletRegistry.js +78 -0
- package/dist/stitching/ensureStitcherProxyInstalled.d.ts +8 -0
- package/dist/stitching/ensureStitcherProxyInstalled.js +81 -0
- package/dist/stitching/useFrameProcessor.d.ts +119 -0
- package/dist/stitching/useFrameProcessor.js +196 -0
- package/dist/stitching/useFrameStream.d.ts +34 -0
- package/dist/stitching/useFrameStream.js +219 -0
- package/dist/stitching/useThrottledFrameProcessor.d.ts +33 -0
- package/dist/stitching/useThrottledFrameProcessor.js +132 -0
- package/dist/types.d.ts +87 -0
- package/ios/Sources/RNImageStitcher/RNSARSession.swift +46 -10
- package/ios/Sources/RNImageStitcher/RNSARWorkletRuntime.h +128 -0
- package/ios/Sources/RNImageStitcher/RNSARWorkletRuntime.mm +313 -0
- package/ios/Sources/RNImageStitcher/SaveFrameAsJpegPlugin.mm +185 -0
- package/ios/Sources/RNImageStitcher/StitcherFrameHostObject.h +60 -0
- package/ios/Sources/RNImageStitcher/StitcherFrameHostObject.mm +214 -0
- package/ios/Sources/RNImageStitcher/StitcherJsiInstaller.h +42 -0
- package/ios/Sources/RNImageStitcher/StitcherJsiInstaller.mm +103 -0
- package/package.json +1 -1
- package/src/camera/Camera.tsx +93 -28
- package/src/index.ts +35 -0
- package/src/stitching/StitcherFrame.ts +197 -0
- package/src/stitching/StitcherWorkletRegistry.ts +156 -0
- package/src/stitching/__tests__/StitcherWorkletRegistry.test.ts +176 -0
- package/src/stitching/__tests__/ensureStitcherProxyInstalled.test.ts +94 -0
- package/src/stitching/__tests__/useThrottledFrameProcessor.test.ts +178 -0
- package/src/stitching/ensureStitcherProxyInstalled.ts +141 -0
- package/src/stitching/useFrameProcessor.ts +226 -0
- package/src/stitching/useFrameStream.ts +255 -0
- package/src/stitching/useThrottledFrameProcessor.ts +145 -0
- package/src/types.ts +95 -0
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* Unit tests for the v0.9.0 Layer 2 `useThrottledFrameProcessor` hook.
|
|
4
|
+
*
|
|
5
|
+
* The worklet runtime can't run in jest (no JSI, no worklets-core).
|
|
6
|
+
* What we CAN test:
|
|
7
|
+
*
|
|
8
|
+
* - The `sampleHz` clamping (`[0.5, 30]`)
|
|
9
|
+
* - `minIntervalMs` math (1000 / sampleHz)
|
|
10
|
+
* - The deps propagation (host's deps → useFrameProcessor's deps)
|
|
11
|
+
* - The throttle gate logic (extracted as a pure function for
|
|
12
|
+
* isolated verification — see `_throttleGateForTests`).
|
|
13
|
+
*
|
|
14
|
+
* The hook itself is tested via a thin React-renderer-free harness:
|
|
15
|
+
* we mock `useFrameProcessor` + `useSharedValue` so we can verify
|
|
16
|
+
* the call shape without booting the worklet runtime.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { useThrottledFrameProcessor } from '../useThrottledFrameProcessor';
|
|
20
|
+
|
|
21
|
+
// ─── Mock vision-camera + worklets-core ─────────────────────────────
|
|
22
|
+
// These are minimal-shim mocks — enough surface for the hook to call
|
|
23
|
+
// `useFrameProcessor(workletBody, deps)` and `useSharedValue(0)`.
|
|
24
|
+
|
|
25
|
+
const useFrameProcessorMock = jest.fn();
|
|
26
|
+
const useSharedValueMock = jest.fn();
|
|
27
|
+
|
|
28
|
+
jest.mock('../useFrameProcessor', () => ({
|
|
29
|
+
useFrameProcessor: (...args: unknown[]) => useFrameProcessorMock(...args),
|
|
30
|
+
}));
|
|
31
|
+
|
|
32
|
+
jest.mock('react-native-worklets-core', () => ({
|
|
33
|
+
useSharedValue: (initial: number) => useSharedValueMock(initial),
|
|
34
|
+
}));
|
|
35
|
+
|
|
36
|
+
describe('useThrottledFrameProcessor', () => {
|
|
37
|
+
beforeEach(() => {
|
|
38
|
+
useFrameProcessorMock.mockReset();
|
|
39
|
+
useSharedValueMock.mockReset();
|
|
40
|
+
// Default behaviour for useSharedValue: return an object with a
|
|
41
|
+
// mutable `.value` field (mirrors worklets-core's API).
|
|
42
|
+
useSharedValueMock.mockImplementation((initial: number) => ({
|
|
43
|
+
value: initial,
|
|
44
|
+
}));
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
describe('sampleHz clamping', () => {
|
|
48
|
+
it('clamps below 0.5 to 0.5', () => {
|
|
49
|
+
const noop = (() => {}) as unknown as Parameters<typeof useThrottledFrameProcessor>[0];
|
|
50
|
+
useThrottledFrameProcessor(noop, { sampleHz: 0.1 }, []);
|
|
51
|
+
// useFrameProcessor receives the wrapped worklet; the deps
|
|
52
|
+
// array's first entry is `minIntervalMs`. For sampleHz=0.5,
|
|
53
|
+
// minIntervalMs = 2000.
|
|
54
|
+
const [, deps] = useFrameProcessorMock.mock.calls[0]!;
|
|
55
|
+
expect(deps[0]).toBeCloseTo(2000);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('clamps above 30 to 30', () => {
|
|
59
|
+
const noop = (() => {}) as unknown as Parameters<typeof useThrottledFrameProcessor>[0];
|
|
60
|
+
useThrottledFrameProcessor(noop, { sampleHz: 999 }, []);
|
|
61
|
+
const [, deps] = useFrameProcessorMock.mock.calls[0]!;
|
|
62
|
+
// sampleHz=30 → minIntervalMs = 33.333...
|
|
63
|
+
expect(deps[0]).toBeCloseTo(1000 / 30);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('passes through in-range sampleHz unchanged', () => {
|
|
67
|
+
const noop = (() => {}) as unknown as Parameters<typeof useThrottledFrameProcessor>[0];
|
|
68
|
+
useThrottledFrameProcessor(noop, { sampleHz: 2 }, []);
|
|
69
|
+
const [, deps] = useFrameProcessorMock.mock.calls[0]!;
|
|
70
|
+
expect(deps[0]).toBeCloseTo(500);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('accepts boundary values exactly', () => {
|
|
74
|
+
const noop = (() => {}) as unknown as Parameters<typeof useThrottledFrameProcessor>[0];
|
|
75
|
+
useThrottledFrameProcessor(noop, { sampleHz: 0.5 }, []);
|
|
76
|
+
let deps = useFrameProcessorMock.mock.calls[0]![1];
|
|
77
|
+
expect(deps[0]).toBeCloseTo(2000);
|
|
78
|
+
|
|
79
|
+
useFrameProcessorMock.mockClear();
|
|
80
|
+
useThrottledFrameProcessor(noop, { sampleHz: 30 }, []);
|
|
81
|
+
deps = useFrameProcessorMock.mock.calls[0]![1];
|
|
82
|
+
expect(deps[0]).toBeCloseTo(1000 / 30);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
describe('deps propagation', () => {
|
|
87
|
+
it('appends host deps after the internal interval + worklet deps', () => {
|
|
88
|
+
const noop = (() => {}) as unknown as Parameters<typeof useThrottledFrameProcessor>[0];
|
|
89
|
+
const hostDep1 = { id: 'a' };
|
|
90
|
+
const hostDep2 = 42;
|
|
91
|
+
useThrottledFrameProcessor(noop, { sampleHz: 2 }, [hostDep1, hostDep2]);
|
|
92
|
+
const [, deps] = useFrameProcessorMock.mock.calls[0]!;
|
|
93
|
+
// Expected shape: [minIntervalMs, worklet, ...hostDeps]
|
|
94
|
+
expect(deps).toHaveLength(4);
|
|
95
|
+
expect(deps[0]).toBeCloseTo(500);
|
|
96
|
+
expect(deps[1]).toBe(noop);
|
|
97
|
+
expect(deps[2]).toBe(hostDep1);
|
|
98
|
+
expect(deps[3]).toBe(hostDep2);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('with empty host deps: deps = [minIntervalMs, worklet]', () => {
|
|
102
|
+
const noop = (() => {}) as unknown as Parameters<typeof useThrottledFrameProcessor>[0];
|
|
103
|
+
useThrottledFrameProcessor(noop, { sampleHz: 2 }, []);
|
|
104
|
+
const [, deps] = useFrameProcessorMock.mock.calls[0]!;
|
|
105
|
+
expect(deps).toHaveLength(2);
|
|
106
|
+
expect(deps[0]).toBeCloseTo(500);
|
|
107
|
+
expect(deps[1]).toBe(noop);
|
|
108
|
+
});
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
describe('throttle gate', () => {
|
|
112
|
+
// The throttle logic lives INSIDE the wrapped worklet body, which
|
|
113
|
+
// jest can't execute directly (it's a `'worklet'`-prefixed
|
|
114
|
+
// function). But the wrapped function IS just a plain JS
|
|
115
|
+
// function until the worklets-core babel plugin transforms it,
|
|
116
|
+
// so we can call it manually with mock frames + a mock
|
|
117
|
+
// shared-value gate.
|
|
118
|
+
//
|
|
119
|
+
// The body's logic:
|
|
120
|
+
// if (frame.timestamp - lastSampleMs.value < minIntervalMs) return;
|
|
121
|
+
// lastSampleMs.value = frame.timestamp;
|
|
122
|
+
// worklet(frame);
|
|
123
|
+
|
|
124
|
+
it('fires the worklet on the first frame regardless of timestamp', () => {
|
|
125
|
+
const hostWorklet = jest.fn();
|
|
126
|
+
useThrottledFrameProcessor(hostWorklet, { sampleHz: 2 }, []);
|
|
127
|
+
const [wrappedBody] = useFrameProcessorMock.mock.calls[0]!;
|
|
128
|
+
|
|
129
|
+
const frame = { timestamp: 12345 } as Parameters<typeof hostWorklet>[0];
|
|
130
|
+
wrappedBody(frame);
|
|
131
|
+
|
|
132
|
+
expect(hostWorklet).toHaveBeenCalledTimes(1);
|
|
133
|
+
expect(hostWorklet).toHaveBeenCalledWith(frame);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it('skips a frame too close to the previous sample', () => {
|
|
137
|
+
const hostWorklet = jest.fn();
|
|
138
|
+
useThrottledFrameProcessor(hostWorklet, { sampleHz: 2 }, []); // 500ms interval
|
|
139
|
+
const [wrappedBody] = useFrameProcessorMock.mock.calls[0]!;
|
|
140
|
+
|
|
141
|
+
wrappedBody({ timestamp: 1000 } as never);
|
|
142
|
+
wrappedBody({ timestamp: 1100 } as never); // 100ms after — too soon
|
|
143
|
+
wrappedBody({ timestamp: 1200 } as never); // 200ms after — too soon
|
|
144
|
+
|
|
145
|
+
expect(hostWorklet).toHaveBeenCalledTimes(1);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it('fires again exactly at the interval boundary', () => {
|
|
149
|
+
const hostWorklet = jest.fn();
|
|
150
|
+
useThrottledFrameProcessor(hostWorklet, { sampleHz: 2 }, []); // 500ms
|
|
151
|
+
const [wrappedBody] = useFrameProcessorMock.mock.calls[0]!;
|
|
152
|
+
|
|
153
|
+
wrappedBody({ timestamp: 1000 } as never);
|
|
154
|
+
wrappedBody({ timestamp: 1500 } as never); // exactly at boundary
|
|
155
|
+
|
|
156
|
+
expect(hostWorklet).toHaveBeenCalledTimes(2);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it('fires again past the interval boundary', () => {
|
|
160
|
+
const hostWorklet = jest.fn();
|
|
161
|
+
useThrottledFrameProcessor(hostWorklet, { sampleHz: 2 }, []); // 500ms
|
|
162
|
+
const [wrappedBody] = useFrameProcessorMock.mock.calls[0]!;
|
|
163
|
+
|
|
164
|
+
wrappedBody({ timestamp: 1000 } as never);
|
|
165
|
+
wrappedBody({ timestamp: 1600 } as never); // 600ms after
|
|
166
|
+
|
|
167
|
+
expect(hostWorklet).toHaveBeenCalledTimes(2);
|
|
168
|
+
});
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
describe('shared value lifecycle', () => {
|
|
172
|
+
it('initializes lastSampleMs to 0', () => {
|
|
173
|
+
const noop = (() => {}) as unknown as Parameters<typeof useThrottledFrameProcessor>[0];
|
|
174
|
+
useThrottledFrameProcessor(noop, { sampleHz: 2 }, []);
|
|
175
|
+
expect(useSharedValueMock).toHaveBeenCalledWith(0);
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
});
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import { NativeModules } from 'react-native';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* v0.8.0 Phase 4b — one-shot installer that asks the native side
|
|
7
|
+
* to install `globalThis.__stitcherProxy` on the main JS runtime.
|
|
8
|
+
*
|
|
9
|
+
* ## When this runs
|
|
10
|
+
*
|
|
11
|
+
* The first call to `useFrameProcessor` triggers this. Idempotent:
|
|
12
|
+
* once the global is installed, subsequent calls short-circuit.
|
|
13
|
+
*
|
|
14
|
+
* ## What it does
|
|
15
|
+
*
|
|
16
|
+
* Calls into the platform-native `StitcherJsiInstaller` RN module
|
|
17
|
+
* which is registered with a `RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(install)`
|
|
18
|
+
* on iOS (see `ios/Sources/RNImageStitcher/StitcherJsiInstaller.mm`)
|
|
19
|
+
* and — Phase 4b.ii — an analogous Kotlin TurboModule on Android.
|
|
20
|
+
*
|
|
21
|
+
* The native module reaches into the main JS runtime via
|
|
22
|
+
* `RCTCxxBridge.runtime` (iOS) / the equivalent Android JSI access
|
|
23
|
+
* pattern and installs a host object on `globalThis.__stitcherProxy`
|
|
24
|
+
* exposing `install(workletFn)` / `uninstall(id)` / `count()`.
|
|
25
|
+
*
|
|
26
|
+
* ## Failure modes (and what happens then)
|
|
27
|
+
*
|
|
28
|
+
* 1. **Module not registered** (Android in Phase 4b.i; old iOS
|
|
29
|
+
* builds without the new pod files). `NativeModules
|
|
30
|
+
* .StitcherJsiInstaller` is `undefined`. This function returns
|
|
31
|
+
* `false` and the hook falls back to the JS-side
|
|
32
|
+
* `StitcherWorkletRegistry` — host worklets are registered
|
|
33
|
+
* on the JS side but never fan out to AR mode. No crash, no
|
|
34
|
+
* regression vs. Phase 4a.
|
|
35
|
+
*
|
|
36
|
+
* 2. **JSI runtime unreachable** (e.g., remote debug mode). The
|
|
37
|
+
* sync method returns `false`. Same JS-side-registry fallback.
|
|
38
|
+
*
|
|
39
|
+
* 3. **Native install succeeds but global not yet visible.**
|
|
40
|
+
* The native call is SYNCHRONOUS (`BLOCKING_SYNCHRONOUS_METHOD`),
|
|
41
|
+
* so by the time the function returns the global is installed.
|
|
42
|
+
* No race here.
|
|
43
|
+
*
|
|
44
|
+
* ## Why a separate module
|
|
45
|
+
*
|
|
46
|
+
* The install method is a one-time runtime bootstrap, not a
|
|
47
|
+
* per-call API. Putting it on its own RN module (vs. on the
|
|
48
|
+
* existing `StitcherBridge` / `IncrementalStitcherBridge`) keeps
|
|
49
|
+
* the responsibility surface narrow and the failure mode easy
|
|
50
|
+
* to diagnose ("`__stitcherProxy` not installed" → check
|
|
51
|
+
* `StitcherJsiInstaller` module registration first).
|
|
52
|
+
*/
|
|
53
|
+
|
|
54
|
+
interface StitcherJsiInstallerModule {
|
|
55
|
+
install(): boolean;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* `__DEV__` is RN's global dev-flag. Guard the read with `typeof`
|
|
60
|
+
* so the helper works in any environment that imports it without
|
|
61
|
+
* defining __DEV__ (jest, SSR, custom tooling). Same pattern RN's
|
|
62
|
+
* own debug code uses.
|
|
63
|
+
*/
|
|
64
|
+
function isDev(): boolean {
|
|
65
|
+
return typeof __DEV__ !== 'undefined' && __DEV__;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
let installed = false;
|
|
69
|
+
|
|
70
|
+
export function ensureStitcherProxyInstalled(): boolean {
|
|
71
|
+
if (installed) return true;
|
|
72
|
+
// Already installed by an earlier hook mount. Cheap fast-path.
|
|
73
|
+
if (typeof (globalThis as { __stitcherProxy?: unknown }).__stitcherProxy !== 'undefined') {
|
|
74
|
+
installed = true;
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const mod = (NativeModules as { StitcherJsiInstaller?: StitcherJsiInstallerModule })
|
|
79
|
+
.StitcherJsiInstaller;
|
|
80
|
+
if (mod == null || typeof mod.install !== 'function') {
|
|
81
|
+
// Module not present — Android until Phase 4b.ii lands, or
|
|
82
|
+
// an old iOS build. Surface this once at debug-info level so
|
|
83
|
+
// the host can see "your worklets are JS-registered only" in
|
|
84
|
+
// logcat / Console.app without a noisy per-frame warning.
|
|
85
|
+
if (isDev() && !warnedAboutMissingModule) {
|
|
86
|
+
warnedAboutMissingModule = true;
|
|
87
|
+
console.info(
|
|
88
|
+
'[react-native-image-stitcher] StitcherJsiInstaller native ' +
|
|
89
|
+
'module not found; host worklets registered in JS-side ' +
|
|
90
|
+
'registry only. AR-mode dispatch requires the native install ' +
|
|
91
|
+
'(iOS Phase 4b.i — included in v0.8.0; Android Phase 4b.ii ' +
|
|
92
|
+
'— follow-up release).',
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
const ok = mod.install();
|
|
100
|
+
if (!ok) {
|
|
101
|
+
// Native module ran but couldn't install (JSI runtime
|
|
102
|
+
// unreachable). Same fallback as the missing-module case.
|
|
103
|
+
if (isDev() && !warnedAboutFailedInstall) {
|
|
104
|
+
warnedAboutFailedInstall = true;
|
|
105
|
+
console.info(
|
|
106
|
+
'[react-native-image-stitcher] StitcherJsiInstaller.install() ' +
|
|
107
|
+
'returned false (JSI runtime unreachable — remote debug ' +
|
|
108
|
+
'mode?). Falling back to JS-side host worklet registry.',
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
installed = true;
|
|
114
|
+
return true;
|
|
115
|
+
} catch (err) {
|
|
116
|
+
if (isDev() && !warnedAboutFailedInstall) {
|
|
117
|
+
warnedAboutFailedInstall = true;
|
|
118
|
+
console.info(
|
|
119
|
+
'[react-native-image-stitcher] StitcherJsiInstaller.install() ' +
|
|
120
|
+
'threw: ' +
|
|
121
|
+
String(err) +
|
|
122
|
+
'. Falling back to JS-side host worklet registry.',
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
let warnedAboutMissingModule = false;
|
|
130
|
+
let warnedAboutFailedInstall = false;
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Test-only — reset module-internal state. Used by jest to allow
|
|
134
|
+
* multiple test cases to re-trigger the install path independently.
|
|
135
|
+
* NOT exported from `src/index.ts`.
|
|
136
|
+
*/
|
|
137
|
+
export function _resetStitcherProxyInstallStateForTests(): void {
|
|
138
|
+
installed = false;
|
|
139
|
+
warnedAboutMissingModule = false;
|
|
140
|
+
warnedAboutFailedInstall = false;
|
|
141
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import { useEffect, type DependencyList } from 'react';
|
|
4
|
+
import {
|
|
5
|
+
useFrameProcessor as visionCameraUseFrameProcessor,
|
|
6
|
+
type DrawableFrameProcessor,
|
|
7
|
+
type Frame,
|
|
8
|
+
type ReadonlyFrameProcessor,
|
|
9
|
+
} from 'react-native-vision-camera';
|
|
10
|
+
|
|
11
|
+
import { ensureStitcherProxyInstalled } from './ensureStitcherProxyInstalled';
|
|
12
|
+
import { StitcherWorkletRegistry } from './StitcherWorkletRegistry';
|
|
13
|
+
import type { StitcherFrameProcessor } from './StitcherFrame';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Shape of the native-installed `globalThis.__stitcherProxy` host
|
|
17
|
+
* object (iOS Phase 4b.i; Android Phase 4b.ii). When present, the
|
|
18
|
+
* hook prefers the native registry over the JS-side mirror — the
|
|
19
|
+
* native AR worklet runtime reads from the native side directly.
|
|
20
|
+
*/
|
|
21
|
+
interface StitcherProxy {
|
|
22
|
+
install(workletFn: StitcherFrameProcessor): string;
|
|
23
|
+
uninstall(id: string): void;
|
|
24
|
+
count(): number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* v0.8.0 Phase 4a — public hook for hosts to attach a per-frame
|
|
29
|
+
* worklet that runs in BOTH AR and non-AR capture modes.
|
|
30
|
+
*
|
|
31
|
+
* ## Quick start
|
|
32
|
+
*
|
|
33
|
+
* ```tsx
|
|
34
|
+
* import { useFrameProcessor, type StitcherFrame } from 'react-native-image-stitcher';
|
|
35
|
+
*
|
|
36
|
+
* function MyOcrOverlay() {
|
|
37
|
+
* const processor = useFrameProcessor((frame: StitcherFrame) => {
|
|
38
|
+
* 'worklet';
|
|
39
|
+
* // Pixel data is in `frame.toArrayBuffer()`.
|
|
40
|
+
* // AR-only fields: `frame.arDepth`, `frame.arAnchors`, `frame.arTrackingState`.
|
|
41
|
+
* // Discriminate via `frame.source === 'ar'` / `'vc'`.
|
|
42
|
+
* }, []);
|
|
43
|
+
* return <Camera frameProcessor={processor} ... />;
|
|
44
|
+
* }
|
|
45
|
+
* ```
|
|
46
|
+
*
|
|
47
|
+
* ## Two behaviours, depending on mode
|
|
48
|
+
*
|
|
49
|
+
* **Non-AR mode (today, fully working):** the worklet runs on
|
|
50
|
+
* vision-camera's Frame Processor runtime. Same thread + same
|
|
51
|
+
* cost envelope as a plain `useFrameProcessor` from
|
|
52
|
+
* `react-native-vision-camera`. The lib's own first-party
|
|
53
|
+
* stitching plugin runs alongside on the same producer-thread
|
|
54
|
+
* runtime (composition is handled by vision-camera's own dispatch
|
|
55
|
+
* order).
|
|
56
|
+
*
|
|
57
|
+
* Your worklet receives whatever vision-camera delivers — vc's raw
|
|
58
|
+
* `Frame`. This is a structural subset of `StitcherFrame`: the
|
|
59
|
+
* vc-shaped fields (`width`, `height`, `pixelFormat`, `orientation`,
|
|
60
|
+
* `timestamp`, `toArrayBuffer`) are guaranteed; the
|
|
61
|
+
* `StitcherFrame`-only fields (`source`, `pose`, `arDepth`,
|
|
62
|
+
* `arAnchors`, `arTrackingState`) are **undefined** at runtime
|
|
63
|
+
* because the lib does NOT wrap or augment vc's `Frame` in Phase 4a
|
|
64
|
+
* (cross-worklet-boundary field injection is Phase 4b work).
|
|
65
|
+
* Worklets that need to read `source` / `pose` MUST guard for
|
|
66
|
+
* `undefined`:
|
|
67
|
+
*
|
|
68
|
+
* ```ts
|
|
69
|
+
* if (frame.source === 'ar') { ... } // false in non-AR mode
|
|
70
|
+
* if (frame.pose) { ... } // skipped in non-AR mode
|
|
71
|
+
* ```
|
|
72
|
+
*
|
|
73
|
+
* **AR mode — iOS Phase 4b.i (this release):** the worklet is
|
|
74
|
+
* installed into the native registry via
|
|
75
|
+
* `globalThis.__stitcherProxy.install(workletFn)`, where
|
|
76
|
+
* `__stitcherProxy` is a JSI host object installed at lib
|
|
77
|
+
* bootstrap by the native `StitcherJsiInstaller` module. The
|
|
78
|
+
* AR worklet runtime (`RNSARWorkletRuntime`) reads from the
|
|
79
|
+
* native registry on each `dispatchFrame:pose:` call and fans
|
|
80
|
+
* out invocations — your worklet fires alongside the lib's
|
|
81
|
+
* first-party stitching path.
|
|
82
|
+
*
|
|
83
|
+
* **AR mode — Android Phase 4b.ii (deferred):** the native
|
|
84
|
+
* installer + JNI bridge from `StitcherWorkletRuntime.kt`'s
|
|
85
|
+
* `runFirstParty {...}` path to a parallel C++ registry land in
|
|
86
|
+
* a follow-up release. Until then, on Android the hook falls
|
|
87
|
+
* back to the JS-side `StitcherWorkletRegistry`; AR-mode host
|
|
88
|
+
* worklets register but do not invoke. No regression vs.
|
|
89
|
+
* Phase 4a; iOS gets the API first.
|
|
90
|
+
*
|
|
91
|
+
* ### When Phase 4b.ii lands (Android)
|
|
92
|
+
*
|
|
93
|
+
* The hook's call signature does NOT change. Android hosts that
|
|
94
|
+
* write code today against this API will see their worklets
|
|
95
|
+
* start firing in AR mode automatically when Phase 4b.ii is
|
|
96
|
+
* merged. No migration required.
|
|
97
|
+
*
|
|
98
|
+
* ## Frame contract
|
|
99
|
+
*
|
|
100
|
+
* The worklet receives a {@link StitcherFrame} (see
|
|
101
|
+
* `src/stitching/StitcherFrame.ts` for the full contract +
|
|
102
|
+
* lifecycle). Highlights:
|
|
103
|
+
*
|
|
104
|
+
* - **`source`** discriminator: `'vc'` or `'ar'`. Branch on this
|
|
105
|
+
* before reading `arDepth` / `arAnchors` / `arTrackingState`
|
|
106
|
+
* so non-AR captures don't break.
|
|
107
|
+
* - **`pose`** always present. `pose.translation` is `undefined`
|
|
108
|
+
* in non-AR mode (gyro provides only rotation; no spatial
|
|
109
|
+
* anchor).
|
|
110
|
+
* - **Buffer lifetime**: pixel data is valid only for the
|
|
111
|
+
* duration of the worklet call. Worklets that need to retain
|
|
112
|
+
* data must `toArrayBuffer()` synchronously inside the
|
|
113
|
+
* worklet body — returning a reference and reading it later
|
|
114
|
+
* reads freed memory.
|
|
115
|
+
*
|
|
116
|
+
* ## Threading
|
|
117
|
+
*
|
|
118
|
+
* The worklet runs on the producer thread (vision-camera's
|
|
119
|
+
* runtime in non-AR mode; the AR-session callback thread under
|
|
120
|
+
* Phase 4b). Worklets MUST NOT block the producer thread for
|
|
121
|
+
* more than a few ms — the next frame's processing is gated on
|
|
122
|
+
* the previous frame returning. Long work belongs on a queue
|
|
123
|
+
* crossed via Reanimated / worklets-core's `runOnJS`.
|
|
124
|
+
*
|
|
125
|
+
* @param worklet The host's frame processor function. Must be
|
|
126
|
+
* `'worklet'`-prefixed at the call site. TS
|
|
127
|
+
* cannot enforce the prefix; the runtime will
|
|
128
|
+
* throw at attempt to invoke a non-worklet
|
|
129
|
+
* function.
|
|
130
|
+
* @param deps Standard React deps array. When `deps` change,
|
|
131
|
+
* the previous registration is removed and the
|
|
132
|
+
* new worklet is registered. Same semantics as
|
|
133
|
+
* vision-camera's `useFrameProcessor`.
|
|
134
|
+
*
|
|
135
|
+
* @returns A vision-camera frame-processor object that
|
|
136
|
+
* `<Camera frameProcessor={...}>` accepts. In non-AR
|
|
137
|
+
* mode this is what drives the per-frame worklet
|
|
138
|
+
* invocation; in AR mode it's currently a no-op (vc
|
|
139
|
+
* isn't mounted in AR mode anyway).
|
|
140
|
+
*/
|
|
141
|
+
export function useFrameProcessor(
|
|
142
|
+
worklet: StitcherFrameProcessor,
|
|
143
|
+
deps: DependencyList,
|
|
144
|
+
): ReadonlyFrameProcessor | DrawableFrameProcessor {
|
|
145
|
+
// Non-AR path: delegate to vision-camera's hook. The returned
|
|
146
|
+
// processor object is what `<Camera>` hands to vc. Worklet
|
|
147
|
+
// fires on vc's producer-thread runtime.
|
|
148
|
+
//
|
|
149
|
+
// Cast rationale: vc's hook expects `(frame: Frame) => void`.
|
|
150
|
+
// Our worklet is typed `(frame: StitcherFrame) => void`.
|
|
151
|
+
// `StitcherFrame` is a structural superset of `Frame` (it adds
|
|
152
|
+
// required `source` + `pose` and the optional AR fields), so
|
|
153
|
+
// assigning a function that consumes `StitcherFrame` to a
|
|
154
|
+
// `Frame`-consuming slot is unsound at the type level — TS is
|
|
155
|
+
// right to reject the direct assignment. At RUNTIME the worklet
|
|
156
|
+
// will see vc's raw `Frame`; the `source` / `pose` / AR fields
|
|
157
|
+
// are undefined (the hook's docstring above documents this and
|
|
158
|
+
// tells hosts to guard). We double-cast through `unknown` to
|
|
159
|
+
// suppress, accepting the explicit type-system gap as the price
|
|
160
|
+
// of Phase 4a's pre-Phase-4b deferral on cross-runtime frame
|
|
161
|
+
// wrapping.
|
|
162
|
+
const vcProcessor = visionCameraUseFrameProcessor(
|
|
163
|
+
worklet as unknown as (frame: Frame) => void,
|
|
164
|
+
deps,
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
// AR path: install into the native registry if available (iOS
|
|
168
|
+
// Phase 4b.i — and Android Phase 4b.ii once it lands). Falls
|
|
169
|
+
// back to the JS-side `StitcherWorkletRegistry` when the native
|
|
170
|
+
// installer isn't present (Android in 4b.i; remote debug mode;
|
|
171
|
+
// unit tests). The fallback path matches Phase 4a's
|
|
172
|
+
// register-but-not-invoke semantics.
|
|
173
|
+
//
|
|
174
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
175
|
+
useEffect(() => {
|
|
176
|
+
const nativeReady = ensureStitcherProxyInstalled();
|
|
177
|
+
if (
|
|
178
|
+
nativeReady &&
|
|
179
|
+
typeof (globalThis as { __stitcherProxy?: StitcherProxy }).__stitcherProxy !== 'undefined'
|
|
180
|
+
) {
|
|
181
|
+
// Native path — install through the JSI proxy. Errors here
|
|
182
|
+
// most commonly mean the worklet doesn't have the
|
|
183
|
+
// `'worklet'` directive at the call site (the worklets-core
|
|
184
|
+
// babel plugin didn't transform it). Surface them via the
|
|
185
|
+
// proxy's own throw with a host-side log so the failure is
|
|
186
|
+
// obvious.
|
|
187
|
+
let id: string | undefined;
|
|
188
|
+
try {
|
|
189
|
+
id = (globalThis as unknown as { __stitcherProxy: StitcherProxy }).__stitcherProxy.install(
|
|
190
|
+
worklet,
|
|
191
|
+
);
|
|
192
|
+
} catch (err) {
|
|
193
|
+
// Guard `__DEV__` read so the hook works in any environment
|
|
194
|
+
// that imports it without defining the flag (jest, SSR,
|
|
195
|
+
// custom tooling).
|
|
196
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
197
|
+
console.error(
|
|
198
|
+
'[react-native-image-stitcher] __stitcherProxy.install ' +
|
|
199
|
+
'threw — is the worklet function decorated with ' +
|
|
200
|
+
"`'worklet';` and processed by react-native-worklets-core's " +
|
|
201
|
+
'babel plugin? Original error: ' +
|
|
202
|
+
String(err),
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
return; // No cleanup needed — nothing was installed.
|
|
206
|
+
}
|
|
207
|
+
return () => {
|
|
208
|
+
try {
|
|
209
|
+
(globalThis as unknown as { __stitcherProxy: StitcherProxy }).__stitcherProxy.uninstall(id!);
|
|
210
|
+
} catch {
|
|
211
|
+
// Uninstall is best-effort; an exception here means the
|
|
212
|
+
// proxy was already gone (e.g., app reload mid-cleanup).
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// Fallback — JS-side registry. Same as Phase 4a.
|
|
218
|
+
const jsId = StitcherWorkletRegistry.register({
|
|
219
|
+
worklet,
|
|
220
|
+
isFirstParty: false,
|
|
221
|
+
});
|
|
222
|
+
return () => StitcherWorkletRegistry.unregister(jsId);
|
|
223
|
+
}, deps);
|
|
224
|
+
|
|
225
|
+
return vcProcessor;
|
|
226
|
+
}
|