react-native-vision-camera-spoof-detector 1.2.7 → 1.2.8

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
@@ -173,9 +173,26 @@ interface UseFaceAntiSpoofFrameOutputOptions {
173
173
  }
174
174
  ```
175
175
 
176
- Providing `onFacesDetected` enables face detection inside this same camera output. Android uses one YUV `ImageAnalysis` for both ML Kit face detection and anti-spoof inference; iOS uses its existing video-data output for Vision face detection and anti-spoof inference. Face stability, liveness thresholds, and capture-once gating run natively. Face updates are rate-limited by `uiUpdateIntervalMs`; `onStableFaceDetected` fires once when both face stability and liveness criteria pass. Call `resetFaceAntiSpoofFrameOutput(output)` to reset native capture state without recreating the output.
176
+ Android runs ML Kit face detection for each analyzed frame, even when face callbacks are omitted. It scores only a single eligible face, using a padded square face crop aligned to the eye line from that same frame. Frames rejected for brightness, face count, or liveness quality clear accumulated live-frame evidence; a previous passing score cannot authorize capture after a rejected frame. Face callbacks remain opt-in. iOS uses its video-data output and Vision face detection. Face updates are rate-limited by `uiUpdateIntervalMs`; `onStableFaceDetected` fires once after the configured face and liveness gates pass. Call `resetFaceAntiSpoofFrameOutput(output)` to reset native capture state without recreating the output.
177
177
 
178
- The liveness defaults are aligned with the bundled model: `maxNeuralSpoofScore: 0.2`, `laplacianThreshold: 1000`, and `antispoofLevel: 0.8`. UI callbacks default to a 100 ms interval. On low-memory devices, the analysis target is reduced proportionally to a 640-pixel width; higher-memory devices retain the requested target resolution.
178
+ Android defaults are `maxNeuralSpoofScore: 0.1`, `laplacianThreshold: 2000`, `antispoofLevel: 0.4`, `requiredLiveFrames: 1`, and `uiUpdateIntervalMs: 500`. These are starting values, not validated operating thresholds; calibrate them on a representative held-out presentation-attack dataset. The brightness and Laplacian checks are quality gates, not independent proof of liveness. On low-memory devices, the analysis target is reduced proportionally to a 640-pixel width; higher-memory devices retain the requested target resolution.
179
+
180
+ ### Local threshold evaluation
181
+
182
+ The package includes a JSONL evaluator that reports APCER, BPCER, and ACER overall and by attack type, lighting, distance, and device. Each `presentationId` must identify one complete bona fide or attack presentation; keep its frame rows consecutive and in capture order. Include rejected-quality frames with `qualityPass: false` so they reset the live-frame streak. Do not treat individual frames as independent presentations.
183
+
184
+ ```bash
185
+ node --test scripts/evaluate-antispoof.test.mjs
186
+ node scripts/evaluate-antispoof.mjs --input path/to/holdout.jsonl --required-frames 3
187
+ ```
188
+
189
+ Each JSONL row contains these fields:
190
+
191
+ ```json
192
+ {"presentationId":"person01-print-office-40cm-deviceA","groundTruth":"attack","attackType":"print","lighting":"office","distance":"40cm","device":"deviceA","neuralNetworkScore":0.14,"laplacianScore":2100,"confidence":0.55,"qualityPass":true,"faceCount":1}
193
+ ```
194
+
195
+ Use `groundTruth: "bona_fide"` for real-user presentations and `"attack"` for print or replay attempts (for example, `phone_replay` and `tablet_replay`). Collect across lighting levels, distances, and device models; keep subjects and capture sessions separated between calibration and final holdout sets. The evaluator has no bundled biometric samples, so its synthetic unit tests do not establish real APCER/BPCER performance.
179
196
 
180
197
  ---
181
198
 
@@ -231,7 +248,7 @@ Result fields:
231
248
  ### Android
232
249
 
233
250
  - Uses a native `ImageAnalysis`-based output pipeline
234
- - Reads RGBA frame data and applies brightness / variance gating before inference
251
+ - Converts YUV frames, applies a coarse brightness gate, and evaluates a face-aligned crop
235
252
  - Uses the bundled TensorFlow Lite model and prefers GPU delegate, with NNAPI/CPU fallback
236
253
  - Normalizes frames for model input and returns a JS callback result after evaluation
237
254
 
@@ -3,6 +3,8 @@ package com.faceantispoof
3
3
  import android.content.res.AssetManager
4
4
  import android.graphics.Bitmap
5
5
  import android.graphics.Matrix
6
+ import android.graphics.PointF
7
+ import android.graphics.RectF
6
8
  import org.tensorflow.lite.Interpreter
7
9
  import org.tensorflow.lite.gpu.CompatibilityList
8
10
  import org.tensorflow.lite.gpu.GpuDelegate
@@ -202,7 +204,10 @@ class FaceAntiSpoofingAdvanced(private val assetManager: AssetManager) {
202
204
  height: Int,
203
205
  rowStrides: IntArray,
204
206
  pixelStrides: IntArray,
205
- rotationDegrees: Int = 0
207
+ rotationDegrees: Int = 0,
208
+ faceBounds: RectF? = null,
209
+ leftEye: PointF? = null,
210
+ rightEye: PointF? = null,
206
211
  ): AntiSpoofingResult {
207
212
  if (planes.size < 3) {
208
213
  throw IllegalArgumentException("Expected Y, U and V planes")
@@ -224,12 +229,60 @@ class FaceAntiSpoofingAdvanced(private val assetManager: AssetManager) {
224
229
  ).also { sourceBitmap.recycle() }
225
230
  }
226
231
  return try {
227
- runBlocking { advancedAntiSpoofing(bitmap).getOrThrow() }
232
+ val inputBitmap = if (faceBounds != null) {
233
+ cropAndAlignFace(bitmap, faceBounds, leftEye, rightEye)
234
+ } else {
235
+ bitmap
236
+ }
237
+ try {
238
+ runBlocking { advancedAntiSpoofing(inputBitmap).getOrThrow() }
239
+ } finally {
240
+ if (inputBitmap !== bitmap) inputBitmap.recycle()
241
+ }
228
242
  } finally {
229
243
  bitmap.recycle()
230
244
  }
231
245
  }
232
246
 
247
+ private fun cropAndAlignFace(
248
+ source: Bitmap,
249
+ faceBounds: RectF,
250
+ leftEye: PointF?,
251
+ rightEye: PointF?,
252
+ ): Bitmap {
253
+ val cropSide = (max(faceBounds.width(), faceBounds.height()) * 1.4f)
254
+ .coerceAtMost(min(source.width, source.height).toFloat())
255
+ .toInt()
256
+ .coerceAtLeast(1)
257
+ val halfSide = cropSide / 2f
258
+ val centerX = faceBounds.centerX().coerceIn(halfSide, source.width - halfSide)
259
+ val centerY = faceBounds.centerY().coerceIn(halfSide, source.height - halfSide)
260
+ val left = (centerX - halfSide).toInt().coerceIn(0, source.width - cropSide)
261
+ val top = (centerY - halfSide).toInt().coerceIn(0, source.height - cropSide)
262
+ val crop = Bitmap.createBitmap(source, left, top, cropSide, cropSide)
263
+
264
+ if (leftEye == null || rightEye == null) return crop
265
+ val eyeAngle = Math.toDegrees(
266
+ kotlin.math.atan2(
267
+ (rightEye.y - leftEye.y).toDouble(),
268
+ (rightEye.x - leftEye.x).toDouble(),
269
+ )
270
+ ).toFloat()
271
+ if (kotlin.math.abs(eyeAngle) < 0.5f) return crop
272
+
273
+ return Bitmap.createBitmap(
274
+ crop,
275
+ 0,
276
+ 0,
277
+ crop.width,
278
+ crop.height,
279
+ Matrix().apply { postRotate(-eyeAngle) },
280
+ true,
281
+ ).also { aligned ->
282
+ if (aligned !== crop) crop.recycle()
283
+ }
284
+ }
285
+
233
286
  fun advancedAntiSpoofingRGBA(rgba: ByteArray, width: Int, height: Int): AntiSpoofingResult {
234
287
  if (!isInitialized) {
235
288
  return AntiSpoofingResult(
@@ -1,6 +1,7 @@
1
1
  package com.margelo.nitro.camera.spoofdetector
2
2
 
3
3
  import android.graphics.Matrix
4
+ import android.graphics.PointF
4
5
  import android.graphics.RectF
5
6
  import android.os.SystemClock
6
7
  import android.app.ActivityManager
@@ -49,28 +50,26 @@ class HybridSpoofDetectorOutput(
49
50
  private val executor = Executors.newSingleThreadExecutor()
50
51
  private val busy = AtomicBoolean(false)
51
52
  private val disposed = AtomicBoolean(false)
53
+ private val detectorLock = Any()
52
54
  private val detector = FaceAntiSpoofingAdvanced(
53
55
  NitroModules.applicationContext?.assets ?: error("FaceAntiSpoof: no application context")
54
56
  )
55
- private val faceDetector = (options.onFacesDetected != null || options.onStableFaceDetected != null).let { enabled ->
56
- if (!enabled) return@let null
57
- FaceDetection.getClient(
58
- FaceDetectorOptions.Builder()
59
- .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE)
60
- .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL)
61
- .setMinFaceSize(MIN_FACE_WIDTH_RATIO)
62
- .enableTracking()
63
- .build()
64
- )
65
- }
57
+ private val faceDetector = FaceDetection.getClient(
58
+ FaceDetectorOptions.Builder()
59
+ .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE)
60
+ .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL)
61
+ .setMinFaceSize(MIN_FACE_WIDTH_RATIO)
62
+ .enableTracking()
63
+ .build()
64
+ )
66
65
  private val faceDetectorTask = java.util.concurrent.atomic.AtomicReference<Task<List<Face>>?>()
67
66
  private val stateLock = Any()
68
67
  private val antispoofLevel = options.antispoofLevel ?: 0.4
69
- private val stableFrames = (options.stableFrames ?: 1.0).toInt().coerceAtLeast(1)
70
- private val requiredLiveFrames = (options.requiredLiveFrames ?: 1.0).toInt().coerceAtLeast(1)
68
+ private val stableFrames = (options.stableFrames ?: 3.0).toInt().coerceAtLeast(1)
69
+ private val requiredLiveFrames = (options.requiredLiveFrames ?: 3.0).toInt().coerceAtLeast(1)
71
70
  private val laplacianThreshold = options.laplacianThreshold ?: 2000.0
72
71
  private val maxNeuralSpoofScore = options.maxNeuralSpoofScore ?: 0.1
73
- private val uiUpdateIntervalMs = (options.uiUpdateIntervalMs ?: 500.0).toLong().coerceAtLeast(0L)
72
+ private val uiUpdateIntervalMs = (options.uiUpdateIntervalMs ?: 100.0).toLong().coerceAtLeast(0L)
74
73
  private val isLowRamDevice by lazy {
75
74
  val context = NitroModules.applicationContext
76
75
  val activityManager = context?.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
@@ -92,7 +91,6 @@ class HybridSpoofDetectorOutput(
92
91
  private const val MAX_FACE_POSE_ANGLE_DEGREES = 25f
93
92
  private const val MIN_FRAME_BRIGHTNESS = 24f
94
93
  private const val MAX_FRAME_BRIGHTNESS = 220f
95
- private const val MIN_VARIANCE_FOR_ANALYSIS = 1500f
96
94
  }
97
95
 
98
96
  override fun createUseCase(
@@ -138,62 +136,51 @@ class HybridSpoofDetectorOutput(
138
136
  image.close()
139
137
  return
140
138
  }
141
- val pendingOperations = java.util.concurrent.atomic.AtomicInteger(
142
- if (faceDetector == null) 1 else 2
143
- )
144
- val releaseImage = {
145
- if (pendingOperations.decrementAndGet() == 0) {
146
- image.close()
147
- busy.set(false)
148
- }
149
- }
150
- var faceTaskRegistered = false
151
-
152
139
  try {
153
- if (faceDetector != null) {
154
- try {
155
- val mediaImage = image.image ?: throw IllegalStateException("ImageProxy has no media image")
156
- val inputImage = InputImage.fromMediaImage(mediaImage, image.imageInfo.rotationDegrees)
157
- val transform = createMLKitToCameraTransform(image)
158
- val rotation = ((image.imageInfo.rotationDegrees % 360) + 360) % 360
159
- val detectorFrameWidth = if (rotation == 90 || rotation == 270) image.height else image.width
160
- val detectorFrameHeight = if (rotation == 90 || rotation == 270) image.width else image.height
161
- val task = faceDetector.process(inputImage)
162
- faceDetectorTask.set(task)
163
- task.addOnSuccessListener { faces ->
164
- try {
165
- processDetectedFaces(faces, transform, detectorFrameWidth, detectorFrameHeight)
166
- } catch (error: Throwable) {
167
- options.onError?.invoke(error)
168
- }
169
- }.addOnFailureListener { error ->
170
- options.onError?.invoke(error)
171
- }.addOnCompleteListener {
172
- faceDetectorTask.compareAndSet(task, null)
173
- releaseImage()
174
- }
175
- faceTaskRegistered = true
176
- } catch (error: Throwable) {
177
- options.onError?.invoke(error)
178
- }
179
- }
140
+ val mediaImage = image.image ?: throw IllegalStateException("ImageProxy has no media image")
141
+ val inputImage = InputImage.fromMediaImage(mediaImage, image.imageInfo.rotationDegrees)
142
+ val task = faceDetector.process(inputImage)
143
+ faceDetectorTask.set(task)
144
+ val faces = Tasks.await(task)
145
+ faceDetectorTask.compareAndSet(task, null)
180
146
 
181
- if (!shouldProcessFrame(image)) return
147
+ val transform = createMLKitToCameraTransform(image)
148
+ val rotation = ((image.imageInfo.rotationDegrees % 360) + 360) % 360
149
+ val frameWidth = if (rotation == 90 || rotation == 270) image.height else image.width
150
+ val frameHeight = if (rotation == 90 || rotation == 270) image.width else image.height
151
+ val eligibleFaces = faces.filter { it.isFullFace(frameWidth, frameHeight) }
152
+ processDetectedFaces(eligibleFaces, transform, frameWidth, frameHeight)
182
153
 
154
+ if (!shouldProcessFrame(image) || eligibleFaces.size != 1) {
155
+ invalidateLiveEvidence()
156
+ return
157
+ }
158
+
159
+ val face = eligibleFaces.single()
160
+ val leftEye = face.getLandmark(com.google.mlkit.vision.face.FaceLandmark.LEFT_EYE)?.position
161
+ ?: throw IllegalStateException("Face is missing the left eye landmark")
162
+ val rightEye = face.getLandmark(com.google.mlkit.vision.face.FaceLandmark.RIGHT_EYE)?.position
163
+ ?: throw IllegalStateException("Face is missing the right eye landmark")
183
164
  val planes = image.planes.map { plane ->
184
165
  val buffer = plane.buffer.duplicate()
185
166
  ByteArray(buffer.remaining()).also(buffer::get)
186
167
  }.toTypedArray()
187
168
  val rowStrides = image.planes.map { it.rowStride }.toIntArray()
188
169
  val pixelStrides = image.planes.map { it.pixelStride }.toIntArray()
189
- val result = detector.advancedAntiSpoofing(
190
- planes,
191
- image.width,
192
- image.height,
193
- rowStrides,
194
- pixelStrides,
195
- image.imageInfo.rotationDegrees,
196
- )
170
+ val result = synchronized(detectorLock) {
171
+ if (disposed.get()) return
172
+ detector.advancedAntiSpoofing(
173
+ planes,
174
+ image.width,
175
+ image.height,
176
+ rowStrides,
177
+ pixelStrides,
178
+ image.imageInfo.rotationDegrees,
179
+ RectF(face.boundingBox),
180
+ PointF(leftEye.x, leftEye.y),
181
+ PointF(rightEye.x, rightEye.y),
182
+ )
183
+ }
197
184
  processAntiSpoofResult(
198
185
  AntiSpoofingResult(
199
186
  result.neuralNetworkScore.toDouble(),
@@ -203,12 +190,12 @@ class HybridSpoofDetectorOutput(
203
190
  )
204
191
  )
205
192
  } catch (error: Throwable) {
193
+ invalidateLiveEvidence()
206
194
  options.onError?.invoke(error)
207
195
  } finally {
208
- releaseImage()
209
- if (faceDetector != null && !faceTaskRegistered) {
210
- releaseImage()
211
- }
196
+ faceDetectorTask.set(null)
197
+ image.close()
198
+ busy.set(false)
212
199
  }
213
200
  }
214
201
 
@@ -224,7 +211,6 @@ class HybridSpoofDetectorOutput(
224
211
  .toTypedArray()
225
212
  val now = SystemClock.elapsedRealtime()
226
213
  var shouldNotify = false
227
- var capture: Pair<SpoofDetectedFaceBounds, AntiSpoofingResult>? = null
228
214
 
229
215
  synchronized(stateLock) {
230
216
  if (detectedFaces.size == 1) {
@@ -245,11 +231,9 @@ class HybridSpoofDetectorOutput(
245
231
  lastFaceCount = detectedFaces.size
246
232
  lastFacesUpdateAtMs = now
247
233
  }
248
- capture = readyToCaptureLocked()
249
234
  }
250
235
 
251
236
  if (shouldNotify) options.onFacesDetected?.invoke(detectedFaces)
252
- capture?.let { (bounds, result) -> options.onStableFaceDetected?.invoke(bounds, result) }
253
237
  }
254
238
 
255
239
  private fun processAntiSpoofResult(result: AntiSpoofingResult) {
@@ -263,20 +247,13 @@ class HybridSpoofDetectorOutput(
263
247
  if (isNeuralSpoof) {
264
248
  consecutiveLiveFrames = 0
265
249
  } else {
266
- val targetPercent = (antispoofLevel * 100).roundToInt()
267
- val currentPercent = (result.confidence * 100).roundToInt()
268
- val combinedPercent = (result.combinedScore * 100).roundToInt()
269
- val meetsConfidence = currentPercent >= targetPercent ||
270
- result.confidence >= antispoofLevel ||
271
- combinedPercent >= targetPercent ||
272
- result.combinedScore >= antispoofLevel
273
- val meetsLaplacian = result.laplacianScore == 0.0 ||
274
- result.laplacianScore >= laplacianThreshold
250
+ val meetsConfidence = result.confidence >= antispoofLevel
251
+ val meetsLaplacian = result.laplacianScore >= laplacianThreshold
275
252
  val framePassesLiveness = meetsConfidence && meetsLaplacian
276
253
  consecutiveLiveFrames = if (framePassesLiveness) {
277
254
  min(requiredLiveFrames, consecutiveLiveFrames + 1)
278
255
  } else {
279
- max(0, consecutiveLiveFrames - 1)
256
+ 0
280
257
  }
281
258
  }
282
259
 
@@ -302,6 +279,13 @@ class HybridSpoofDetectorOutput(
302
279
  return Pair(bounds, result)
303
280
  }
304
281
 
282
+ private fun invalidateLiveEvidence() {
283
+ synchronized(stateLock) {
284
+ consecutiveLiveFrames = 0
285
+ lastSpoofResult = null
286
+ }
287
+ }
288
+
305
289
  fun resetState() {
306
290
  synchronized(stateLock) {
307
291
  captured = false
@@ -320,7 +304,6 @@ class HybridSpoofDetectorOutput(
320
304
  val buffer = plane.buffer.duplicate()
321
305
  val sampleStep = max(1, min(image.width, image.height) / 32)
322
306
  var brightnessSum = 0L
323
- var brightnessSquaredSum = 0L
324
307
  var sampleCount = 0
325
308
 
326
309
  for (y in 0 until image.height step sampleStep) {
@@ -330,7 +313,6 @@ class HybridSpoofDetectorOutput(
330
313
  if (index >= buffer.limit()) continue
331
314
  val luma = buffer.get(index).toInt() and 0xFF
332
315
  brightnessSum += luma.toLong()
333
- brightnessSquaredSum += (luma.toLong() * luma.toLong())
334
316
  sampleCount += 1
335
317
  }
336
318
  }
@@ -340,12 +322,7 @@ class HybridSpoofDetectorOutput(
340
322
  }
341
323
 
342
324
  val avgBrightness = brightnessSum.toFloat() / sampleCount
343
- val variance = (brightnessSquaredSum.toFloat() / sampleCount) - (avgBrightness * avgBrightness)
344
-
345
- val brightnessOk = avgBrightness in MIN_FRAME_BRIGHTNESS..MAX_FRAME_BRIGHTNESS
346
- val textureOk = variance >= MIN_VARIANCE_FOR_ANALYSIS
347
-
348
- return brightnessOk && textureOk
325
+ return avgBrightness in MIN_FRAME_BRIGHTNESS..MAX_FRAME_BRIGHTNESS
349
326
  }
350
327
 
351
328
  private fun createMLKitToCameraTransform(image: ImageProxy): Matrix {
@@ -435,7 +412,9 @@ class HybridSpoofDetectorOutput(
435
412
  } catch (_: Exception) {}
436
413
  }
437
414
  faceDetector?.close()
438
- detector.close()
415
+ synchronized(detectorLock) {
416
+ detector.close()
417
+ }
439
418
  executor.shutdownNow()
440
419
  super.dispose()
441
420
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-vision-camera-spoof-detector",
3
- "version": "1.2.7",
3
+ "version": "1.2.8",
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": {