react-native-vision-camera-spoof-detector 1.2.4 → 1.2.6

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.
@@ -24,7 +24,7 @@ class FaceAntiSpoofModule(reactContext: ReactApplicationContext) : ReactContextB
24
24
  pixelStrides: IntArray
25
25
  ): DoubleArray {
26
26
  val module = activeModule
27
- ?: return doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0)
27
+ ?: return doubleArrayOf(0.0, 0.0, 0.0, 0.0)
28
28
  return module.processNativeFrame(planes, width, height, rowStrides, pixelStrides)
29
29
  }
30
30
  }
@@ -121,13 +121,9 @@ class FaceAntiSpoofModule(reactContext: ReactApplicationContext) : ReactContextB
121
121
  yuvRowStrides,
122
122
  yuvPixelStrides
123
123
  )
124
- val isLive = result.neuralNetworkScore < FaceAntiSpoofingAdvanced.BASE_THRESHOLD &&
125
- result.laplacianScore > FaceAntiSpoofingAdvanced.LAPLACIAN_THRESHOLD
126
124
  promise.resolve(
127
125
  Arguments.makeNativeMap(
128
126
  mapOf(
129
- "isLive" to isLive,
130
- "label" to if (isLive) "Live Face" else "Spoof Face",
131
127
  "neuralNetworkScore" to result.neuralNetworkScore.toDouble(),
132
128
  "laplacianScore" to result.laplacianScore,
133
129
  "combinedScore" to result.combinedScore.toDouble(),
@@ -149,7 +145,7 @@ class FaceAntiSpoofModule(reactContext: ReactApplicationContext) : ReactContextB
149
145
  pixelStrides: IntArray
150
146
  ): DoubleArray {
151
147
  if (!isModuleInitialized || faceAntiSpoofing == null || planes.size < 3) {
152
- return doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0)
148
+ return doubleArrayOf(0.0, 0.0, 0.0, 0.0)
153
149
  }
154
150
 
155
151
  return try {
@@ -160,10 +156,7 @@ class FaceAntiSpoofModule(reactContext: ReactApplicationContext) : ReactContextB
160
156
  rowStrides,
161
157
  pixelStrides
162
158
  )
163
- val isLive = result.neuralNetworkScore < FaceAntiSpoofingAdvanced.BASE_THRESHOLD &&
164
- result.laplacianScore > FaceAntiSpoofingAdvanced.LAPLACIAN_THRESHOLD
165
159
  doubleArrayOf(
166
- if (isLive) 1.0 else 0.0,
167
160
  result.neuralNetworkScore.toDouble(),
168
161
  result.laplacianScore.toDouble(),
169
162
  result.combinedScore.toDouble(),
@@ -171,7 +164,7 @@ class FaceAntiSpoofModule(reactContext: ReactApplicationContext) : ReactContextB
171
164
  )
172
165
  } catch (error: Exception) {
173
166
  android.util.Log.e("FaceAntiSpoof", "Native frame processing failed", error)
174
- doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0)
167
+ doubleArrayOf(0.0, 0.0, 0.0, 0.0)
175
168
  }
176
169
  }
177
170
 
@@ -2,6 +2,7 @@ package com.faceantispoof
2
2
 
3
3
  import android.content.res.AssetManager
4
4
  import android.graphics.Bitmap
5
+ import android.graphics.Matrix
5
6
  import org.tensorflow.lite.Interpreter
6
7
  import org.tensorflow.lite.gpu.CompatibilityList
7
8
  import org.tensorflow.lite.gpu.GpuDelegate
