react-native-vision-camera-spoof-detector 1.2.7 → 1.2.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.
- package/README.md +20 -3
- package/android/src/main/java/com/faceantispoof/FaceAntiSpoofingAdvanced.kt +55 -2
- package/android/src/main/java/com/margelo/nitro/camera/spoofdetector/HybridSpoofDetectorOutput.kt +67 -88
- package/ios/HybridSpoofDetectorFactory.swift +4 -0
- package/ios/HybridSpoofDetectorOutput.swift +97 -46
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -173,9 +173,26 @@ interface UseFaceAntiSpoofFrameOutputOptions {
|
|
|
173
173
|
}
|
|
174
174
|
```
|
|
175
175
|
|
|
176
|
-
|
|
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
|
-
|
|
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
|
-
-
|
|
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
|
-
|
|
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(
|
package/android/src/main/java/com/margelo/nitro/camera/spoofdetector/HybridSpoofDetectorOutput.kt
CHANGED
|
@@ -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 = (
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
FaceDetectorOptions.
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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 ?:
|
|
70
|
-
private val requiredLiveFrames = (options.requiredLiveFrames ?:
|
|
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 ?:
|
|
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
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
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
|
-
|
|
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 =
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
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
|
-
|
|
209
|
-
|
|
210
|
-
|
|
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
|
|
267
|
-
val
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
415
|
+
synchronized(detectorLock) {
|
|
416
|
+
detector.close()
|
|
417
|
+
}
|
|
439
418
|
executor.shutdownNow()
|
|
440
419
|
super.dispose()
|
|
441
420
|
}
|
|
@@ -7,4 +7,8 @@ final class HybridSpoofDetectorFactory: HybridSpoofDetectorFactorySpec {
|
|
|
7
7
|
{
|
|
8
8
|
return HybridSpoofDetectorOutput(options: options)
|
|
9
9
|
}
|
|
10
|
+
|
|
11
|
+
func resetSpoofDetectorOutput(output: any HybridCameraOutputSpec) throws {
|
|
12
|
+
(output as? HybridSpoofDetectorOutput)?.resetState()
|
|
13
|
+
}
|
|
10
14
|
}
|
|
@@ -6,6 +6,13 @@ import Vision
|
|
|
6
6
|
import VisionCamera
|
|
7
7
|
|
|
8
8
|
final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutput {
|
|
9
|
+
private struct DetectedFace {
|
|
10
|
+
let observation: VNFaceObservation
|
|
11
|
+
let face: SpoofDetectedFace
|
|
12
|
+
let leftEye: CGPoint
|
|
13
|
+
let rightEye: CGPoint
|
|
14
|
+
}
|
|
15
|
+
|
|
9
16
|
private let queue = DispatchQueue(label: "com.faceantispoof.output", qos: .userInitiated)
|
|
10
17
|
private let options: SpoofDetectorOutputOptions
|
|
11
18
|
private let delegate: SpoofDetectorDelegate
|
|
@@ -13,8 +20,6 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
13
20
|
private let targetSize = 256
|
|
14
21
|
private var isBusy = false
|
|
15
22
|
private var isDisposed = false
|
|
16
|
-
private var frameCounter = 0
|
|
17
|
-
private var lastFrameBrightness: Float = 0
|
|
18
23
|
private var captured = false
|
|
19
24
|
private var stableCount = 0
|
|
20
25
|
private var lastFaceBounds: SpoofDetectedFaceBounds?
|
|
@@ -25,12 +30,12 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
25
30
|
private var lastFacesUpdateAt = 0.0
|
|
26
31
|
private var lastResultUpdateAt = 0.0
|
|
27
32
|
|
|
28
|
-
private var antispoofLevel: Double { options.antispoofLevel ?? 0.
|
|
29
|
-
private var stableFrames: Int { max(1, Int(options.stableFrames ??
|
|
30
|
-
private var requiredLiveFrames: Int { max(1, Int(options.requiredLiveFrames ??
|
|
33
|
+
private var antispoofLevel: Double { options.antispoofLevel ?? 0.4 }
|
|
34
|
+
private var stableFrames: Int { max(1, Int(options.stableFrames ?? 3)) }
|
|
35
|
+
private var requiredLiveFrames: Int { max(1, Int(options.requiredLiveFrames ?? 3)) }
|
|
31
36
|
private var laplacianThreshold: Double { options.laplacianThreshold ?? 2000 }
|
|
32
37
|
private var maxNeuralSpoofScore: Double { options.maxNeuralSpoofScore ?? 0.1 }
|
|
33
|
-
private var uiUpdateInterval: Double { max(0, options.uiUpdateIntervalMs ??
|
|
38
|
+
private var uiUpdateInterval: Double { max(0, options.uiUpdateIntervalMs ?? 100) / 1000 }
|
|
34
39
|
private var isLowMemoryDevice: Bool {
|
|
35
40
|
ProcessInfo.processInfo.physicalMemory <= 4 * 1024 * 1024 * 1024
|
|
36
41
|
}
|
|
@@ -130,12 +135,12 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
130
135
|
CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly)
|
|
131
136
|
}
|
|
132
137
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
}
|
|
138
|
+
let faces = detectFaces(pixelBuffer)
|
|
139
|
+
processDetectedFaces(faces.map(\.face))
|
|
136
140
|
|
|
137
|
-
guard shouldProcessFrame(pixelBuffer),
|
|
138
|
-
let input = makeRGBInput(from: pixelBuffer) else {
|
|
141
|
+
guard shouldProcessFrame(pixelBuffer), faces.count == 1,
|
|
142
|
+
let input = makeRGBInput(from: pixelBuffer, face: faces[0]) else {
|
|
143
|
+
invalidateLiveEvidence()
|
|
139
144
|
stateLock.lock()
|
|
140
145
|
isBusy = false
|
|
141
146
|
stateLock.unlock()
|
|
@@ -161,6 +166,7 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
161
166
|
)
|
|
162
167
|
)
|
|
163
168
|
} catch {
|
|
169
|
+
invalidateLiveEvidence()
|
|
164
170
|
options.onError?(error)
|
|
165
171
|
}
|
|
166
172
|
}
|
|
@@ -174,8 +180,8 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
174
180
|
}
|
|
175
181
|
}
|
|
176
182
|
|
|
177
|
-
private func detectFaces(_ pixelBuffer: CVPixelBuffer) -> [
|
|
178
|
-
let request =
|
|
183
|
+
private func detectFaces(_ pixelBuffer: CVPixelBuffer) -> [DetectedFace] {
|
|
184
|
+
let request = VNDetectFaceLandmarksRequest()
|
|
179
185
|
do {
|
|
180
186
|
try VNImageRequestHandler(
|
|
181
187
|
cvPixelBuffer: pixelBuffer,
|
|
@@ -185,13 +191,31 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
185
191
|
|
|
186
192
|
let width = CVPixelBufferGetWidth(pixelBuffer)
|
|
187
193
|
let height = CVPixelBufferGetHeight(pixelBuffer)
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
194
|
+
let isQuarterTurn = outputOrientation == .right || outputOrientation == .left
|
|
195
|
+
let orientedWidth = isQuarterTurn ? height : width
|
|
196
|
+
let orientedHeight = isQuarterTurn ? width : height
|
|
197
|
+
return (request.results ?? []).compactMap { observation in
|
|
198
|
+
guard isEligibleFace(observation, width: orientedWidth, height: orientedHeight),
|
|
199
|
+
let landmarks = observation.landmarks,
|
|
200
|
+
let leftEye = landmarkCenter(landmarks.leftEye, in: observation.boundingBox),
|
|
201
|
+
let rightEye = landmarkCenter(landmarks.rightEye, in: observation.boundingBox) else {
|
|
202
|
+
return nil
|
|
203
|
+
}
|
|
204
|
+
let leftEyePoint = CGPoint(
|
|
205
|
+
x: leftEye.x * CGFloat(orientedWidth),
|
|
206
|
+
y: leftEye.y * CGFloat(orientedHeight)
|
|
207
|
+
)
|
|
208
|
+
let rightEyePoint = CGPoint(
|
|
209
|
+
x: rightEye.x * CGFloat(orientedWidth),
|
|
210
|
+
y: rightEye.y * CGFloat(orientedHeight)
|
|
211
|
+
)
|
|
212
|
+
return DetectedFace(
|
|
213
|
+
observation: observation,
|
|
214
|
+
face: SpoofDetectedFace(
|
|
215
|
+
bounds: makeBufferBounds(from: observation.boundingBox, width: width, height: height)
|
|
216
|
+
),
|
|
217
|
+
leftEye: leftEyePoint,
|
|
218
|
+
rightEye: rightEyePoint
|
|
195
219
|
)
|
|
196
220
|
}
|
|
197
221
|
} catch {
|
|
@@ -221,7 +245,6 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
221
245
|
lastFacesUpdateAt = now
|
|
222
246
|
options.onFacesDetected?(faces)
|
|
223
247
|
}
|
|
224
|
-
notifyStableFaceIfReady()
|
|
225
248
|
}
|
|
226
249
|
|
|
227
250
|
private func processAntiSpoofResult(_ result: AntiSpoofingResult) {
|
|
@@ -230,19 +253,12 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
230
253
|
consecutiveLiveFrames = 0
|
|
231
254
|
isLive = false
|
|
232
255
|
} else {
|
|
233
|
-
let
|
|
234
|
-
let
|
|
235
|
-
let combinedPercent = Int((result.combinedScore * 100).rounded())
|
|
236
|
-
let meetsConfidence = currentPercent >= targetPercent ||
|
|
237
|
-
result.confidence >= antispoofLevel ||
|
|
238
|
-
combinedPercent >= targetPercent ||
|
|
239
|
-
result.combinedScore >= antispoofLevel
|
|
240
|
-
let meetsLaplacian = result.laplacianScore == 0 ||
|
|
241
|
-
result.laplacianScore >= laplacianThreshold
|
|
256
|
+
let meetsConfidence = result.confidence >= antispoofLevel
|
|
257
|
+
let meetsLaplacian = result.laplacianScore >= laplacianThreshold
|
|
242
258
|
if meetsConfidence && meetsLaplacian {
|
|
243
259
|
consecutiveLiveFrames = min(requiredLiveFrames, consecutiveLiveFrames + 1)
|
|
244
260
|
} else {
|
|
245
|
-
consecutiveLiveFrames =
|
|
261
|
+
consecutiveLiveFrames = 0
|
|
246
262
|
}
|
|
247
263
|
isLive = consecutiveLiveFrames >= requiredLiveFrames
|
|
248
264
|
}
|
|
@@ -298,9 +314,6 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
298
314
|
}
|
|
299
315
|
|
|
300
316
|
private func shouldProcessFrame(_ pixelBuffer: CVPixelBuffer) -> Bool {
|
|
301
|
-
frameCounter += 1
|
|
302
|
-
guard frameCounter % 3 == 0 else { return false }
|
|
303
|
-
|
|
304
317
|
let width = CVPixelBufferGetWidth(pixelBuffer)
|
|
305
318
|
let height = CVPixelBufferGetHeight(pixelBuffer)
|
|
306
319
|
let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
|
|
@@ -308,7 +321,6 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
308
321
|
let bytes = baseAddress.assumingMemoryBound(to: UInt8.self)
|
|
309
322
|
let sampleStep = max(1, min(width, height) / 32)
|
|
310
323
|
var brightnessSum: Float = 0
|
|
311
|
-
var brightnessSquaredSum: Float = 0
|
|
312
324
|
var sampleCount: Float = 0
|
|
313
325
|
|
|
314
326
|
for y in stride(from: 0, to: height, by: sampleStep) {
|
|
@@ -319,23 +331,16 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
319
331
|
let red = Float(bytes[offset + 2])
|
|
320
332
|
let luma = 0.299 * red + 0.587 * green + 0.114 * blue
|
|
321
333
|
brightnessSum += luma
|
|
322
|
-
brightnessSquaredSum += luma * luma
|
|
323
334
|
sampleCount += 1
|
|
324
335
|
}
|
|
325
336
|
}
|
|
326
337
|
|
|
327
338
|
guard sampleCount > 0 else { return false }
|
|
328
339
|
let average = brightnessSum / sampleCount
|
|
329
|
-
|
|
330
|
-
let brightnessDelta = abs(average - lastFrameBrightness)
|
|
331
|
-
let isFirstSample = lastFrameBrightness == 0
|
|
332
|
-
lastFrameBrightness = average
|
|
333
|
-
|
|
334
|
-
return average >= 24 && average <= 220 && variance >= 1500 &&
|
|
335
|
-
(isFirstSample || brightnessDelta >= 8)
|
|
340
|
+
return average >= 24 && average <= 220
|
|
336
341
|
}
|
|
337
342
|
|
|
338
|
-
private func makeRGBInput(from pixelBuffer: CVPixelBuffer) -> [Float]? {
|
|
343
|
+
private func makeRGBInput(from pixelBuffer: CVPixelBuffer, face: DetectedFace) -> [Float]? {
|
|
339
344
|
guard CVPixelBufferGetPixelFormatType(pixelBuffer) == kCVPixelFormatType_32BGRA,
|
|
340
345
|
let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else { return nil }
|
|
341
346
|
|
|
@@ -347,11 +352,23 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
347
352
|
let isQuarterTurn = outputOrientation == .right || outputOrientation == .left
|
|
348
353
|
let orientedWidth = isQuarterTurn ? sourceHeight : sourceWidth
|
|
349
354
|
let orientedHeight = isQuarterTurn ? sourceWidth : sourceHeight
|
|
355
|
+
let box = face.observation.boundingBox
|
|
356
|
+
let faceWidth = box.width * CGFloat(orientedWidth)
|
|
357
|
+
let faceHeight = box.height * CGFloat(orientedHeight)
|
|
358
|
+
let cropSide = min(min(orientedWidth, orientedHeight), max(1, Int((max(faceWidth, faceHeight) * 1.4).rounded())))
|
|
359
|
+
let halfSide = CGFloat(cropSide) / 2
|
|
360
|
+
let centerX = min(max(box.midX * CGFloat(orientedWidth), halfSide), CGFloat(orientedWidth) - halfSide)
|
|
361
|
+
let centerY = min(max((1 - box.midY) * CGFloat(orientedHeight), halfSide), CGFloat(orientedHeight) - halfSide)
|
|
362
|
+
let eyeAngle = atan2(face.rightEye.y - face.leftEye.y, face.rightEye.x - face.leftEye.x)
|
|
363
|
+
let cosine = cos(eyeAngle)
|
|
364
|
+
let sine = sin(eyeAngle)
|
|
350
365
|
|
|
351
366
|
for targetY in 0..<targetSize {
|
|
352
|
-
let
|
|
367
|
+
let cropY = (CGFloat(targetY) + 0.5) * CGFloat(cropSide) / CGFloat(targetSize) - halfSide
|
|
353
368
|
for targetX in 0..<targetSize {
|
|
354
|
-
let
|
|
369
|
+
let cropX = (CGFloat(targetX) + 0.5) * CGFloat(cropSide) / CGFloat(targetSize) - halfSide
|
|
370
|
+
let orientedX = min(orientedWidth - 1, max(0, Int((centerX + cosine * cropX - sine * cropY).rounded())))
|
|
371
|
+
let orientedY = min(orientedHeight - 1, max(0, Int((centerY + sine * cropX + cosine * cropY).rounded())))
|
|
355
372
|
let sourcePoint: (x: Int, y: Int)
|
|
356
373
|
switch outputOrientation {
|
|
357
374
|
case .right:
|
|
@@ -373,6 +390,40 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
373
390
|
}
|
|
374
391
|
return result
|
|
375
392
|
}
|
|
393
|
+
|
|
394
|
+
private func isEligibleFace(_ face: VNFaceObservation, width: Int, height: Int) -> Bool {
|
|
395
|
+
guard width > 0, height > 0 else { return false }
|
|
396
|
+
let box = face.boundingBox
|
|
397
|
+
let marginX: CGFloat = 0.02
|
|
398
|
+
let marginY: CGFloat = 0.02
|
|
399
|
+
guard box.minX >= marginX, box.maxX <= 1 - marginX,
|
|
400
|
+
box.minY >= marginY, box.maxY <= 1 - marginY,
|
|
401
|
+
box.width >= 0.18, box.height >= 0.18,
|
|
402
|
+
abs(face.yaw?.doubleValue ?? 0) <= 25 * .pi / 180,
|
|
403
|
+
abs(face.roll?.doubleValue ?? 0) <= 25 * .pi / 180,
|
|
404
|
+
let landmarks = face.landmarks,
|
|
405
|
+
landmarks.leftEye != nil, landmarks.rightEye != nil,
|
|
406
|
+
landmarks.nose != nil, landmarks.outerLips != nil else {
|
|
407
|
+
return false
|
|
408
|
+
}
|
|
409
|
+
return true
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
private func landmarkCenter(_ landmark: VNFaceLandmarkRegion2D?, in box: CGRect) -> CGPoint? {
|
|
413
|
+
guard let points = landmark?.normalizedPoints, !points.isEmpty else { return nil }
|
|
414
|
+
let average = points.reduce(CGPoint.zero) { partial, point in
|
|
415
|
+
CGPoint(x: partial.x + point.x, y: partial.y + point.y)
|
|
416
|
+
}
|
|
417
|
+
let normalizedX = box.minX + average.x / CGFloat(points.count) * box.width
|
|
418
|
+
let normalizedY = 1 - (box.minY + average.y / CGFloat(points.count) * box.height)
|
|
419
|
+
return CGPoint(x: normalizedX, y: normalizedY)
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
private func invalidateLiveEvidence() {
|
|
423
|
+
consecutiveLiveFrames = 0
|
|
424
|
+
isLive = false
|
|
425
|
+
lastSpoofResult = nil
|
|
426
|
+
}
|
|
376
427
|
}
|
|
377
428
|
|
|
378
429
|
private final class SpoofDetectorDelegate: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-native-vision-camera-spoof-detector",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.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": {
|