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.
Files changed (40) hide show
  1. package/README.md +12 -3
  2. package/android/build.gradle +1 -0
  3. package/android/src/main/java/com/faceantispoof/FaceAntiSpoofingAdvanced.kt +18 -2
  4. package/android/src/main/java/com/margelo/nitro/camera/spoofdetector/HybridSpoofDetectorFactory.kt +4 -0
  5. package/android/src/main/java/com/margelo/nitro/camera/spoofdetector/HybridSpoofDetectorOutput.kt +404 -214
  6. package/index.d.ts +14 -0
  7. package/index.js +50 -3
  8. package/ios/HybridSpoofDetectorOutput.swift +186 -2
  9. package/nitrogen/generated/android/VisionCameraSpoofDetectorOnLoad.cpp +4 -0
  10. package/nitrogen/generated/android/c++/JFunc_void_SpoofDetectedFaceBounds_AntiSpoofingResult.hpp +80 -0
  11. package/nitrogen/generated/android/c++/JFunc_void_std__vector_SpoofDetectedFace_.hpp +98 -0
  12. package/nitrogen/generated/android/c++/JHybridSpoofDetectorFactorySpec.cpp +15 -0
  13. package/nitrogen/generated/android/c++/JHybridSpoofDetectorFactorySpec.hpp +1 -0
  14. package/nitrogen/generated/android/c++/JSpoofDetectedFace.hpp +58 -0
  15. package/nitrogen/generated/android/c++/JSpoofDetectedFaceBounds.hpp +69 -0
  16. package/nitrogen/generated/android/c++/JSpoofDetectorOutputOptions.hpp +56 -1
  17. package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/Func_void_SpoofDetectedFaceBounds_AntiSpoofingResult.kt +78 -0
  18. package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/Func_void_std__vector_SpoofDetectedFace_.kt +78 -0
  19. package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/HybridSpoofDetectorFactorySpec.kt +4 -0
  20. package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/SpoofDetectedFace.kt +51 -0
  21. package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/SpoofDetectedFaceBounds.kt +66 -0
  22. package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/SpoofDetectorOutputOptions.kt +44 -4
  23. package/nitrogen/generated/ios/VisionCameraSpoofDetector-Swift-Cxx-Bridge.cpp +16 -0
  24. package/nitrogen/generated/ios/VisionCameraSpoofDetector-Swift-Cxx-Bridge.hpp +116 -0
  25. package/nitrogen/generated/ios/VisionCameraSpoofDetector-Swift-Cxx-Umbrella.hpp +7 -0
  26. package/nitrogen/generated/ios/c++/HybridSpoofDetectorFactorySpecSwift.hpp +13 -0
  27. package/nitrogen/generated/ios/swift/Func_void_SpoofDetectedFaceBounds_AntiSpoofingResult.swift +46 -0
  28. package/nitrogen/generated/ios/swift/Func_void_std__vector_SpoofDetectedFace_.swift +46 -0
  29. package/nitrogen/generated/ios/swift/HybridSpoofDetectorFactorySpec.swift +1 -0
  30. package/nitrogen/generated/ios/swift/HybridSpoofDetectorFactorySpec_cxx.swift +15 -0
  31. package/nitrogen/generated/ios/swift/SpoofDetectedFace.swift +29 -0
  32. package/nitrogen/generated/ios/swift/SpoofDetectedFaceBounds.swift +44 -0
  33. package/nitrogen/generated/ios/swift/SpoofDetectorOutputOptions.swift +167 -1
  34. package/nitrogen/generated/shared/c++/HybridSpoofDetectorFactorySpec.cpp +1 -0
  35. package/nitrogen/generated/shared/c++/HybridSpoofDetectorFactorySpec.hpp +1 -0
  36. package/nitrogen/generated/shared/c++/SpoofDetectedFace.hpp +84 -0
  37. package/nitrogen/generated/shared/c++/SpoofDetectedFaceBounds.hpp +95 -0
  38. package/nitrogen/generated/shared/c++/SpoofDetectorOutputOptions.hpp +41 -2
  39. package/package.json +1 -1
  40. package/src/specs/SpoofDetectorFactory.nitro.ts +47 -24