@@ -126,7 +127,6 @@ class FaceAntiSpoofingAdvanced(private val assetManager: AssetManager) {
126
127
  } else {
127
128
  val nnScore = neuralNetworkAntiSpoofing(bitmap).getOrThrow()
128
129
  val laplacianScore = laplacian(bitmap).getOrThrow()
129
- val isLive = nnScore < BASE_THRESHOLD && laplacianScore > LAPLACIAN_THRESHOLD
130
130
  val combinedScore = calculateCombinedScore(nnScore, laplacianScore)
131
131
  val confidence = calculateConfidence(nnScore, laplacianScore)
132
132
 
@@ -201,13 +201,28 @@ class FaceAntiSpoofingAdvanced(private val assetManager: AssetManager) {
201
201
  width: Int,
202
202
  height: Int,
203
203
  rowStrides: IntArray,
204
- pixelStrides: IntArray
204
+ pixelStrides: IntArray,
205
+ rotationDegrees: Int = 0
205
206
  ): AntiSpoofingResult {
206
207
  if (planes.size < 3) {
207
208
  throw IllegalArgumentException("Expected Y, U and V planes")
208
209
  }
209
210
 
210
- val bitmap = yuv420ToBitmap(planes, width, height, rowStrides, pixelStrides)
211
+ val sourceBitmap = yuv420ToBitmap(planes, width, height, rowStrides, pixelStrides)
212
+ val rotation = ((rotationDegrees % 360) + 360) % 360
213
+ val bitmap = if (rotation == 0) {
214
+ sourceBitmap
215
+ } else {
216
+ Bitmap.createBitmap(
217
+ sourceBitmap,
218
+ 0,
219
+ 0,
220
+ sourceBitmap.width,
221
+ sourceBitmap.height,
222
+ Matrix().apply { postRotate(rotation.toFloat()) },
223
+ true
224
+ ).also { sourceBitmap.recycle() }
225
+ }
211
226
  return try {
212
227
  runBlocking { advancedAntiSpoofing(bitmap).getOrThrow() }
213
228
  } finally {
@@ -233,7 +248,6 @@ class FaceAntiSpoofingAdvanced(private val assetManager: AssetManager) {
233
248
  val nnResult = neuralNetworkAntiSpoofingSampled(sampled.rgbBuffer)
234
249
  val nnScore = nnResult.getOrNull() ?: throw IllegalStateException(nnResult.exceptionOrNull()?.message ?: "NN inference failed")
235
250
  val laplacianScore = calculateLaplacianFromGray(sampled.grayBuffer)
236
- val isLive = nnScore < BASE_THRESHOLD && laplacianScore > LAPLACIAN_THRESHOLD
237
251
  val combinedScore = calculateCombinedScore(nnScore, laplacianScore)
238
252
  val confidence = calculateConfidence(nnScore, laplacianScore)
239
253
 
@@ -78,7 +78,6 @@ class HybridSpoofDetectorOutput(
78
78
  private var stableCount = 0
79
79
  private var lastFaceBounds: SpoofDetectedFaceBounds? = null
80
80
  private var consecutiveLiveFrames = 0
81
- private var isLive = false
82
81
  private var lastSpoofResult: AntiSpoofingResult? = null
83
82
  private var lastFaceCount = -1
84
83
  private var lastFacesUpdateAtMs = 0L
@@ -184,13 +183,10 @@ class HybridSpoofDetectorOutput(
184
183
  image.height,
185
184
  rowStrides,
186
185
  pixelStrides,
186
+ image.imageInfo.rotationDegrees,
187
187
  )
188
- val isLive = result.neuralNetworkScore < FaceAntiSpoofingAdvanced.BASE_THRESHOLD &&
189
- result.laplacianScore > FaceAntiSpoofingAdvanced.LAPLACIAN_THRESHOLD
190
188
  processAntiSpoofResult(
191
189
  AntiSpoofingResult(
192
- isLive,
193
- if (isLive) "Live Face" else "Spoof Face",
194
190
  result.neuralNetworkScore.toDouble(),
195
191
  result.laplacianScore.toDouble(),
196
192
  result.combinedScore.toDouble(),
@@ -223,7 +219,6 @@ class HybridSpoofDetectorOutput(
223
219
  stableCount = 0
224
220
  lastFaceBounds = null
225
221
  consecutiveLiveFrames = 0
226
- isLive = false
227
222
  lastSpoofResult = null
228
223
  }
229
224
 
@@ -250,7 +245,6 @@ class HybridSpoofDetectorOutput(
250
245
  val isNeuralSpoof = result.neuralNetworkScore >= maxNeuralSpoofScore
251
246
  if (isNeuralSpoof) {
252
247
  consecutiveLiveFrames = 0
253
- isLive = false
254
248
  } else {
255
249
  val targetPercent = (antispoofLevel * 100).roundToInt()
256
250
  val currentPercent = (result.confidence * 100).roundToInt()
@@ -261,13 +255,12 @@ class HybridSpoofDetectorOutput(
261
255
  result.combinedScore >= antispoofLevel
262
256
  val meetsLaplacian = result.laplacianScore == 0.0 ||
263
257
  result.laplacianScore >= laplacianThreshold
264
- val isLiveFrame = meetsConfidence && meetsLaplacian
265
- consecutiveLiveFrames = if (isLiveFrame) {
258
+ val framePassesLiveness = meetsConfidence && meetsLaplacian
259
+ consecutiveLiveFrames = if (framePassesLiveness) {
266
260
  min(requiredLiveFrames, consecutiveLiveFrames + 1)
267
261
  } else {
268
262
  max(0, consecutiveLiveFrames - 1)
269
263
  }
270
- isLive = consecutiveLiveFrames >= requiredLiveFrames
271
264
  }
272
265
 
273
266
  shouldNotify = now - lastResultUpdateAtMs >= uiUpdateIntervalMs
@@ -282,7 +275,7 @@ class HybridSpoofDetectorOutput(
282
275
  }
283
276
 
284
277
  private fun readyToCaptureLocked(): Pair<SpoofDetectedFaceBounds, AntiSpoofingResult>? {
285
- if (captured || stableCount < stableFrames || !isLive ||
278
+ if (captured || stableCount < stableFrames ||
286
279
  consecutiveLiveFrames < requiredLiveFrames
287
280
  ) return null
288
281
  val bounds = lastFaceBounds ?: return null
@@ -298,7 +291,6 @@ class HybridSpoofDetectorOutput(
298
291
  stableCount = 0
299
292
  lastFaceBounds = null
300
293
  consecutiveLiveFrames = 0
301
- isLive = false
302
294
  lastSpoofResult = null
303
295
  lastFaceCount = -1
304
296
  lastFacesUpdateAtMs = 0L
package/index.js CHANGED
@@ -3,76 +3,76 @@ import { NativeModules } from 'react-native';
3
3
  import { NitroModules } from 'react-native-nitro-modules';
4
4
 
5
5
  const { FaceAntiSpoof } = NativeModules;
6
- let sharedSpoofDetectorFactory;
6
+ let sharedSpoofDetectorFactory;
7
7
 
8
- const getSpoofDetectorFactory = () => {
9
- if (!sharedSpoofDetectorFactory) {
10
- sharedSpoofDetectorFactory = NitroModules.createHybridObject('SpoofDetectorFactory');
11
- }
12
- return sharedSpoofDetectorFactory;
13
- };
14
-
15
- export const useFaceAntiSpoofFrameOutput = ({
16
- onResult,
17
- onFacesDetected,
18
- onStableFaceDetected,
19
- ...options
20
- } = {}) => {
8
+ const getSpoofDetectorFactory = () => {
9
+ if (!sharedSpoofDetectorFactory) {
10
+ sharedSpoofDetectorFactory = NitroModules.createHybridObject('SpoofDetectorFactory');
11
+ }
12
+ return sharedSpoofDetectorFactory;
13
+ };
14
+
15
+ export const useFaceAntiSpoofFrameOutput = ({
16
+ onResult,
17
+ onFacesDetected,
18
+ onStableFaceDetected,
19
+ ...options
20
+ } = {}) => {
21
21
  const resultRef = useRef(onResult);
22
22
  resultRef.current = onResult;
23
- const facesRef = useRef(onFacesDetected);
24
- facesRef.current = onFacesDetected;
25
- const stableFaceRef = useRef(onStableFaceDetected);
26
- stableFaceRef.current = onStableFaceDetected;
23
+ const facesRef = useRef(onFacesDetected);
24
+ facesRef.current = onFacesDetected;
25
+ const stableFaceRef = useRef(onStableFaceDetected);
26
+ stableFaceRef.current = onStableFaceDetected;
27
27
  const errorRef = useRef(options.onError);
28
28
  errorRef.current = options.onError;
29
- const hasFaceCallback = typeof onFacesDetected === 'function';
30
- const hasStableFaceCallback = typeof onStableFaceDetected === 'function';
29
+ const hasFaceCallback = typeof onFacesDetected === 'function';
30
+ const hasStableFaceCallback = typeof onStableFaceDetected === 'function';
31
31
  const factory = useMemo(
32
- getSpoofDetectorFactory,
32
+ getSpoofDetectorFactory,
33
33
  [],
34
34
  );
35
35
  return useMemo(
36
36
  () => factory.createSpoofDetectorOutput({
37
- targetResolution: options.targetResolution,
38
- antispoofLevel: options.antispoofLevel,
39
- stableFrames: options.stableFrames,
40
- requiredLiveFrames: options.requiredLiveFrames,
41
- laplacianThreshold: options.laplacianThreshold,
42
- maxNeuralSpoofScore: options.maxNeuralSpoofScore,
43
- uiUpdateIntervalMs: options.uiUpdateIntervalMs,
37
+ targetResolution: options.targetResolution,
38
+ antispoofLevel: options.antispoofLevel,
39
+ stableFrames: options.stableFrames,
40
+ requiredLiveFrames: options.requiredLiveFrames,
41
+ laplacianThreshold: options.laplacianThreshold,
42
+ maxNeuralSpoofScore: options.maxNeuralSpoofScore,
43
+ uiUpdateIntervalMs: options.uiUpdateIntervalMs,
44
44
  onResult(result) {
45
45
  resultRef.current?.(result);
46
46
  },
47
- onFacesDetected: hasFaceCallback
48
- ? (faces) => facesRef.current?.(faces)
49
- : undefined,
50
- onStableFaceDetected: hasStableFaceCallback
51
- ? (face, result) => stableFaceRef.current?.(face, result)
52
- : undefined,
47
+ onFacesDetected: hasFaceCallback
48
+ ? (faces) => facesRef.current?.(faces)
49
+ : undefined,
50
+ onStableFaceDetected: hasStableFaceCallback
51
+ ? (face, result) => stableFaceRef.current?.(face, result)
52
+ : undefined,
53
53
  onError(error) {
54
54
  errorRef.current?.(error);
55
55
  },
56
56
  }),
57
- [
58
- factory,
59
- options.targetResolution,
60
- options.antispoofLevel,
61
- options.stableFrames,
62
- options.requiredLiveFrames,
63
- options.laplacianThreshold,
64
- options.maxNeuralSpoofScore,
65
- options.uiUpdateIntervalMs,
66
- hasFaceCallback,
67
- hasStableFaceCallback,
68
- ],
57
+ [
58
+ factory,
59
+ options.targetResolution,
60
+ options.antispoofLevel,
61
+ options.stableFrames,
62
+ options.requiredLiveFrames,
63
+ options.laplacianThreshold,
64
+ options.maxNeuralSpoofScore,
65
+ options.uiUpdateIntervalMs,
66
+ hasFaceCallback,
67
+ hasStableFaceCallback,
68
+ ],
69
69
  );
70
70
  };
71
71
 
72
- export const resetFaceAntiSpoofFrameOutput = (output) => {
73
- getSpoofDetectorFactory().resetSpoofDetectorOutput(output);
74
- };
75
-
72
+ export const resetFaceAntiSpoofFrameOutput = (output) => {
73
+ getSpoofDetectorFactory().resetSpoofDetectorOutput(output);
74
+ };
75
+
76
76
  export default FaceAntiSpoof;
77
77
 
78
78
  // Utility functions
@@ -10,8 +10,6 @@
10
10
  #include <fbjni/fbjni.h>
11
11
  #include "AntiSpoofingResult.hpp"
12
12
 
13
- #include <string>
14
-
15
13
  namespace margelo::nitro::camera::spoofdetector {
16
14
 
17
15
  using namespace facebook;
@@ -31,10 +29,6 @@ namespace margelo::nitro::camera::spoofdetector {
31
29
  [[nodiscard]]
32
30
  AntiSpoofingResult toCpp() const {
33
31
  static const auto clazz = javaClassStatic();
34
- static const auto fieldIsLive = clazz->getField<jboolean>("isLive");
35
- jboolean isLive = this->getFieldValue(fieldIsLive);
36
- static const auto fieldLabel = clazz->getField<jni::JString>("label");
37
- jni::local_ref<jni::JString> label = this->getFieldValue(fieldLabel);
38
32
  static const auto fieldNeuralNetworkScore = clazz->getField<double>("neuralNetworkScore");
39
33
  double neuralNetworkScore = this->getFieldValue(fieldNeuralNetworkScore);
40
34
  static const auto fieldLaplacianScore = clazz->getField<double>("laplacianScore");
@@ -43,14 +37,12 @@ namespace margelo::nitro::camera::spoofdetector {
43
37
  double combinedScore = this->getFieldValue(fieldCombinedScore);
44
38
  static const auto fieldConfidence = clazz->getField<double>("confidence");
45
39
  double confidence = this->getFieldValue(fieldConfidence);
46
- return AntiSpoofingResult(
47
- static_cast<bool>(isLive),
48
- label->toStdString(),
49
- neuralNetworkScore,
50
- laplacianScore,
51
- combinedScore,
52
- confidence
53
- );
40
+ AntiSpoofingResult result{};
41
+ result.neuralNetworkScore = neuralNetworkScore;
42
+ result.laplacianScore = laplacianScore;
43
+ result.combinedScore = combinedScore;
44
+ result.confidence = confidence;
45
+ return result;
54
46
  }
55
47
 
56
48
  public:
@@ -59,13 +51,11 @@ namespace margelo::nitro::camera::spoofdetector {
59
51
  */
60
52
  [[maybe_unused]]
61
53
  static jni::local_ref<JAntiSpoofingResult::javaobject> fromCpp(const AntiSpoofingResult& value) {
62
- using JSignature = JAntiSpoofingResult(jboolean, jni::alias_ref<jni::JString>, double, double, double, double);
54
+ using JSignature = JAntiSpoofingResult(double, double, double, double);
63
55
  static const auto clazz = javaClassStatic();
64
56
  static const auto create = clazz->getStaticMethod<JSignature>("fromCpp");
65
57
  return create(
66
58
  clazz,
67
- value.isLive,
68
- jni::make_jstring(value.label),
69
59
  value.neuralNetworkScore,
70
60
  value.laplacianScore,
71
61
  value.combinedScore,
@@ -18,12 +18,6 @@ import java.util.Objects
18
18
  @DoNotStrip
19
19
  @Keep
20
20
  data class AntiSpoofingResult(
21
- @DoNotStrip
22
- @Keep
23
- val isLive: Boolean,
24
- @DoNotStrip
25
- @Keep
26
- val label: String,
27
21
  @DoNotStrip
28
22
  @Keep
29
23
  val neuralNetworkScore: Double,
@@ -42,9 +36,7 @@ data class AntiSpoofingResult(
42
36
  override fun equals(other: Any?): Boolean {
43
37
  if (this === other) return true
44
38
  if (other !is AntiSpoofingResult) return false
45
- return Objects.deepEquals(this.isLive, other.isLive)
46
- && Objects.deepEquals(this.label, other.label)
47
- && Objects.deepEquals(this.neuralNetworkScore, other.neuralNetworkScore)
39
+ return Objects.deepEquals(this.neuralNetworkScore, other.neuralNetworkScore)
48
40
  && Objects.deepEquals(this.laplacianScore, other.laplacianScore)
49
41
  && Objects.deepEquals(this.combinedScore, other.combinedScore)
50
42
  && Objects.deepEquals(this.confidence, other.confidence)
@@ -52,8 +44,6 @@ data class AntiSpoofingResult(
52
44
 
53
45
  override fun hashCode(): Int {
54
46
  return arrayOf<Any?>(
55
- isLive,
56
- label,
57
47
  neuralNetworkScore,
58
48
  laplacianScore,
59
49
  combinedScore,
@@ -69,8 +59,8 @@ data class AntiSpoofingResult(
69
59
  @Keep
70
60
  @Suppress("unused")
71
61
  @JvmStatic
72
- private fun fromCpp(isLive: Boolean, label: String, neuralNetworkScore: Double, laplacianScore: Double, combinedScore: Double, confidence: Double): AntiSpoofingResult {
73
- return AntiSpoofingResult(isLive, label, neuralNetworkScore, laplacianScore, combinedScore, confidence)
62
+ private fun fromCpp(neuralNetworkScore: Double, laplacianScore: Double, combinedScore: Double, confidence: Double): AntiSpoofingResult {
63
+ return AntiSpoofingResult(neuralNetworkScore, laplacianScore, combinedScore, confidence)
74
64
  }
75
65
  }
76
66
  }
@@ -74,8 +74,10 @@ namespace margelo::nitro {
74
74
  }
75
75
  static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::camera::spoofdetector::AntiSpoofingResult& arg) {
76
76
  jsi::Object obj(runtime);
77
+ #if !defined(__ANDROID__)
77
78
  obj.setProperty(runtime, PropNameIDCache::get(runtime, "isLive"), JSIConverter<bool>::toJSI(runtime, arg.isLive));
78
79
  obj.setProperty(runtime, PropNameIDCache::get(runtime, "label"), JSIConverter<std::string>::toJSI(runtime, arg.label));
80
+ #endif
79
81
  obj.setProperty(runtime, PropNameIDCache::get(runtime, "neuralNetworkScore"), JSIConverter<double>::toJSI(runtime, arg.neuralNetworkScore));
80
82
  obj.setProperty(runtime, PropNameIDCache::get(runtime, "laplacianScore"), JSIConverter<double>::toJSI(runtime, arg.laplacianScore));
81
83
  obj.setProperty(runtime, PropNameIDCache::get(runtime, "combinedScore"), JSIConverter<double>::toJSI(runtime, arg.combinedScore));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-vision-camera-spoof-detector",
3
- "version": "1.2.4",
3
+ "version": "1.2.6",
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": {