react-native-vision-camera-spoof-detector 1.4.0 → 1.5.0

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 (29) hide show
  1. package/README.md +16 -29
  2. package/android/build.gradle +0 -13
  3. package/android/src/main/java/com/faceantispoof/FaceAntiSpoofPackage.kt +1 -3
  4. package/android/src/main/java/com/faceantispoof/FaceAntiSpoofingAdvanced.kt +78 -961
  5. package/android/src/main/java/com/lengdev/livenessdetector/LivenessDetector.kt +228 -0
  6. package/android/src/main/java/com/margelo/nitro/camera/spoofdetector/HybridSpoofDetectorOutput.kt +17 -31
  7. package/android/src/main/jniLibs/arm64-v8a/libliveness_detector.so +0 -0
  8. package/android/src/main/jniLibs/armeabi-v7a/libliveness_detector.so +0 -0
  9. package/index.d.ts +2 -9
  10. package/index.js +6 -6
  11. package/ios/FaceAntiSpoofModule.m +3 -2
  12. package/ios/HybridSpoofDetectorOutput.swift +3 -3
  13. package/lib/assets/live/config.json +1 -0
  14. package/lib/assets/live/model_1.bin +0 -0
  15. package/lib/assets/live/model_1.param +214 -0
  16. package/lib/assets/live/model_2.bin +0 -0
  17. package/lib/assets/live/model_2.param +238 -0
  18. package/nitrogen/generated/android/c++/JSpoofDetectorOutputOptions.hpp +1 -9
  19. package/nitrogen/generated/android/kotlin/com/margelo/nitro/camera/spoofdetector/SpoofDetectorOutputOptions.kt +4 -14
  20. package/nitrogen/generated/ios/swift/SpoofDetectorOutputOptions.swift +1 -37
  21. package/nitrogen/generated/shared/c++/SpoofDetectorOutputOptions.hpp +1 -9
  22. package/package.json +1 -2
  23. package/src/specs/SpoofDetectorFactory.nitro.ts +0 -2
  24. package/android/fix-prefab.gradle +0 -4
  25. package/android/src/main/java/com/faceantispoof/AcceleratorConfig.kt +0 -97
  26. package/android/src/main/java/com/faceantispoof/FaceAntiSpoofModule.kt +0 -242
  27. package/android/src/main/res/values/strings.xml +0 -3
  28. package/lib/assets/FaceAntiSpoofing.tflite +0 -0
  29. package/lib/assets/model_spec.json +0 -16
@@ -1,278 +1,25 @@
1
1
  package com.faceantispoof
2
2
 
3
3
  import android.content.res.AssetManager
4
- import android.graphics.Bitmap
5
- import android.graphics.Matrix
6
- import android.graphics.PointF
7
4
  import android.graphics.RectF
8
- import org.tensorflow.lite.Interpreter
9
- import org.tensorflow.lite.gpu.CompatibilityList
10
- import org.tensorflow.lite.gpu.GpuDelegate
11
- import java.io.IOException
12
- import java.nio.MappedByteBuffer
13
- import java.nio.channels.FileChannel
14
- import java.io.FileInputStream
15
- import kotlin.math.*
5
+ import com.lengdev.livenessdetector.FaceBox
6
+ import com.lengdev.livenessdetector.LivenessDetector
16
7
  import java.nio.ByteBuffer
17
- import java.nio.ByteOrder
18
- import java.util.*
19
- import android.util.Log
20
- import kotlin.collections.ArrayList
21
- import kotlinx.coroutines.runBlocking
8
+ import kotlin.math.roundToInt
22
9
 
