react-native-vision-camera-spoof-detector 1.2.1 → 1.2.4

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 (39) hide show
  1. package/README.md +12 -3
  2. package/android/build.gradle +1 -0
  3. package/android/src/main/java/com/margelo/nitro/camera/spoofdetector/HybridSpoofDetectorFactory.kt +4 -0
  4. package/android/src/main/java/com/margelo/nitro/camera/spoofdetector/HybridSpoofDetectorOutput.kt +403 -214
  5. package/index.d.ts +14 -0
  6. package/index.js +50 -3
  7. package/ios/HybridSpoofDetectorOutput.swift +186 -2
  8. package/nitrogen/generated/android/VisionCameraSpoofDetectorOnLoad.cpp +4 -0
  9. package/nitrogen/generated/android/c++/JFunc_void_SpoofDetectedFaceBounds_AntiSpoofingResult.hpp +80 -0
  10. package/nitrogen/generated/android/c++/JFunc_void_std__vector_SpoofDetectedFace_.hpp +98 -0
  11. package/nitrogen/generated/android/c++/JHybridSpoofDetectorFactorySpec.cpp +15 -0
  12. package/nitrogen/generated/android/c++/JHybridSpoofDetectorFactorySpec.hpp +1 -0
  13. package/nitrogen/generated/android/c++/JSpoofDetectedFace.hpp +58 -0
  14. package/nitrogen/generated/android/c++/JSpoofDetectedFaceBounds.hpp +69 -0
  15. package/nitrogen/generated/android/c++/JSpoofDetectorOutputOptions.hpp +56 -1
  16. package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/Func_void_SpoofDetectedFaceBounds_AntiSpoofingResult.kt +78 -0
  17. package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/Func_void_std__vector_SpoofDetectedFace_.kt +78 -0
  18. package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/HybridSpoofDetectorFactorySpec.kt +4 -0
  19. package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/SpoofDetectedFace.kt +51 -0
  20. package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/SpoofDetectedFaceBounds.kt +66 -0
  21. package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/SpoofDetectorOutputOptions.kt +44 -4
  22. package/nitrogen/generated/ios/VisionCameraSpoofDetector-Swift-Cxx-Bridge.cpp +16 -0
  23. package/nitrogen/generated/ios/VisionCameraSpoofDetector-Swift-Cxx-Bridge.hpp +116 -0
  24. package/nitrogen/generated/ios/VisionCameraSpoofDetector-Swift-Cxx-Umbrella.hpp +7 -0
  25. package/nitrogen/generated/ios/c++/HybridSpoofDetectorFactorySpecSwift.hpp +13 -0
  26. package/nitrogen/generated/ios/swift/Func_void_SpoofDetectedFaceBounds_AntiSpoofingResult.swift +46 -0
  27. package/nitrogen/generated/ios/swift/Func_void_std__vector_SpoofDetectedFace_.swift +46 -0
  28. package/nitrogen/generated/ios/swift/HybridSpoofDetectorFactorySpec.swift +1 -0
  29. package/nitrogen/generated/ios/swift/HybridSpoofDetectorFactorySpec_cxx.swift +15 -0
  30. package/nitrogen/generated/ios/swift/SpoofDetectedFace.swift +29 -0
  31. package/nitrogen/generated/ios/swift/SpoofDetectedFaceBounds.swift +44 -0
  32. package/nitrogen/generated/ios/swift/SpoofDetectorOutputOptions.swift +167 -1
  33. package/nitrogen/generated/shared/c++/HybridSpoofDetectorFactorySpec.cpp +1 -0
  34. package/nitrogen/generated/shared/c++/HybridSpoofDetectorFactorySpec.hpp +1 -0
  35. package/nitrogen/generated/shared/c++/SpoofDetectedFace.hpp +84 -0
  36. package/nitrogen/generated/shared/c++/SpoofDetectedFaceBounds.hpp +95 -0
  37. package/nitrogen/generated/shared/c++/SpoofDetectorOutputOptions.hpp +41 -2
  38. package/package.json +1 -1
  39. package/src/specs/SpoofDetectorFactory.nitro.ts +47 -24
