react-native-face-match-sdk 0.0.0-stage → 1.0.3
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/FaceMatch.podspec +55 -0
- package/LICENSE +21 -0
- package/README.md +190 -2
- package/android/build.gradle +59 -0
- package/android/consumer-rules.pro +5 -0
- package/android/src/main/AndroidManifest.xml +11 -0
- package/android/src/main/java/com/facematch/sdk/AntiSpoofHelper.kt +216 -0
- package/android/src/main/java/com/facematch/sdk/BitmapUtils.kt +138 -0
- package/android/src/main/java/com/facematch/sdk/CameraFrameView.kt +75 -0
- package/android/src/main/java/com/facematch/sdk/FaceAlignmentHelper.kt +156 -0
- package/android/src/main/java/com/facematch/sdk/FaceCameraView.kt +628 -0
- package/android/src/main/java/com/facematch/sdk/FaceCameraViewManager.kt +79 -0
- package/android/src/main/java/com/facematch/sdk/FaceCandidateFilter.kt +65 -0
- package/android/src/main/java/com/facematch/sdk/FaceDetectionHelper.kt +225 -0
- package/android/src/main/java/com/facematch/sdk/FaceEmbeddingHelper.kt +242 -0
- package/android/src/main/java/com/facematch/sdk/FaceFrameAnalyzer.kt +228 -0
- package/android/src/main/java/com/facematch/sdk/FaceMatchModule.kt +249 -0
- package/android/src/main/java/com/facematch/sdk/FaceMatchPackage.kt +14 -0
- package/android/src/main/java/com/facematch/sdk/FaceMatchRuntime.kt +138 -0
- package/android/src/main/java/com/facematch/sdk/FaceMatcherHelper.kt +92 -0
- package/android/src/main/java/com/facematch/sdk/FaceOverlayView.kt +236 -0
- package/android/src/main/java/com/facematch/sdk/LivenessDetector.kt +483 -0
- package/android/src/main/java/com/facematch/sdk/LivenessPrompts.kt +137 -0
- package/android/src/main/java/com/facematch/sdk/LivenessVoice.kt +270 -0
- package/android/src/main/java/com/facematch/sdk/PrivateCaptureStore.kt +50 -0
- package/ios/Sources/AntiSpoofHelper.swift +239 -0
- package/ios/Sources/FaceAlignmentHelper.swift +169 -0
- package/ios/Sources/FaceCameraView.swift +1161 -0
- package/ios/Sources/FaceCameraViewManager.m +28 -0
- package/ios/Sources/FaceCameraViewManager.swift +57 -0
- package/ios/Sources/FaceCandidateFilter.swift +62 -0
- package/ios/Sources/FaceDetectionHelper.swift +283 -0
- package/ios/Sources/FaceEmbeddingHelper.swift +188 -0
- package/ios/Sources/FaceFrameAnalyzer.swift +179 -0
- package/ios/Sources/FaceFrameResult.swift +96 -0
- package/ios/Sources/FaceMatchBundle.swift +26 -0
- package/ios/Sources/FaceMatchEngine.swift +136 -0
- package/ios/Sources/FaceMatchError.swift +40 -0
- package/ios/Sources/FaceMatchModule.m +55 -0
- package/ios/Sources/FaceMatchModule.swift +288 -0
- package/ios/Sources/FaceMatcherHelper.swift +107 -0
- package/ios/Sources/FaceOverlayView.swift +285 -0
- package/ios/Sources/ImageUtils.swift +322 -0
- package/ios/Sources/LivenessDetector.swift +505 -0
- package/ios/Sources/LivenessPrompts.swift +121 -0
- package/ios/Sources/LivenessVoice.swift +229 -0
- package/ios/Sources/OnnxRuntime/ORTShim.h +91 -0
- package/ios/Sources/OnnxRuntime/ORTShim.mm +260 -0
- package/ios/Sources/PrivateCaptureStore.swift +71 -0
- package/ios/Sources/VisionFaceFallback.swift +95 -0
- package/ios/onnxruntime-c.podspec +47 -0
- package/models/anti_spoof_minifasnet_v2.onnx +0 -0
- package/models/w600k_mbf.onnx +0 -0
- package/package.json +47 -4
- package/react-native.config.js +16 -0
- package/src/FaceCameraView.tsx +75 -0
- package/src/FaceMatch.ts +66 -0
- package/src/index.ts +4 -0
- package/src/types.ts +87 -0
|
@@ -0,0 +1,628 @@
|
|
|
1
|
+
package com.facematch.sdk
|
|
2
|
+
|
|
3
|
+
import android.Manifest
|
|
4
|
+
import android.content.pm.PackageManager
|
|
5
|
+
import android.graphics.Bitmap
|
|
6
|
+
import android.net.Uri
|
|
7
|
+
import android.view.Surface
|
|
8
|
+
import android.view.WindowManager
|
|
9
|
+
import android.widget.FrameLayout
|
|
10
|
+
import androidx.camera.core.CameraSelector
|
|
11
|
+
import androidx.camera.core.ImageAnalysis
|
|
12
|
+
import androidx.camera.core.ImageCapture
|
|
13
|
+
import androidx.camera.core.ImageCaptureException
|
|
14
|
+
import androidx.camera.core.ImageProxy
|
|
15
|
+
import androidx.camera.core.Preview
|
|
16
|
+
import androidx.camera.lifecycle.ProcessCameraProvider
|
|
17
|
+
import androidx.camera.view.PreviewView
|
|
18
|
+
import androidx.core.content.ContextCompat
|
|
19
|
+
import androidx.lifecycle.LifecycleOwner
|
|
20
|
+
import com.facebook.react.bridge.Arguments
|
|
21
|
+
import com.facebook.react.bridge.LifecycleEventListener
|
|
22
|
+
import com.facebook.react.bridge.WritableMap
|
|
23
|
+
import com.facebook.react.uimanager.ThemedReactContext
|
|
24
|
+
import com.facebook.react.uimanager.events.RCTEventEmitter
|
|
25
|
+
import kotlinx.coroutines.CoroutineScope
|
|
26
|
+
import kotlinx.coroutines.Dispatchers
|
|
27
|
+
import kotlinx.coroutines.SupervisorJob
|
|
28
|
+
import kotlinx.coroutines.cancel
|
|
29
|
+
import kotlinx.coroutines.launch
|
|
30
|
+
import kotlinx.coroutines.withContext
|
|
31
|
+
import java.io.File
|
|
32
|
+
import java.io.FileOutputStream
|
|
33
|
+
import java.util.concurrent.ExecutorService
|
|
34
|
+
import java.util.concurrent.Executors
|
|
35
|
+
import kotlin.math.sqrt
|
|
36
|
+
|
|
37
|
+
@Suppress("DEPRECATION")
|
|
38
|
+
class FaceCameraView(private val reactContext: ThemedReactContext) :
|
|
39
|
+
FrameLayout(reactContext), LifecycleEventListener {
|
|
40
|
+
|
|
41
|
+
private companion object {
|
|
42
|
+
// Averaging a short burst reduces capture-to-capture variation from
|
|
43
|
+
// sensor noise, expression changes and small landmark shifts.
|
|
44
|
+
//
|
|
45
|
+
// Two, not three: each extra sample is a full shutter round trip plus a
|
|
46
|
+
// detect + align + embed, and the shutter for sample N+1 only fires after
|
|
47
|
+
// sample N's inference finishes — so the third sample was costing roughly
|
|
48
|
+
// a third of the entire post-liveness wait for a third averaging term.
|
|
49
|
+
// Averaging is retained because the matcher's score boundaries were
|
|
50
|
+
// calibrated against averaged embeddings; dropping to a single sample
|
|
51
|
+
// would shift that distribution and wants a labelled re-validation first.
|
|
52
|
+
const val IDENTITY_CAPTURE_BURST_SIZE = 2
|
|
53
|
+
|
|
54
|
+
// Perceived-brightness band (0-255). Below ENTER the screen is driven to
|
|
55
|
+
// full brightness to light the user's face; it only drops back once the
|
|
56
|
+
// frame recovers past EXIT, so the boost does not flicker at the edge.
|
|
57
|
+
const val LOW_LIGHT_ENTER = 62f
|
|
58
|
+
const val LOW_LIGHT_EXIT = 92f
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
private data class CaptureBurstState(
|
|
62
|
+
var sampleCount: Int = 0,
|
|
63
|
+
var embeddingSum: FloatArray? = null,
|
|
64
|
+
var captureFile: File? = null,
|
|
65
|
+
var width: Int = 0,
|
|
66
|
+
var height: Int = 0,
|
|
67
|
+
var faceCount: Int = 0
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
private val previewView = PreviewView(reactContext).apply {
|
|
71
|
+
// TextureView composes reliably inside React Native views, including
|
|
72
|
+
// clipped/scrolling containers where MIUI may not create a SurfaceView.
|
|
73
|
+
implementationMode = PreviewView.ImplementationMode.COMPATIBLE
|
|
74
|
+
scaleType = PreviewView.ScaleType.FILL_CENTER
|
|
75
|
+
visibility = VISIBLE
|
|
76
|
+
alpha = 1f
|
|
77
|
+
}
|
|
78
|
+
private val cameraFrameView = CameraFrameView(reactContext)
|
|
79
|
+
private val overlayView = FaceOverlayView(reactContext)
|
|
80
|
+
private val voice = LivenessVoice(reactContext)
|
|
81
|
+
private val cameraExecutor: ExecutorService = Executors.newSingleThreadExecutor()
|
|
82
|
+
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
|
83
|
+
private val livenessDetector = LivenessDetector()
|
|
84
|
+
private val faceMatchEngine = FaceMatchRuntime.get(reactContext)
|
|
85
|
+
private val analyzer = FaceFrameAnalyzer(
|
|
86
|
+
::onFaceFrame,
|
|
87
|
+
cameraFrameView::update,
|
|
88
|
+
faceMatchEngine::classifyAntiSpoof
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
private var cameraProvider: ProcessCameraProvider? = null
|
|
92
|
+
private var preview: Preview? = null
|
|
93
|
+
private var imageCapture: ImageCapture? = null
|
|
94
|
+
private var imageAnalysis: ImageAnalysis? = null
|
|
95
|
+
private var requestedStart = false
|
|
96
|
+
private var cameraStartPending = false
|
|
97
|
+
private var cameraStartGeneration = 0L
|
|
98
|
+
private var cameraStarted = false
|
|
99
|
+
private var requireLiveness = true
|
|
100
|
+
private var autoCaptureOnLiveness = false
|
|
101
|
+
private var autoCaptureTriggered = false
|
|
102
|
+
private var captureInProgress = false
|
|
103
|
+
private var brightenOnLowLight = true
|
|
104
|
+
private var smoothedLuma = -1f
|
|
105
|
+
private var screenBoosted = false
|
|
106
|
+
private var voiceLanguage = "none"
|
|
107
|
+
@Volatile private var antiSpoofThreshold = AntiSpoofHelper.DEFAULT_THRESHOLD
|
|
108
|
+
@Volatile private var lastAntiSpoofStatus: AntiSpoofStatus? = null
|
|
109
|
+
@Volatile private var lastFaceCount = 0
|
|
110
|
+
private var livenessProgress = livenessDetector.reset()
|
|
111
|
+
private var lastLivenessSignature = ""
|
|
112
|
+
private var lastAntiSpoofErrorSignature = ""
|
|
113
|
+
private var lastFaceEmitAt = 0L
|
|
114
|
+
|
|
115
|
+
init {
|
|
116
|
+
addView(previewView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
|
|
117
|
+
addView(cameraFrameView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
|
|
118
|
+
addView(overlayView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
|
|
119
|
+
reactContext.addLifecycleEventListener(this)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private val measureAndLayout = Runnable {
|
|
123
|
+
measure(
|
|
124
|
+
MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
|
|
125
|
+
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)
|
|
126
|
+
)
|
|
127
|
+
layout(left, top, right, bottom)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* React Native owns layout and swallows requestLayout() from native
|
|
132
|
+
* children. PreviewView attaches its TextureView only once CameraX hands it
|
|
133
|
+
* a surface — after React's layout pass — so without this that child stayed
|
|
134
|
+
* 0x0 and the camera box opened empty until the screen was reopened.
|
|
135
|
+
*/
|
|
136
|
+
override fun requestLayout() {
|
|
137
|
+
super.requestLayout()
|
|
138
|
+
// Null while FrameLayout's own constructor calls requestLayout().
|
|
139
|
+
@Suppress("SENSELESS_COMPARISON")
|
|
140
|
+
if (measureAndLayout != null) post(measureAndLayout)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
fun setRequireLiveness(value: Boolean) {
|
|
144
|
+
requireLiveness = value
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
fun setAutoCaptureOnLiveness(value: Boolean) {
|
|
148
|
+
autoCaptureOnLiveness = value
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
fun setBrightenOnLowLight(value: Boolean) {
|
|
152
|
+
brightenOnLowLight = value
|
|
153
|
+
if (!value) applyScreenBoost(false)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** "en", "hi" or "none" — controls the spoken liveness instructions. */
|
|
157
|
+
fun setVoiceLanguage(value: String) {
|
|
158
|
+
voiceLanguage = when (value.lowercase()) {
|
|
159
|
+
"hi", "hi-in", "hindi" -> "hi"
|
|
160
|
+
"en", "en-in", "en-us", "english" -> "en"
|
|
161
|
+
else -> "none"
|
|
162
|
+
}
|
|
163
|
+
voice.setLanguage(voiceLanguage)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** "female" (default) or "male" — preferred India voice for the spoken guidance. */
|
|
167
|
+
fun setVoiceGender(value: String) {
|
|
168
|
+
voice.setGender(value)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Drive the host window to full brightness (or release the override) so the
|
|
173
|
+
* front camera has enough light on the user's face in a dim room. This is a
|
|
174
|
+
* per-window override and needs no runtime permission.
|
|
175
|
+
*/
|
|
176
|
+
private fun applyScreenBoost(boost: Boolean) {
|
|
177
|
+
if (boost == screenBoosted) return
|
|
178
|
+
val activity = reactContext.currentActivity ?: return
|
|
179
|
+
screenBoosted = boost
|
|
180
|
+
activity.runOnUiThread {
|
|
181
|
+
runCatching {
|
|
182
|
+
val params = activity.window.attributes
|
|
183
|
+
params.screenBrightness =
|
|
184
|
+
if (boost) 1.0f else WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE
|
|
185
|
+
activity.window.attributes = params
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
fun setAntiSpoofThreshold(value: Float) {
|
|
191
|
+
antiSpoofThreshold = AntiSpoofHelper.sanitizeThreshold(value)
|
|
192
|
+
analyzer.setAntiSpoofThreshold(antiSpoofThreshold)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
fun setAutoStart(value: Boolean) {
|
|
196
|
+
if (value) startCamera() else stopCamera()
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
fun startCamera() {
|
|
200
|
+
requestedStart = true
|
|
201
|
+
smoothedLuma = -1f
|
|
202
|
+
// ProcessCameraProvider is obtained asynchronously. React may request a
|
|
203
|
+
// start from both the autoStart prop and the imperative command (or a
|
|
204
|
+
// lifecycle resume) before that future completes. Without a pending
|
|
205
|
+
// guard, every callback binds another Preview/Capture/Analysis trio and
|
|
206
|
+
// CameraX rejects the second trio as an unsupported surface combination.
|
|
207
|
+
if (cameraStarted || cameraStartPending) return
|
|
208
|
+
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
|
|
209
|
+
emitError("E_CAMERA_PERMISSION", "Camera permission has not been granted")
|
|
210
|
+
return
|
|
211
|
+
}
|
|
212
|
+
val lifecycleOwner = reactContext.currentActivity as? LifecycleOwner
|
|
213
|
+
if (lifecycleOwner == null) {
|
|
214
|
+
emitError("E_NO_ACTIVITY", "The current Activity is not a LifecycleOwner")
|
|
215
|
+
return
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
cameraStartPending = true
|
|
219
|
+
val startGeneration = ++cameraStartGeneration
|
|
220
|
+
val future = ProcessCameraProvider.getInstance(context)
|
|
221
|
+
future.addListener({
|
|
222
|
+
// A stop/pause/dispose invalidates callbacks that were queued while
|
|
223
|
+
// the provider was loading. A later start gets its own generation.
|
|
224
|
+
if (startGeneration != cameraStartGeneration) return@addListener
|
|
225
|
+
cameraStartPending = false
|
|
226
|
+
if (!requestedStart || cameraStarted) return@addListener
|
|
227
|
+
|
|
228
|
+
try {
|
|
229
|
+
val provider = future.get()
|
|
230
|
+
val newPreview = Preview.Builder().build().also {
|
|
231
|
+
it.setSurfaceProvider(previewView.surfaceProvider)
|
|
232
|
+
}
|
|
233
|
+
val capture = ImageCapture.Builder()
|
|
234
|
+
.setCaptureMode(ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY)
|
|
235
|
+
.setTargetRotation(display?.rotation ?: Surface.ROTATION_0)
|
|
236
|
+
.build()
|
|
237
|
+
val analysis = ImageAnalysis.Builder()
|
|
238
|
+
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
|
239
|
+
.setTargetRotation(display?.rotation ?: Surface.ROTATION_0)
|
|
240
|
+
.build()
|
|
241
|
+
.also { it.setAnalyzer(cameraExecutor, analyzer) }
|
|
242
|
+
|
|
243
|
+
provider.bindToLifecycle(
|
|
244
|
+
lifecycleOwner,
|
|
245
|
+
CameraSelector.DEFAULT_FRONT_CAMERA,
|
|
246
|
+
newPreview,
|
|
247
|
+
capture,
|
|
248
|
+
analysis
|
|
249
|
+
)
|
|
250
|
+
cameraProvider = provider
|
|
251
|
+
preview = newPreview
|
|
252
|
+
imageCapture = capture
|
|
253
|
+
imageAnalysis = analysis
|
|
254
|
+
cameraStarted = true
|
|
255
|
+
previewView.visibility = VISIBLE
|
|
256
|
+
previewView.alpha = 1f
|
|
257
|
+
previewView.requestLayout()
|
|
258
|
+
overlayView.visibility = VISIBLE
|
|
259
|
+
overlayView.bringToFront()
|
|
260
|
+
emitCameraState("started")
|
|
261
|
+
} catch (error: Throwable) {
|
|
262
|
+
cameraStartPending = false
|
|
263
|
+
emitError("E_CAMERA_START", error.message ?: "Unable to start the front camera")
|
|
264
|
+
}
|
|
265
|
+
}, ContextCompat.getMainExecutor(context))
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
fun stopCamera() {
|
|
269
|
+
requestedStart = false
|
|
270
|
+
stopCameraUseCases()
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
private fun stopCameraUseCases() {
|
|
274
|
+
// Invalidate any ProcessCameraProvider callback that has not run yet.
|
|
275
|
+
cameraStartGeneration++
|
|
276
|
+
cameraStartPending = false
|
|
277
|
+
val useCases = listOfNotNull(preview, imageCapture, imageAnalysis).toTypedArray()
|
|
278
|
+
if (useCases.isNotEmpty()) runCatching { cameraProvider?.unbind(*useCases) }
|
|
279
|
+
preview = null
|
|
280
|
+
imageCapture = null
|
|
281
|
+
imageAnalysis = null
|
|
282
|
+
if (cameraStarted) emitCameraState("stopped")
|
|
283
|
+
cameraStarted = false
|
|
284
|
+
captureInProgress = false
|
|
285
|
+
lastAntiSpoofStatus = null
|
|
286
|
+
lastFaceCount = 0
|
|
287
|
+
smoothedLuma = -1f
|
|
288
|
+
applyScreenBoost(false)
|
|
289
|
+
voice.stop()
|
|
290
|
+
cameraFrameView.clear()
|
|
291
|
+
overlayView.reset()
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
fun startLiveness(actions: List<String>?) {
|
|
295
|
+
livenessProgress = livenessDetector.reset(actions)
|
|
296
|
+
lastLivenessSignature = ""
|
|
297
|
+
autoCaptureTriggered = false
|
|
298
|
+
lastAntiSpoofStatus = null
|
|
299
|
+
lastFaceCount = 0
|
|
300
|
+
lastAntiSpoofErrorSignature = ""
|
|
301
|
+
voice.resetSpokenHistory()
|
|
302
|
+
overlayView.reset()
|
|
303
|
+
emitLiveness(livenessProgress)
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
fun capture() {
|
|
307
|
+
if (captureInProgress) return
|
|
308
|
+
val capture = imageCapture
|
|
309
|
+
if (!cameraStarted || capture == null) {
|
|
310
|
+
emitError("E_CAMERA_NOT_READY", "Camera is not ready")
|
|
311
|
+
return
|
|
312
|
+
}
|
|
313
|
+
if (lastFaceCount > 1) {
|
|
314
|
+
emitError("E_MULTIPLE_FACES", "Multiple faces detected. Only one person is allowed")
|
|
315
|
+
return
|
|
316
|
+
}
|
|
317
|
+
if (requireLiveness && !livenessDetector.isComplete()) {
|
|
318
|
+
emitError("E_LIVENESS_REQUIRED", "Complete all liveness actions before capture")
|
|
319
|
+
return
|
|
320
|
+
}
|
|
321
|
+
when (lastAntiSpoofStatus) {
|
|
322
|
+
// A preview-frame score may fluctuate during the blink itself.
|
|
323
|
+
// Always take the photo after a valid blink and let extractLive()
|
|
324
|
+
// perform the definitive anti-spoof check on that exact image.
|
|
325
|
+
AntiSpoofStatus.SPOOF -> Unit
|
|
326
|
+
AntiSpoofStatus.ERROR -> {
|
|
327
|
+
emitError("E_ANTI_SPOOF_MODEL", "Passive anti-spoofing is unavailable")
|
|
328
|
+
return
|
|
329
|
+
}
|
|
330
|
+
else -> Unit // The captured high-resolution image is checked again below.
|
|
331
|
+
}
|
|
332
|
+
captureInProgress = true
|
|
333
|
+
// Liveness is settled and every gate above has passed, so per-frame
|
|
334
|
+
// analysis has nothing left to decide. Detaching it for the duration of
|
|
335
|
+
// the burst hands the whole CPU — and the ONNX session the anti-spoof
|
|
336
|
+
// re-check needs — to the capture pipeline instead of competing with it.
|
|
337
|
+
imageAnalysis?.clearAnalyzer()
|
|
338
|
+
captureBurst(capture, CaptureBurstState())
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Re-attach per-frame analysis after a failed burst so a retry still gets
|
|
343
|
+
* liveness guidance. Null-safe, so it no-ops once [stopCameraUseCases] has
|
|
344
|
+
* cleared the use cases.
|
|
345
|
+
*/
|
|
346
|
+
private fun reattachAnalyzer() {
|
|
347
|
+
imageAnalysis?.setAnalyzer(cameraExecutor, analyzer)
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
private fun captureBurst(capture: ImageCapture, state: CaptureBurstState) {
|
|
351
|
+
capture.takePicture(
|
|
352
|
+
ContextCompat.getMainExecutor(context),
|
|
353
|
+
object : ImageCapture.OnImageCapturedCallback() {
|
|
354
|
+
override fun onCaptureSuccess(image: ImageProxy) {
|
|
355
|
+
// The decode and rotate are deferred into the coroutine in
|
|
356
|
+
// processCaptureSample rather than done here. At full sensor
|
|
357
|
+
// resolution they cost 200-450 ms, and this callback runs on
|
|
358
|
+
// the main executor — so they used to stall React Native's UI
|
|
359
|
+
// thread for exactly that long, per sample, precisely while it
|
|
360
|
+
// renders the "verifying" state the user is waiting on.
|
|
361
|
+
processCaptureSample(capture, image, state)
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
override fun onError(exception: ImageCaptureException) {
|
|
365
|
+
captureInProgress = false
|
|
366
|
+
reattachAnalyzer()
|
|
367
|
+
cleanupFailedBurst(state)
|
|
368
|
+
emitError("E_CAPTURE", exception.message ?: "Image capture failed")
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
)
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
private fun processCaptureSample(
|
|
375
|
+
capture: ImageCapture,
|
|
376
|
+
image: ImageProxy,
|
|
377
|
+
state: CaptureBurstState
|
|
378
|
+
) {
|
|
379
|
+
scope.launch {
|
|
380
|
+
var bitmap: Bitmap? = null
|
|
381
|
+
try {
|
|
382
|
+
// Keep the saved/inference image in the camera sensor's natural
|
|
383
|
+
// orientation. CameraFrameView mirrors only the on-screen preview;
|
|
384
|
+
// mirroring the captured pixels made them less comparable with
|
|
385
|
+
// ordinary reference photos.
|
|
386
|
+
//
|
|
387
|
+
// Wrapped so a decode failure still surfaces as E_CAPTURE, exactly
|
|
388
|
+
// as it did when this ran in the capture callback.
|
|
389
|
+
val decoded = withContext(Dispatchers.Default) {
|
|
390
|
+
try {
|
|
391
|
+
BitmapUtils.rotateDegrees(image.toBitmap(), image.imageInfo.rotationDegrees)
|
|
392
|
+
} catch (error: Throwable) {
|
|
393
|
+
throw FaceMatchException(
|
|
394
|
+
"E_CAPTURE",
|
|
395
|
+
error.message ?: "Unable to read captured image",
|
|
396
|
+
error
|
|
397
|
+
)
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
bitmap = decoded
|
|
401
|
+
// Re-check the exact first image for liveness. The remaining
|
|
402
|
+
// images are taken immediately in the same verified burst and
|
|
403
|
+
// contribute identity embeddings only.
|
|
404
|
+
val extraction = if (state.sampleCount == 0) {
|
|
405
|
+
faceMatchEngine.extractLive(decoded, antiSpoofThreshold)
|
|
406
|
+
} else {
|
|
407
|
+
faceMatchEngine.extract(decoded)
|
|
408
|
+
}
|
|
409
|
+
if (state.sampleCount == 0) {
|
|
410
|
+
val file = PrivateCaptureStore.create(context)
|
|
411
|
+
FileOutputStream(file).use { stream ->
|
|
412
|
+
if (!decoded.compress(Bitmap.CompressFormat.JPEG, 95, stream)) {
|
|
413
|
+
throw FaceMatchException(
|
|
414
|
+
"E_CAPTURE_FILE",
|
|
415
|
+
"Unable to encode the captured image"
|
|
416
|
+
)
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
state.captureFile = file
|
|
420
|
+
state.width = decoded.width
|
|
421
|
+
state.height = decoded.height
|
|
422
|
+
state.faceCount = extraction.faceCount
|
|
423
|
+
state.embeddingSum = extraction.embedding.copyOf()
|
|
424
|
+
} else {
|
|
425
|
+
val sum = requireNotNull(state.embeddingSum)
|
|
426
|
+
extraction.embedding.forEachIndexed { index, value -> sum[index] += value }
|
|
427
|
+
}
|
|
428
|
+
state.sampleCount++
|
|
429
|
+
|
|
430
|
+
if (state.sampleCount < IDENTITY_CAPTURE_BURST_SIZE) {
|
|
431
|
+
withContext(Dispatchers.Main) {
|
|
432
|
+
if (!cameraStarted || imageCapture !== capture) {
|
|
433
|
+
throw FaceMatchException("E_CAMERA_NOT_READY", "Camera stopped during capture")
|
|
434
|
+
}
|
|
435
|
+
captureBurst(capture, state)
|
|
436
|
+
}
|
|
437
|
+
return@launch
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
val identityEmbedding = normalizeSum(requireNotNull(state.embeddingSum))
|
|
441
|
+
val file = state.captureFile
|
|
442
|
+
?: throw FaceMatchException("E_CAPTURE_FILE", "Capture file is unavailable")
|
|
443
|
+
val event = Arguments.createMap().apply {
|
|
444
|
+
putString("uri", Uri.fromFile(file).toString())
|
|
445
|
+
putInt("width", state.width)
|
|
446
|
+
putInt("height", state.height)
|
|
447
|
+
putInt("faceCount", state.faceCount)
|
|
448
|
+
putArray("embedding", Arguments.createArray().also { array ->
|
|
449
|
+
identityEmbedding.forEach { array.pushDouble(it.toDouble()) }
|
|
450
|
+
})
|
|
451
|
+
}
|
|
452
|
+
withContext(Dispatchers.Main) {
|
|
453
|
+
emit("topCapture", event)
|
|
454
|
+
requestedStart = false
|
|
455
|
+
stopCameraUseCases()
|
|
456
|
+
}
|
|
457
|
+
} catch (error: Throwable) {
|
|
458
|
+
cleanupFailedBurst(state)
|
|
459
|
+
withContext(Dispatchers.Main) {
|
|
460
|
+
captureInProgress = false
|
|
461
|
+
reattachAnalyzer()
|
|
462
|
+
emitError((error as? FaceMatchException)?.errorCode ?: "E_CAPTURE_PROCESSING",
|
|
463
|
+
error.message ?: "Unable to process capture")
|
|
464
|
+
}
|
|
465
|
+
} finally {
|
|
466
|
+
// The proxy is closed here rather than in the capture callback,
|
|
467
|
+
// because the decode that reads it now happens inside this
|
|
468
|
+
// coroutine. Holding it any longer would stall the next shutter.
|
|
469
|
+
runCatching { image.close() }
|
|
470
|
+
bitmap?.let { if (!it.isRecycled) it.recycle() }
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
private fun normalizeSum(sum: FloatArray): FloatArray {
|
|
476
|
+
val norm = sqrt(sum.fold(0.0) { total, value ->
|
|
477
|
+
total + value.toDouble() * value
|
|
478
|
+
}).toFloat()
|
|
479
|
+
if (!norm.isFinite() || norm < 1e-6f) {
|
|
480
|
+
throw FaceMatchException("E_EMBEDDING", "Could not aggregate face embeddings")
|
|
481
|
+
}
|
|
482
|
+
return FloatArray(sum.size) { sum[it] / norm }
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
private fun cleanupFailedBurst(state: CaptureBurstState) {
|
|
486
|
+
state.captureFile?.let { file ->
|
|
487
|
+
runCatching { if (file.isFile) file.delete() }
|
|
488
|
+
}
|
|
489
|
+
state.captureFile = null
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
private fun onFaceFrame(frame: FaceFrameResult) {
|
|
493
|
+
lastFaceCount = frame.faceCount
|
|
494
|
+
lastAntiSpoofStatus = frame.antiSpoof?.status
|
|
495
|
+
val wasComplete = livenessProgress.isComplete
|
|
496
|
+
val progress = livenessDetector.update(frame)
|
|
497
|
+
livenessProgress = progress
|
|
498
|
+
overlayView.update(frame, progress)
|
|
499
|
+
|
|
500
|
+
// Low-light detection: exponentially smooth the per-frame brightness and
|
|
501
|
+
// apply a hysteresis band before boosting the screen.
|
|
502
|
+
smoothedLuma =
|
|
503
|
+
if (smoothedLuma < 0f) frame.luminance
|
|
504
|
+
else smoothedLuma * 0.8f + frame.luminance * 0.2f
|
|
505
|
+
val lowLight = when {
|
|
506
|
+
smoothedLuma < LOW_LIGHT_ENTER -> true
|
|
507
|
+
smoothedLuma > LOW_LIGHT_EXIT -> false
|
|
508
|
+
else -> screenBoosted
|
|
509
|
+
}
|
|
510
|
+
if (brightenOnLowLight) applyScreenBoost(lowLight)
|
|
511
|
+
|
|
512
|
+
val now = System.currentTimeMillis()
|
|
513
|
+
if (now - lastFaceEmitAt >= 200L) {
|
|
514
|
+
lastFaceEmitAt = now
|
|
515
|
+
emit("topFaceState", Arguments.createMap().apply {
|
|
516
|
+
putBoolean("lowLight", lowLight)
|
|
517
|
+
putDouble("luminance", smoothedLuma.toDouble())
|
|
518
|
+
putBoolean("hasFace", frame.hasFace)
|
|
519
|
+
putInt("faceCount", frame.faceCount)
|
|
520
|
+
putBoolean("hasMultipleFaces", frame.hasMultipleFaces)
|
|
521
|
+
putBoolean("isPositioned", frame.isPositioned)
|
|
522
|
+
putBoolean("isGoodPose", frame.isGoodPose)
|
|
523
|
+
putDouble("yaw", frame.yaw.toDouble())
|
|
524
|
+
putDouble("pitch", frame.pitch.toDouble())
|
|
525
|
+
putDouble("roll", frame.roll.toDouble())
|
|
526
|
+
frame.leftEyeOpenProbability?.let { putDouble("leftEyeOpenProbability", it.toDouble()) }
|
|
527
|
+
frame.rightEyeOpenProbability?.let { putDouble("rightEyeOpenProbability", it.toDouble()) }
|
|
528
|
+
frame.antiSpoof?.let { antiSpoof ->
|
|
529
|
+
putString("antiSpoofStatus", antiSpoof.status.wireName)
|
|
530
|
+
antiSpoof.realScore?.let { putDouble("antiSpoofRealScore", it.toDouble()) }
|
|
531
|
+
putDouble("antiSpoofThreshold", antiSpoof.threshold.toDouble())
|
|
532
|
+
}
|
|
533
|
+
})
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
frame.antiSpoof?.let { antiSpoof ->
|
|
537
|
+
val errorSignature = "${antiSpoof.status}|${antiSpoof.errorMessage.orEmpty()}"
|
|
538
|
+
when (antiSpoof.status) {
|
|
539
|
+
AntiSpoofStatus.REAL -> Unit
|
|
540
|
+
// Motion and lighting can make individual analysis frames
|
|
541
|
+
// fluctuate. Liveness pauses through its one guidance message;
|
|
542
|
+
// the exact captured image remains fail-closed below.
|
|
543
|
+
AntiSpoofStatus.SPOOF -> Unit
|
|
544
|
+
AntiSpoofStatus.ERROR -> if (errorSignature != lastAntiSpoofErrorSignature) {
|
|
545
|
+
lastAntiSpoofErrorSignature = errorSignature
|
|
546
|
+
emitError(
|
|
547
|
+
"E_ANTI_SPOOF_MODEL",
|
|
548
|
+
antiSpoof.errorMessage ?: "Passive anti-spoofing is unavailable"
|
|
549
|
+
)
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
val signature = "${progress.promptKey.name}|${progress.completedActions.size}|${progress.isComplete}"
|
|
555
|
+
if (signature != lastLivenessSignature) {
|
|
556
|
+
lastLivenessSignature = signature
|
|
557
|
+
emitLiveness(progress)
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
if (!wasComplete && progress.isComplete && autoCaptureOnLiveness && !autoCaptureTriggered) {
|
|
561
|
+
autoCaptureTriggered = true
|
|
562
|
+
post { capture() }
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
private fun emitLiveness(progress: LivenessProgress) {
|
|
567
|
+
val prompt = progress.promptKey
|
|
568
|
+
emit("topLiveness", Arguments.createMap().apply {
|
|
569
|
+
progress.currentAction?.let { putString("currentAction", it.wireName) }
|
|
570
|
+
putString("promptKey", prompt.name)
|
|
571
|
+
putString("promptEn", prompt.en)
|
|
572
|
+
putString("promptHi", prompt.hi)
|
|
573
|
+
putString("instruction", prompt.en)
|
|
574
|
+
putBoolean("isComplete", progress.isComplete)
|
|
575
|
+
putInt("stepIndex", progress.stepIndex)
|
|
576
|
+
putInt("stepCount", progress.stepCount)
|
|
577
|
+
putDouble("actionProgress", progress.actionProgress.toDouble())
|
|
578
|
+
putArray("completedActions", Arguments.createArray().also { array ->
|
|
579
|
+
progress.completedActions.forEach { array.pushString(it.wireName) }
|
|
580
|
+
})
|
|
581
|
+
})
|
|
582
|
+
if (voiceLanguage != "none" && prompt.spoken) {
|
|
583
|
+
voice.speak(prompt.name, prompt.localized(voiceLanguage))
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
private fun emitCameraState(state: String) {
|
|
588
|
+
emit("topCameraState", Arguments.createMap().apply { putString("state", state) })
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
private fun emitError(code: String, message: String) {
|
|
592
|
+
emit("topError", Arguments.createMap().apply {
|
|
593
|
+
putString("code", code)
|
|
594
|
+
putString("message", message)
|
|
595
|
+
})
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
private fun emit(eventName: String, payload: WritableMap) {
|
|
599
|
+
post {
|
|
600
|
+
if (id != NO_ID) {
|
|
601
|
+
reactContext.getJSModule(RCTEventEmitter::class.java).receiveEvent(id, eventName, payload)
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
override fun onHostResume() {
|
|
607
|
+
if (requestedStart) startCamera()
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
override fun onHostPause() {
|
|
611
|
+
stopCameraUseCases()
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
override fun onHostDestroy() {
|
|
615
|
+
dispose()
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
fun dispose() {
|
|
619
|
+
requestedStart = false
|
|
620
|
+
stopCameraUseCases()
|
|
621
|
+
applyScreenBoost(false)
|
|
622
|
+
voice.shutdown()
|
|
623
|
+
analyzer.close()
|
|
624
|
+
cameraExecutor.shutdown()
|
|
625
|
+
scope.cancel()
|
|
626
|
+
reactContext.removeLifecycleEventListener(this)
|
|
627
|
+
}
|
|
628
|
+
}
|