react-native-vision-camera-spoof-detector 1.3.5 → 1.3.7

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/README.md CHANGED
@@ -14,7 +14,7 @@ Face anti-spoofing and liveness scoring for React Native Vision Camera 5. A Nitr
14
14
  - Face size, frame-edge, pose, landmark, brightness, and liveness-quality gates
15
15
  - Optional callbacks for scores, detected faces, stable-face capture, and errors
16
16
  - Output reset without recreating the camera output
17
- - Optional target-resolution and liveness threshold configuration
17
+ - Configurable liveness thresholds; uses Vision Camera's selected analysis resolution
18
18
 
19
19
  ## Requirements
20
20
 
@@ -161,7 +161,6 @@ Options:
161
161
 
162
162
  ```ts
163
163
  interface UseFaceAntiSpoofFrameOutputOptions {
164
- targetResolution?: { width: number; height: number };
165
164
  antispoofLevel?: number;
166
165
  stableFrames?: number;
167
166
  requiredLiveFrames?: number;
@@ -194,9 +193,8 @@ Default output options on both platforms:
194
193
  | `requiredLiveFrames` | `3` | Consecutive score-passing frames required before notification |
195
194
  | `laplacianThreshold` | `1100` | Minimum Laplacian score for a frame to pass |
196
195
  | `maxNeuralSpoofScore` | `0.1` | Neural scores at or above this value fail the liveness gate |
197
- | `targetResolution` | Camera-selected | Optional requested analysis resolution |
198
196
 
199
- On Android devices identified by the system as low-RAM, and on iOS devices with 4 GB physical memory or less, a requested resolution wider than 640 pixels is scaled down proportionally. With no `targetResolution`, the camera selects the analysis resolution. Android uses YUV frames and ML Kit; iOS uses BGRA frames and Vision. Platform model runtimes and score calculations may differ, so calibrate thresholds on representative devices and presentation-attack data rather than assuming identical score distributions.
197
+ Vision Camera selects the analysis resolution. Android uses YUV frames and ML Kit; iOS uses BGRA frames and Vision. Platform model runtimes and score calculations may differ, so calibrate thresholds on representative devices and presentation-attack data rather than assuming identical score distributions.
200
198
 
201
199
  The brightness and Laplacian checks are image-quality gates, not independent proof of liveness. Threshold defaults are starting points, not validated biometric security thresholds. Evaluate the complete capture flow against bona fide and attack presentations before relying on it in production.
202
200
 
@@ -249,14 +247,14 @@ Result fields:
249
247
  - Uses CameraX `ImageAnalysis`, ML Kit face detection, and the bundled TensorFlow Lite model
250
248
  - Prefers GPU inference, falls back to NNAPI, then CPU
251
249
  - Uses YUV input, a brightness gate, face-size/frame-margin/pose/landmark checks, and a padded, eye-aligned face crop
252
- - Uses `MirrorMode.AUTO` and applies a requested analysis resolution when provided
250
+ - Uses `MirrorMode.AUTO` and Vision Camera's selected analysis resolution
253
251
 
254
252
  ### iOS
255
253
 
256
254
  - Uses `AVCaptureVideoDataOutput`, Apple Vision face/landmark detection, and the bundled TensorFlow Lite model
257
255
  - Uses Metal when available, with CPU fallback
258
256
  - Uses BGRA input, a brightness gate, face-size/frame-margin/pose/landmark checks, and a padded, eye-aligned face crop
259
- - Automatically adjusts video mirroring and only constrains resolution when `targetResolution` is provided
257
+ - Automatically adjusts video mirroring and uses Vision Camera's selected analysis resolution
260
258
 
261
259
  ## Troubleshooting
262
260
 
@@ -3,14 +3,10 @@ package com.margelo.nitro.camera.spoofdetector
3
3
  import android.graphics.Matrix
4
4
  import android.graphics.PointF
5
5
  import android.graphics.RectF
6
- import android.app.ActivityManager
7
- import android.content.Context
8
6
  import androidx.annotation.OptIn
9
7
  import androidx.camera.core.ExperimentalGetImage
10
8
  import androidx.camera.core.ImageAnalysis
11
9
  import androidx.camera.core.ImageProxy
12
- import androidx.camera.core.resolutionselector.ResolutionSelector
13
- import androidx.camera.core.resolutionselector.ResolutionStrategy
14
10
  import com.google.android.gms.tasks.Task
15
11
  import com.google.android.gms.tasks.Tasks
16
12
  import com.google.mlkit.vision.common.InputImage
@@ -68,11 +64,6 @@ class HybridSpoofDetectorOutput(
68
64
  private val requiredLiveFrames = (options.requiredLiveFrames ?: 3.0).toInt().coerceAtLeast(1)
69
65
  private val laplacianThreshold = options.laplacianThreshold ?: 1100.0
70
66
  private val maxNeuralSpoofScore = options.maxNeuralSpoofScore ?: 0.1
71
- private val isLowRamDevice by lazy {
72
- val context = NitroModules.applicationContext
73
- val activityManager = context?.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
74
- activityManager?.isLowRamDevice == true
75
- }
76
67
  private var captured = false
77
68
  private var stableCount = 0
78
69
  private var lastFaceBounds: SpoofDetectedFaceBounds? = null
@@ -92,32 +83,12 @@ class HybridSpoofDetectorOutput(
92
83
  mirrorMode: MirrorMode,
93
84
  config: NativeCameraOutput.Config,
94
85
  ): NativeCameraOutput.PreparedUseCase {
95
- val requestedTarget = options.targetResolution
96
- val target = requestedTarget?.let {
97
- if (isLowRamDevice && it.width > 640.0) {
98
- val scale = 640.0 / it.width
99
- android.util.Size(640, (it.height * scale).toInt().coerceAtLeast(1))
100
- } else {
101
- android.util.Size(it.width.toInt(), it.height.toInt())
102
- }
103
- }
104
- val selector = target?.let {
105
- ResolutionSelector.Builder()
106
- .setResolutionStrategy(
107
- ResolutionStrategy(
108
- it,
109
- ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER,
110
- )
111
- )
112
- .build()
113
- }
114
86
  val analysis = ImageAnalysis.Builder()
115
87
  .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888)
116
88
  .setTargetRotation(outputOrientation.surfaceRotation)
117
89
  .setOutputImageRotationEnabled(false)
118
90
  .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
119
91
  .setAllowDroppingLateFrames(true)
120
- .apply { if (selector != null) setResolutionSelector(selector) }
121
92
  .build()
122
93
  return NativeCameraOutput.PreparedUseCase(analysis) {
123
94
  imageAnalysis = analysis
package/index.d.ts CHANGED
@@ -1,60 +1,16 @@
1
- /**
2
- * React Native Vision Camera Face Anti-Spoofing Detector
3
- * High-performance face anti-spoofing and liveness detection module
4
- * TypeScript type definitions
5
- */
1
+ import type { CameraOutput } from 'react-native-vision-camera';
6
2
 
7
- import type { CameraFrameOutput, Frame, FrameOutputOptions, FrameProcessor } from 'react-native-vision-camera';
8
- import type { SharedValue } from 'react-native-reanimated';
9
-
10
- // ============================================================================
11
- // Core Detection Results
12
- // ============================================================================
13
-
14
- /**
15
- * Face anti-spoofing detection result
16
- * Contains comprehensive information about face liveness detection
17
- */
18
3
  export interface FaceAntiSpoofingResult {
19
- /**
20
- * Neural network confidence score
21
- * Range: 0.0 to 1.0
22
- * Lower values indicate more likely to be live
23
- */
24
4
  neuralNetworkScore: number;
25
-
26
- /**
27
- * Laplacian variance-based image quality score
28
- * Range: 0.0 to 5000+
29
- * Higher values = better image quality
30
- * Used to distinguish blur from spoofing
31
- */
32
5
  laplacianScore: number;
33
-
34
- /**
35
- * Combined weighted score from multiple models
36
- * Range: 0.0 to 1.0
37
- * Provides robust detection by ensemble voting
38
- */
39
6
  combinedScore: number;
40
-
41
- /**
42
- * Derived score used with the configured liveness thresholds
43
- */
44
7
  confidence: number;
45
8
  }
46
9
 
47
- /**
48
- * Face rectangle/bounds information
49
- */
50
10
  export interface FaceRect {
51
- /** X coordinate in pixels */
52
11
  x: number;
53
- /** Y coordinate in pixels */
54
12
  y: number;
55
- /** Face width in pixels */
56
13
  width: number;
57
- /** Face height in pixels */
58
14
  height: number;
59
15
  }
60
16
 
@@ -62,420 +18,62 @@ export interface SpoofDetectedFace {
62
18
  bounds: FaceRect;
63
19
  }
64
20
 
65
- // ============================================================================
66
- // Anti-spoofing State & Configuration
67
- // ============================================================================
68
-
69
- /**
70
- * Anti-spoofing detection state
71
- */
72
- export interface AntiSpoofState {
73
- /** Confidence score (0.0-1.0) */
74
- confidence: number;
75
- /** Consecutive frames detected as live */
76
- consecutiveLiveFrames: number;
77
- /** Last detection result */
78
- lastResult: FaceAntiSpoofingResult | null;
79
- /** Whether face is single and detected */
80
- hasSingleFace: boolean;
81
- /** Whether face is centered in frame */
82
- isFaceCentered: boolean;
83
- }
84
-
85
- /**
86
- * Face tracking state
87
- */
88
- export interface FaceTrackingState {
89
- lastX: number;
90
- lastY: number;
91
- lastW: number;
92
- lastH: number;
93
- stableCount: number;
94
- }
95
-
96
- /**
97
- * Liveness detection state
98
- */
99
- export interface LivenessState {
100
- level: number;
101
- step: number;
102
- blinkCount: number;
103
- }
104
-
105
- /**
106
- * Complete shared state for frame processing
107
- */
108
- export interface SharedFrameProcessorState {
109
- lastProcessedTime: number;
110
- faceTracking: FaceTrackingState;
111
- flags: {
112
- captured: boolean;
113
- showCodeScanner: boolean;
114
- isActive: boolean;
115
- hasSingleFace: boolean;
116
- isFaceCentered: boolean;
117
- eyeClosed: boolean;
118
- };
119
- liveness: LivenessState;
120
- antiSpoof: AntiSpoofState;
121
- centering: {
122
- centeredFrames: number;
123
- frameWidth: number;
124
- frameHeight: number;
125
- };
126
- performance: {
127
- batchCounter: number;
128
- lastBatchUpdate: number;
129
- };
130
- }
131
-
132
- /**
133
- * Face detection update callback data
134
- */
135
- export interface FacesUpdateData {
136
- count: number;
137
- progress: number;
138
- step: number;
139
- isCentered: boolean;
140
- antiSpoofState: AntiSpoofState;
141
- }
142
-
143
- /**
144
- * Anti-spoof update callback data
145
- */
146
- export interface OnAntiSpoofUpdateData {
147
- confidence: number;
148
- rawResult?: FaceAntiSpoofingResult;
149
- consecutiveLiveFrames: number;
150
- isFaceCentered: boolean;
151
- }
152
-
153
- // ============================================================================
154
- // Hook Configuration
155
- // ============================================================================
156
-
157
- /**
158
- * Configuration options for useFaceDetectionFrameProcessor hook
159
- */
160
- export interface UseFaceDetectionFrameProcessorOptions {
161
- /**
162
- * Callback when a stable, live face is detected
163
- * @param faceRect - Face position and size
164
- * @param antiSpoofResult - Anti-spoofing detection result
165
- */
166
- onStableFaceDetected?: (
167
- faceRect: FaceRect,
168
- antiSpoofResult?: FaceAntiSpoofingResult
169
- ) => void;
170
-
171
- /**
172
- * Callback for face updates during detection
173
- * Called periodically with detection progress
174
- */
175
- onFacesUpdate?: (data: FacesUpdateData) => void;
176
-
177
- /**
178
- * Callback for liveness verification updates
179
- * @param step - Liveness step (0-2)
180
- * @param extra - Additional data like blink count
181
- */
182
- onLivenessUpdate?: (step: number, extra?: Record<string, any>) => void;
183
-
184
- /**
185
- * Callback for anti-spoof detection updates
186
- * Called when anti-spoofing detection result changes
187
- */
188
- onAntiSpoofUpdate?: (result: OnAntiSpoofUpdateData) => void;
189
-
190
- /**
191
- * Show code scanner overlay
192
- * @default false
193
- */
194
- showCodeScanner?: boolean;
195
-
196
- /**
197
- * Loading state - pauses frame processing
198
- * @default false
199
- */
200
- isLoading?: boolean;
201
-
202
- /**
203
- * Enable/disable frame processing
204
- * @default true
205
- */
206
- isActive?: boolean;
207
-
208
- /**
209
- * Liveness verification level
210
- * @values 0 - Anti-spoofing only (fast)
211
- * @values 1 - Anti-spoofing + blink detection (more thorough)
212
- * @default 0
213
- */
214
- livenessLevel?: number;
215
-
216
- /**
217
- * Anti-spoofing confidence threshold
218
- * Range: 0.0 - 1.0
219
- * Lower values = more lenient, higher values = stricter
220
- * @default 0.35
221
- */
222
- antispooflevel?: number;
223
- }
224
-
225
- /**
226
- * Return value from useFaceDetectionFrameProcessor hook
227
- */
228
- export interface UseFaceDetectionFrameProcessorReturn {
229
- /**
230
- * Frame processor function for Vision Camera
231
- */
232
- frameProcessor: FrameProcessor;
233
-
234
- /**
235
- * Reset capture state to initial values
236
- */
237
- resetCaptureState: () => void;
238
-
239
- /**
240
- * Force reset all states including shared values
241
- */
242
- forceResetCaptureState: () => void;
243
-
244
- /**
245
- * Update code scanner visibility
246
- */
247
- updateShowCodeScanner: (value: boolean) => void;
248
-
249
- /**
250
- * Update processing active state
251
- */
252
- updateIsActive: (active: boolean) => void;
253
-
254
- /**
255
- * Initialize anti-spoofing module
256
- */
257
- initializeAntiSpoof: () => Promise<boolean>;
258
-
259
- /**
260
- * Shared value for capture state
261
- * Use .value to access: capturedSV.value.value
262
- */
263
- capturedSV: SharedValue<boolean>;
264
-
265
- /**
266
- * Current anti-spoofing detection state
267
- */
268
- antiSpoofState: AntiSpoofState;
269
- }
270
-
271
- /**
272
- * VisionCamera 5 frame-output options for spoof detection.
273
- * The callback runs on the React Native runtime after native inference.
274
- */
275
- export interface UseFaceAntiSpoofFrameOutputOptions extends Partial<FrameOutputOptions> {
21
+ export interface UseFaceAntiSpoofFrameOutputOptions {
276
22
  antispoofLevel?: number;
277
23
  stableFrames?: number;
278
24
  requiredLiveFrames?: number;
279
25
  laplacianThreshold?: number;
280
26
  maxNeuralSpoofScore?: number;
281
- onResult?: (result: FaceAntiSpoofingResult) => void;
282
27
  onFacesDetected?: (faces: SpoofDetectedFace[]) => void;
283
- onStableFaceDetected?: (face: FaceRect, result: FaceAntiSpoofingResult) => void;
28
+ onResult?: (result: FaceAntiSpoofingResult) => void;
29
+ onStableFaceDetected?: (
30
+ face: FaceRect,
31
+ result: FaceAntiSpoofingResult,
32
+ ) => void;
284
33
  onError?: (error: Error) => void;
285
34
  }
286
35
 
287
- /** Create a VisionCamera 5 frame output backed by the native detector. */
288
- export function useFaceAntiSpoofFrameOutput(
289
- options?: UseFaceAntiSpoofFrameOutputOptions,
290
- ): CameraFrameOutput;
291
-
292
- export function resetFaceAntiSpoofFrameOutput(output: CameraFrameOutput): void;
293
-
294
- // ============================================================================
295
- // Module Functions
296
- // ============================================================================
297
-
298
- /**
299
- * Frame processor function for real-time face anti-spoofing detection
300
- * Call within a Vision Camera frame processor
301
- *
302
- * @example
303
- * ```typescript
304
- * const frameProcessor = useFrameProcessor((frame) => {
305
- * 'worklet';
306
- * const result = faceAntiSpoofFrameProcessor(frame);
307
- * if (result && result.confidence > 0.5) {
308
- * // Evaluate confidence together with neuralNetworkScore and laplacianScore.
309
- * }
310
- * }, []);
311
- * ```
312
- *
313
- * @param frame - Vision Camera frame object
314
- * @returns Detection result or null if no face detected
315
- */
316
- export function faceAntiSpoofFrameProcessor(
317
- frame: Frame
318
- ): FaceAntiSpoofingResult | null;
319
-
320
- /**
321
- * Check if face anti-spoofing module is available on device
322
- * Call before attempting to use the module
323
- *
324
- * @returns true if module is available, false otherwise
325
- */
326
- export function isFaceAntiSpoofAvailable(): boolean;
327
-
328
- /**
329
- * Initialize the face anti-spoofing module
330
- * Must be called before using the frame processor
331
- *
332
- * @returns Promise<boolean> - true if initialization successful
333
- *
334
- * @example
335
- * ```typescript
336
- * useEffect(() => {
337
- * initializeFaceAntiSpoof()
338
- * .then(success => {
339
- * if (success) {
340
- * console.log('Anti-spoof ready');
341
- * }
342
- * });
343
- * }, []);
344
- * ```
345
- */
346
- export function initializeFaceAntiSpoof(): Promise<boolean>;
347
-
348
- /**
349
- * Custom React Native hook for comprehensive face detection with anti-spoofing
350
- * Provides advanced features like blink detection and face centering
351
- *
352
- * @param options - Configuration options
353
- * @returns Hook return value with frame processor and callbacks
354
- *
355
- * @example
356
- * ```typescript
357
- * const { frameProcessor, resetCaptureState, antiSpoofState } =
358
- * useFaceDetectionFrameProcessor({
359
- * livenessLevel: 1,
360
- * antispooflevel: 0.35,
361
- * onStableFaceDetected: (rect, result) => {
362
- * console.log('Capture complete!', rect);
363
- * },
364
- * });
365
- * ```
366
- */
367
- export function useFaceDetectionFrameProcessor(
368
- options: UseFaceDetectionFrameProcessorOptions
369
- ): UseFaceDetectionFrameProcessorReturn;
370
-
371
- // ============================================================================
372
- // Accelerator Types
373
- // ============================================================================
374
-
375
- /**
376
- * TensorFlow Lite accelerator type
377
- * Determines which hardware is used for inference
378
- */
379
- export type AcceleratorType = 'CPU' | 'GPU' | 'NNAPI';
380
-
381
- /**
382
- * Module information
383
- */
384
- export interface ModuleInfo {
385
- /** Module name */
386
- name: string;
387
- /** Available API methods */
388
- methods: string[];
389
- /** Module version */
390
- version: string;
391
- /** Active accelerator (if available) */
392
- accelerator?: AcceleratorType;
393
- }
394
-
395
- /**
396
- * Model status information
397
- */
398
- export interface ModelStatus {
399
- /** Whether plugin is available on this device */
36
+ export interface FaceAntiSpoofModelStatus {
400
37
  pluginAvailable: boolean;
401
- /** Whether TensorFlow Lite model is loaded */
402
38
  modelLoaded: boolean;
403
- /** Active accelerator type */
404
- accelerator?: AcceleratorType;
39
+ moduleInitialized: boolean;
405
40
  }
406
41
 
407
- // ============================================================================
408
- // Native Module Interface
409
- // ============================================================================
42
+ export interface FaceAntiSpoofModuleInfo {
43
+ name: string;
44
+ methods: string[];
45
+ accelerators?: string[];
46
+ }
410
47
 
411
- /**
412
- * Native module interface for advanced use cases
413
- * Generally not needed - use the exported functions instead
414
- */
415
48
  export interface FaceAntiSpoofModule {
416
- /**
417
- * Initialize native module
418
- */
419
49
  initialize(): Promise<boolean>;
420
-
421
- /**
422
- * Check model loading status
423
- */
424
- checkModelStatus(): Promise<ModelStatus>;
425
-
426
- /**
427
- * Check module availability
428
- */
50
+ checkModelStatus(): Promise<FaceAntiSpoofModelStatus>;
429
51
  isAvailable(): Promise<boolean>;
430
-
431
- /**
432
- * Test connection to native module
433
- */
434
52
  testMethod(): Promise<string>;
435
-
436
- /**
437
- * Get module information
438
- */
439
- getModuleInfo(): Promise<ModuleInfo>;
440
-
441
- /**
442
- * Install/setup native dependencies
443
- */
53
+ getModuleInfo(): Promise<FaceAntiSpoofModuleInfo>;
444
54
  install(): Promise<boolean>;
55
+ processFrame?(
56
+ frameData: number[][],
57
+ width: number,
58
+ height: number,
59
+ rowStrides: number[],
60
+ pixelStrides: number[],
61
+ ): Promise<FaceAntiSpoofingResult>;
62
+ cleanup?(): Promise<boolean>;
63
+ getAccelerator?(): Promise<string>;
445
64
  }
446
65
 
447
- /**
448
- * Native module instance
449
- */
450
- declare const FaceAntiSpoof: FaceAntiSpoofModule;
451
-
452
- export default FaceAntiSpoof;
453
-
454
- // ============================================================================
455
- // Constants
456
- // ============================================================================
457
-
458
- /**
459
- * Default anti-spoofing confidence threshold
460
- */
461
- export const DEFAULT_ANTI_SPOOF_LEVEL = 0.35;
66
+ export declare function useFaceAntiSpoofFrameOutput(
67
+ options?: UseFaceAntiSpoofFrameOutputOptions,
68
+ ): CameraOutput;
462
69
 
463
- /**
464
- * Default face stability threshold (frames)
465
- */
466
- export const DEFAULT_FACE_STABILITY_THRESHOLD = 3;
70
+ export declare function resetFaceAntiSpoofFrameOutput(
71
+ output: CameraOutput,
72
+ ): void;
467
73
 
468
- /**
469
- * Default face movement threshold (pixels)
470
- */
471
- export const DEFAULT_FACE_MOVEMENT_THRESHOLD = 15;
74
+ export declare function isFaceAntiSpoofAvailable(): boolean;
472
75
 
473
- /**
474
- * Minimum required blinks for liveness verification
475
- */
476
- export const DEFAULT_REQUIRED_BLINKS = 3;
76
+ export declare function initializeFaceAntiSpoof(): Promise<boolean>;
477
77
 
478
- /**
479
- * Blink detection threshold (eye closure probability)
480
- */
481
- export const DEFAULT_BLINK_THRESHOLD = 0.3;
78
+ declare const FaceAntiSpoof: FaceAntiSpoofModule | undefined;
79
+ export default FaceAntiSpoof;
package/index.js CHANGED
@@ -34,7 +34,6 @@ export const useFaceAntiSpoofFrameOutput = ({
34
34
  );
35
35
  return useMemo(
36
36
  () => factory.createSpoofDetectorOutput({
37
- targetResolution: options.targetResolution,
38
37
  antispoofLevel: options.antispoofLevel,
39
38
  stableFrames: options.stableFrames,
40
39
  requiredLiveFrames: options.requiredLiveFrames,
@@ -55,7 +54,6 @@ export const useFaceAntiSpoofFrameOutput = ({
55
54
  }),
56
55
  [
57
56
  factory,
58
- options.targetResolution,
59
57
  options.antispoofLevel,
60
58
  options.stableFrames,
61
59
  options.requiredLiveFrames,
@@ -31,10 +31,6 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
31
31
  private var requiredLiveFrames: Int { max(1, Int(options.requiredLiveFrames ?? 3)) }
32
32
  private var laplacianThreshold: Double { options.laplacianThreshold ?? 1100 }
33
33
  private var maxNeuralSpoofScore: Double { options.maxNeuralSpoofScore ?? 0.1 }
34
- private var isLowMemoryDevice: Bool {
35
- ProcessInfo.processInfo.physicalMemory <= 4 * 1024 * 1024 * 1024
36
- }
37
-
38
34
  let output = AVCaptureVideoDataOutput()
39
35
  let requiresAudioInput = false
40
36
  let requiresDepthFormat = false
@@ -48,24 +44,7 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
48
44
  }
49
45
 
50
46
  var targetResolution: ResolutionRule {
51
- guard let requestedSize = options.targetResolution else {
52
- return .any
53
- }
54
- let requestedResolution = margelo.nitro.camera.Size(
55
- width: requestedSize.width,
56
- height: requestedSize.height
57
- )
58
- let resolution: margelo.nitro.camera.Size
59
- if isLowMemoryDevice && requestedResolution.width > 640 {
60
- let scale = 640 / requestedResolution.width
61
- resolution = margelo.nitro.camera.Size(
62
- width: 640,
63
- height: max(1, (requestedResolution.height * scale).rounded())
64
- )
65
- } else {
66
- resolution = requestedResolution
67
- }
68
- return .closestTo(resolution)
47
+ return .any
69
48
  }
70
49
 
71
50
  init(options: SpoofDetectorOutputOptions) {
@@ -16,10 +16,8 @@
16
16
  #include "JFunc_void_SpoofDetectedFaceBounds_AntiSpoofingResult.hpp"
17
17
  #include "JFunc_void_std__exception_ptr.hpp"
18
18
  #include "JFunc_void_std__vector_SpoofDetectedFace_.hpp"
19
- #include "JSize.hpp"
20
19
  #include "JSpoofDetectedFace.hpp"
21
20
  #include "JSpoofDetectedFaceBounds.hpp"
22
- #include "Size.hpp"
23
21
  #include "SpoofDetectedFace.hpp"
24
22
  #include "SpoofDetectedFaceBounds.hpp"
25
23
  #include <NitroModules/JNICallable.hpp>
@@ -48,8 +46,6 @@ namespace margelo::nitro::camera::spoofdetector {
48
46
  [[nodiscard]]
49
47
  SpoofDetectorOutputOptions toCpp() const {
50
48
  static const auto clazz = javaClassStatic();
51
- static const auto fieldTargetResolution = clazz->getField<JSize>("targetResolution");
52
- jni::local_ref<JSize> targetResolution = this->getFieldValue(fieldTargetResolution);
53
49
  static const auto fieldAntispoofLevel = clazz->getField<jni::JDouble>("antispoofLevel");
54
50
  jni::local_ref<jni::JDouble> antispoofLevel = this->getFieldValue(fieldAntispoofLevel);
55
51
  static const auto fieldStableFrames = clazz->getField<jni::JDouble>("stableFrames");
@@ -69,7 +65,6 @@ namespace margelo::nitro::camera::spoofdetector {
69
65
  static const auto fieldOnError = clazz->getField<JFunc_void_std__exception_ptr::javaobject>("onError");
70
66
  jni::local_ref<JFunc_void_std__exception_ptr::javaobject> onError = this->getFieldValue(fieldOnError);
71
67
  return SpoofDetectorOutputOptions(
72
- targetResolution != nullptr ? std::make_optional(targetResolution->toCpp()) : std::nullopt,
73
68
  antispoofLevel != nullptr ? std::make_optional(antispoofLevel->value()) : std::nullopt,
74
69
  stableFrames != nullptr ? std::make_optional(stableFrames->value()) : std::nullopt,
75
70
  requiredLiveFrames != nullptr ? std::make_optional(requiredLiveFrames->value()) : std::nullopt,
@@ -120,12 +115,11 @@ namespace margelo::nitro::camera::spoofdetector {
120
115
  */
121
116
  [[maybe_unused]]
122
117
  static jni::local_ref<JSpoofDetectorOutputOptions::javaobject> fromCpp(const SpoofDetectorOutputOptions& value) {
123
- using JSignature = JSpoofDetectorOutputOptions(jni::alias_ref<JSize>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<JFunc_void_AntiSpoofingResult::javaobject>, jni::alias_ref<JFunc_void_std__vector_SpoofDetectedFace_::javaobject>, jni::alias_ref<JFunc_void_SpoofDetectedFaceBounds_AntiSpoofingResult::javaobject>, jni::alias_ref<JFunc_void_std__exception_ptr::javaobject>);
118
+ using JSignature = JSpoofDetectorOutputOptions(jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<JFunc_void_AntiSpoofingResult::javaobject>, jni::alias_ref<JFunc_void_std__vector_SpoofDetectedFace_::javaobject>, jni::alias_ref<JFunc_void_SpoofDetectedFaceBounds_AntiSpoofingResult::javaobject>, jni::alias_ref<JFunc_void_std__exception_ptr::javaobject>);
124
119
  static const auto clazz = javaClassStatic();
125
120
  static const auto create = clazz->getStaticMethod<JSignature>("fromCpp");
126
121
  return create(
127
122
  clazz,
128
- value.targetResolution.has_value() ? JSize::fromCpp(value.targetResolution.value()) : nullptr,
129
123
  value.antispoofLevel.has_value() ? jni::JDouble::valueOf(value.antispoofLevel.value()) : nullptr,
130
124
  value.stableFrames.has_value() ? jni::JDouble::valueOf(value.stableFrames.value()) : nullptr,
131
125
  value.requiredLiveFrames.has_value() ? jni::JDouble::valueOf(value.requiredLiveFrames.value()) : nullptr,
@@ -18,9 +18,6 @@ import java.util.Objects
18
18
  @DoNotStrip
19
19
  @Keep
20
20
  data class SpoofDetectorOutputOptions(
21
- @DoNotStrip
22
- @Keep
23
- val targetResolution: Size?,
24
21
  @DoNotStrip
25
22
  @Keep
26
23
  val antispoofLevel: Double?,
@@ -52,14 +49,13 @@ data class SpoofDetectorOutputOptions(
52
49
  /**
53
50
  * Create a new instance of SpoofDetectorOutputOptions from Kotlin
54
51
  */
55
- constructor(targetResolution: Size?, antispoofLevel: Double?, stableFrames: Double?, requiredLiveFrames: Double?, laplacianThreshold: Double?, maxNeuralSpoofScore: Double?, onResult: (result: AntiSpoofingResult) -> Unit, onFacesDetected: ((faces: Array<SpoofDetectedFace>) -> Unit)?, onStableFaceDetected: ((face: SpoofDetectedFaceBounds, result: AntiSpoofingResult) -> Unit)?, onError: ((error: Throwable) -> Unit)?):
56
- this(targetResolution, antispoofLevel, stableFrames, requiredLiveFrames, laplacianThreshold, maxNeuralSpoofScore, Func_void_AntiSpoofingResult_java(onResult), onFacesDetected?.let { Func_void_std__vector_SpoofDetectedFace__java(it) }, onStableFaceDetected?.let { Func_void_SpoofDetectedFaceBounds_AntiSpoofingResult_java(it) }, onError?.let { Func_void_std__exception_ptr_java(it) })
52
+ constructor(antispoofLevel: Double?, stableFrames: Double?, requiredLiveFrames: Double?, laplacianThreshold: Double?, maxNeuralSpoofScore: Double?, onResult: (result: AntiSpoofingResult) -> Unit, onFacesDetected: ((faces: Array<SpoofDetectedFace>) -> Unit)?, onStableFaceDetected: ((face: SpoofDetectedFaceBounds, result: AntiSpoofingResult) -> Unit)?, onError: ((error: Throwable) -> Unit)?):
53
+ this(antispoofLevel, stableFrames, requiredLiveFrames, laplacianThreshold, maxNeuralSpoofScore, Func_void_AntiSpoofingResult_java(onResult), onFacesDetected?.let { Func_void_std__vector_SpoofDetectedFace__java(it) }, onStableFaceDetected?.let { Func_void_SpoofDetectedFaceBounds_AntiSpoofingResult_java(it) }, onError?.let { Func_void_std__exception_ptr_java(it) })
57
54
 
58
55
  override fun equals(other: Any?): Boolean {
59
56
  if (this === other) return true
60
57
  if (other !is SpoofDetectorOutputOptions) return false
61
- return Objects.deepEquals(this.targetResolution, other.targetResolution)
62
- && Objects.deepEquals(this.antispoofLevel, other.antispoofLevel)
58
+ return Objects.deepEquals(this.antispoofLevel, other.antispoofLevel)
63
59
  && Objects.deepEquals(this.stableFrames, other.stableFrames)
64
60
  && Objects.deepEquals(this.requiredLiveFrames, other.requiredLiveFrames)
65
61
  && Objects.deepEquals(this.laplacianThreshold, other.laplacianThreshold)
@@ -72,7 +68,6 @@ data class SpoofDetectorOutputOptions(
72
68
 
73
69
  override fun hashCode(): Int {
74
70
  return arrayOf<Any?>(
75
- targetResolution,
76
71
  antispoofLevel,
77
72
  stableFrames,
78
73
  requiredLiveFrames,
@@ -93,8 +88,8 @@ data class SpoofDetectorOutputOptions(
93
88
  @Keep
94
89
  @Suppress("unused")
95
90
  @JvmStatic
96
- private fun fromCpp(targetResolution: Size?, antispoofLevel: Double?, stableFrames: Double?, requiredLiveFrames: Double?, laplacianThreshold: Double?, maxNeuralSpoofScore: Double?, onResult: Func_void_AntiSpoofingResult, onFacesDetected: Func_void_std__vector_SpoofDetectedFace_?, onStableFaceDetected: Func_void_SpoofDetectedFaceBounds_AntiSpoofingResult?, onError: Func_void_std__exception_ptr?): SpoofDetectorOutputOptions {
97
- return SpoofDetectorOutputOptions(targetResolution, antispoofLevel, stableFrames, requiredLiveFrames, laplacianThreshold, maxNeuralSpoofScore, onResult, onFacesDetected, onStableFaceDetected, onError)
91
+ private fun fromCpp(antispoofLevel: Double?, stableFrames: Double?, requiredLiveFrames: Double?, laplacianThreshold: Double?, maxNeuralSpoofScore: Double?, onResult: Func_void_AntiSpoofingResult, onFacesDetected: Func_void_std__vector_SpoofDetectedFace_?, onStableFaceDetected: Func_void_SpoofDetectedFaceBounds_AntiSpoofingResult?, onError: Func_void_std__exception_ptr?): SpoofDetectorOutputOptions {
92
+ return SpoofDetectorOutputOptions(antispoofLevel, stableFrames, requiredLiveFrames, laplacianThreshold, maxNeuralSpoofScore, onResult, onFacesDetected, onStableFaceDetected, onError)
98
93
  }
99
94
  }
100
95
  }
@@ -18,14 +18,8 @@ public extension SpoofDetectorOutputOptions {
18
18
  /**
19
19
  * Create a new instance of `SpoofDetectorOutputOptions`.
20
20
  */
21
- init(targetResolution: Size?, antispoofLevel: Double?, stableFrames: Double?, requiredLiveFrames: Double?, laplacianThreshold: Double?, maxNeuralSpoofScore: Double?, onResult: @escaping (_ result: AntiSpoofingResult) -> Void, onFacesDetected: ((_ faces: [SpoofDetectedFace]) -> Void)?, onStableFaceDetected: ((_ face: SpoofDetectedFaceBounds, _ result: AntiSpoofingResult) -> Void)?, onError: ((_ error: Error) -> Void)?) {
22
- self.init({ () -> bridge.std__optional_Size_ in
23
- if let __unwrappedValue = targetResolution {
24
- return bridge.create_std__optional_Size_(__unwrappedValue)
25
- } else {
26
- return .init()
27
- }
28
- }(), { () -> bridge.std__optional_double_ in
21
+ init(antispoofLevel: Double?, stableFrames: Double?, requiredLiveFrames: Double?, laplacianThreshold: Double?, maxNeuralSpoofScore: Double?, onResult: @escaping (_ result: AntiSpoofingResult) -> Void, onFacesDetected: ((_ faces: [SpoofDetectedFace]) -> Void)?, onStableFaceDetected: ((_ face: SpoofDetectedFaceBounds, _ result: AntiSpoofingResult) -> Void)?, onError: ((_ error: Error) -> Void)?) {
22
+ self.init({ () -> bridge.std__optional_double_ in
29
23
  if let __unwrappedValue = antispoofLevel {
30
24
  return bridge.create_std__optional_double_(__unwrappedValue)
31
25
  } else {
@@ -89,10 +83,6 @@ public extension SpoofDetectorOutputOptions {
89
83
  }
90
84
 
91
85
  @inline(__always)
92
- var targetResolution: Size? {
93
- return self.__targetResolution.value
94
- }
95
-
96
86
  @inline(__always)
97
87
  var antispoofLevel: Double? {
98
88
  return { () -> Double? in
@@ -28,8 +28,6 @@
28
28
  #error NitroModules cannot be found! Are you sure you installed NitroModules properly?
29
29
  #endif
30
30
 
31
- // Forward declaration of `Size` to properly resolve imports.
32
- namespace margelo::nitro::camera::spoofdetector { struct Size; }
33
31
  // Forward declaration of `AntiSpoofingResult` to properly resolve imports.
34
32
  namespace margelo::nitro::camera::spoofdetector { struct AntiSpoofingResult; }
35
33
  // Forward declaration of `SpoofDetectedFace` to properly resolve imports.
@@ -37,7 +35,6 @@ namespace margelo::nitro::camera::spoofdetector { struct SpoofDetectedFace; }
37
35
  // Forward declaration of `SpoofDetectedFaceBounds` to properly resolve imports.
38
36
  namespace margelo::nitro::camera::spoofdetector { struct SpoofDetectedFaceBounds; }
39
37
 
40
- #include "Size.hpp"
41
38
  #include <optional>
42
39
  #include "AntiSpoofingResult.hpp"
43
40
  #include <functional>
@@ -53,7 +50,6 @@ namespace margelo::nitro::camera::spoofdetector {
53
50
  */
54
51
  struct SpoofDetectorOutputOptions final {
55
52
  public:
56
- std::optional<Size> targetResolution SWIFT_PRIVATE;
57
53
  std::optional<double> antispoofLevel SWIFT_PRIVATE;
58
54
  std::optional<double> stableFrames SWIFT_PRIVATE;
59
55
  std::optional<double> requiredLiveFrames SWIFT_PRIVATE;
@@ -66,7 +62,7 @@ namespace margelo::nitro::camera::spoofdetector {
66
62
 
67
63
  public:
68
64
  SpoofDetectorOutputOptions() = default;
69
- explicit SpoofDetectorOutputOptions(std::optional<Size> targetResolution, std::optional<double> antispoofLevel, std::optional<double> stableFrames, std::optional<double> requiredLiveFrames, std::optional<double> laplacianThreshold, std::optional<double> maxNeuralSpoofScore, std::function<void(const AntiSpoofingResult& /* result */)> onResult, std::optional<std::function<void(const std::vector<SpoofDetectedFace>& /* faces */)>> onFacesDetected, std::optional<std::function<void(const SpoofDetectedFaceBounds& /* face */, const AntiSpoofingResult& /* result */)>> onStableFaceDetected, std::optional<std::function<void(const std::exception_ptr& /* error */)>> onError): targetResolution(targetResolution), antispoofLevel(antispoofLevel), stableFrames(stableFrames), requiredLiveFrames(requiredLiveFrames), laplacianThreshold(laplacianThreshold), maxNeuralSpoofScore(maxNeuralSpoofScore), onResult(onResult), onFacesDetected(onFacesDetected), onStableFaceDetected(onStableFaceDetected), onError(onError) {}
65
+ explicit SpoofDetectorOutputOptions(std::optional<double> antispoofLevel, std::optional<double> stableFrames, std::optional<double> requiredLiveFrames, std::optional<double> laplacianThreshold, std::optional<double> maxNeuralSpoofScore, std::function<void(const AntiSpoofingResult& /* result */)> onResult, std::optional<std::function<void(const std::vector<SpoofDetectedFace>& /* faces */)>> onFacesDetected, std::optional<std::function<void(const SpoofDetectedFaceBounds& /* face */, const AntiSpoofingResult& /* result */)>> onStableFaceDetected, std::optional<std::function<void(const std::exception_ptr& /* error */)>> onError): antispoofLevel(antispoofLevel), stableFrames(stableFrames), requiredLiveFrames(requiredLiveFrames), laplacianThreshold(laplacianThreshold), maxNeuralSpoofScore(maxNeuralSpoofScore), onResult(onResult), onFacesDetected(onFacesDetected), onStableFaceDetected(onStableFaceDetected), onError(onError) {}
70
66
 
71
67
  public:
72
68
  // SpoofDetectorOutputOptions is not equatable because these properties are not equatable: onResult, onFacesDetected, onStableFaceDetected, onError
@@ -82,7 +78,6 @@ namespace margelo::nitro {
82
78
  static inline margelo::nitro::camera::spoofdetector::SpoofDetectorOutputOptions fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
83
79
  jsi::Object obj = arg.asObject(runtime);
84
80
  return margelo::nitro::camera::spoofdetector::SpoofDetectorOutputOptions(
85
- JSIConverter<std::optional<margelo::nitro::camera::spoofdetector::Size>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "targetResolution"))),
86
81
  JSIConverter<std::optional<double>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "antispoofLevel"))),
87
82
  JSIConverter<std::optional<double>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "stableFrames"))),
88
83
  JSIConverter<std::optional<double>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "requiredLiveFrames"))),
@@ -96,7 +91,6 @@ namespace margelo::nitro {
96
91
  }
97
92
  static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::camera::spoofdetector::SpoofDetectorOutputOptions& arg) {
98
93
  jsi::Object obj(runtime);
99
- obj.setProperty(runtime, PropNameIDCache::get(runtime, "targetResolution"), JSIConverter<std::optional<margelo::nitro::camera::spoofdetector::Size>>::toJSI(runtime, arg.targetResolution));
100
94
  obj.setProperty(runtime, PropNameIDCache::get(runtime, "antispoofLevel"), JSIConverter<std::optional<double>>::toJSI(runtime, arg.antispoofLevel));
101
95
  obj.setProperty(runtime, PropNameIDCache::get(runtime, "stableFrames"), JSIConverter<std::optional<double>>::toJSI(runtime, arg.stableFrames));
102
96
  obj.setProperty(runtime, PropNameIDCache::get(runtime, "requiredLiveFrames"), JSIConverter<std::optional<double>>::toJSI(runtime, arg.requiredLiveFrames));
@@ -116,7 +110,6 @@ namespace margelo::nitro {
116
110
  if (!nitro::isPlainObject(runtime, obj)) {
117
111
  return false;
118
112
  }
119
- if (!JSIConverter<std::optional<margelo::nitro::camera::spoofdetector::Size>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "targetResolution")))) return false;
120
113
  if (!JSIConverter<std::optional<double>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "antispoofLevel")))) return false;
121
114
  if (!JSIConverter<std::optional<double>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "stableFrames")))) return false;
122
115
  if (!JSIConverter<std::optional<double>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "requiredLiveFrames")))) return false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-vision-camera-spoof-detector",
3
- "version": "1.3.5",
3
+ "version": "1.3.7",
4
4
  "description": "High-performance face anti-spoofing and liveness detection module for React Native Vision Camera. Uses TensorFlow Lite with GPU acceleration and optimized YUV processing.",
5
5
  "homepage": "https://github.com/dpraful/react-native-vision-camera-spoof-detector",
6
6
  "repository": {
@@ -1,4 +1,4 @@
1
- import type { CameraOutput, Size } from 'react-native-vision-camera'
1
+ import type { CameraOutput } from 'react-native-vision-camera'
2
2
  import type { HybridObject } from 'react-native-nitro-modules'
3
3
 
4
4
  export interface AntiSpoofingResult {
@@ -20,7 +20,6 @@ export interface SpoofDetectedFace {
20
20
  }
21
21
 
22
22
  export interface SpoofDetectorOutputOptions {
23
- targetResolution?: Size
24
23
  antispoofLevel?: number
25
24
  stableFrames?: number
26
25
  requiredLiveFrames?: number