@@ -1,214 +1,403 @@
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
+ )
188
+ val isLive = result.neuralNetworkScore < FaceAntiSpoofingAdvanced.BASE_THRESHOLD &&
189
+ result.laplacianScore > FaceAntiSpoofingAdvanced.LAPLACIAN_THRESHOLD
190
+ processAntiSpoofResult(
191
+ AntiSpoofingResult(
192
+ isLive,
193
+ if (isLive) "Live Face" else "Spoof Face",
194
+ result.neuralNetworkScore.toDouble(),
195
+ result.laplacianScore.toDouble(),
196
+ result.combinedScore.toDouble(),
197
+ result.confidence.toDouble(),
198
+ )
199
+ )
200
+ } catch (error: Throwable) {
201
+ options.onError?.invoke(error)
202
+ } finally {
203
+ releaseImage()
204
+ if (faceDetector != null && !faceTaskRegistered) {
205
+ releaseImage()
206
+ }
207
+ }
208
+ }
209
+
210
+ private fun processDetectedFaces(faces: List<Face>, transform: Matrix) {
211
+ val detectedFaces = faces.map { it.toSpoofDetectedFace(transform) }.toTypedArray()
212
+ val now = SystemClock.elapsedRealtime()
213
+ var shouldNotify = false
214
+ var capture: Pair<SpoofDetectedFaceBounds, AntiSpoofingResult>? = null
215
+
216
+ synchronized(stateLock) {
217
+ if (detectedFaces.size == 1) {
218
+ val bounds = detectedFaces[0].bounds
219
+ stableCount += 1
220
+ lastFaceBounds = bounds
221
+ } else {
222
+ captured = false
223
+ stableCount = 0
224
+ lastFaceBounds = null
225
+ consecutiveLiveFrames = 0
226
+ isLive = false
227
+ lastSpoofResult = null
228
+ }
229
+
230
+ shouldNotify = detectedFaces.size != lastFaceCount ||
231
+ now - lastFacesUpdateAtMs >= uiUpdateIntervalMs
232
+ if (shouldNotify) {
233
+ lastFaceCount = detectedFaces.size
234
+ lastFacesUpdateAtMs = now
235
+ }
236
+ capture = readyToCaptureLocked()
237
+ }
238
+
239
+ if (shouldNotify) options.onFacesDetected?.invoke(detectedFaces)
240
+ capture?.let { (bounds, result) -> options.onStableFaceDetected?.invoke(bounds, result) }
241
+ }
242
+
243
+ private fun processAntiSpoofResult(result: AntiSpoofingResult) {
244
+ val now = SystemClock.elapsedRealtime()
245
+ var shouldNotify = false
246
+ var capture: Pair<SpoofDetectedFaceBounds, AntiSpoofingResult>? = null
247
+
248
+ synchronized(stateLock) {
249
+ lastSpoofResult = result
250
+ val isNeuralSpoof = result.neuralNetworkScore >= maxNeuralSpoofScore
251
+ if (isNeuralSpoof) {
252
+ consecutiveLiveFrames = 0
253
+ isLive = false
254
+ } else {
255
+ val targetPercent = (antispoofLevel * 100).roundToInt()
256
+ val currentPercent = (result.confidence * 100).roundToInt()
257
+ val combinedPercent = (result.combinedScore * 100).roundToInt()
258
+ val meetsConfidence = currentPercent >= targetPercent ||
259
+ result.confidence >= antispoofLevel ||
260
+ combinedPercent >= targetPercent ||
261
+ result.combinedScore >= antispoofLevel
262
+ val meetsLaplacian = result.laplacianScore == 0.0 ||
263
+ result.laplacianScore >= laplacianThreshold
264
+ val isLiveFrame = meetsConfidence && meetsLaplacian
265
+ consecutiveLiveFrames = if (isLiveFrame) {
266
+ min(requiredLiveFrames, consecutiveLiveFrames + 1)
267
+ } else {
268
+ max(0, consecutiveLiveFrames - 1)
269
+ }
270
+ isLive = consecutiveLiveFrames >= requiredLiveFrames
271
+ }
272
+
273
+ shouldNotify = now - lastResultUpdateAtMs >= uiUpdateIntervalMs
274
+ if (shouldNotify) lastResultUpdateAtMs = now
275
+ capture = readyToCaptureLocked()
276
+ }
277
+
278
+ if (shouldNotify) options.onResult.invoke(result)
279
+ capture?.let { (bounds, capturedResult) ->
280
+ options.onStableFaceDetected?.invoke(bounds, capturedResult)
281
+ }
282
+ }
283
+
284
+ private fun readyToCaptureLocked(): Pair<SpoofDetectedFaceBounds, AntiSpoofingResult>? {
285
+ if (captured || stableCount < stableFrames || !isLive ||
286
+ consecutiveLiveFrames < requiredLiveFrames
287
+ ) return null
288
+ val bounds = lastFaceBounds ?: return null
289
+ val result = lastSpoofResult ?: return null
290
+ if (options.onStableFaceDetected == null) return null
291
+ captured = true
292
+ return Pair(bounds, result)
293
+ }
294
+
295
+ fun resetState() {
296
+ synchronized(stateLock) {
297
+ captured = false
298
+ stableCount = 0
299
+ lastFaceBounds = null
300
+ consecutiveLiveFrames = 0
301
+ isLive = false
302
+ lastSpoofResult = null
303
+ lastFaceCount = -1
304
+ lastFacesUpdateAtMs = 0L
305
+ lastResultUpdateAtMs = 0L
306
+ }
307
+ }
308
+
309
+ private fun shouldProcessFrame(image: ImageProxy): Boolean {
310
+ val plane = image.planes.firstOrNull() ?: return false
311
+ val buffer = plane.buffer.duplicate()
312
+ val sampleStep = max(1, min(image.width, image.height) / 32)
313
+ var brightnessSum = 0L
314
+ var brightnessSquaredSum = 0L
315
+ var sampleCount = 0
316
+
317
+ for (y in 0 until image.height step sampleStep) {
318
+ val rowOffset = y * plane.rowStride
319
+ for (x in 0 until image.width step sampleStep) {
320
+ val index = rowOffset + x * plane.pixelStride
321
+ if (index >= buffer.limit()) continue
322
+ val luma = buffer.get(index).toInt() and 0xFF
323
+ brightnessSum += luma.toLong()
324
+ brightnessSquaredSum += (luma.toLong() * luma.toLong())
325
+ sampleCount += 1
326
+ }
327
+ }
328
+
329
+ if (sampleCount == 0) {
330
+ return false
331
+ }
332
+
333
+ val avgBrightness = brightnessSum.toFloat() / sampleCount
334
+ val variance = (brightnessSquaredSum.toFloat() / sampleCount) - (avgBrightness * avgBrightness)
335
+
336
+ val brightnessOk = avgBrightness in MIN_FRAME_BRIGHTNESS..MAX_FRAME_BRIGHTNESS
337
+ val textureOk = variance >= MIN_VARIANCE_FOR_ANALYSIS
338
+
339
+ return brightnessOk && textureOk
340
+ }
341
+
342
+ private fun createMLKitToCameraTransform(image: ImageProxy): Matrix {
343
+ val rotation = ((image.imageInfo.rotationDegrees % 360) + 360) % 360
344
+ require(rotation % 90 == 0) { "Invalid ML Kit rotation: $rotation" }
345
+ val source = RectF(0f, 0f, image.width.toFloat(), image.height.toFloat())
346
+ val target = if (rotation == 90 || rotation == 270) {
347
+ RectF(0f, 0f, image.height.toFloat(), image.width.toFloat())
348
+ } else {
349
+ source
350
+ }
351
+ val normalized = RectF(-1f, -1f, 1f, 1f)
352
+ val bufferToMLKit = Matrix().apply {
353
+ setRectToRect(source, normalized, Matrix.ScaleToFit.FILL)
354
+ postRotate(rotation.toFloat())
355
+ postConcat(Matrix().apply {
356
+ setRectToRect(normalized, target, Matrix.ScaleToFit.FILL)
357
+ })
358
+ }
359
+ val sensorToMLKit = Matrix(image.imageInfo.sensorToBufferTransformMatrix).apply {
360
+ postConcat(bufferToMLKit)
361
+ }
362
+ return Matrix().also { inverse ->
363
+ check(sensorToMLKit.invert(inverse)) { "Could not invert the face coordinate transform." }
364
+ }
365
+ }
366
+
367
+ private fun Face.toSpoofDetectedFace(transform: Matrix): SpoofDetectedFace {
368
+ val bounds = boundingBox
369
+ val points = floatArrayOf(
370
+ bounds.left.toFloat(), bounds.top.toFloat(),
371
+ bounds.right.toFloat(), bounds.top.toFloat(),
372
+ bounds.left.toFloat(), bounds.bottom.toFloat(),
373
+ bounds.right.toFloat(), bounds.bottom.toFloat(),
374
+ )
375
+ transform.mapPoints(points)
376
+ val xs = listOf(points[0], points[2], points[4], points[6])
377
+ val ys = listOf(points[1], points[3], points[5], points[7])
378
+ val left = xs.min().toDouble()
379
+ val top = ys.min().toDouble()
380
+ return SpoofDetectedFace(
381
+ SpoofDetectedFaceBounds(
382
+ left,
383
+ top,
384
+ (xs.max() - xs.min()).toDouble(),
385
+ (ys.max() - ys.min()).toDouble(),
386
+ )
387
+ )
388
+ }
389
+
390
+ override fun dispose() {
391
+ disposed.set(true)
392
+ imageAnalysis?.clearAnalyzer()
393
+ faceDetectorTask.get()?.let {
394
+ try {
395
+ Tasks.await(it)
396
+ } catch (_: Exception) {}
397
+ }
398
+ faceDetector?.close()
399
+ detector.close()
400
+ executor.shutdownNow()
401
+ super.dispose()
402
+ }
403
+ }
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
  // ============================================================================