23
- class FaceAntiSpoofingAdvanced(private val assetManager: AssetManager) {
24
-
25
- companion object {
26
- const val INPUT_IMAGE_SIZE = 256
27
- const val BASE_THRESHOLD = 0.2f
28
- const val ROUTE_INDEX = 6
29
- const val LAPLACE_THRESHOLD = 50
30
- const val LAPLACIAN_THRESHOLD = 1000
31
- const val MODEL_FILE = "FaceAntiSpoofing.tflite"
32
- private const val TAG = "FaceAntiSpoofing"
33
-
34
- // Accelerator types
35
- const val ACCELERATOR_CPU = "CPU"
36
- const val ACCELERATOR_GPU = "GPU"
37
- const val ACCELERATOR_NNAPI = "NNAPI"
38
- }
39
-
40
- private var interpreter: Interpreter? = null
41
- private var isInitialized = false
42
- private var gpuDelegate: GpuDelegate? = null
43
- private var currentAccelerator: String = ACCELERATOR_CPU
44
-
45
- // Reuse output arrays to avoid allocations
46
- private val clssPred = Array(1) { FloatArray(8) }
47
- private val leafNodeMask = Array(1) { FloatArray(8) }
48
- private val outputs = mutableMapOf<Int, Any>()
49
- private var outputIndex0: Int = 0
50
- private var outputIndex1: Int = 1
51
- private val modelInputBuffer = Array(INPUT_IMAGE_SIZE) { Array(INPUT_IMAGE_SIZE) { FloatArray(3) } }
52
- private val modelInput = arrayOf(modelInputBuffer)
53
- private val grayBuffer = Array(INPUT_IMAGE_SIZE) { IntArray(INPUT_IMAGE_SIZE) }
54
- private val inputPlanePositions = IntArray(3)
10
+ class FaceAntiSpoofingAdvanced(assetManager: AssetManager) {
11
+ private val livenessDetector = LivenessDetector()
12
+ @Volatile private var initialized = false
55
13
 
56
14
  init {
57
- initializeInterpreter()
58
- }
59
-
60
- private fun initializeInterpreter() {
61
15
  try {
62
- val modelBuffer = loadModelFile(assetManager, MODEL_FILE)
63
- val optimalThreads = 4
64
- val compatibilityList = CompatibilityList()
65
-
66
- if (compatibilityList.isDelegateSupportedOnThisDevice) {
67
- try {
68
- val delegate = GpuDelegate(compatibilityList.bestOptionsForThisDevice)
69
- val options = Interpreter.Options().apply {
70
- setNumThreads(optimalThreads)
71
- addDelegate(delegate)
72
- }
73
- interpreter = Interpreter(modelBuffer, options)
74
- gpuDelegate = delegate
75
- currentAccelerator = ACCELERATOR_GPU
76
- Log.i(TAG, "Face Anti-Spoof initialized | GPU delegate enabled | Threads: $optimalThreads")
77
- } catch (gpuError: Exception) {
78
- Log.w(TAG, "GPU delegate initialization failed; using CPU: ${gpuError.message}", gpuError)
79
- interpreter = null
80
- gpuDelegate?.close()
81
- gpuDelegate = null
82
- }
83
- }
84
-
85
- if (interpreter == null) {
86
- val options = Interpreter.Options().apply {
87
- setNumThreads(optimalThreads)
88
- }
89
- interpreter = Interpreter(modelBuffer, options)
90
- currentAccelerator = ACCELERATOR_CPU
91
- Log.i(TAG, "Face Anti-Spoof initialized | CPU inference enabled | Threads: $optimalThreads")
92
- }
93
-
94
- resolveOutputIndices()
95
- isInitialized = true
96
- } catch (e: Exception) {
97
- Log.e(TAG, "FAILED to load TFLite model: ${e.message}", e)
98
- isInitialized = false
99
- currentAccelerator = ACCELERATOR_CPU
100
- }
101
- }
102
-
103
- private fun resolveOutputIndices() {
104
- try {
105
- outputIndex0 = interpreter!!.getOutputIndex("Identity")
106
- outputIndex1 = interpreter!!.getOutputIndex("Identity_1")
107
- } catch (e: Exception) {
108
- Log.w(TAG, "Could not resolve named output indices, using defaults: ${e.message}")
109
- outputIndex0 = 0
110
- outputIndex1 = 1
111
- }
112
- outputs[outputIndex0] = clssPred
113
- outputs[outputIndex1] = leafNodeMask
114
- }
115
-
116
- @Synchronized
117
- private fun runInference(input: Any) {
118
- try {
119
- interpreter!!.runForMultipleInputsOutputs(arrayOf(input), outputs)
120
- } catch (gpuError: Exception) {
121
- if (currentAccelerator != ACCELERATOR_GPU) throw gpuError
122
-
123
- Log.w(TAG, "GPU inference failed; retrying this frame on CPU: ${gpuError.message}", gpuError)
124
- switchToCpu()
125
- interpreter!!.runForMultipleInputsOutputs(arrayOf(input), outputs)
126
- }
127
- }
128
-
129
- private fun switchToCpu() {
130
- try {
131
- interpreter?.close()
132
- } catch (closeError: Exception) {
133
- Log.w(TAG, "Error closing GPU interpreter before CPU fallback: ${closeError.message}", closeError)
134
- } finally {
135
- interpreter = null
136
- }
137
- try {
138
- gpuDelegate?.close()
139
- } catch (closeError: Exception) {
140
- Log.w(TAG, "Error closing GPU delegate before CPU fallback: ${closeError.message}", closeError)
141
- } finally {
142
- gpuDelegate = null
143
- }
144
-
145
- val options = Interpreter.Options().apply {
146
- setNumThreads(4)
147
- }
148
- interpreter = Interpreter(loadModelFile(assetManager, MODEL_FILE), options)
149
- currentAccelerator = ACCELERATOR_CPU
150
- resolveOutputIndices()
151
- Log.i(TAG, "Face Anti-Spoof switched to CPU inference")
152
- }
153
-
154
- fun getAccelerator(): String = currentAccelerator
155
-
156
- // NEW: Add this method to accept Bitmap as input (matching working version)
157
- suspend fun advancedAntiSpoofing(bitmap: Bitmap): Result<AntiSpoofingResult> {
158
- return try {
159
- if (!isInitialized) {
160
- Result.failure(IllegalStateException("Classifier not initialized"))
161
- } else {
162
- val nnScore = neuralNetworkAntiSpoofing(bitmap).getOrThrow()
163
- val laplacianScore = laplacian(bitmap).getOrThrow()
164
- val combinedScore = calculateCombinedScore(nnScore, laplacianScore)
165
- val confidence = calculateConfidence(nnScore, laplacianScore)
166
-
167
- Result.success(
168
- AntiSpoofingResult(
169
- neuralNetworkScore = nnScore,
170
- laplacianScore = laplacianScore,
171
- textureComplexity = 0, // Not calculated in working version
172
- temporalConsistency = 0f, // Not calculated in working version
173
- colorSaturation = 0f, // Not calculated in working version
174
- combinedScore = combinedScore,
175
- confidence = confidence
176
- )
177
- )
178
- }
179
- } catch (e: Exception) {
180
- Log.e(TAG, "Error in advancedAntiSpoofing", e)
181
- Result.failure(e)
182
- }
183
- }
184
-
185
- // NEW: Legacy method for NV21 compatibility
186
- fun advancedAntiSpoofing(nv21: ByteArray, width: Int, height: Int): AntiSpoofingResult {
187
- if (!isInitialized) {
188
- return AntiSpoofingResult(
189
- neuralNetworkScore = 0f,
190
- laplacianScore = 0,
191
- textureComplexity = 0,
192
- temporalConsistency = 0f,
193
- colorSaturation = 0f,
194
- combinedScore = 0f,
195
- confidence = 0f
196
- )
197
- }
198
-
199
- return try {
200
- // Convert NV21 to Bitmap
201
- val bitmap = nv21ToBitmap(nv21, width, height)
202
- val result = runBlocking { advancedAntiSpoofing(bitmap) }
203
-
204
- val spoofResult = result.getOrNull()
205
- if (spoofResult != null) {
206
- spoofResult
207
- } else {
208
- Log.e(TAG, "Anti-spoofing analysis failed", result.exceptionOrNull())
209
- AntiSpoofingResult(
210
- neuralNetworkScore = 0f,
211
- laplacianScore = 0,
212
- textureComplexity = 0,
213
- temporalConsistency = 0f,
214
- colorSaturation = 0f,
215
- combinedScore = 0f,
216
- confidence = 0f
217
- )
218
- }
219
- } catch (e: Exception) {
220
- Log.e(TAG, "Error in advancedAntiSpoofing", e)
221
- AntiSpoofingResult(
222
- neuralNetworkScore = 0f,
223
- laplacianScore = 0,
224
- textureComplexity = 0,
225
- temporalConsistency = 0f,
226
- colorSaturation = 0f,
227
- combinedScore = 0f,
228
- confidence = 0f
229
- )
230
- }
231
- }
232
-
233
- fun advancedAntiSpoofing(
234
- planes: Array<ByteArray>,
235
- width: Int,
236
- height: Int,
237
- rowStrides: IntArray,
238
- pixelStrides: IntArray,
239
- rotationDegrees: Int = 0,
240
- faceBounds: RectF? = null,
241
- leftEye: PointF? = null,
242
- rightEye: PointF? = null,
243
- ): AntiSpoofingResult {
244
- if (planes.size < 3) {
245
- throw IllegalArgumentException("Expected Y, U and V planes")
246
- }
247
-
248
- val sourceBitmap = yuv420ToBitmap(planes, width, height, rowStrides, pixelStrides)
249
- val rotation = ((rotationDegrees % 360) + 360) % 360
250
- val bitmap = if (rotation == 0) {
251
- sourceBitmap
252
- } else {
253
- Bitmap.createBitmap(
254
- sourceBitmap,
255
- 0,
256
- 0,
257
- sourceBitmap.width,
258
- sourceBitmap.height,
259
- Matrix().apply { postRotate(rotation.toFloat()) },
260
- true
261
- ).also { sourceBitmap.recycle() }
262
- }
263
- return try {
264
- val inputBitmap = if (faceBounds != null) {
265
- cropAndAlignFace(bitmap, faceBounds, leftEye, rightEye)
266
- } else {
267
- bitmap
268
- }
269
- try {
270
- runBlocking { advancedAntiSpoofing(inputBitmap).getOrThrow() }
271
- } finally {
272
- if (inputBitmap !== bitmap) inputBitmap.recycle()
16
+ check(livenessDetector.loadModel(assetManager) == 0) {
17
+ "Failed to load the NCNN liveness models"
273
18
  }
274
- } finally {
275
- bitmap.recycle()
19
+ initialized = true
20
+ } catch (error: Exception) {
21
+ livenessDetector.close()
22
+ throw error
276
23
  }
277
24
  }
278
25
 
@@ -285,727 +32,97 @@ class FaceAntiSpoofingAdvanced(private val assetManager: AssetManager) {
285
32
  pixelStrides: IntArray,
286
33
  rotationDegrees: Int,
287
34
  faceBounds: RectF,
288
- leftEye: PointF,
289
- rightEye: PointF,
290
- ): AntiSpoofingResult {
291
- if (!isInitialized) {
292
- throw IllegalStateException("Classifier not initialized")
35
+ ): Float {
36
+ check(initialized) { "NCNN liveness detector is not initialized" }
37
+ require(planes.size >= 3 && rowStrides.size >= 3 && pixelStrides.size >= 3) {
38
+ "Expected Y, U and V camera planes with row and pixel strides"
293
39
  }
294
- require(planes.size >= 3) { "Expected Y, U and V planes" }
295
- require(rowStrides.size >= 3 && pixelStrides.size >= 3) {
296
- "Expected row and pixel strides for Y, U and V planes"
40
+ require(width > 0 && height > 0 && width % 2 == 0 && height % 2 == 0) {
41
+ "YUV420 frame dimensions must be positive and even"
297
42
  }
298
- require(width > 0 && height > 0) { "Frame dimensions must be positive" }
299
-
300
43
  val rotation = ((rotationDegrees % 360) + 360) % 360
301
44
  require(rotation % 90 == 0) { "Invalid frame rotation: $rotation" }
302
-
303
- val orientedWidth = if (rotation == 90 || rotation == 270) height else width
304
- val orientedHeight = if (rotation == 90 || rotation == 270) width else height
305
- val cropSide = (max(faceBounds.width(), faceBounds.height()) * 1.4f)
306
- .coerceAtMost(min(orientedWidth, orientedHeight).toFloat())
307
- .toInt()
308
- .coerceAtLeast(1)
309
- val halfSide = cropSide / 2f
310
- val centerX = faceBounds.centerX().coerceIn(halfSide, orientedWidth - halfSide)
311
- val centerY = faceBounds.centerY().coerceIn(halfSide, orientedHeight - halfSide)
312
- val cropLeft = (centerX - halfSide).toInt().coerceIn(0, orientedWidth - cropSide)
313
- val cropTop = (centerY - halfSide).toInt().coerceIn(0, orientedHeight - cropSide)
314
- val cropRight = cropLeft + cropSide - 1
315
- val cropBottom = cropTop + cropSide - 1
316
- val eyeAngle = atan2(
317
- (rightEye.y - leftEye.y).toDouble(),
318
- (rightEye.x - leftEye.x).toDouble(),
319
- ).toFloat().takeIf { abs(Math.toDegrees(it.toDouble())) >= 0.5 } ?: 0f
320
- val cosine = cos(eyeAngle)
321
- val sine = sin(eyeAngle)
322
- val cropCenter = (cropSide - 1) / 2f
323
- val sampleScale = cropSide.toFloat() / INPUT_IMAGE_SIZE
324
- for (planeIndex in 0 until 3) {
325
- inputPlanePositions[planeIndex] = planes[planeIndex].position()
326
- }
327
-
328
- for (targetY in 0 until INPUT_IMAGE_SIZE) {
329
- val cropY = (targetY + 0.5f) * sampleScale - 0.5f
330
- val relativeY = cropY - cropCenter
331
- for (targetX in 0 until INPUT_IMAGE_SIZE) {
332
- val cropX = (targetX + 0.5f) * sampleScale - 0.5f
333
- val relativeX = cropX - cropCenter
334
- val orientedX = (cropLeft + cropCenter + cosine * relativeX - sine * relativeY)
335
- .coerceIn(cropLeft.toFloat(), cropRight.toFloat())
336
- val orientedY = (cropTop + cropCenter + sine * relativeX + cosine * relativeY)
337
- .coerceIn(cropTop.toFloat(), cropBottom.toFloat())
338
- val sourceX: Float
339
- val sourceY: Float
340
- when (rotation) {
341
- 90 -> {
342
- sourceX = orientedY
343
- sourceY = height - 1f - orientedX
344
- }
345
- 180 -> {
346
- sourceX = width - 1f - orientedX
347
- sourceY = height - 1f - orientedY
348
- }
349
- 270 -> {
350
- sourceX = width - 1f - orientedY
351
- sourceY = orientedX
352
- }
353
- else -> {
354
- sourceX = orientedX
355
- sourceY = orientedY
356
- }
357
- }
358
- val rgb = sampleYuvBilinear(
359
- planes,
360
- rowStrides,
361
- pixelStrides,
362
- width,
363
- height,
364
- sourceX,
365
- sourceY,
366
- )
367
- val red = (rgb ushr 16) and 0xFF
368
- val green = (rgb ushr 8) and 0xFF
369
- val blue = rgb and 0xFF
370
- modelInputBuffer[targetY][targetX][0] = red / 255f
371
- modelInputBuffer[targetY][targetX][1] = green / 255f
372
- modelInputBuffer[targetY][targetX][2] = blue / 255f
373
- grayBuffer[targetY][targetX] = (
374
- 0.299f * red + 0.587f * green + 0.114f * blue
375
- ).toInt()
376
- }
377
- }
378
-
379
- val nnResult = neuralNetworkAntiSpoofingSampled()
380
- val nnScore = nnResult.getOrThrow()
381
- val laplacianScore = calculateLaplacianFromGray(grayBuffer)
382
- val combinedScore = calculateCombinedScore(nnScore, laplacianScore)
383
- return AntiSpoofingResult(
384
- neuralNetworkScore = nnScore,
385
- laplacianScore = laplacianScore,
386
- textureComplexity = 0,
387
- temporalConsistency = 0f,
388
- colorSaturation = 0f,
389
- combinedScore = combinedScore,
390
- confidence = calculateConfidence(nnScore, laplacianScore),
45
+ require(faceBounds.width() > 0f && faceBounds.height() > 0f) {
46
+ "Face bounds must have positive dimensions"
47
+ }
48
+
49
+ val nv21 = yuvPlanesToNv21(planes, width, height, rowStrides, pixelStrides)
50
+ return livenessDetector.detect(
51
+ nv21,
52
+ width,
53
+ height,
54
+ rotation,
55
+ FaceBox(
56
+ faceBounds.left.roundToInt(),
57
+ faceBounds.top.roundToInt(),
58
+ faceBounds.right.roundToInt(),
59
+ faceBounds.bottom.roundToInt(),
60
+ 1f,
61
+ ),
391
62
  )
392
63
  }
393
64
 
394
- private fun sampleYuvBilinear(
395
- planes: Array<ByteBuffer>,
396
- rowStrides: IntArray,
397
- pixelStrides: IntArray,
398
- sourceWidth: Int,
399
- sourceHeight: Int,
400
- x: Float,
401
- y: Float,
402
- ): Int {
403
- val boundedX = x.coerceIn(0f, sourceWidth - 1f)
404
- val boundedY = y.coerceIn(0f, sourceHeight - 1f)
405
- val x0 = floor(boundedX).toInt()
406
- val y0 = floor(boundedY).toInt()
407
- val x1 = min(x0 + 1, sourceWidth - 1)
408
- val y1 = min(y0 + 1, sourceHeight - 1)
409
- val xWeight = boundedX - x0
410
- val yWeight = boundedY - y0
411
- val topLeft = readYuvRgb(planes, rowStrides, pixelStrides, x0, y0)
412
- val topRight = readYuvRgb(planes, rowStrides, pixelStrides, x1, y0)
413
- val bottomLeft = readYuvRgb(planes, rowStrides, pixelStrides, x0, y1)
414
- val bottomRight = readYuvRgb(planes, rowStrides, pixelStrides, x1, y1)
415
-
416
- val red = interpolateChannel(topLeft, topRight, bottomLeft, bottomRight, 16, xWeight, yWeight)
417
- val green = interpolateChannel(topLeft, topRight, bottomLeft, bottomRight, 8, xWeight, yWeight)
418
- val blue = interpolateChannel(topLeft, topRight, bottomLeft, bottomRight, 0, xWeight, yWeight)
419
- return (red shl 16) or (green shl 8) or blue
420
- }
421
-
422
- private fun interpolateChannel(
423
- topLeft: Int,
424
- topRight: Int,
425
- bottomLeft: Int,
426
- bottomRight: Int,
427
- shift: Int,
428
- xWeight: Float,
429
- yWeight: Float,
430
- ): Int {
431
- val top = ((topLeft ushr shift) and 0xFF) * (1 - xWeight) +
432
- ((topRight ushr shift) and 0xFF) * xWeight
433
- val bottom = ((bottomLeft ushr shift) and 0xFF) * (1 - xWeight) +
434
- ((bottomRight ushr shift) and 0xFF) * xWeight
435
- return (top * (1 - yWeight) + bottom * yWeight).roundToInt().coerceIn(0, 255)
436
- }
437
-
438
- private fun readYuvRgb(
65
+ private fun yuvPlanesToNv21(
439
66
  planes: Array<ByteBuffer>,
440
- rowStrides: IntArray,
441
- pixelStrides: IntArray,
442
- x: Int,
443
- y: Int,
444
- ): Int {
445
- val luma = readPlaneSample(0, planes[0], rowStrides[0], pixelStrides[0], x, y)
446
- val chromaX = x / 2
447
- val chromaY = y / 2
448
- val u = readPlaneSample(1, planes[1], rowStrides[1], pixelStrides[1], chromaX, chromaY) - 128
449
- val v = readPlaneSample(2, planes[2], rowStrides[2], pixelStrides[2], chromaX, chromaY) - 128
450
- val red = (luma + 1.402f * v).toInt().coerceIn(0, 255)
451
- val green = (luma - 0.344f * u - 0.714f * v).toInt().coerceIn(0, 255)
452
- val blue = (luma + 1.772f * u).toInt().coerceIn(0, 255)
453
- return (red shl 16) or (green shl 8) or blue
454
- }
455
-
456
- private fun readPlaneSample(
457
- planeIndex: Int,
458
- buffer: ByteBuffer,
459
- rowStride: Int,
460
- pixelStride: Int,
461
- x: Int,
462
- y: Int,
463
- ): Int {
464
- val bufferPosition = inputPlanePositions[planeIndex]
465
- val index = bufferPosition + y * rowStride + x * pixelStride
466
- require(index >= bufferPosition && index < buffer.limit()) {
467
- "Camera plane buffer is too small for the requested sample"
468
- }
469
- return buffer.get(index).toInt() and 0xFF
470
- }
471
-
472
- private fun cropAndAlignFace(
473
- source: Bitmap,
474
- faceBounds: RectF,
475
- leftEye: PointF?,
476
- rightEye: PointF?,
477
- ): Bitmap {
478
- val cropSide = (max(faceBounds.width(), faceBounds.height()) * 1.4f)
479
- .coerceAtMost(min(source.width, source.height).toFloat())
480
- .toInt()
481
- .coerceAtLeast(1)
482
- val halfSide = cropSide / 2f
483
- val centerX = faceBounds.centerX().coerceIn(halfSide, source.width - halfSide)
484
- val centerY = faceBounds.centerY().coerceIn(halfSide, source.height - halfSide)
485
- val left = (centerX - halfSide).toInt().coerceIn(0, source.width - cropSide)
486
- val top = (centerY - halfSide).toInt().coerceIn(0, source.height - cropSide)
487
- val crop = Bitmap.createBitmap(source, left, top, cropSide, cropSide)
488
-
489
- if (leftEye == null || rightEye == null) return crop
490
- val eyeAngle = Math.toDegrees(
491
- kotlin.math.atan2(
492
- (rightEye.y - leftEye.y).toDouble(),
493
- (rightEye.x - leftEye.x).toDouble(),
494
- )
495
- ).toFloat()
496
- if (kotlin.math.abs(eyeAngle) < 0.5f) return crop
497
-
498
- return Bitmap.createBitmap(
499
- crop,
500
- 0,
501
- 0,
502
- crop.width,
503
- crop.height,
504
- Matrix().apply { postRotate(-eyeAngle) },
505
- true,
506
- ).also { aligned ->
507
- if (aligned !== crop) crop.recycle()
508
- }
509
- }
510
-
511
- fun advancedAntiSpoofingRGBA(rgba: ByteArray, width: Int, height: Int): AntiSpoofingResult {
512
- if (!isInitialized) {
513
- return AntiSpoofingResult(
514
- neuralNetworkScore = 0f,
515
- laplacianScore = 0,
516
- textureComplexity = 0,
517
- temporalConsistency = 0f,
518
- colorSaturation = 0f,
519
- combinedScore = 0f,
520
- confidence = 0f
521
- )
522
- }
523
-
524
- return try {
525
- val sampled = sampleRgbaToModelAndGray(rgba, width, height)
526
- val nnResult = neuralNetworkAntiSpoofingSampled()
527
- val nnScore = nnResult.getOrNull() ?: throw IllegalStateException(nnResult.exceptionOrNull()?.message ?: "NN inference failed")
528
- val laplacianScore = calculateLaplacianFromGray(sampled.grayBuffer)
529
- val combinedScore = calculateCombinedScore(nnScore, laplacianScore)
530
- val confidence = calculateConfidence(nnScore, laplacianScore)
531
-
532
- AntiSpoofingResult(
533
- neuralNetworkScore = nnScore,
534
- laplacianScore = laplacianScore,
535
- textureComplexity = 0,
536
- temporalConsistency = 0f,
537
- colorSaturation = 0f,
538
- combinedScore = combinedScore,
539
- confidence = confidence
540
- )
541
- } catch (e: Exception) {
542
- Log.e(TAG, "Error in advancedAntiSpoofingRGBA", e)
543
- AntiSpoofingResult(
544
- neuralNetworkScore = 0f,
545
- laplacianScore = 0,
546
- textureComplexity = 0,
547
- temporalConsistency = 0f,
548
- colorSaturation = 0f,
549
- combinedScore = 0f,
550
- confidence = 0f
551
- )
552
- }
553
- }
554
-
555
- fun advancedAntiSpoofingRGBA(buffer: ByteBuffer, width: Int, height: Int, rowStride: Int, pixelStride: Int): AntiSpoofingResult {
556
- if (!isInitialized) {
557
- return AntiSpoofingResult(
558
- neuralNetworkScore = 0f,
559
- laplacianScore = 0,
560
- textureComplexity = 0,
561
- temporalConsistency = 0f,
562
- colorSaturation = 0f,
563
- combinedScore = 0f,
564
- confidence = 0f
565
- )
566
- }
567
-
568
- return try {
569
- val sampled = sampleRgbaBufferToModelAndGray(buffer, width, height, rowStride, pixelStride)
570
- val nnResult = neuralNetworkAntiSpoofingSampled()
571
- val nnScore = nnResult.getOrNull() ?: throw IllegalStateException(nnResult.exceptionOrNull()?.message ?: "NN inference failed")
572
- val laplacianScore = calculateLaplacianFromGray(sampled.grayBuffer)
573
- val combinedScore = calculateCombinedScore(nnScore, laplacianScore)
574
- val confidence = calculateConfidence(nnScore, laplacianScore)
575
-
576
- AntiSpoofingResult(
577
- neuralNetworkScore = nnScore,
578
- laplacianScore = laplacianScore,
579
- textureComplexity = 0,
580
- temporalConsistency = 0f,
581
- colorSaturation = 0f,
582
- combinedScore = combinedScore,
583
- confidence = confidence
584
- )
585
- } catch (e: Exception) {
586
- Log.e(TAG, "Error in advancedAntiSpoofingRGBA buffer path", e)
587
- AntiSpoofingResult(
588
- neuralNetworkScore = 0f,
589
- laplacianScore = 0,
590
- textureComplexity = 0,
591
- temporalConsistency = 0f,
592
- colorSaturation = 0f,
593
- combinedScore = 0f,
594
- confidence = 0f
595
- )
596
- }
597
- }
598
-
599
- // FROM WORKING VERSION: neuralNetworkAntiSpoofing with Bitmap
600
- private fun neuralNetworkAntiSpoofing(bitmap: Bitmap): Result<Float> {
601
- var bitmapScale: Bitmap? = null
602
- return try {
603
- val scaledBitmap = Bitmap.createScaledBitmap(bitmap, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE, true)
604
- bitmapScale = scaledBitmap
605
- val img = normalizeImage(scaledBitmap)
606
- val input = arrayOf(img)
607
-
608
- // Clear and prepare outputs
609
- clssPred[0].fill(0f)
610
- leafNodeMask[0].fill(0f)
611
-
612
- outputs[outputIndex0] = clssPred
613
- outputs[outputIndex1] = leafNodeMask
614
-
615
- runInference(input)
616
-
617
- val score = leafScore1(clssPred, leafNodeMask)
618
-
619
- Result.success(score)
620
- } catch (e: Exception) {
621
- Log.e(TAG, "Error in neuralNetworkAntiSpoofing", e)
622
- Result.failure(e)
623
- } finally {
624
- bitmapScale?.takeIf { it !== bitmap }?.recycle()
625
- }
626
- }
627
-
628
- private fun neuralNetworkAntiSpoofingSampled(): Result<Float> {
629
- return try {
630
- clssPred[0].fill(0f)
631
- leafNodeMask[0].fill(0f)
632
- outputs[outputIndex0] = clssPred
633
- outputs[outputIndex1] = leafNodeMask
634
- runInference(modelInput)
635
- Result.success(leafScore1(clssPred, leafNodeMask))
636
- } catch (e: Exception) {
637
- Log.e(TAG, "Error in neuralNetworkAntiSpoofingSampled", e)
638
- Result.failure(e)
639
- }
640
- }
641
-
642
- // FROM WORKING VERSION: leafScore1
643
- private fun leafScore1(clssPred: Array<FloatArray>, leafNodeMask: Array<FloatArray>): Float {
644
- var score = 0f
645
- for (i in 0 until 8) {
646
- score += abs(clssPred[0][i]) * leafNodeMask[0][i]
647
- }
648
- return score
649
- }
650
-
651
- // FROM WORKING VERSION: normalizeImage
652
- private fun normalizeImage(bitmap: Bitmap): Array<Array<FloatArray>> {
653
- val h = bitmap.height
654
- val w = bitmap.width
655
- val floatValues = Array(h) { Array(w) { FloatArray(3) } }
656
-
657
- val imageStd = 255f
658
- val pixels = IntArray(h * w)
659
- bitmap.getPixels(pixels, 0, w, 0, 0, w, h)
660
-
661
- for (i in 0 until h) {
662
- for (j in 0 until w) {
663
- val pixel = pixels[i * w + j]
664
- val r = ((pixel shr 16) and 0xFF) / imageStd
665
- val g = ((pixel shr 8) and 0xFF) / imageStd
666
- val b = (pixel and 0xFF) / imageStd
667
- floatValues[i][j] = floatArrayOf(r, g, b)
668
- }
669
- }
670
- return floatValues
671
- }
672
-
673
- private data class SampledFrame(
674
- val rgbBuffer: Array<Array<FloatArray>>,
675
- val grayBuffer: Array<IntArray>
676
- )
677
-
678
- // Single-pass resize: one source pixel sample writes both the model RGB tensor
679
- // and the grayscale buffer used for Laplacian scoring.
680
- private fun sampleRgbaToModelAndGray(
681
- rgba: ByteArray,
682
- srcWidth: Int,
683
- srcHeight: Int
684
- ): SampledFrame {
685
- val targetWidth = INPUT_IMAGE_SIZE
686
- val targetHeight = INPUT_IMAGE_SIZE
687
- val scaleX = srcWidth.toFloat() / targetWidth
688
- val scaleY = srcHeight.toFloat() / targetHeight
689
-
690
- for (targetY in 0 until targetHeight) {
691
- val srcY = (targetY * scaleY).toInt().coerceIn(0, srcHeight - 1)
692
- for (targetX in 0 until targetWidth) {
693
- val srcX = (targetX * scaleX).toInt().coerceIn(0, srcWidth - 1)
694
- val srcIndex = (srcY * srcWidth + srcX) * 4
695
-
696
- val r = (rgba[srcIndex].toInt() and 0xFF) / 255f
697
- val g = (rgba[srcIndex + 1].toInt() and 0xFF) / 255f
698
- val b = (rgba[srcIndex + 2].toInt() and 0xFF) / 255f
699
-
700
- modelInputBuffer[targetY][targetX][0] = r
701
- modelInputBuffer[targetY][targetX][1] = g
702
- modelInputBuffer[targetY][targetX][2] = b
703
- grayBuffer[targetY][targetX] = (
704
- 0.299f * rgba[srcIndex].toInt() +
705
- 0.587f * rgba[srcIndex + 1].toInt() +
706
- 0.114f * rgba[srcIndex + 2].toInt()
707
- ).toInt()
708
- }
709
- }
710
-
711
- return SampledFrame(modelInputBuffer, grayBuffer)
712
- }
713
-
714
- private fun sampleRgbaBufferToModelAndGray(
715
- buffer: ByteBuffer,
716
- srcWidth: Int,
717
- srcHeight: Int,
718
- rowStride: Int,
719
- pixelStride: Int
720
- ): SampledFrame {
721
- val targetWidth = INPUT_IMAGE_SIZE
722
- val targetHeight = INPUT_IMAGE_SIZE
723
- val scaleX = srcWidth.toFloat() / targetWidth
724
- val scaleY = srcHeight.toFloat() / targetHeight
725
- val duplicated = buffer.duplicate()
726
- duplicated.order(ByteOrder.nativeOrder())
727
-
728
- for (targetY in 0 until targetHeight) {
729
- val srcY = (targetY * scaleY).toInt().coerceIn(0, srcHeight - 1)
730
- val rowOffset = srcY * rowStride
731
- for (targetX in 0 until targetWidth) {
732
- val srcX = (targetX * scaleX).toInt().coerceIn(0, srcWidth - 1)
733
- val pixelIndex = rowOffset + srcX * pixelStride
734
-
735
- val r = duplicated.get(pixelIndex).toInt() and 0xFF
736
- val g = duplicated.get(pixelIndex + 1).toInt() and 0xFF
737
- val b = duplicated.get(pixelIndex + 2).toInt() and 0xFF
738
-
739
- modelInputBuffer[targetY][targetX][0] = r / 255f
740
- modelInputBuffer[targetY][targetX][1] = g / 255f
741
- modelInputBuffer[targetY][targetX][2] = b / 255f
742
- grayBuffer[targetY][targetX] = (
743
- 0.299f * r +
744
- 0.587f * g +
745
- 0.114f * b
746
- ).toInt()
747
- }
748
- }
749
-
750
- return SampledFrame(modelInputBuffer, grayBuffer)
751
- }
752
-
753
- // FROM WORKING VERSION: laplacian with Bitmap
754
- private fun laplacian(bitmap: Bitmap): Result<Int> {
755
- return try {
756
- val bitmapScale = Bitmap.createScaledBitmap(bitmap, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE, true)
757
- val score = calculateLaplacianScore(bitmapScale)
758
-
759
- if (bitmapScale != bitmap) {
760
- bitmapScale.recycle()
761
- }
762
-
763
- Result.success(score)
764
- } catch (e: Exception) {
765
- Log.e(TAG, "Error in laplacian calculation", e)
766
- Result.failure(e)
767
- }
768
- }
769
-
770
- // FROM WORKING VERSION: calculateLaplacianScore
771
- private fun calculateLaplacianScore(bitmap: Bitmap): Int {
772
- val laplace = arrayOf(
773
- intArrayOf(0, 1, 0),
774
- intArrayOf(1, -4, 1),
775
- intArrayOf(0, 1, 0)
776
- )
777
-
778
- val size = laplace.size
779
- val img = convertGreyImg(bitmap)
780
- val height = img.size
781
- val width = img[0].size
782
-
783
- var score = 0
784
- for (x in 0 until height - size + 1) {
785
- for (y in 0 until width - size + 1) {
786
- var result = 0
787
- for (i in 0 until size) {
788
- for (j in 0 until size) {
789
- result += img[x + i][y + j] * laplace[i][j]
790
- }
791
- }
792
- if (result > LAPLACE_THRESHOLD) {
793
- score++
794
- }
795
- }
796
- }
797
- return score
798
- }
799
-
800
- // FROM WORKING VERSION: convertGreyImg
801
- private fun convertGreyImg(bitmap: Bitmap): Array<IntArray> {
802
- val width = bitmap.width
803
- val height = bitmap.height
804
- val greyImg = Array(height) { IntArray(width) }
805
-
806
- val pixels = IntArray(width * height)
807
- bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
808
-
809
- for (i in 0 until height) {
810
- for (j in 0 until width) {
811
- val pixel = pixels[i * width + j]
812
- val r = (pixel shr 16) and 0xFF
813
- val g = (pixel shr 8) and 0xFF
814
- val b = pixel and 0xFF
815
- greyImg[i][j] = (0.299 * r + 0.587 * g + 0.114 * b).toInt()
816
- }
817
- }
818
- return greyImg
819
- }
820
-
821
- private fun calculateLaplacianFromGray(img: Array<IntArray>): Int {
822
- val laplace = arrayOf(
823
- intArrayOf(0, 1, 0),
824
- intArrayOf(1, -4, 1),
825
- intArrayOf(0, 1, 0)
826
- )
827
-
828
- val height = img.size
829
- val width = img[0].size
830
- var score = 0
831
- for (x in 0 until height - laplace.size + 1) {
832
- for (y in 0 until width - laplace.size + 1) {
833
- var result = 0
834
- for (i in 0 until laplace.size) {
835
- for (j in 0 until laplace.size) {
836
- result += img[x + i][y + j] * laplace[i][j]
837
- }
838
- }
839
- if (result > LAPLACE_THRESHOLD) {
840
- score++
841
- }
842
- }
843
- }
844
- return score
845
- }
846
-
847
- // FROM WORKING VERSION: calculateCombinedScore
848
- private fun calculateCombinedScore(neuralScore: Float, laplacianScore: Int): Float {
849
- // Normalize both scores to 0-1 range
850
- val normalizedNeural = neuralScore.coerceIn(0f, 1f)
851
- val normalizedLaplacian = (laplacianScore.toFloat() / LAPLACIAN_THRESHOLD).coerceIn(0f, 1f)
852
-
853
- // For real face: neuralScore should be LOW (< 0.2), laplacianScore should be HIGH (> 3000)
854
- // Combined score: lower neural + higher laplacian = higher (more live)
855
- val neuralWeight = 0.6f
856
- val laplacianWeight = 0.4f
857
-
858
- // Invert neural score since low neural = live, high neural = spoof
859
- val invertedNeural = 1f - normalizedNeural
860
-
861
- return (invertedNeural * neuralWeight) + (normalizedLaplacian * laplacianWeight)
862
- }
863
-
864
- // NEW: Helper function to calculate confidence
865
- private fun calculateConfidence(neuralScore: Float, laplacianScore: Int): Float {
866
- // Confidence based on how well both metrics indicate a real face
867
- val neuralConfidence = neuralScore.coerceIn(0f, 1f) // High neural score = spoof (lower confidence)
868
- val laplacianConfidence = (laplacianScore.toFloat() / LAPLACIAN_THRESHOLD).coerceIn(0f, 1f)
869
-
870
- // For real face: neural should be high (bad) and laplacian should be high (good)
871
- // So: (1 - neural) gives us confidence from neural, and laplacian gives direct confidence
872
- val invertedNeural = 1f - neuralConfidence
873
-
874
- return (invertedNeural * 0.6f + laplacianConfidence * 0.4f)
875
- }
876
-
877
- // NEW: Convert NV21 to Bitmap
878
- private fun nv21ToBitmap(nv21: ByteArray, width: Int, height: Int): Bitmap {
879
- val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
880
- val pixels = IntArray(width * height)
881
-
882
- val ySize = width * height
883
- val uvSize = (width * height) / 4
884
- val uvOffset = ySize
885
-
886
- for (y in 0 until height) {
887
- for (x in 0 until width) {
888
- val yIndex = y * width + x
889
- val uvIndex = uvOffset + ((y / 2) * (width / 2) + (x / 2)) * 2
890
-
891
- val yValue = (nv21[yIndex].toInt() and 0xFF)
892
- val uValue = (nv21[uvIndex].toInt() and 0xFF) - 128
893
- val vValue = (nv21[uvIndex + 1].toInt() and 0xFF) - 128
894
-
895
- // YUV to RGB conversion
896
- var r = yValue + (1.402f * vValue)
897
- var g = yValue - (0.344f * uValue) - (0.714f * vValue)
898
- var b = yValue + (1.772f * uValue)
899
-
900
- // Clamp values
901
- r = r.coerceIn(0f, 255f)
902
- g = g.coerceIn(0f, 255f)
903
- b = b.coerceIn(0f, 255f)
904
-
905
- pixels[yIndex] = (0xFF shl 24) or
906
- ((r.toInt() and 0xFF) shl 16) or
907
- ((g.toInt() and 0xFF) shl 8) or
908
- (b.toInt() and 0xFF)
909
- }
910
- }
911
-
912
- bitmap.setPixels(pixels, 0, width, 0, 0, width, height)
913
- return bitmap
914
- }
915
-
916
- private fun yuv420ToBitmap(
917
- planes: Array<ByteArray>,
918
67
  width: Int,
919
68
  height: Int,
920
69
  rowStrides: IntArray,
921
- pixelStrides: IntArray
922
- ): Bitmap {
923
- val pixels = IntArray(width * height)
924
- val yPlane = planes[0]
925
- val uPlane = planes[1]
926
- val vPlane = planes[2]
927
-
928
- fun sample(plane: ByteArray, row: Int, column: Int, rowStride: Int, pixelStride: Int): Int {
929
- val index = row * rowStride + column * pixelStride
930
- return if (index in plane.indices) plane[index].toInt() and 0xFF else 128
931
- }
70
+ pixelStrides: IntArray,
71
+ ): ByteArray {
72
+ val frameSize = width.toLong() * height
73
+ val byteCount = frameSize + frameSize / 2
74
+ require(byteCount <= Int.MAX_VALUE) { "Camera frame is too large for NCNN input" }
75
+ val nv21 = ByteArray(byteCount.toInt())
76
+ val positions = IntArray(3) { planes[it].position() }
932
77
 
933
78
  for (y in 0 until height) {
934
79
  for (x in 0 until width) {
935
- val yValue = sample(yPlane, y, x, rowStrides[0], pixelStrides[0])
936
- val chromaRow = y / 2
937
- val chromaColumn = x / 2
938
- val uValue = sample(uPlane, chromaRow, chromaColumn, rowStrides[1], pixelStrides[1]) - 128
939
- val vValue = sample(vPlane, chromaRow, chromaColumn, rowStrides[2], pixelStrides[2]) - 128
940
-
941
- val red = (yValue + 1.402f * vValue).coerceIn(0f, 255f).toInt()
942
- val green = (yValue - 0.344f * uValue - 0.714f * vValue).coerceIn(0f, 255f).toInt()
943
- val blue = (yValue + 1.772f * uValue).coerceIn(0f, 255f).toInt()
944
- pixels[y * width + x] = (0xFF shl 24) or
945
- (red shl 16) or
946
- (green shl 8) or
947
- blue
80
+ nv21[y * width + x] = readPlaneSample(
81
+ planes, rowStrides, pixelStrides, positions, 0, x, y,
82
+ )
948
83
  }
949
84
  }
950
85
 
951
- return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888)
952
- }
953
-
954
- private fun rgbaToBitmap(rgba: ByteArray, width: Int, height: Int): Bitmap {
955
- val pixels = IntArray(width * height)
956
- var index = 0
957
- for (y in 0 until height) {
958
- for (x in 0 until width) {
959
- val r = rgba[index].toInt() and 0xFF
960
- val g = rgba[index + 1].toInt() and 0xFF
961
- val b = rgba[index + 2].toInt() and 0xFF
962
- val a = rgba[index + 3].toInt() and 0xFF
963
- pixels[y * width + x] = (a shl 24) or (r shl 16) or (g shl 8) or b
964
- index += 4
86
+ var chromaIndex = frameSize.toInt()
87
+ for (y in 0 until height / 2) {
88
+ for (x in 0 until width / 2) {
89
+ nv21[chromaIndex++] = readPlaneSample(
90
+ planes, rowStrides, pixelStrides, positions, 2, x, y,
91
+ )
92
+ nv21[chromaIndex++] = readPlaneSample(
93
+ planes, rowStrides, pixelStrides, positions, 1, x, y,
94
+ )
965
95
  }
966
96
  }
967
- return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888)
97
+ return nv21
968
98
  }
969
99
 
970
- @Throws(IOException::class)
971
- private fun loadModelFile(assetManager: AssetManager, modelName: String): MappedByteBuffer {
972
- return try {
973
- val fileDescriptor = assetManager.openFd(modelName)
974
- val inputStream = FileInputStream(fileDescriptor.fileDescriptor)
975
- val fileChannel = inputStream.channel
976
- fileChannel.map(
977
- FileChannel.MapMode.READ_ONLY,
978
- fileDescriptor.startOffset,
979
- fileDescriptor.declaredLength
980
- )
981
- } catch (e: Exception) {
982
- Log.e(TAG, "Error loading model file", e)
983
- throw e
100
+ private fun readPlaneSample(
101
+ planes: Array<ByteBuffer>,
102
+ rowStrides: IntArray,
103
+ pixelStrides: IntArray,
104
+ positions: IntArray,
105
+ planeIndex: Int,
106
+ x: Int,
107
+ y: Int,
108
+ ): Byte {
109
+ require(rowStrides[planeIndex] > 0 && pixelStrides[planeIndex] > 0) {
110
+ "Camera plane strides must be positive"
111
+ }
112
+ val index = positions[planeIndex].toLong() +
113
+ y.toLong() * rowStrides[planeIndex] +
114
+ x.toLong() * pixelStrides[planeIndex]
115
+ require(index >= positions[planeIndex] && index < planes[planeIndex].limit()) {
116
+ "Camera plane $planeIndex buffer is too small"
984
117
  }
118
+ return planes[planeIndex].get(index.toInt())
985
119
  }
986
120
 
987
- fun isInitialized(): Boolean = isInitialized
988
-
121
+ @Synchronized
989
122
  fun close() {
990
- try {
991
- interpreter?.close()
992
- interpreter = null
993
- gpuDelegate?.close()
994
- gpuDelegate = null
995
- currentAccelerator = ACCELERATOR_CPU
996
- Log.i(TAG, "Interpreter and delegates closed successfully")
997
- } catch (e: Exception) {
998
- Log.e(TAG, "Error closing interpreter", e)
123
+ if (initialized) {
124
+ livenessDetector.close()
125
+ initialized = false
999
126
  }
1000
127
  }
1001
128
  }
1002
-
1003
- data class AntiSpoofingResult(
1004
- val neuralNetworkScore: Float,
1005
- val laplacianScore: Int,
1006
- val textureComplexity: Int,
1007
- val temporalConsistency: Float,
1008
- val colorSaturation: Float,
1009
- val combinedScore: Float,
1010
- val confidence: Float
1011
- )