react-native-vision-camera-spoof-detector 1.4.1 → 1.5.1

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