react-native-vision-camera-spoof-detector 1.2.6 → 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,26 +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_FAST)
60
- .enableTracking()
61
- .build()
62
- )
63
- }
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
+ )
64
65
  private val faceDetectorTask = java.util.concurrent.atomic.AtomicReference<Task<List<Face>>?>()
65
66
  private val stateLock = Any()
66
67
  private val antispoofLevel = options.antispoofLevel ?: 0.4
67
- private val stableFrames = (options.stableFrames ?: 1.0).toInt().coerceAtLeast(1)
68
- 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)
69
70
  private val laplacianThreshold = options.laplacianThreshold ?: 2000.0
70
71
  private val maxNeuralSpoofScore = options.maxNeuralSpoofScore ?: 0.1
71
- private val uiUpdateIntervalMs = (options.uiUpdateIntervalMs ?: 500.0).toLong().coerceAtLeast(0L)
72
+ private val uiUpdateIntervalMs = (options.uiUpdateIntervalMs ?: 100.0).toLong().coerceAtLeast(0L)
72
73
  private val isLowRamDevice by lazy {
73
74
  val context = NitroModules.applicationContext
74
75
  val activityManager = context?.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
@@ -84,9 +85,12 @@ class HybridSpoofDetectorOutput(
84
85
  private var lastResultUpdateAtMs = 0L
85
86
  private var imageAnalysis: ImageAnalysis? = null
86
87
  private companion object {
88
+ private const val MIN_FACE_WIDTH_RATIO = 0.18f
89
+ private const val MIN_FACE_HEIGHT_RATIO = 0.18f
90
+ private const val FACE_FRAME_MARGIN_RATIO = 0.02f
91
+ private const val MAX_FACE_POSE_ANGLE_DEGREES = 25f
87
92
  private const val MIN_FRAME_BRIGHTNESS = 24f
88
93
  private const val MAX_FRAME_BRIGHTNESS = 220f
89
- private const val MIN_VARIANCE_FOR_ANALYSIS = 1500f
90
94
  }
91
95
 
92
96
  override fun createUseCase(
@@ -132,59 +136,51 @@ class HybridSpoofDetectorOutput(
132
136
  image.close()
133
137
  return
134
138
  }
135
- val pendingOperations = java.util.concurrent.atomic.AtomicInteger(
136
- if (faceDetector == null) 1 else 2
137
- )
138
- val releaseImage = {
139
- if (pendingOperations.decrementAndGet() == 0) {
140
- image.close()
141
- busy.set(false)
142
- }
143
- }
144
- var faceTaskRegistered = false
145
-
146
139
  try {
147
- if (faceDetector != null) {
148
- try {
149
- val mediaImage = image.image ?: throw IllegalStateException("ImageProxy has no media image")
150
- val inputImage = InputImage.fromMediaImage(mediaImage, image.imageInfo.rotationDegrees)
151
- val transform = createMLKitToCameraTransform(image)
152
- val task = faceDetector.process(inputImage)
153
- faceDetectorTask.set(task)
154
- task.addOnSuccessListener { faces ->
155
- try {
156
- processDetectedFaces(faces, transform)
157
- } catch (error: Throwable) {
158
- options.onError?.invoke(error)
159
- }
160
- }.addOnFailureListener { error ->
161
- options.onError?.invoke(error)
162
- }.addOnCompleteListener {
163
- faceDetectorTask.compareAndSet(task, null)
164
- releaseImage()
165
- }
166
- faceTaskRegistered = true
167
- } catch (error: Throwable) {
168
- options.onError?.invoke(error)
169
- }
170
- }
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)
171
146
 
172
- 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)
173
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")
174
164
  val planes = image.planes.map { plane ->
175
165
  val buffer = plane.buffer.duplicate()
176
166
  ByteArray(buffer.remaining()).also(buffer::get)
177
167
  }.toTypedArray()
178
168
  val rowStrides = image.planes.map { it.rowStride }.toIntArray()
179
169
  val pixelStrides = image.planes.map { it.pixelStride }.toIntArray()
180
- val result = detector.advancedAntiSpoofing(
181
- planes,
182
- image.width,
183
- image.height,
184
- rowStrides,
185
- pixelStrides,
186
- image.imageInfo.rotationDegrees,
187
- )
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
+ }
188
184
  processAntiSpoofResult(
189
185
  AntiSpoofingResult(
190
186
  result.neuralNetworkScore.toDouble(),
@@ -194,20 +190,27 @@ class HybridSpoofDetectorOutput(
194
190
  )
195
191
  )
196
192
  } catch (error: Throwable) {
193
+ invalidateLiveEvidence()
197
194
  options.onError?.invoke(error)
198
195
  } finally {
199
- releaseImage()
200
- if (faceDetector != null && !faceTaskRegistered) {
201
- releaseImage()
202
- }
196
+ faceDetectorTask.set(null)
197
+ image.close()
198
+ busy.set(false)
203
199
  }
204
200
  }