@@ -1,214 +1,404 @@
1
- package com.margelo.nitro.camera.spoofdetector
2
-
3
- import androidx.camera.core.ImageAnalysis
4
- import androidx.camera.core.ImageProxy
5
- import androidx.camera.core.resolutionselector.ResolutionSelector
6
- import androidx.camera.core.resolutionselector.ResolutionStrategy
7
- import com.margelo.nitro.NitroModules
8
- import com.margelo.nitro.camera.CameraOrientation
9
- import com.margelo.nitro.camera.HybridCameraOutputSpec
10
- import com.margelo.nitro.camera.MediaType
11
- import com.margelo.nitro.camera.MirrorMode
12
- import com.margelo.nitro.camera.extensions.setAllowDroppingLateFrames
13
- import com.margelo.nitro.camera.extensions.surfaceRotation
14
- import com.margelo.nitro.camera.public.NativeCameraOutput
15
- import com.faceantispoof.FaceAntiSpoofingAdvanced
16
- import kotlin.math.abs
17
- import kotlin.math.max
18
- import kotlin.math.min
19
- import java.util.concurrent.Executors
20
- import java.util.concurrent.atomic.AtomicBoolean
21
-
22
- class HybridSpoofDetectorOutput(
23
- private val options: SpoofDetectorOutputOptions,
24
- ) : HybridCameraOutputSpec(), ImageAnalysis.Analyzer, NativeCameraOutput {
25
- override val mediaType: MediaType = MediaType.VIDEO
26
- override val mirrorMode: MirrorMode = MirrorMode.AUTO
27
- override var outputOrientation: CameraOrientation = CameraOrientation.UP
28
- set(value) {
29
- field = value
30
- imageAnalysis?.targetRotation = value.surfaceRotation
31
- }
32
- override val currentResolution: com.margelo.nitro.camera.Size?
33
- get() = null
34
-
35
- private val executor = Executors.newSingleThreadExecutor()
36
- private val busy = AtomicBoolean(false)
37
- private val disposed = AtomicBoolean(false)
38
- private val frameCounter = java.util.concurrent.atomic.AtomicInteger(0)
39
- private var lastFrameBrightness = 0f
40
- private val detector = FaceAntiSpoofingAdvanced(
41
- NitroModules.applicationContext?.assets ?: error("FaceAntiSpoof: no application context")
42
- )
43
- private var imageAnalysis: ImageAnalysis? = null
44
- private companion object {
45
- private const val FRAME_EVALUATION_INTERVAL = 3
46
- private const val MIN_FRAME_BRIGHTNESS = 24f
47
- private const val MAX_FRAME_BRIGHTNESS = 220f
48
- private const val MIN_VARIANCE_FOR_ANALYSIS = 1500f
49
- private const val MIN_BRIGHTNESS_DELTA = 8f
50
- }
51
-
52
- override fun createUseCase(
53
- mirrorMode: MirrorMode,
54
- config: NativeCameraOutput.Config,
55
- ): NativeCameraOutput.PreparedUseCase {
56
- val target = options.targetResolution
57
- val selector = target?.let {
58
- ResolutionSelector.Builder()
59
- .setResolutionStrategy(
60
- ResolutionStrategy(
61
- android.util.Size(it.width.toInt(), it.height.toInt()),
62
- ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER,
63
- )
64
- )
65
- .build()
66
- }
67
- val analysis = ImageAnalysis.Builder()
68
- .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888)
69
- .setOutputImageRotationEnabled(false)
70
- .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
71
- .setAllowDroppingLateFrames(true)
72
- .apply { if (selector != null) setResolutionSelector(selector) }
73
- .build()
74
- return NativeCameraOutput.PreparedUseCase(analysis) {
75
- imageAnalysis = analysis
76
- analysis.setAnalyzer(executor, this)
77
- }
78
- }
79
-
80
- override fun analyze(image: ImageProxy) {
81
- if (disposed.get() || !busy.compareAndSet(false, true)) {
82
- image.close()
83
- return
84
- }
85
- try {
86
- val plane = image.planes.firstOrNull() ?: throw IllegalStateException("RGBA image has no planes")
87
- val rgba = plane.buffer.duplicate()
88
- rgba.order(java.nio.ByteOrder.nativeOrder())
89
-
90
- if (!shouldProcessFrameFromPlane(rgba, image.width, image.height, plane.rowStride, plane.pixelStride)) {
91
- return
92
- }
93
-
94
- val result = detector.advancedAntiSpoofingRGBA(
95
- rgba,
96
- image.width,
97
- image.height,
98
- plane.rowStride,
99
- plane.pixelStride,
100
- )
101
- val isLive = result.neuralNetworkScore < FaceAntiSpoofingAdvanced.BASE_THRESHOLD &&
102
- result.laplacianScore > FaceAntiSpoofingAdvanced.LAPLACIAN_THRESHOLD
103
- options.onResult.invoke(
104
- AntiSpoofingResult(
105
- isLive,
106
- if (isLive) "Live Face" else "Spoof Face",
107
- result.neuralNetworkScore.toDouble(),
108
- result.laplacianScore.toDouble(),
109
- result.combinedScore.toDouble(),
110
- result.confidence.toDouble(),
111
- )
112
- )
113
- } catch (error: Throwable) {
114
- options.onError?.invoke(error)
115
- } finally {
116
- image.close()
117
- busy.set(false)
118
- }
119
- }
120
-
121
- private fun shouldProcessFrameFromPlane(
122
- buffer: java.nio.ByteBuffer,
123
- width: Int,
124
- height: Int,
125
- rowStride: Int,
126
- pixelStride: Int,
127
- ): Boolean {
128
- val frameIndex = frameCounter.incrementAndGet()
129
- if (frameIndex % FRAME_EVALUATION_INTERVAL != 0) {
130
- return false
131
- }
132
-
133
- val sampleStep = max(1, min(width, height) / 32)
134
- var brightnessSum = 0L
135
- var brightnessSquaredSum = 0L
136
- var sampleCount = 0
137
-
138
- for (y in 0 until height step sampleStep) {
139
- val rowOffset = y * rowStride
140
- for (x in 0 until width step sampleStep) {
141
- val index = rowOffset + x * pixelStride
142
- if (index + 2 >= buffer.capacity()) continue
143
-
144
- val r = buffer.get(index).toInt() and 0xFF
145
- val g = buffer.get(index + 1).toInt() and 0xFF
146
- val b = buffer.get(index + 2).toInt() and 0xFF
147
- val luma = (0.299 * r + 0.587 * g + 0.114 * b).toInt()
148
-
149
- brightnessSum += luma.toLong()
150
- brightnessSquaredSum += (luma.toLong() * luma.toLong())
151
- sampleCount += 1
152
- }
153
- }
154
-
155
- if (sampleCount == 0) {
156
- return false
157
- }
158
-
159
- val avgBrightness = brightnessSum.toFloat() / sampleCount
160
- val variance = (brightnessSquaredSum.toFloat() / sampleCount) - (avgBrightness * avgBrightness)
161
- val brightnessDelta = abs(avgBrightness - lastFrameBrightness)
162
- lastFrameBrightness = avgBrightness
163
-
164
- val brightnessOk = avgBrightness in MIN_FRAME_BRIGHTNESS..MAX_FRAME_BRIGHTNESS
165
- val textureOk = variance >= MIN_VARIANCE_FOR_ANALYSIS
166
- val motionLikely = brightnessDelta >= MIN_BRIGHTNESS_DELTA || lastFrameBrightness == 0f
167
-
168
- return brightnessOk && textureOk && motionLikely
169
- }
170
-
171
- private fun extractRgbaBytes(image: ImageProxy): ByteArray {
172
- val plane = image.planes.firstOrNull() ?: throw IllegalStateException("RGBA image has no planes")
173
- val rowStride = plane.rowStride
174
- val pixelStride = plane.pixelStride
175
- val width = image.width
176
- val height = image.height
177
- val bytesPerPixel = 4
178
- val outputSize = width * height * bytesPerPixel
179
- val packed = ByteArray(outputSize)
180
- val buffer = plane.buffer.duplicate()
181
- buffer.order(java.nio.ByteOrder.nativeOrder())
182
-
183
- if (pixelStride == bytesPerPixel && rowStride == width * bytesPerPixel) {
184
- buffer.get(packed)
185
- return packed
186
- }
187
-
188
- var outputIndex = 0
189
- for (y in 0 until height) {
190
- val rowOffset = y * rowStride
191
- for (x in 0 until width) {
192
- val pixelOffset = rowOffset + x * pixelStride
193
- val r = buffer.get(pixelOffset).toInt() and 0xFF
194
- val g = buffer.get(pixelOffset + 1).toInt() and 0xFF
195
- val b = buffer.get(pixelOffset + 2).toInt() and 0xFF
196
- val a = buffer.get(pixelOffset + 3).toInt() and 0xFF
197
- packed[outputIndex++] = r.toByte()
198
- packed[outputIndex++] = g.toByte()
199
- packed[outputIndex++] = b.toByte()
200
- packed[outputIndex++] = a.toByte()
201
- }
202
- }
203
-
204
- return packed
205
- }
206
-
207
- override fun dispose() {
208
- disposed.set(true)
209
- imageAnalysis?.clearAnalyzer()
210
- detector.close()
211
- executor.shutdownNow()
212
- super.dispose()
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
  // ============================================================================