react-native-vision-camera-spoof-detector 1.2.1 → 1.2.5
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 +12 -3
- package/android/build.gradle +1 -0
- package/android/src/main/java/com/faceantispoof/FaceAntiSpoofingAdvanced.kt +18 -2
- package/android/src/main/java/com/margelo/nitro/camera/spoofdetector/HybridSpoofDetectorFactory.kt +4 -0
- package/android/src/main/java/com/margelo/nitro/camera/spoofdetector/HybridSpoofDetectorOutput.kt +404 -214
- package/index.d.ts +14 -0
- package/index.js +50 -3
- package/ios/HybridSpoofDetectorOutput.swift +186 -2
- package/nitrogen/generated/android/VisionCameraSpoofDetectorOnLoad.cpp +4 -0
- package/nitrogen/generated/android/c++/JFunc_void_SpoofDetectedFaceBounds_AntiSpoofingResult.hpp +80 -0
- package/nitrogen/generated/android/c++/JFunc_void_std__vector_SpoofDetectedFace_.hpp +98 -0
- package/nitrogen/generated/android/c++/JHybridSpoofDetectorFactorySpec.cpp +15 -0
- package/nitrogen/generated/android/c++/JHybridSpoofDetectorFactorySpec.hpp +1 -0
- package/nitrogen/generated/android/c++/JSpoofDetectedFace.hpp +58 -0
- package/nitrogen/generated/android/c++/JSpoofDetectedFaceBounds.hpp +69 -0
- package/nitrogen/generated/android/c++/JSpoofDetectorOutputOptions.hpp +56 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/Func_void_SpoofDetectedFaceBounds_AntiSpoofingResult.kt +78 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/Func_void_std__vector_SpoofDetectedFace_.kt +78 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/HybridSpoofDetectorFactorySpec.kt +4 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/SpoofDetectedFace.kt +51 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/SpoofDetectedFaceBounds.kt +66 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/SpoofDetectorOutputOptions.kt +44 -4
- package/nitrogen/generated/ios/VisionCameraSpoofDetector-Swift-Cxx-Bridge.cpp +16 -0
- package/nitrogen/generated/ios/VisionCameraSpoofDetector-Swift-Cxx-Bridge.hpp +116 -0
- package/nitrogen/generated/ios/VisionCameraSpoofDetector-Swift-Cxx-Umbrella.hpp +7 -0
- package/nitrogen/generated/ios/c++/HybridSpoofDetectorFactorySpecSwift.hpp +13 -0
- package/nitrogen/generated/ios/swift/Func_void_SpoofDetectedFaceBounds_AntiSpoofingResult.swift +46 -0
- package/nitrogen/generated/ios/swift/Func_void_std__vector_SpoofDetectedFace_.swift +46 -0
- package/nitrogen/generated/ios/swift/HybridSpoofDetectorFactorySpec.swift +1 -0
- package/nitrogen/generated/ios/swift/HybridSpoofDetectorFactorySpec_cxx.swift +15 -0
- package/nitrogen/generated/ios/swift/SpoofDetectedFace.swift +29 -0
- package/nitrogen/generated/ios/swift/SpoofDetectedFaceBounds.swift +44 -0
- package/nitrogen/generated/ios/swift/SpoofDetectorOutputOptions.swift +167 -1
- package/nitrogen/generated/shared/c++/HybridSpoofDetectorFactorySpec.cpp +1 -0
- package/nitrogen/generated/shared/c++/HybridSpoofDetectorFactorySpec.hpp +1 -0
- package/nitrogen/generated/shared/c++/SpoofDetectedFace.hpp +84 -0
- package/nitrogen/generated/shared/c++/SpoofDetectedFaceBounds.hpp +95 -0
- package/nitrogen/generated/shared/c++/SpoofDetectorOutputOptions.hpp +41 -2
- package/package.json +1 -1
- package/src/specs/SpoofDetectorFactory.nitro.ts +47 -24
package/android/src/main/java/com/margelo/nitro/camera/spoofdetector/HybridSpoofDetectorOutput.kt
CHANGED
|
@@ -1,214 +1,404 @@
|
|
|
1
|
-
package com.margelo.nitro.camera.spoofdetector
|
|
2
|
-
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
import
|
|
8
|
-
import
|
|
9
|
-
import
|
|
10
|
-
import
|
|
11
|
-
import
|
|
12
|
-
import
|
|
13
|
-
import
|
|
14
|
-
import com.
|
|
15
|
-
import com.
|
|
16
|
-
import
|
|
17
|
-
import
|
|
18
|
-
import
|
|
19
|
-
import
|
|
20
|
-
import
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
private val
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
.
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
1
|
+
package com.margelo.nitro.camera.spoofdetector
|
|
2
|
+
|
|
3
|
+
import android.graphics.Matrix
|
|
4
|
+
import android.graphics.RectF
|
|
5
|
+
import android.os.SystemClock
|
|
6
|
+
import android.app.ActivityManager
|
|
7
|
+
import android.content.Context
|
|
8
|
+
import androidx.annotation.OptIn
|
|
9
|
+
import androidx.camera.core.ExperimentalGetImage
|
|
10
|
+
import androidx.camera.core.ImageAnalysis
|
|
11
|
+
import androidx.camera.core.ImageProxy
|
|
12
|
+
import androidx.camera.core.resolutionselector.ResolutionSelector
|
|
13
|
+
import androidx.camera.core.resolutionselector.ResolutionStrategy
|
|
14
|
+
import com.google.android.gms.tasks.Task
|
|
15
|
+
import com.google.android.gms.tasks.Tasks
|
|
16
|
+
import com.google.mlkit.vision.common.InputImage
|
|
17
|
+
import com.google.mlkit.vision.face.Face
|
|
18
|
+
import com.google.mlkit.vision.face.FaceDetection
|
|
19
|
+
import com.google.mlkit.vision.face.FaceDetectorOptions
|
|
20
|
+
import com.margelo.nitro.NitroModules
|
|
21
|
+
import com.margelo.nitro.camera.CameraOrientation
|
|
22
|
+
import com.margelo.nitro.camera.HybridCameraOutputSpec
|
|
23
|
+
import com.margelo.nitro.camera.MediaType
|
|
24
|
+
import com.margelo.nitro.camera.MirrorMode
|
|
25
|
+
import com.margelo.nitro.camera.extensions.setAllowDroppingLateFrames
|
|
26
|
+
import com.margelo.nitro.camera.extensions.surfaceRotation
|
|
27
|
+
import com.margelo.nitro.camera.public.NativeCameraOutput
|
|
28
|
+
import com.faceantispoof.FaceAntiSpoofingAdvanced
|
|
29
|
+
import kotlin.math.abs
|
|
30
|
+
import kotlin.math.max
|
|
31
|
+
import kotlin.math.min
|
|
32
|
+
import kotlin.math.roundToInt
|
|
33
|
+
import java.util.concurrent.Executors
|
|
34
|
+
import java.util.concurrent.atomic.AtomicBoolean
|
|
35
|
+
|
|
36
|
+
class HybridSpoofDetectorOutput(
|
|
37
|
+
private val options: SpoofDetectorOutputOptions,
|
|
38
|
+
) : HybridCameraOutputSpec(), ImageAnalysis.Analyzer, NativeCameraOutput {
|
|
39
|
+
override val mediaType: MediaType = MediaType.VIDEO
|
|
40
|
+
override val mirrorMode: MirrorMode = MirrorMode.AUTO
|
|
41
|
+
override var outputOrientation: CameraOrientation = CameraOrientation.UP
|
|
42
|
+
set(value) {
|
|
43
|
+
field = value
|
|
44
|
+
imageAnalysis?.targetRotation = value.surfaceRotation
|
|
45
|
+
}
|
|
46
|
+
override val currentResolution: com.margelo.nitro.camera.Size?
|
|
47
|
+
get() = null
|
|
48
|
+
|
|
49
|
+
private val executor = Executors.newSingleThreadExecutor()
|
|
50
|
+
private val busy = AtomicBoolean(false)
|
|
51
|
+
private val disposed = AtomicBoolean(false)
|
|
52
|
+
private val detector = FaceAntiSpoofingAdvanced(
|
|
53
|
+
NitroModules.applicationContext?.assets ?: error("FaceAntiSpoof: no application context")
|
|
54
|
+
)
|
|
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
|
+
}
|
|
64
|
+
private val faceDetectorTask = java.util.concurrent.atomic.AtomicReference<Task<List<Face>>?>()
|
|
65
|
+
private val stateLock = Any()
|
|
66
|
+
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)
|
|
69
|
+
private val laplacianThreshold = options.laplacianThreshold ?: 2000.0
|
|
70
|
+
private val maxNeuralSpoofScore = options.maxNeuralSpoofScore ?: 0.1
|
|
71
|
+
private val uiUpdateIntervalMs = (options.uiUpdateIntervalMs ?: 500.0).toLong().coerceAtLeast(0L)
|
|
72
|
+
private val isLowRamDevice by lazy {
|
|
73
|
+
val context = NitroModules.applicationContext
|
|
74
|
+
val activityManager = context?.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
|
|
75
|
+
activityManager?.isLowRamDevice == true
|
|
76
|
+
}
|
|
77
|
+
private var captured = false
|
|
78
|
+
private var stableCount = 0
|
|
79
|
+
private var lastFaceBounds: SpoofDetectedFaceBounds? = null
|
|
80
|
+
private var consecutiveLiveFrames = 0
|
|
81
|
+
private var isLive = false
|
|
82
|
+
private var lastSpoofResult: AntiSpoofingResult? = null
|
|
83
|
+
private var lastFaceCount = -1
|
|
84
|
+
private var lastFacesUpdateAtMs = 0L
|
|
85
|
+
private var lastResultUpdateAtMs = 0L
|
|
86
|
+
private var imageAnalysis: ImageAnalysis? = null
|
|
87
|
+
private companion object {
|
|
88
|
+
private const val MIN_FRAME_BRIGHTNESS = 24f
|
|
89
|
+
private const val MAX_FRAME_BRIGHTNESS = 220f
|
|
90
|
+
private const val MIN_VARIANCE_FOR_ANALYSIS = 1500f
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
override fun createUseCase(
|
|
94
|
+
mirrorMode: MirrorMode,
|
|
95
|
+
config: NativeCameraOutput.Config,
|
|
96
|
+
): NativeCameraOutput.PreparedUseCase {
|
|
97
|
+
val requestedTarget = options.targetResolution
|
|
98
|
+
val target = requestedTarget?.let {
|
|
99
|
+
if (isLowRamDevice && it.width > 640.0) {
|
|
100
|
+
val scale = 640.0 / it.width
|
|
101
|
+
android.util.Size(640, (it.height * scale).toInt().coerceAtLeast(1))
|
|
102
|
+
} else {
|
|
103
|
+
android.util.Size(it.width.toInt(), it.height.toInt())
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
val selector = target?.let {
|
|
107
|
+
ResolutionSelector.Builder()
|
|
108
|
+
.setResolutionStrategy(
|
|
109
|
+
ResolutionStrategy(
|
|
110
|
+
it,
|
|
111
|
+
ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER,
|
|
112
|
+
)
|
|
113
|
+
)
|
|
114
|
+
.build()
|
|
115
|
+
}
|
|
116
|
+
val analysis = ImageAnalysis.Builder()
|
|
117
|
+
.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888)
|
|
118
|
+
.setTargetRotation(outputOrientation.surfaceRotation)
|
|
119
|
+
.setOutputImageRotationEnabled(false)
|
|
120
|
+
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
|
121
|
+
.setAllowDroppingLateFrames(true)
|
|
122
|
+
.apply { if (selector != null) setResolutionSelector(selector) }
|
|
123
|
+
.build()
|
|
124
|
+
return NativeCameraOutput.PreparedUseCase(analysis) {
|
|
125
|
+
imageAnalysis = analysis
|
|
126
|
+
analysis.setAnalyzer(executor, this)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
@OptIn(ExperimentalGetImage::class)
|
|
131
|
+
override fun analyze(image: ImageProxy) {
|
|
132
|
+
if (disposed.get() || !busy.compareAndSet(false, true)) {
|
|
133
|
+
image.close()
|
|
134
|
+
return
|
|
135
|
+
}
|
|
136
|
+
val pendingOperations = java.util.concurrent.atomic.AtomicInteger(
|
|
137
|
+
if (faceDetector == null) 1 else 2
|
|
138
|
+
)
|
|
139
|
+
val releaseImage = {
|
|
140
|
+
if (pendingOperations.decrementAndGet() == 0) {
|
|
141
|
+
image.close()
|
|
142
|
+
busy.set(false)
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
var faceTaskRegistered = false
|
|
146
|
+
|
|
147
|
+
try {
|
|
148
|
+
if (faceDetector != null) {
|
|
149
|
+
try {
|
|
150
|
+
val mediaImage = image.image ?: throw IllegalStateException("ImageProxy has no media image")
|
|
151
|
+
val inputImage = InputImage.fromMediaImage(mediaImage, image.imageInfo.rotationDegrees)
|
|
152
|
+
val transform = createMLKitToCameraTransform(image)
|
|
153
|
+
val task = faceDetector.process(inputImage)
|
|
154
|
+
faceDetectorTask.set(task)
|
|
155
|
+
task.addOnSuccessListener { faces ->
|
|
156
|
+
try {
|
|
157
|
+
processDetectedFaces(faces, transform)
|
|
158
|
+
} catch (error: Throwable) {
|
|
159
|
+
options.onError?.invoke(error)
|
|
160
|
+
}
|
|
161
|
+
}.addOnFailureListener { error ->
|
|
162
|
+
options.onError?.invoke(error)
|
|
163
|
+
}.addOnCompleteListener {
|
|
164
|
+
faceDetectorTask.compareAndSet(task, null)
|
|
165
|
+
releaseImage()
|
|
166
|
+
}
|
|
167
|
+
faceTaskRegistered = true
|
|
168
|
+
} catch (error: Throwable) {
|
|
169
|
+
options.onError?.invoke(error)
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (!shouldProcessFrame(image)) return
|
|
174
|
+
|
|
175
|
+
val planes = image.planes.map { plane ->
|
|
176
|
+
val buffer = plane.buffer.duplicate()
|
|
177
|
+
ByteArray(buffer.remaining()).also(buffer::get)
|
|
178
|
+
}.toTypedArray()
|
|
179
|
+
val rowStrides = image.planes.map { it.rowStride }.toIntArray()
|
|
180
|
+
val pixelStrides = image.planes.map { it.pixelStride }.toIntArray()
|
|
181
|
+
val result = detector.advancedAntiSpoofing(
|
|
182
|
+
planes,
|
|
183
|
+
image.width,
|
|
184
|
+
image.height,
|
|
185
|
+
rowStrides,
|
|
186
|
+
pixelStrides,
|
|
187
|
+
image.imageInfo.rotationDegrees,
|
|
188
|
+
)
|
|
189
|
+
val isLive = result.neuralNetworkScore < FaceAntiSpoofingAdvanced.BASE_THRESHOLD &&
|
|
190
|
+
result.laplacianScore > FaceAntiSpoofingAdvanced.LAPLACIAN_THRESHOLD
|
|
191
|
+
processAntiSpoofResult(
|
|
192
|
+
AntiSpoofingResult(
|
|
193
|
+
isLive,
|
|
194
|
+
if (isLive) "Live Face" else "Spoof Face",
|
|
195
|
+
result.neuralNetworkScore.toDouble(),
|
|
196
|
+
result.laplacianScore.toDouble(),
|
|
197
|
+
result.combinedScore.toDouble(),
|
|
198
|
+
result.confidence.toDouble(),
|
|
199
|
+
)
|
|
200
|
+
)
|
|
201
|
+
} catch (error: Throwable) {
|
|
202
|
+
options.onError?.invoke(error)
|
|
203
|
+
} finally {
|
|
204
|
+
releaseImage()
|
|
205
|
+
if (faceDetector != null && !faceTaskRegistered) {
|
|
206
|
+
releaseImage()
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
private fun processDetectedFaces(faces: List<Face>, transform: Matrix) {
|
|
212
|
+
val detectedFaces = faces.map { it.toSpoofDetectedFace(transform) }.toTypedArray()
|
|
213
|
+
val now = SystemClock.elapsedRealtime()
|
|
214
|
+
var shouldNotify = false
|
|
215
|
+
var capture: Pair<SpoofDetectedFaceBounds, AntiSpoofingResult>? = null
|
|
216
|
+
|
|
217
|
+
synchronized(stateLock) {
|
|
218
|
+
if (detectedFaces.size == 1) {
|
|
219
|
+
val bounds = detectedFaces[0].bounds
|
|
220
|
+
stableCount += 1
|
|
221
|
+
lastFaceBounds = bounds
|
|
222
|
+
} else {
|
|
223
|
+
captured = false
|
|
224
|
+
stableCount = 0
|
|
225
|
+
lastFaceBounds = null
|
|
226
|
+
consecutiveLiveFrames = 0
|
|
227
|
+
isLive = false
|
|
228
|
+
lastSpoofResult = null
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
shouldNotify = detectedFaces.size != lastFaceCount ||
|
|
232
|
+
now - lastFacesUpdateAtMs >= uiUpdateIntervalMs
|
|
233
|
+
if (shouldNotify) {
|
|
234
|
+
lastFaceCount = detectedFaces.size
|
|
235
|
+
lastFacesUpdateAtMs = now
|
|
236
|
+
}
|
|
237
|
+
capture = readyToCaptureLocked()
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
if (shouldNotify) options.onFacesDetected?.invoke(detectedFaces)
|
|
241
|
+
capture?.let { (bounds, result) -> options.onStableFaceDetected?.invoke(bounds, result) }
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
private fun processAntiSpoofResult(result: AntiSpoofingResult) {
|
|
245
|
+
val now = SystemClock.elapsedRealtime()
|
|
246
|
+
var shouldNotify = false
|
|
247
|
+
var capture: Pair<SpoofDetectedFaceBounds, AntiSpoofingResult>? = null
|
|
248
|
+
|
|
249
|
+
synchronized(stateLock) {
|
|
250
|
+
lastSpoofResult = result
|
|
251
|
+
val isNeuralSpoof = result.neuralNetworkScore >= maxNeuralSpoofScore
|
|
252
|
+
if (isNeuralSpoof) {
|
|
253
|
+
consecutiveLiveFrames = 0
|
|
254
|
+
isLive = false
|
|
255
|
+
} else {
|
|
256
|
+
val targetPercent = (antispoofLevel * 100).roundToInt()
|
|
257
|
+
val currentPercent = (result.confidence * 100).roundToInt()
|
|
258
|
+
val combinedPercent = (result.combinedScore * 100).roundToInt()
|
|
259
|
+
val meetsConfidence = currentPercent >= targetPercent ||
|
|
260
|
+
result.confidence >= antispoofLevel ||
|
|
261
|
+
combinedPercent >= targetPercent ||
|
|
262
|
+
result.combinedScore >= antispoofLevel
|
|
263
|
+
val meetsLaplacian = result.laplacianScore == 0.0 ||
|
|
264
|
+
result.laplacianScore >= laplacianThreshold
|
|
265
|
+
val isLiveFrame = meetsConfidence && meetsLaplacian
|
|
266
|
+
consecutiveLiveFrames = if (isLiveFrame) {
|
|
267
|
+
min(requiredLiveFrames, consecutiveLiveFrames + 1)
|
|
268
|
+
} else {
|
|
269
|
+
max(0, consecutiveLiveFrames - 1)
|
|
270
|
+
}
|
|
271
|
+
isLive = consecutiveLiveFrames >= requiredLiveFrames
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
shouldNotify = now - lastResultUpdateAtMs >= uiUpdateIntervalMs
|
|
275
|
+
if (shouldNotify) lastResultUpdateAtMs = now
|
|
276
|
+
capture = readyToCaptureLocked()
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
if (shouldNotify) options.onResult.invoke(result)
|
|
280
|
+
capture?.let { (bounds, capturedResult) ->
|
|
281
|
+
options.onStableFaceDetected?.invoke(bounds, capturedResult)
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
private fun readyToCaptureLocked(): Pair<SpoofDetectedFaceBounds, AntiSpoofingResult>? {
|
|
286
|
+
if (captured || stableCount < stableFrames || !isLive ||
|
|
287
|
+
consecutiveLiveFrames < requiredLiveFrames
|
|
288
|
+
) return null
|
|
289
|
+
val bounds = lastFaceBounds ?: return null
|
|
290
|
+
val result = lastSpoofResult ?: return null
|
|
291
|
+
if (options.onStableFaceDetected == null) return null
|
|
292
|
+
captured = true
|
|
293
|
+
return Pair(bounds, result)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
fun resetState() {
|
|
297
|
+
synchronized(stateLock) {
|
|
298
|
+
captured = false
|
|
299
|
+
stableCount = 0
|
|
300
|
+
lastFaceBounds = null
|
|
301
|
+
consecutiveLiveFrames = 0
|
|
302
|
+
isLive = false
|
|
303
|
+
lastSpoofResult = null
|
|
304
|
+
lastFaceCount = -1
|
|
305
|
+
lastFacesUpdateAtMs = 0L
|
|
306
|
+
lastResultUpdateAtMs = 0L
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
private fun shouldProcessFrame(image: ImageProxy): Boolean {
|
|
311
|
+
val plane = image.planes.firstOrNull() ?: return false
|
|
312
|
+
val buffer = plane.buffer.duplicate()
|
|
313
|
+
val sampleStep = max(1, min(image.width, image.height) / 32)
|
|
314
|
+
var brightnessSum = 0L
|
|
315
|
+
var brightnessSquaredSum = 0L
|
|
316
|
+
var sampleCount = 0
|
|
317
|
+
|
|
318
|
+
for (y in 0 until image.height step sampleStep) {
|
|
319
|
+
val rowOffset = y * plane.rowStride
|
|
320
|
+
for (x in 0 until image.width step sampleStep) {
|
|
321
|
+
val index = rowOffset + x * plane.pixelStride
|
|
322
|
+
if (index >= buffer.limit()) continue
|
|
323
|
+
val luma = buffer.get(index).toInt() and 0xFF
|
|
324
|
+
brightnessSum += luma.toLong()
|
|
325
|
+
brightnessSquaredSum += (luma.toLong() * luma.toLong())
|
|
326
|
+
sampleCount += 1
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
if (sampleCount == 0) {
|
|
331
|
+
return false
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
val avgBrightness = brightnessSum.toFloat() / sampleCount
|
|
335
|
+
val variance = (brightnessSquaredSum.toFloat() / sampleCount) - (avgBrightness * avgBrightness)
|
|
336
|
+
|
|
337
|
+
val brightnessOk = avgBrightness in MIN_FRAME_BRIGHTNESS..MAX_FRAME_BRIGHTNESS
|
|
338
|
+
val textureOk = variance >= MIN_VARIANCE_FOR_ANALYSIS
|
|
339
|
+
|
|
340
|
+
return brightnessOk && textureOk
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
private fun createMLKitToCameraTransform(image: ImageProxy): Matrix {
|
|
344
|
+
val rotation = ((image.imageInfo.rotationDegrees % 360) + 360) % 360
|
|
345
|
+
require(rotation % 90 == 0) { "Invalid ML Kit rotation: $rotation" }
|
|
346
|
+
val source = RectF(0f, 0f, image.width.toFloat(), image.height.toFloat())
|
|
347
|
+
val target = if (rotation == 90 || rotation == 270) {
|
|
348
|
+
RectF(0f, 0f, image.height.toFloat(), image.width.toFloat())
|
|
349
|
+
} else {
|
|
350
|
+
source
|
|
351
|
+
}
|
|
352
|
+
val normalized = RectF(-1f, -1f, 1f, 1f)
|
|
353
|
+
val bufferToMLKit = Matrix().apply {
|
|
354
|
+
setRectToRect(source, normalized, Matrix.ScaleToFit.FILL)
|
|
355
|
+
postRotate(rotation.toFloat())
|
|
356
|
+
postConcat(Matrix().apply {
|
|
357
|
+
setRectToRect(normalized, target, Matrix.ScaleToFit.FILL)
|
|
358
|
+
})
|
|
359
|
+
}
|
|
360
|
+
val sensorToMLKit = Matrix(image.imageInfo.sensorToBufferTransformMatrix).apply {
|
|
361
|
+
postConcat(bufferToMLKit)
|
|
362
|
+
}
|
|
363
|
+
return Matrix().also { inverse ->
|
|
364
|
+
check(sensorToMLKit.invert(inverse)) { "Could not invert the face coordinate transform." }
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
private fun Face.toSpoofDetectedFace(transform: Matrix): SpoofDetectedFace {
|
|
369
|
+
val bounds = boundingBox
|
|
370
|
+
val points = floatArrayOf(
|
|
371
|
+
bounds.left.toFloat(), bounds.top.toFloat(),
|
|
372
|
+
bounds.right.toFloat(), bounds.top.toFloat(),
|
|
373
|
+
bounds.left.toFloat(), bounds.bottom.toFloat(),
|
|
374
|
+
bounds.right.toFloat(), bounds.bottom.toFloat(),
|
|
375
|
+
)
|
|
376
|
+
transform.mapPoints(points)
|
|
377
|
+
val xs = listOf(points[0], points[2], points[4], points[6])
|
|
378
|
+
val ys = listOf(points[1], points[3], points[5], points[7])
|
|
379
|
+
val left = xs.min().toDouble()
|
|
380
|
+
val top = ys.min().toDouble()
|
|
381
|
+
return SpoofDetectedFace(
|
|
382
|
+
SpoofDetectedFaceBounds(
|
|
383
|
+
left,
|
|
384
|
+
top,
|
|
385
|
+
(xs.max() - xs.min()).toDouble(),
|
|
386
|
+
(ys.max() - ys.min()).toDouble(),
|
|
387
|
+
)
|
|
388
|
+
)
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
override fun dispose() {
|
|
392
|
+
disposed.set(true)
|
|
393
|
+
imageAnalysis?.clearAnalyzer()
|
|
394
|
+
faceDetectorTask.get()?.let {
|
|
395
|
+
try {
|
|
396
|
+
Tasks.await(it)
|
|
397
|
+
} catch (_: Exception) {}
|
|
398
|
+
}
|
|
399
|
+
faceDetector?.close()
|
|
400
|
+
detector.close()
|
|
401
|
+
executor.shutdownNow()
|
|
402
|
+
super.dispose()
|
|
403
|
+
}
|
|
404
|
+
}
|
package/index.d.ts
CHANGED
|
@@ -72,6 +72,10 @@ export interface FaceRect {
|
|
|
72
72
|
height: number;
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
export interface SpoofDetectedFace {
|
|
76
|
+
bounds: FaceRect;
|
|
77
|
+
}
|
|
78
|
+
|
|
75
79
|
// ============================================================================
|
|
76
80
|
// Anti-spoofing State & Configuration
|
|
77
81
|
// ============================================================================
|
|
@@ -286,7 +290,15 @@ export interface UseFaceDetectionFrameProcessorReturn {
|
|
|
286
290
|
* The callback runs on the React Native runtime after native inference.
|
|
287
291
|
*/
|
|
288
292
|
export interface UseFaceAntiSpoofFrameOutputOptions extends Partial<FrameOutputOptions> {
|
|
293
|
+
antispoofLevel?: number;
|
|
294
|
+
stableFrames?: number;
|
|
295
|
+
requiredLiveFrames?: number;
|
|
296
|
+
laplacianThreshold?: number;
|
|
297
|
+
maxNeuralSpoofScore?: number;
|
|
298
|
+
uiUpdateIntervalMs?: number;
|
|
289
299
|
onResult?: (result: FaceAntiSpoofingResult) => void;
|
|
300
|
+
onFacesDetected?: (faces: SpoofDetectedFace[]) => void;
|
|
301
|
+
onStableFaceDetected?: (face: FaceRect, result: FaceAntiSpoofingResult) => void;
|
|
290
302
|
}
|
|
291
303
|
|
|
292
304
|
/** Create a VisionCamera 5 frame output backed by the native detector. */
|
|
@@ -294,6 +306,8 @@ export function useFaceAntiSpoofFrameOutput(
|
|
|
294
306
|
options?: UseFaceAntiSpoofFrameOutputOptions,
|
|
295
307
|
): CameraFrameOutput;
|
|
296
308
|
|
|
309
|
+
export function resetFaceAntiSpoofFrameOutput(output: CameraFrameOutput): void;
|
|
310
|
+
|
|
297
311
|
// ============================================================================
|
|
298
312
|
// Module Functions
|
|
299
313
|
// ============================================================================
|