205
201
 
206
- private fun processDetectedFaces(faces: List<Face>, transform: Matrix) {
207
- val detectedFaces = faces.map { it.toSpoofDetectedFace(transform) }.toTypedArray()
202
+ private fun processDetectedFaces(
203
+ faces: List<Face>,
204
+ transform: Matrix,
205
+ frameWidth: Int,
206
+ frameHeight: Int,
207
+ ) {
208
+ val detectedFaces = faces
209
+ .filter { it.isFullFace(frameWidth, frameHeight) }
210
+ .map { it.toSpoofDetectedFace(transform) }
211
+ .toTypedArray()
208
212
  val now = SystemClock.elapsedRealtime()
209
213
  var shouldNotify = false
210
- var capture: Pair<SpoofDetectedFaceBounds, AntiSpoofingResult>? = null
211
214
 
212
215
  synchronized(stateLock) {
213
216
  if (detectedFaces.size == 1) {
@@ -228,11 +231,9 @@ class HybridSpoofDetectorOutput(
228
231
  lastFaceCount = detectedFaces.size
229
232
  lastFacesUpdateAtMs = now
230
233
  }
231
- capture = readyToCaptureLocked()
232
234
  }
233
235
 
234
236
  if (shouldNotify) options.onFacesDetected?.invoke(detectedFaces)
235
- capture?.let { (bounds, result) -> options.onStableFaceDetected?.invoke(bounds, result) }
236
237
  }
237
238
 
238
239
  private fun processAntiSpoofResult(result: AntiSpoofingResult) {
@@ -246,20 +247,13 @@ class HybridSpoofDetectorOutput(
246
247
  if (isNeuralSpoof) {
247
248
  consecutiveLiveFrames = 0
248
249
  } else {
249
- val targetPercent = (antispoofLevel * 100).roundToInt()
250
- val currentPercent = (result.confidence * 100).roundToInt()
251
- val combinedPercent = (result.combinedScore * 100).roundToInt()
252
- val meetsConfidence = currentPercent >= targetPercent ||
253
- result.confidence >= antispoofLevel ||
254
- combinedPercent >= targetPercent ||
255
- result.combinedScore >= antispoofLevel
256
- val meetsLaplacian = result.laplacianScore == 0.0 ||
257
- result.laplacianScore >= laplacianThreshold
250
+ val meetsConfidence = result.confidence >= antispoofLevel
251
+ val meetsLaplacian = result.laplacianScore >= laplacianThreshold
258
252
  val framePassesLiveness = meetsConfidence && meetsLaplacian
259
253
  consecutiveLiveFrames = if (framePassesLiveness) {
260
254
  min(requiredLiveFrames, consecutiveLiveFrames + 1)
261
255
  } else {
262
- max(0, consecutiveLiveFrames - 1)
256
+ 0
263
257
  }
264
258
  }
265
259
 
@@ -285,6 +279,13 @@ class HybridSpoofDetectorOutput(
285
279
  return Pair(bounds, result)
286
280
  }
287
281
 
282
+ private fun invalidateLiveEvidence() {
283
+ synchronized(stateLock) {
284
+ consecutiveLiveFrames = 0
285
+ lastSpoofResult = null
286
+ }
287
+ }
288
+
288
289
  fun resetState() {
289
290
  synchronized(stateLock) {
290
291
  captured = false
@@ -303,7 +304,6 @@ class HybridSpoofDetectorOutput(
303
304
  val buffer = plane.buffer.duplicate()
304
305
  val sampleStep = max(1, min(image.width, image.height) / 32)
305
306
  var brightnessSum = 0L
306
- var brightnessSquaredSum = 0L
307
307
  var sampleCount = 0
308
308
 
309
309
  for (y in 0 until image.height step sampleStep) {
@@ -313,7 +313,6 @@ class HybridSpoofDetectorOutput(
313
313
  if (index >= buffer.limit()) continue
314
314
  val luma = buffer.get(index).toInt() and 0xFF
315
315
  brightnessSum += luma.toLong()
316
- brightnessSquaredSum += (luma.toLong() * luma.toLong())
317
316
  sampleCount += 1
318
317
  }
319
318
  }
@@ -323,12 +322,7 @@ class HybridSpoofDetectorOutput(
323
322
  }
324
323
 
325
324
  val avgBrightness = brightnessSum.toFloat() / sampleCount
326
- val variance = (brightnessSquaredSum.toFloat() / sampleCount) - (avgBrightness * avgBrightness)
327
-
328
- val brightnessOk = avgBrightness in MIN_FRAME_BRIGHTNESS..MAX_FRAME_BRIGHTNESS
329
- val textureOk = variance >= MIN_VARIANCE_FOR_ANALYSIS
330
-
331
- return brightnessOk && textureOk
325
+ return avgBrightness in MIN_FRAME_BRIGHTNESS..MAX_FRAME_BRIGHTNESS
332
326
  }
333
327
 
334
328
  private fun createMLKitToCameraTransform(image: ImageProxy): Matrix {
@@ -379,6 +373,36 @@ class HybridSpoofDetectorOutput(
379
373
  )
380
374
  }
381
375
 
376
+ private fun Face.isFullFace(frameWidth: Int, frameHeight: Int): Boolean {
377
+ if (frameWidth <= 0 || frameHeight <= 0) return false
378
+
379
+ val bounds = boundingBox
380
+ val marginX = frameWidth * FACE_FRAME_MARGIN_RATIO
381
+ val marginY = frameHeight * FACE_FRAME_MARGIN_RATIO
382
+ if (bounds.left < marginX || bounds.top < marginY ||
383
+ bounds.right > frameWidth - marginX || bounds.bottom > frameHeight - marginY
384
+ ) return false
385
+ if (bounds.width() < frameWidth * MIN_FACE_WIDTH_RATIO ||
386
+ bounds.height() < frameHeight * MIN_FACE_HEIGHT_RATIO
387
+ ) return false
388
+ if (abs(headEulerAngleY) > MAX_FACE_POSE_ANGLE_DEGREES ||
389
+ abs(headEulerAngleX) > MAX_FACE_POSE_ANGLE_DEGREES
390
+ ) return false
391
+
392
+ val requiredLandmarks = intArrayOf(
393
+ com.google.mlkit.vision.face.FaceLandmark.LEFT_EYE,
394
+ com.google.mlkit.vision.face.FaceLandmark.RIGHT_EYE,
395
+ com.google.mlkit.vision.face.FaceLandmark.NOSE_BASE,
396
+ com.google.mlkit.vision.face.FaceLandmark.MOUTH_LEFT,
397
+ com.google.mlkit.vision.face.FaceLandmark.MOUTH_RIGHT,
398
+ )
399
+ return requiredLandmarks.all { landmarkType ->
400
+ val point = getLandmark(landmarkType)?.position ?: return@all false
401
+ point.x >= bounds.left && point.x <= bounds.right &&
402
+ point.y >= bounds.top && point.y <= bounds.bottom
403
+ }
404
+ }
405
+
382
406
  override fun dispose() {
383
407
  disposed.set(true)
384
408
  imageAnalysis?.clearAnalyzer()
@@ -388,7 +412,9 @@ class HybridSpoofDetectorOutput(
388
412
  } catch (_: Exception) {}
389
413
  }
390
414
  faceDetector?.close()
391
- detector.close()
415
+ synchronized(detectorLock) {
416
+ detector.close()
417
+ }
392
418
  executor.shutdownNow()
393
419
  super.dispose()
394
420
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-vision-camera-spoof-detector",
3
- "version": "1.2.6",
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": {