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

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.
@@ -49,7 +49,9 @@ class FaceAntiSpoofingAdvanced(private val assetManager: AssetManager) {
49
49
  private var outputIndex0: Int = 0
50
50
  private var outputIndex1: Int = 1
51
51
  private val modelInputBuffer = Array(INPUT_IMAGE_SIZE) { Array(INPUT_IMAGE_SIZE) { FloatArray(3) } }
52
+ private val modelInput = arrayOf(modelInputBuffer)
52
53
  private val grayBuffer = Array(INPUT_IMAGE_SIZE) { IntArray(INPUT_IMAGE_SIZE) }
54
+ private val inputPlanePositions = IntArray(3)
53
55
 
54
56
  init {
55
57
  initializeInterpreter()
@@ -274,6 +276,199 @@ class FaceAntiSpoofingAdvanced(private val assetManager: AssetManager) {
274
276
  }
275
277
  }
276
278
 
279
+ @Synchronized
280
+ fun advancedAntiSpoofing(
281
+ planes: Array<ByteBuffer>,
282
+ width: Int,
283
+ height: Int,
284
+ rowStrides: IntArray,
285
+ pixelStrides: IntArray,
286
+ rotationDegrees: Int,
287
+ faceBounds: RectF,
288
+ leftEye: PointF,
289
+ rightEye: PointF,
290
+ ): AntiSpoofingResult {
291
+ if (!isInitialized) {
292
+ throw IllegalStateException("Classifier not initialized")
293
+ }
294
+ require(planes.size >= 3) { "Expected Y, U and V planes" }
295
+ require(rowStrides.size >= 3 && pixelStrides.size >= 3) {
296
+ "Expected row and pixel strides for Y, U and V planes"
297
+ }
298
+ require(width > 0 && height > 0) { "Frame dimensions must be positive" }
299
+
300
+ val rotation = ((rotationDegrees % 360) + 360) % 360
301
+ require(rotation % 90 == 0) { "Invalid frame rotation: $rotation" }
302
+
303
+ val orientedWidth = if (rotation == 90 || rotation == 270) height else width
304
+ val orientedHeight = if (rotation == 90 || rotation == 270) width else height
305
+ val cropSide = (max(faceBounds.width(), faceBounds.height()) * 1.4f)
306
+ .coerceAtMost(min(orientedWidth, orientedHeight).toFloat())
307
+ .toInt()
308
+ .coerceAtLeast(1)
309
+ val halfSide = cropSide / 2f
310
+ val centerX = faceBounds.centerX().coerceIn(halfSide, orientedWidth - halfSide)
311
+ val centerY = faceBounds.centerY().coerceIn(halfSide, orientedHeight - halfSide)
312
+ val cropLeft = (centerX - halfSide).toInt().coerceIn(0, orientedWidth - cropSide)
313
+ val cropTop = (centerY - halfSide).toInt().coerceIn(0, orientedHeight - cropSide)
314
+ val cropRight = cropLeft + cropSide - 1
315
+ val cropBottom = cropTop + cropSide - 1
316
+ val eyeAngle = atan2(
317
+ (rightEye.y - leftEye.y).toDouble(),
318
+ (rightEye.x - leftEye.x).toDouble(),
319
+ ).toFloat().takeIf { abs(Math.toDegrees(it.toDouble())) >= 0.5 } ?: 0f
320
+ val cosine = cos(eyeAngle)
321
+ val sine = sin(eyeAngle)
322
+ val cropCenter = (cropSide - 1) / 2f
323
+ val sampleScale = cropSide.toFloat() / INPUT_IMAGE_SIZE
324
+ for (planeIndex in 0 until 3) {
325
+ inputPlanePositions[planeIndex] = planes[planeIndex].position()
326
+ }
327
+
328
+ for (targetY in 0 until INPUT_IMAGE_SIZE) {
329
+ val cropY = (targetY + 0.5f) * sampleScale - 0.5f
330
+ val relativeY = cropY - cropCenter
331
+ for (targetX in 0 until INPUT_IMAGE_SIZE) {
332
+ val cropX = (targetX + 0.5f) * sampleScale - 0.5f
333
+ val relativeX = cropX - cropCenter
334
+ val orientedX = (cropLeft + cropCenter + cosine * relativeX - sine * relativeY)
335
+ .coerceIn(cropLeft.toFloat(), cropRight.toFloat())
336
+ val orientedY = (cropTop + cropCenter + sine * relativeX + cosine * relativeY)
337
+ .coerceIn(cropTop.toFloat(), cropBottom.toFloat())
338
+ val sourceX: Float
339
+ val sourceY: Float
340
+ when (rotation) {
341
+ 90 -> {
342
+ sourceX = orientedY
343
+ sourceY = height - 1f - orientedX
344
+ }
345
+ 180 -> {
346
+ sourceX = width - 1f - orientedX
347
+ sourceY = height - 1f - orientedY
348
+ }
349
+ 270 -> {
350
+ sourceX = width - 1f - orientedY
351
+ sourceY = orientedX
352
+ }
353
+ else -> {
354
+ sourceX = orientedX
355
+ sourceY = orientedY
356
+ }
357
+ }
358
+ val rgb = sampleYuvBilinear(
359
+ planes,
360
+ rowStrides,
361
+ pixelStrides,
362
+ width,
363
+ height,
364
+ sourceX,
365
+ sourceY,
366
+ )
367
+ val red = (rgb ushr 16) and 0xFF
368
+ val green = (rgb ushr 8) and 0xFF
369
+ val blue = rgb and 0xFF
370
+ modelInputBuffer[targetY][targetX][0] = red / 255f
371
+ modelInputBuffer[targetY][targetX][1] = green / 255f
372
+ modelInputBuffer[targetY][targetX][2] = blue / 255f
373
+ grayBuffer[targetY][targetX] = (
374
+ 0.299f * red + 0.587f * green + 0.114f * blue
375
+ ).toInt()
376
+ }
377
+ }
378
+
379
+ val nnResult = neuralNetworkAntiSpoofingSampled()
380
+ val nnScore = nnResult.getOrThrow()
381
+ val laplacianScore = calculateLaplacianFromGray(grayBuffer)
382
+ val combinedScore = calculateCombinedScore(nnScore, laplacianScore)
383
+ return AntiSpoofingResult(
384
+ neuralNetworkScore = nnScore,
385
+ laplacianScore = laplacianScore,
386
+ textureComplexity = 0,
387
+ temporalConsistency = 0f,
388
+ colorSaturation = 0f,
389
+ combinedScore = combinedScore,
390
+ confidence = calculateConfidence(nnScore, laplacianScore),
391
+ )
392
+ }
393
+
394
+ private fun sampleYuvBilinear(
395
+ planes: Array<ByteBuffer>,
396
+ rowStrides: IntArray,
397
+ pixelStrides: IntArray,
398
+ sourceWidth: Int,
399
+ sourceHeight: Int,
400
+ x: Float,
401
+ y: Float,
402
+ ): Int {
403
+ val boundedX = x.coerceIn(0f, sourceWidth - 1f)
404
+ val boundedY = y.coerceIn(0f, sourceHeight - 1f)
405
+ val x0 = floor(boundedX).toInt()
406
+ val y0 = floor(boundedY).toInt()
407
+ val x1 = min(x0 + 1, sourceWidth - 1)
408
+ val y1 = min(y0 + 1, sourceHeight - 1)
409
+ val xWeight = boundedX - x0
410
+ val yWeight = boundedY - y0
411
+ val topLeft = readYuvRgb(planes, rowStrides, pixelStrides, x0, y0)
412
+ val topRight = readYuvRgb(planes, rowStrides, pixelStrides, x1, y0)
413
+ val bottomLeft = readYuvRgb(planes, rowStrides, pixelStrides, x0, y1)
414
+ val bottomRight = readYuvRgb(planes, rowStrides, pixelStrides, x1, y1)
415
+
416
+ val red = interpolateChannel(topLeft, topRight, bottomLeft, bottomRight, 16, xWeight, yWeight)
417
+ val green = interpolateChannel(topLeft, topRight, bottomLeft, bottomRight, 8, xWeight, yWeight)
418
+ val blue = interpolateChannel(topLeft, topRight, bottomLeft, bottomRight, 0, xWeight, yWeight)
419
+ return (red shl 16) or (green shl 8) or blue
420
+ }
421
+
422
+ private fun interpolateChannel(
423
+ topLeft: Int,
424
+ topRight: Int,
425
+ bottomLeft: Int,
426
+ bottomRight: Int,
427
+ shift: Int,
428
+ xWeight: Float,
429
+ yWeight: Float,
430
+ ): Int {
431
+ val top = ((topLeft ushr shift) and 0xFF) * (1 - xWeight) +
432
+ ((topRight ushr shift) and 0xFF) * xWeight
433
+ val bottom = ((bottomLeft ushr shift) and 0xFF) * (1 - xWeight) +
434
+ ((bottomRight ushr shift) and 0xFF) * xWeight
435
+ return (top * (1 - yWeight) + bottom * yWeight).roundToInt().coerceIn(0, 255)
436
+ }
437
+
438
+ private fun readYuvRgb(
439
+ planes: Array<ByteBuffer>,
440
+ rowStrides: IntArray,
441
+ pixelStrides: IntArray,
442
+ x: Int,
443
+ y: Int,
444
+ ): Int {
445
+ val luma = readPlaneSample(0, planes[0], rowStrides[0], pixelStrides[0], x, y)
446
+ val chromaX = x / 2
447
+ val chromaY = y / 2
448
+ val u = readPlaneSample(1, planes[1], rowStrides[1], pixelStrides[1], chromaX, chromaY) - 128
449
+ val v = readPlaneSample(2, planes[2], rowStrides[2], pixelStrides[2], chromaX, chromaY) - 128
450
+ val red = (luma + 1.402f * v).toInt().coerceIn(0, 255)
451
+ val green = (luma - 0.344f * u - 0.714f * v).toInt().coerceIn(0, 255)
452
+ val blue = (luma + 1.772f * u).toInt().coerceIn(0, 255)
453
+ return (red shl 16) or (green shl 8) or blue
454
+ }
455
+
456
+ private fun readPlaneSample(
457
+ planeIndex: Int,
458
+ buffer: ByteBuffer,
459
+ rowStride: Int,
460
+ pixelStride: Int,
461
+ x: Int,
462
+ y: Int,
463
+ ): Int {
464
+ val bufferPosition = inputPlanePositions[planeIndex]
465
+ val index = bufferPosition + y * rowStride + x * pixelStride
466
+ require(index >= bufferPosition && index < buffer.limit()) {
467
+ "Camera plane buffer is too small for the requested sample"
468
+ }
469
+ return buffer.get(index).toInt() and 0xFF
470
+ }
471
+
277
472
  private fun cropAndAlignFace(
278
473
  source: Bitmap,
279
474
  faceBounds: RectF,
@@ -328,7 +523,7 @@ class FaceAntiSpoofingAdvanced(private val assetManager: AssetManager) {
328
523
 
329
524
  return try {
330
525
  val sampled = sampleRgbaToModelAndGray(rgba, width, height)
331
- val nnResult = neuralNetworkAntiSpoofingSampled(sampled.rgbBuffer)
526
+ val nnResult = neuralNetworkAntiSpoofingSampled()
332
527
  val nnScore = nnResult.getOrNull() ?: throw IllegalStateException(nnResult.exceptionOrNull()?.message ?: "NN inference failed")
333
528
  val laplacianScore = calculateLaplacianFromGray(sampled.grayBuffer)
334
529
  val combinedScore = calculateCombinedScore(nnScore, laplacianScore)
@@ -372,7 +567,7 @@ class FaceAntiSpoofingAdvanced(private val assetManager: AssetManager) {
372
567
 
373
568
  return try {
374
569
  val sampled = sampleRgbaBufferToModelAndGray(buffer, width, height, rowStride, pixelStride)
375
- val nnResult = neuralNetworkAntiSpoofingSampled(sampled.rgbBuffer)
570
+ val nnResult = neuralNetworkAntiSpoofingSampled()
376
571
  val nnScore = nnResult.getOrNull() ?: throw IllegalStateException(nnResult.exceptionOrNull()?.message ?: "NN inference failed")
377
572
  val laplacianScore = calculateLaplacianFromGray(sampled.grayBuffer)
378
573
  val combinedScore = calculateCombinedScore(nnScore, laplacianScore)
@@ -419,9 +614,6 @@ class FaceAntiSpoofingAdvanced(private val assetManager: AssetManager) {
419
614
 
420
615
  runInference(input)
421
616
 
422
- Log.i(TAG, "clss_pred: [${clssPred[0].joinToString()}]")
423
- Log.i(TAG, "leaf_node_mask: [${leafNodeMask[0].joinToString()}]")
424
-
425
617
  val score = leafScore1(clssPred, leafNodeMask)
426
618
 
427
619
  Result.success(score)
@@ -433,16 +625,13 @@ class FaceAntiSpoofingAdvanced(private val assetManager: AssetManager) {
433
625
  }
434
626
  }
435
627
 
436
- private fun neuralNetworkAntiSpoofingSampled(rgbBuffer: Array<Array<FloatArray>>): Result<Float> {
628
+ private fun neuralNetworkAntiSpoofingSampled(): Result<Float> {
437
629
  return try {
438
- val input = arrayOf(rgbBuffer)
439
630
  clssPred[0].fill(0f)
440
631
  leafNodeMask[0].fill(0f)
441
632
  outputs[outputIndex0] = clssPred
442
633
  outputs[outputIndex1] = leafNodeMask
443
- runInference(input)
444
- Log.i(TAG, "clss_pred: [${clssPred[0].joinToString()}]")
445
- Log.i(TAG, "leaf_node_mask: [${leafNodeMask[0].joinToString()}]")
634
+ runInference(modelInput)
446
635
  Result.success(leafScore1(clssPred, leafNodeMask))
447
636
  } catch (e: Exception) {
448
637
  Log.e(TAG, "Error in neuralNetworkAntiSpoofingSampled", e)
@@ -2,6 +2,7 @@ package com.margelo.nitro.camera.spoofdetector
2
2
 
3
3
  import android.graphics.Matrix
4
4
  import android.graphics.PointF
5
+ import android.graphics.Rect
5
6
  import android.graphics.RectF
6
7
  import androidx.annotation.OptIn
7
8
  import androidx.camera.core.ExperimentalGetImage
@@ -22,6 +23,7 @@ import com.margelo.nitro.camera.extensions.setAllowDroppingLateFrames
22
23
  import com.margelo.nitro.camera.extensions.surfaceRotation
23
24
  import com.margelo.nitro.camera.public.NativeCameraOutput
24
25
  import com.faceantispoof.FaceAntiSpoofingAdvanced
26
+ import java.nio.ByteBuffer
25
27
  import kotlin.math.abs
26
28
  import kotlin.math.max
27
29
  import kotlin.math.min
@@ -46,6 +48,10 @@ class HybridSpoofDetectorOutput(
46
48
  private val busy = AtomicBoolean(false)
47
49
  private val disposed = AtomicBoolean(false)
48
50
  private val detectorLock = Any()
51
+ private val emptyPlaneBuffer = ByteBuffer.allocate(0)
52
+ private val planeBuffers = Array(3) { emptyPlaneBuffer }
53
+ private val planeRowStrides = IntArray(3)
54
+ private val planePixelStrides = IntArray(3)
49
55
  private val detector = FaceAntiSpoofingAdvanced(
50
56
  NitroModules.applicationContext?.assets ?: error("FaceAntiSpoof: no application context")
51
57
  )
@@ -67,6 +73,8 @@ class HybridSpoofDetectorOutput(
67
73
  private var captured = false
68
74
  private var stableCount = 0
69
75
  private var lastFaceBounds: SpoofDetectedFaceBounds? = null
76
+ private var lastFaceBoundsForContinuity: RectF? = null
77
+ private var lastFaceTrackingId: Int? = null
70
78
  private var consecutiveLiveFrames = 0
71
79
  private var lastSpoofResult: AntiSpoofingResult? = null
72
80
  private var imageAnalysis: ImageAnalysis? = null
@@ -75,6 +83,8 @@ class HybridSpoofDetectorOutput(
75
83
  private const val MIN_FACE_HEIGHT_RATIO = 0.18f
76
84
  private const val FACE_FRAME_MARGIN_RATIO = 0.02f
77
85
  private const val MAX_FACE_POSE_ANGLE_DEGREES = 25f
86
+ private const val MIN_FACE_BOUNDS_IOU = 0.35f
87
+ private const val MAX_FACE_CENTER_SHIFT_RATIO = 0.5f
78
88
  private const val MIN_FRAME_BRIGHTNESS = 24f
79
89
  private const val MAX_FRAME_BRIGHTNESS = 220f
80
90
  }
@@ -127,20 +137,24 @@ class HybridSpoofDetectorOutput(
127
137
  ?: throw IllegalStateException("Face is missing the left eye landmark")
128
138
  val rightEye = face.getLandmark(com.google.mlkit.vision.face.FaceLandmark.RIGHT_EYE)?.position
129
139
  ?: throw IllegalStateException("Face is missing the right eye landmark")
130
- val planes = image.planes.map { plane ->
131
- val buffer = plane.buffer.duplicate()
132
- ByteArray(buffer.remaining()).also(buffer::get)
133
- }.toTypedArray()
134
- val rowStrides = image.planes.map { it.rowStride }.toIntArray()
135
- val pixelStrides = image.planes.map { it.pixelStride }.toIntArray()
140
+ val imagePlanes = image.planes
141
+ if (imagePlanes.size < planeBuffers.size) {
142
+ throw IllegalStateException("Expected Y, U and V camera planes")
143
+ }
144
+ for (planeIndex in planeBuffers.indices) {
145
+ val plane = imagePlanes[planeIndex]
146
+ planeBuffers[planeIndex] = plane.buffer
147
+ planeRowStrides[planeIndex] = plane.rowStride
148
+ planePixelStrides[planeIndex] = plane.pixelStride
149
+ }
136
150
  val result = synchronized(detectorLock) {
137
151
  if (disposed.get()) return
138
152
  detector.advancedAntiSpoofing(
139
- planes,
153
+ planeBuffers,
140
154
  image.width,
141
155
  image.height,
142
- rowStrides,
143
- pixelStrides,
156
+ planeRowStrides,
157
+ planePixelStrides,
144
158
  image.imageInfo.rotationDegrees,
145
159
  RectF(face.boundingBox),
146
160
  PointF(leftEye.x, leftEye.y),
@@ -160,6 +174,9 @@ class HybridSpoofDetectorOutput(
160
174
  options.onError?.invoke(error)
161
175
  } finally {
162
176
  faceDetectorTask.set(null)
177
+ for (planeIndex in planeBuffers.indices) {
178
+ planeBuffers[planeIndex] = emptyPlaneBuffer
179
+ }
163
180
  image.close()
164
181
  busy.set(false)
165
182
  }
@@ -171,19 +188,39 @@ class HybridSpoofDetectorOutput(
171
188
  frameWidth: Int,
172
189
  frameHeight: Int,
173
190
  ) {
174
- val detectedFaces = faces
175
- .filter { it.isFullFace(frameWidth, frameHeight) }
191
+ val eligibleFaces = faces.filter { it.isFullFace(frameWidth, frameHeight) }
192
+ val detectedFaces = eligibleFaces
176
193
  .map { it.toSpoofDetectedFace(transform) }
177
194
  .toTypedArray()
178
195
  synchronized(stateLock) {
179
- if (detectedFaces.size == 1) {
196
+ if (eligibleFaces.size == 1) {
197
+ val face = eligibleFaces.single()
198
+ val normalizedBounds = face.boundingBox.toNormalizedFaceBounds(frameWidth, frameHeight)
199
+ val trackingId = face.trackingId
200
+ val sameTrackedFace = lastFaceTrackingId == null || trackingId == null ||
201
+ lastFaceTrackingId == trackingId
202
+ val continuousBounds = lastFaceBoundsForContinuity?.let {
203
+ it.hasContinuousFace(normalizedBounds)
204
+ } ?: true
205
+
206
+ if (!sameTrackedFace || !continuousBounds) {
207
+ captured = false
208
+ stableCount = 0
209
+ consecutiveLiveFrames = 0
210
+ lastSpoofResult = null
211
+ }
212
+
180
213
  val bounds = detectedFaces[0].bounds
181
214
  stableCount += 1
182
215
  lastFaceBounds = bounds
216
+ lastFaceBoundsForContinuity = normalizedBounds
217
+ lastFaceTrackingId = trackingId
183
218
  } else {
184
219
  captured = false
185
220
  stableCount = 0
186
221
  lastFaceBounds = null
222
+ lastFaceBoundsForContinuity = null
223
+ lastFaceTrackingId = null
187
224
  consecutiveLiveFrames = 0
188
225
  lastSpoofResult = null
189
226
  }
@@ -193,6 +230,33 @@ class HybridSpoofDetectorOutput(
193
230
  options.onFacesDetected?.invoke(detectedFaces)
194
231
  }
195
232
 
233
+ private fun Rect.toNormalizedFaceBounds(frameWidth: Int, frameHeight: Int): RectF =
234
+ RectF(
235
+ left.toFloat() / frameWidth,
236
+ top.toFloat() / frameHeight,
237
+ right.toFloat() / frameWidth,
238
+ bottom.toFloat() / frameHeight,
239
+ )
240
+
241
+ private fun RectF.hasContinuousFace(current: RectF): Boolean {
242
+ val intersectionWidth = (min(right, current.right) - max(left, current.left)).coerceAtLeast(0f)
243
+ val intersectionHeight = (min(bottom, current.bottom) - max(top, current.top)).coerceAtLeast(0f)
244
+ val intersectionArea = intersectionWidth * intersectionHeight
245
+ val unionArea = width() * height() + current.width() * current.height() - intersectionArea
246
+ if (unionArea <= 0f || intersectionArea / unionArea < MIN_FACE_BOUNDS_IOU) return false
247
+
248
+ val centerDistance = kotlin.math.hypot(
249
+ centerX() - current.centerX(),
250
+ centerY() - current.centerY(),
251
+ )
252
+ val maxFaceDiagonal = max(
253
+ kotlin.math.hypot(width(), height()),
254
+ kotlin.math.hypot(current.width(), current.height()),
255
+ )
256
+ return maxFaceDiagonal > 0f &&
257
+ centerDistance <= maxFaceDiagonal * MAX_FACE_CENTER_SHIFT_RATIO
258
+ }
259
+
196
260
  private fun processAntiSpoofResult(result: AntiSpoofingResult) {
197
261
  var capture: Pair<SpoofDetectedFaceBounds, AntiSpoofingResult>? = null
198
262
 
@@ -244,6 +308,8 @@ class HybridSpoofDetectorOutput(
244
308
  captured = false
245
309
  stableCount = 0
246
310
  lastFaceBounds = null
311
+ lastFaceBoundsForContinuity = null
312
+ lastFaceTrackingId = null
247
313
  consecutiveLiveFrames = 0
248
314
  lastSpoofResult = null
249
315
  }
@@ -23,6 +23,7 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
23
23
  private var captured = false
24
24
  private var stableCount = 0
25
25
  private var lastFaceBounds: SpoofDetectedFaceBounds?
26
+ private var lastFaceObservationBounds: CGRect?
26
27
  private var consecutiveLiveFrames = 0
27
28
  private var lastSpoofResult: AntiSpoofingResult?
28
29
 
@@ -82,11 +83,9 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
82
83
  self.captured = false
83
84
  self.stableCount = 0
84
85
  self.lastFaceBounds = nil
86
+ self.lastFaceObservationBounds = nil
85
87
  self.consecutiveLiveFrames = 0
86
88
  self.lastSpoofResult = nil
87
- self.lastFaceCount = -1
88
- self.lastFacesUpdateAt = 0
89
- self.lastResultUpdateAt = 0
90
89
  self.stateLock.unlock()
91
90
  }
92
91
  }
@@ -114,7 +113,7 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
114
113
  }
115
114
 
116
115
  let faces = detectFaces(pixelBuffer)
117
- processDetectedFaces(faces.map(\.face))
116
+ processDetectedFaces(faces)
118
117
 
119
118
  guard shouldProcessFrame(pixelBuffer), faces.count == 1,
120
119
  let input = makeRGBInput(from: pixelBuffer, face: faces[0]) else {
@@ -200,20 +199,48 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
200
199
  }
201
200
  }
202
201
 
203
- private func processDetectedFaces(_ faces: [SpoofDetectedFace]) {
202
+ private func processDetectedFaces(_ faces: [DetectedFace]) {
204
203
  if faces.count == 1 {
205
- let bounds = faces[0].bounds
204
+ let detectedFace = faces[0]
205
+ let bounds = detectedFace.observation.boundingBox
206
+ let isContinuous = lastFaceObservationBounds.map {
207
+ hasContinuousFace(from: $0, to: bounds)
208
+ } ?? true
209
+ if !isContinuous {
210
+ captured = false
211
+ stableCount = 0
212
+ consecutiveLiveFrames = 0
213
+ lastSpoofResult = nil
214
+ }
206
215
  stableCount += 1
207
- lastFaceBounds = bounds
216
+ lastFaceBounds = detectedFace.face.bounds
217
+ lastFaceObservationBounds = bounds
208
218
  } else {
209
219
  captured = false
210
220
  stableCount = 0
211
221
  lastFaceBounds = nil
222
+ lastFaceObservationBounds = nil
212
223
  consecutiveLiveFrames = 0
213
224
  lastSpoofResult = nil
214
225
  }
215
226
 
216
- options.onFacesDetected?(faces)
227
+ options.onFacesDetected?(faces.map(\.face))
228
+ }
229
+
230
+ private func hasContinuousFace(from previous: CGRect, to current: CGRect) -> Bool {
231
+ let intersection = previous.intersection(current)
232
+ guard !intersection.isNull else { return false }
233
+ let intersectionArea = intersection.width * intersection.height
234
+ let unionArea = previous.width * previous.height + current.width * current.height - intersectionArea
235
+ guard unionArea > 0,
236
+ intersectionArea / unionArea >= 0.35 else {
237
+ return false
238
+ }
239
+
240
+ let centerDistance = hypot(previous.midX - current.midX, previous.midY - current.midY)
241
+ let previousDiagonal = hypot(previous.width, previous.height)
242
+ let currentDiagonal = hypot(current.width, current.height)
243
+ return centerDistance <= max(previousDiagonal, currentDiagonal) * 0.5
217
244
  }
218
245
 
219
246
  private func processAntiSpoofResult(_ result: AntiSpoofingResult) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-vision-camera-spoof-detector",
3
- "version": "1.3.7",
3
+ "version": "1.3.9",
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": {