react-native-vision-camera-spoof-detector 1.1.24 → 1.1.26
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.
|
@@ -3,6 +3,27 @@ import Foundation
|
|
|
3
3
|
#if canImport(TensorFlowLite)
|
|
4
4
|
import TensorFlowLite
|
|
5
5
|
#endif
|
|
6
|
+
#if canImport(TensorFlowLiteCMetal)
|
|
7
|
+
import TensorFlowLiteCMetal
|
|
8
|
+
#endif
|
|
9
|
+
|
|
10
|
+
#if canImport(TensorFlowLite) && canImport(TensorFlowLiteCMetal)
|
|
11
|
+
private final class IOSMetalDelegate: Delegate {
|
|
12
|
+
let cDelegate: Delegate.CDelegate
|
|
13
|
+
|
|
14
|
+
init() {
|
|
15
|
+
var options = TFLGpuDelegateOptions()
|
|
16
|
+
options.allow_precision_loss = false
|
|
17
|
+
options.wait_type = TFLGpuDelegateWaitTypePassive
|
|
18
|
+
options.enable_quantization = true
|
|
19
|
+
cDelegate = TFLGpuDelegateCreate(&options)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
deinit {
|
|
23
|
+
TFLGpuDelegateDelete(cDelegate)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
#endif
|
|
6
27
|
|
|
7
28
|
@objcMembers
|
|
8
29
|
public class FaceAntiSpoofManager: NSObject {
|
|
@@ -16,7 +37,16 @@ public class FaceAntiSpoofManager: NSObject {
|
|
|
16
37
|
|
|
17
38
|
#if canImport(TensorFlowLite)
|
|
18
39
|
public static var sharedInterpreter: Interpreter?
|
|
40
|
+
public static private(set) var currentAccelerator = "CPU"
|
|
41
|
+
public static var enableGpu = true
|
|
42
|
+
public static var disableGpuDelegate = false
|
|
43
|
+
public static var enableCpuFallback = true
|
|
44
|
+
public static var forceCpuOnly = false
|
|
45
|
+
public static var cpuThreadCount = 4
|
|
19
46
|
private static let interpreterLock = NSLock()
|
|
47
|
+
#if canImport(TensorFlowLiteCMetal)
|
|
48
|
+
private static var metalDelegate: IOSMetalDelegate?
|
|
49
|
+
#endif
|
|
20
50
|
#endif
|
|
21
51
|
|
|
22
52
|
@objc public class func initializeModel() -> Bool {
|
|
@@ -46,15 +76,48 @@ public class FaceAntiSpoofManager: NSObject {
|
|
|
46
76
|
}
|
|
47
77
|
|
|
48
78
|
do {
|
|
79
|
+
let threadCount = max(1, cpuThreadCount)
|
|
49
80
|
var options = Interpreter.Options()
|
|
50
|
-
options.threadCount =
|
|
51
|
-
|
|
81
|
+
options.threadCount = threadCount
|
|
82
|
+
|
|
83
|
+
#if canImport(TensorFlowLiteCMetal)
|
|
84
|
+
if enableGpu && !disableGpuDelegate && !forceCpuOnly {
|
|
85
|
+
do {
|
|
86
|
+
let delegate = IOSMetalDelegate()
|
|
87
|
+
sharedInterpreter = try Interpreter(
|
|
88
|
+
modelPath: path,
|
|
89
|
+
options: options,
|
|
90
|
+
delegates: [delegate]
|
|
91
|
+
)
|
|
92
|
+
metalDelegate = delegate
|
|
93
|
+
currentAccelerator = "GPU"
|
|
94
|
+
NSLog("[FaceAntiSpoof] Manager: Metal delegate enabled | Threads: \(threadCount)")
|
|
95
|
+
} catch {
|
|
96
|
+
metalDelegate = nil
|
|
97
|
+
NSLog("[FaceAntiSpoof] Manager: Metal delegate unavailable: \(error)")
|
|
98
|
+
guard enableCpuFallback else { throw error }
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
#endif
|
|
102
|
+
|
|
103
|
+
if sharedInterpreter == nil {
|
|
104
|
+
guard enableCpuFallback || forceCpuOnly else {
|
|
105
|
+
throw NSError(domain: "FaceAntiSpoof", code: 4, userInfo: [
|
|
106
|
+
NSLocalizedDescriptionKey: "No enabled TensorFlow Lite accelerator is available"
|
|
107
|
+
])
|
|
108
|
+
}
|
|
109
|
+
sharedInterpreter = try Interpreter(modelPath: path, options: options)
|
|
110
|
+
currentAccelerator = "CPU"
|
|
111
|
+
NSLog("[FaceAntiSpoof] Manager: CPU fallback enabled | Threads: \(threadCount)")
|
|
112
|
+
}
|
|
52
113
|
try sharedInterpreter?.allocateTensors()
|
|
53
114
|
NSLog("[FaceAntiSpoof] Manager: Loaded model at \(path)")
|
|
54
115
|
return true
|
|
55
116
|
} catch {
|
|
56
117
|
NSLog("[FaceAntiSpoof] Manager: Failed to create interpreter: \(error)")
|
|
57
118
|
sharedInterpreter = nil
|
|
119
|
+
metalDelegate = nil
|
|
120
|
+
currentAccelerator = "CPU"
|
|
58
121
|
return false
|
|
59
122
|
}
|
|
60
123
|
#else
|
|
@@ -71,6 +134,14 @@ public class FaceAntiSpoofManager: NSObject {
|
|
|
71
134
|
#endif
|
|
72
135
|
}
|
|
73
136
|
|
|
137
|
+
@objc public class func accelerator() -> String {
|
|
138
|
+
#if canImport(TensorFlowLite)
|
|
139
|
+
return currentAccelerator
|
|
140
|
+
#else
|
|
141
|
+
return "UNAVAILABLE"
|
|
142
|
+
#endif
|
|
143
|
+
}
|
|
144
|
+
|
|
74
145
|
public class func process(input: [Float]) throws -> DetectionResult {
|
|
75
146
|
#if canImport(TensorFlowLite)
|
|
76
147
|
if sharedInterpreter == nil && !initializeModel() {
|
|
@@ -158,7 +229,11 @@ public class FaceAntiSpoofManager: NSObject {
|
|
|
158
229
|
|
|
159
230
|
@objc public class func cleanupModel() {
|
|
160
231
|
#if canImport(TensorFlowLite)
|
|
232
|
+
interpreterLock.lock()
|
|
161
233
|
sharedInterpreter = nil
|
|
234
|
+
metalDelegate = nil
|
|
235
|
+
currentAccelerator = "CPU"
|
|
236
|
+
interpreterLock.unlock()
|
|
162
237
|
#endif
|
|
163
238
|
NSLog("[FaceAntiSpoof] Manager: cleaned up model")
|
|
164
239
|
}
|
|
@@ -110,10 +110,26 @@ RCT_REMAP_METHOD(getModuleInfo,
|
|
|
110
110
|
getModuleInfoWithResolver:(RCTPromiseResolveBlock)resolve
|
|
111
111
|
rejecter:(RCTPromiseRejectBlock)reject)
|
|
112
112
|
{
|
|
113
|
-
NSDictionary *info = @{@"name": @"FaceAntiSpoof", @"methods": @[@"initialize", @"checkModelStatus", @"isAvailable", @"testMethod", @"getModuleInfo", @"install", @"cleanup"]};
|
|
113
|
+
NSDictionary *info = @{ @"name": @"FaceAntiSpoof", @"methods": @[@"initialize", @"checkModelStatus", @"isAvailable", @"testMethod", @"getModuleInfo", @"install", @"cleanup", @"getAccelerator"], @"accelerators": @[@"GPU", @"CPU"] };
|
|
114
114
|
resolve(info);
|
|
115
115
|
}
|
|
116
116
|
|
|
117
|
+
RCT_REMAP_METHOD(getAccelerator,
|
|
118
|
+
getAcceleratorWithResolver:(RCTPromiseResolveBlock)resolve
|
|
119
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
120
|
+
{
|
|
121
|
+
Class managerClass = NSClassFromString(@"FaceAntiSpoofManager");
|
|
122
|
+
if (managerClass != Nil) {
|
|
123
|
+
SEL sel = NSSelectorFromString(@"accelerator");
|
|
124
|
+
if ([managerClass respondsToSelector:sel]) {
|
|
125
|
+
id (*msgSendObject)(id, SEL) = (id (*)(id, SEL))objc_msgSend;
|
|
126
|
+
resolve(msgSendObject((id)managerClass, sel));
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
resolve(@"UNAVAILABLE");
|
|
131
|
+
}
|
|
132
|
+
|
|
117
133
|
RCT_REMAP_METHOD(install,
|
|
118
134
|
installWithResolver:(RCTPromiseResolveBlock)resolve
|
|
119
135
|
rejecter:(RCTPromiseRejectBlock)reject)
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import AVFoundation
|
|
2
|
-
import CoreImage
|
|
3
2
|
import Foundation
|
|
4
3
|
import NitroModules
|
|
5
4
|
import VisionCamera
|
|
@@ -8,11 +7,12 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
8
7
|
private let queue = DispatchQueue(label: "com.faceantispoof.output", qos: .userInitiated)
|
|
9
8
|
private let options: SpoofDetectorOutputOptions
|
|
10
9
|
private let delegate: SpoofDetectorDelegate
|
|
11
|
-
private let ciContext = CIContext(options: nil)
|
|
12
10
|
private let stateLock = NSLock()
|
|
13
11
|
private let targetSize = 256
|
|
14
12
|
private var isBusy = false
|
|
15
13
|
private var isDisposed = false
|
|
14
|
+
private var frameCounter = 0
|
|
15
|
+
private var lastFrameBrightness: Float = 0
|
|
16
16
|
|
|
17
17
|
let output = AVCaptureVideoDataOutput()
|
|
18
18
|
let requiresAudioInput = false
|
|
@@ -27,7 +27,10 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
var targetResolution: ResolutionRule {
|
|
30
|
-
|
|
30
|
+
let resolution = options.targetResolution.map {
|
|
31
|
+
margelo.nitro.camera.Size(width: $0.width, height: $0.height)
|
|
32
|
+
} ?? margelo.nitro.camera.Size(width: 720.0, height: 1280.0)
|
|
33
|
+
return .closestTo(resolution)
|
|
31
34
|
}
|
|
32
35
|
|
|
33
36
|
init(options: SpoofDetectorOutputOptions) {
|
|
@@ -35,6 +38,9 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
35
38
|
self.delegate = SpoofDetectorDelegate()
|
|
36
39
|
super.init()
|
|
37
40
|
|
|
41
|
+
output.videoSettings = [
|
|
42
|
+
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
|
|
43
|
+
]
|
|
38
44
|
delegate.onSampleBuffer = { [weak self] sampleBuffer in
|
|
39
45
|
self?.process(sampleBuffer)
|
|
40
46
|
}
|
|
@@ -63,7 +69,7 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
63
69
|
isBusy = true
|
|
64
70
|
stateLock.unlock()
|
|
65
71
|
|
|
66
|
-
guard let
|
|
72
|
+
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
|
|
67
73
|
stateLock.lock()
|
|
68
74
|
isBusy = false
|
|
69
75
|
stateLock.unlock()
|
|
@@ -71,69 +77,115 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
|
|
|
71
77
|
return
|
|
72
78
|
}
|
|
73
79
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
self.isBusy = false
|
|
79
|
-
self.stateLock.unlock()
|
|
80
|
-
}
|
|
80
|
+
CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly)
|
|
81
|
+
defer {
|
|
82
|
+
CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly)
|
|
83
|
+
}
|
|
81
84
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
neuralNetworkScore: result.neuralNetworkScore,
|
|
89
|
-
laplacianScore: result.laplacianScore,
|
|
90
|
-
combinedScore: result.combinedScore,
|
|
91
|
-
confidence: result.confidence
|
|
92
|
-
)
|
|
93
|
-
)
|
|
94
|
-
} catch {
|
|
95
|
-
self.options.onError?(error)
|
|
96
|
-
}
|
|
85
|
+
guard shouldProcessFrame(pixelBuffer),
|
|
86
|
+
let input = makeRGBInput(from: pixelBuffer) else {
|
|
87
|
+
stateLock.lock()
|
|
88
|
+
isBusy = false
|
|
89
|
+
stateLock.unlock()
|
|
90
|
+
return
|
|
97
91
|
}
|
|
98
|
-
}
|
|
99
92
|
|
|
100
|
-
|
|
101
|
-
|
|
93
|
+
defer {
|
|
94
|
+
stateLock.lock()
|
|
95
|
+
isBusy = false
|
|
96
|
+
stateLock.unlock()
|
|
97
|
+
}
|
|
102
98
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
99
|
+
do {
|
|
100
|
+
let result = try FaceAntiSpoofManager.process(input: input)
|
|
101
|
+
options.onResult(
|
|
102
|
+
AntiSpoofingResult(
|
|
103
|
+
isLive: result.isLive,
|
|
104
|
+
label: result.isLive ? "Live Face" : "Spoof Face",
|
|
105
|
+
neuralNetworkScore: result.neuralNetworkScore,
|
|
106
|
+
laplacianScore: result.laplacianScore,
|
|
107
|
+
combinedScore: result.combinedScore,
|
|
108
|
+
confidence: result.confidence
|
|
109
|
+
)
|
|
110
|
+
)
|
|
111
|
+
} catch {
|
|
112
|
+
options.onError?(error)
|
|
107
113
|
}
|
|
114
|
+
}
|
|
108
115
|
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
let
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
116
|
+
private func shouldProcessFrame(_ pixelBuffer: CVPixelBuffer) -> Bool {
|
|
117
|
+
frameCounter += 1
|
|
118
|
+
guard frameCounter % 3 == 0 else { return false }
|
|
119
|
+
|
|
120
|
+
let width = CVPixelBufferGetWidth(pixelBuffer)
|
|
121
|
+
let height = CVPixelBufferGetHeight(pixelBuffer)
|
|
122
|
+
let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
|
|
123
|
+
guard let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else { return false }
|
|
124
|
+
let bytes = baseAddress.assumingMemoryBound(to: UInt8.self)
|
|
125
|
+
let sampleStep = max(1, min(width, height) / 32)
|
|
126
|
+
var brightnessSum: Float = 0
|
|
127
|
+
var brightnessSquaredSum: Float = 0
|
|
128
|
+
var sampleCount: Float = 0
|
|
129
|
+
|
|
130
|
+
for y in stride(from: 0, to: height, by: sampleStep) {
|
|
131
|
+
for x in stride(from: 0, to: width, by: sampleStep) {
|
|
132
|
+
let offset = y * bytesPerRow + x * 4
|
|
133
|
+
let blue = Float(bytes[offset])
|
|
134
|
+
let green = Float(bytes[offset + 1])
|
|
135
|
+
let red = Float(bytes[offset + 2])
|
|
136
|
+
let luma = 0.299 * red + 0.587 * green + 0.114 * blue
|
|
137
|
+
brightnessSum += luma
|
|
138
|
+
brightnessSquaredSum += luma * luma
|
|
139
|
+
sampleCount += 1
|
|
140
|
+
}
|
|
127
141
|
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
142
|
+
|
|
143
|
+
guard sampleCount > 0 else { return false }
|
|
144
|
+
let average = brightnessSum / sampleCount
|
|
145
|
+
let variance = (brightnessSquaredSum / sampleCount) - (average * average)
|
|
146
|
+
let brightnessDelta = abs(average - lastFrameBrightness)
|
|
147
|
+
let isFirstSample = lastFrameBrightness == 0
|
|
148
|
+
lastFrameBrightness = average
|
|
149
|
+
|
|
150
|
+
return average >= 24 && average <= 220 && variance >= 1500 &&
|
|
151
|
+
(isFirstSample || brightnessDelta >= 8)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
private func makeRGBInput(from pixelBuffer: CVPixelBuffer) -> [Float]? {
|
|
155
|
+
guard CVPixelBufferGetPixelFormatType(pixelBuffer) == kCVPixelFormatType_32BGRA,
|
|
156
|
+
let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else { return nil }
|
|
157
|
+
|
|
158
|
+
let sourceWidth = CVPixelBufferGetWidth(pixelBuffer)
|
|
159
|
+
let sourceHeight = CVPixelBufferGetHeight(pixelBuffer)
|
|
160
|
+
let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
|
|
161
|
+
let bytes = baseAddress.assumingMemoryBound(to: UInt8.self)
|
|
162
|
+
var result = [Float](repeating: 0, count: targetSize * targetSize * 3)
|
|
163
|
+
let isQuarterTurn = outputOrientation == .right || outputOrientation == .left
|
|
164
|
+
let orientedWidth = isQuarterTurn ? sourceHeight : sourceWidth
|
|
165
|
+
let orientedHeight = isQuarterTurn ? sourceWidth : sourceHeight
|
|
166
|
+
|
|
167
|
+
for targetY in 0..<targetSize {
|
|
168
|
+
let orientedY = min(orientedHeight - 1, targetY * orientedHeight / targetSize)
|
|
169
|
+
for targetX in 0..<targetSize {
|
|
170
|
+
let orientedX = min(orientedWidth - 1, targetX * orientedWidth / targetSize)
|
|
171
|
+
let sourcePoint: (x: Int, y: Int)
|
|
172
|
+
switch outputOrientation {
|
|
173
|
+
case .right:
|
|
174
|
+
sourcePoint = (orientedY, sourceHeight - 1 - orientedX)
|
|
175
|
+
case .down:
|
|
176
|
+
sourcePoint = (sourceWidth - 1 - orientedX, sourceHeight - 1 - orientedY)
|
|
177
|
+
case .left:
|
|
178
|
+
sourcePoint = (sourceWidth - 1 - orientedY, orientedX)
|
|
179
|
+
default:
|
|
180
|
+
sourcePoint = (orientedX, orientedY)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
let source = sourcePoint.y * bytesPerRow + sourcePoint.x * 4
|
|
184
|
+
let destination = (targetY * targetSize + targetX) * 3
|
|
185
|
+
result[destination] = Float(bytes[source + 2]) / 255
|
|
186
|
+
result[destination + 1] = Float(bytes[source + 1]) / 255
|
|
187
|
+
result[destination + 2] = Float(bytes[source]) / 255
|
|
188
|
+
}
|
|
137
189
|
}
|
|
138
190
|
return result
|
|
139
191
|
}
|
|
@@ -150,15 +202,3 @@ private final class SpoofDetectorDelegate: NSObject, AVCaptureVideoDataOutputSam
|
|
|
150
202
|
onSampleBuffer?(sampleBuffer)
|
|
151
203
|
}
|
|
152
204
|
}
|
|
153
|
-
|
|
154
|
-
private extension CameraOrientation {
|
|
155
|
-
var exifOrientation: Int32 {
|
|
156
|
-
switch self {
|
|
157
|
-
case .up: return 1
|
|
158
|
-
case .right: return 6
|
|
159
|
-
case .down: return 3
|
|
160
|
-
case .left: return 8
|
|
161
|
-
@unknown default: return 1
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-native-vision-camera-spoof-detector",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.26",
|
|
4
4
|
"description": "High-performance face anti-spoofing and liveness detection module for React Native Vision Camera. Uses TensorFlow Lite with GPU acceleration and optimized YUV processing.",
|
|
5
5
|
"homepage": "https://github.com/dpraful/react-native-vision-camera-spoof-detector",
|
|
6
6
|
"repository": {
|