react-native-vision-camera-spoof-detector 1.3.9 → 1.3.11

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.
@@ -42,34 +42,91 @@ public class FaceAntiSpoofManager: NSObject {
42
42
  public static var enableCpuFallback = true
43
43
  public static var forceCpuOnly = false
44
44
  public static var cpuThreadCount = 4
45
+ private static var classOutputIndex = 0
46
+ private static var leafMaskOutputIndex = 1
47
+ private static var grayBuffer = [Int](repeating: 0, count: 256 * 256)
45
48
  private static let interpreterLock = NSLock()
46
49
  #if canImport(TensorFlowLiteCMetal)
47
50
  private static var metalDelegate: IOSMetalDelegate?
48
51
  #endif
49
- #endif
50
-
51
- @objc public class func initializeModel() -> Bool {
52
- #if canImport(TensorFlowLite)
53
- if sharedInterpreter != nil { return true }
54
52
 
55
- // Look in main bundle then plugin bundle
56
- var modelPath = Bundle.main.path(
53
+ private class func modelPath() -> String? {
54
+ let mainBundlePath = Bundle.main.path(
57
55
  forResource: "FaceAntiSpoofing",
58
56
  ofType: "tflite",
59
57
  inDirectory: "lib/assets"
60
58
  ) ?? Bundle.main.path(forResource: "FaceAntiSpoofing", ofType: "tflite")
61
- if modelPath == nil {
62
- if let managerClass = NSClassFromString("FaceAntiSpoofManager") {
63
- let podBundle = Bundle(for: managerClass)
64
- modelPath = podBundle.path(
65
- forResource: "FaceAntiSpoofing",
66
- ofType: "tflite",
67
- inDirectory: "lib/assets"
68
- ) ?? podBundle.path(forResource: "FaceAntiSpoofing", ofType: "tflite")
69
- }
59
+ if let mainBundlePath {
60
+ return mainBundlePath
61
+ }
62
+
63
+ guard let managerClass = NSClassFromString("FaceAntiSpoofManager") else {
64
+ return nil
65
+ }
66
+ let podBundle = Bundle(for: managerClass)
67
+ return podBundle.path(
68
+ forResource: "FaceAntiSpoofing",
69
+ ofType: "tflite",
70
+ inDirectory: "lib/assets"
71
+ ) ?? podBundle.path(forResource: "FaceAntiSpoofing", ofType: "tflite")
72
+ }
73
+
74
+ private class func runInference(
75
+ inputData: Data,
76
+ interpreter: Interpreter
77
+ ) throws {
78
+ try interpreter.copy(inputData, toInputAt: 0)
79
+ try interpreter.invoke()
80
+ }
81
+
82
+ private class func resolveOutputIndices(for interpreter: Interpreter) throws {
83
+ let outputNames = try (0..<interpreter.outputTensorCount).map {
84
+ try interpreter.output(at: $0).name
85
+ }
86
+ guard outputNames.count >= 2 else {
87
+ throw NSError(domain: "FaceAntiSpoof", code: 6, userInfo: [
88
+ NSLocalizedDescriptionKey: "The model must provide class and leaf-mask output tensors"
89
+ ])
90
+ }
91
+ let classIndex = outputNames.firstIndex(of: "Identity") ?? 0
92
+ let maskIndex = outputNames.firstIndex(of: "Identity_1") ?? 1
93
+ guard classIndex != maskIndex else {
94
+ throw NSError(domain: "FaceAntiSpoof", code: 7, userInfo: [
95
+ NSLocalizedDescriptionKey: "The model class and leaf-mask outputs could not be distinguished"
96
+ ])
70
97
  }
98
+ classOutputIndex = classIndex
99
+ leafMaskOutputIndex = maskIndex
100
+ }
101
+
102
+ private class func switchToCpuInterpreter() throws -> Interpreter {
103
+ guard enableCpuFallback, let path = modelPath() else {
104
+ throw NSError(domain: "FaceAntiSpoof", code: 4, userInfo: [
105
+ NSLocalizedDescriptionKey: "CPU fallback is enabled but the model or fallback is unavailable"
106
+ ])
107
+ }
108
+
109
+ sharedInterpreter = nil
110
+ metalDelegate = nil
111
+ var options = Interpreter.Options()
112
+ options.threadCount = max(1, cpuThreadCount)
113
+ let interpreter = try Interpreter(modelPath: path, options: options)
114
+ try interpreter.allocateTensors()
115
+ try resolveOutputIndices(for: interpreter)
116
+ sharedInterpreter = interpreter
117
+ currentAccelerator = "CPU"
118
+ NSLog("[FaceAntiSpoof] Manager: switched to CPU inference")
119
+ return interpreter
120
+ }
121
+ #endif
122
+
123
+ @objc public class func initializeModel() -> Bool {
124
+ #if canImport(TensorFlowLite)
125
+ interpreterLock.lock()
126
+ defer { interpreterLock.unlock() }
127
+ if sharedInterpreter != nil { return true }
71
128
 
72
- guard let path = modelPath else {
129
+ guard let path = modelPath() else {
73
130
  NSLog("[FaceAntiSpoof] Manager: model not found")
74
131
  return false
75
132
  }
@@ -110,6 +167,9 @@ public class FaceAntiSpoofManager: NSObject {
110
167
  NSLog("[FaceAntiSpoof] Manager: CPU fallback enabled | Threads: \(threadCount)")
111
168
  }
112
169
  try sharedInterpreter?.allocateTensors()
170
+ if let interpreter = sharedInterpreter {
171
+ try resolveOutputIndices(for: interpreter)
172
+ }
113
173
  NSLog("[FaceAntiSpoof] Manager: Loaded model at \(path)")
114
174
  return true
115
175
  } catch {
@@ -142,7 +202,23 @@ public class FaceAntiSpoofManager: NSObject {
142
202
  }
143
203
 
144
204
  public class func process(input: [Float]) throws -> DetectionResult {
205
+ try input.withUnsafeBufferPointer { buffer in
206
+ try process(input: buffer)
207
+ }
208
+ }
209
+
210
+ public class func process(input: UnsafeBufferPointer<Float>) throws -> DetectionResult {
145
211
  #if canImport(TensorFlowLite)
212
+ guard input.count == 256 * 256 * 3 else {
213
+ throw NSError(domain: "FaceAntiSpoof", code: 5, userInfo: [
214
+ NSLocalizedDescriptionKey: "Expected a normalized 256x256 RGB input"
215
+ ])
216
+ }
217
+ guard let baseAddress = input.baseAddress else {
218
+ throw NSError(domain: "FaceAntiSpoof", code: 13, userInfo: [
219
+ NSLocalizedDescriptionKey: "Face image input buffer is empty"
220
+ ])
221
+ }
146
222
  if sharedInterpreter == nil && !initializeModel() {
147
223
  throw NSError(domain: "FaceAntiSpoof", code: 3, userInfo: [
148
224
  NSLocalizedDescriptionKey: "Unable to initialize the TensorFlow Lite interpreter"
@@ -152,25 +228,45 @@ public class FaceAntiSpoofManager: NSObject {
152
228
  interpreterLock.lock()
153
229
  defer { interpreterLock.unlock() }
154
230
 
155
- guard let interpreter = sharedInterpreter else {
231
+ guard var interpreter = sharedInterpreter else {
156
232
  throw NSError(domain: "FaceAntiSpoof", code: 1, userInfo: [
157
233
  NSLocalizedDescriptionKey: "Interpreter not available"
158
234
  ])
159
235
  }
160
236
 
161
- let inputData = input.withUnsafeBufferPointer { buffer in
162
- Data(buffer: buffer)
237
+ // The tensor copy is synchronous, so the input buffer remains valid for Data's lifetime.
238
+ let inputData = Data(
239
+ bytesNoCopy: UnsafeMutableRawPointer(mutating: baseAddress),
240
+ count: input.count * MemoryLayout<Float>.size,
241
+ deallocator: .none
242
+ )
243
+ do {
244
+ try runInference(inputData: inputData, interpreter: interpreter)
245
+ } catch {
246
+ #if canImport(TensorFlowLiteCMetal)
247
+ guard currentAccelerator == "GPU", enableCpuFallback, !forceCpuOnly else {
248
+ throw error
249
+ }
250
+ NSLog("[FaceAntiSpoof] Manager: Metal inference failed; retrying on CPU: \(error)")
251
+ interpreter = try switchToCpuInterpreter()
252
+ try runInference(inputData: inputData, interpreter: interpreter)
253
+ #else
254
+ throw error
255
+ #endif
163
256
  }
164
- try interpreter.copy(inputData, toInputAt: 0)
165
- try interpreter.invoke()
166
257
 
167
- let classOutput = try interpreter.output(at: 0).data.withUnsafeBytes { buffer in
258
+ let classOutput = try interpreter.output(at: classOutputIndex).data.withUnsafeBytes { buffer in
168
259
  Array(buffer.bindMemory(to: Float.self))
169
260
  }
170
- let maskOutput = try interpreter.output(at: 1).data.withUnsafeBytes { buffer in
261
+ let maskOutput = try interpreter.output(at: leafMaskOutputIndex).data.withUnsafeBytes { buffer in
171
262
  Array(buffer.bindMemory(to: Float.self))
172
263
  }
173
264
  let count = min(classOutput.count, maskOutput.count)
265
+ guard count > 0 else {
266
+ throw NSError(domain: "FaceAntiSpoof", code: 8, userInfo: [
267
+ NSLocalizedDescriptionKey: "The model returned empty output tensors"
268
+ ])
269
+ }
174
270
  let neuralScore = (0..<count).reduce(Float.zero) { total, index in
175
271
  total + abs(classOutput[index]) * maskOutput[index]
176
272
  }
@@ -190,27 +286,141 @@ public class FaceAntiSpoofManager: NSObject {
190
286
  #endif
191
287
  }
192
288
 
193
- private class func calculateLaplacianScore(_ input: [Float]) -> Int {
289
+ @objc(processFrameWithFrameData:width:height:rowStrides:pixelStrides:error:)
290
+ public class func processFrame(
291
+ frameData: NSArray,
292
+ width: NSNumber,
293
+ height: NSNumber,
294
+ rowStrides: NSArray,
295
+ pixelStrides: NSArray
296
+ ) throws -> NSDictionary {
297
+ guard isModelLoaded() else {
298
+ throw NSError(domain: "FaceAntiSpoof", code: 1, userInfo: [
299
+ NSLocalizedDescriptionKey: "Face anti-spoofing is not initialized"
300
+ ])
301
+ }
302
+ guard width.intValue > 0, height.intValue > 0,
303
+ frameData.count >= 3, rowStrides.count >= 3, pixelStrides.count >= 3 else {
304
+ throw NSError(domain: "FaceAntiSpoof", code: 9, userInfo: [
305
+ NSLocalizedDescriptionKey: "Expected positive frame dimensions and Y, U and V planes with strides"
306
+ ])
307
+ }
308
+
309
+ let planes = try (0..<3).map { planeIndex -> [UInt8] in
310
+ guard let plane = frameData[planeIndex] as? [NSNumber] else {
311
+ throw NSError(domain: "FaceAntiSpoof", code: 10, userInfo: [
312
+ NSLocalizedDescriptionKey: "Camera plane \(planeIndex) is invalid"
313
+ ])
314
+ }
315
+ return plane.map { UInt8(truncatingIfNeeded: $0.intValue) }
316
+ }
317
+ let yuvRowStrides = (0..<3).map {
318
+ (rowStrides[$0] as? NSNumber)?.intValue ?? 0
319
+ }
320
+ let yuvPixelStrides = (0..<3).map {
321
+ (pixelStrides[$0] as? NSNumber)?.intValue ?? 0
322
+ }
323
+ guard yuvRowStrides.allSatisfy({ $0 > 0 }),
324
+ yuvPixelStrides.allSatisfy({ $0 > 0 }) else {
325
+ throw NSError(domain: "FaceAntiSpoof", code: 11, userInfo: [
326
+ NSLocalizedDescriptionKey: "Camera plane row and pixel strides must be positive"
327
+ ])
328
+ }
329
+
330
+ let sourceWidth = width.intValue
331
+ let sourceHeight = height.intValue
332
+ var input = [Float](repeating: 0, count: 256 * 256 * 3)
333
+
334
+ func readSample(_ planeIndex: Int, _ x: Int, _ y: Int) throws -> Int {
335
+ let index = y * yuvRowStrides[planeIndex] + x * yuvPixelStrides[planeIndex]
336
+ guard index >= 0, index < planes[planeIndex].count else {
337
+ throw NSError(domain: "FaceAntiSpoof", code: 12, userInfo: [
338
+ NSLocalizedDescriptionKey: "Camera plane buffer is too small for the provided dimensions and strides"
339
+ ])
340
+ }
341
+ return Int(planes[planeIndex][index])
342
+ }
343
+
344
+ func readRGB(_ x: Int, _ y: Int) throws -> (red: Int, green: Int, blue: Int) {
345
+ let luma = Float(try readSample(0, x, y))
346
+ let u = Float(try readSample(1, x / 2, y / 2) - 128)
347
+ let v = Float(try readSample(2, x / 2, y / 2) - 128)
348
+ return (
349
+ min(255, max(0, Int(luma + 1.402 * v))),
350
+ min(255, max(0, Int(luma - 0.344 * u - 0.714 * v))),
351
+ min(255, max(0, Int(luma + 1.772 * u)))
352
+ )
353
+ }
354
+
355
+ func sampleRGB(_ x: Float, _ y: Float) throws -> (red: Float, green: Float, blue: Float) {
356
+ let boundedX = min(Float(sourceWidth - 1), max(0, x))
357
+ let boundedY = min(Float(sourceHeight - 1), max(0, y))
358
+ let x0 = Int(boundedX)
359
+ let y0 = Int(boundedY)
360
+ let x1 = min(x0 + 1, sourceWidth - 1)
361
+ let y1 = min(y0 + 1, sourceHeight - 1)
362
+ let xWeight = boundedX - Float(x0)
363
+ let yWeight = boundedY - Float(y0)
364
+ let topLeft = try readRGB(x0, y0)
365
+ let topRight = try readRGB(x1, y0)
366
+ let bottomLeft = try readRGB(x0, y1)
367
+ let bottomRight = try readRGB(x1, y1)
368
+
369
+ func interpolate(
370
+ _ channel: (Int, Int, Int) -> Int
371
+ ) -> Float {
372
+ let top = Float(channel(topLeft.red, topLeft.green, topLeft.blue)) * (1 - xWeight) +
373
+ Float(channel(topRight.red, topRight.green, topRight.blue)) * xWeight
374
+ let bottom = Float(channel(bottomLeft.red, bottomLeft.green, bottomLeft.blue)) * (1 - xWeight) +
375
+ Float(channel(bottomRight.red, bottomRight.green, bottomRight.blue)) * xWeight
376
+ return top * (1 - yWeight) + bottom * yWeight
377
+ }
378
+
379
+ return (
380
+ interpolate { red, _, _ in red },
381
+ interpolate { _, green, _ in green },
382
+ interpolate { _, _, blue in blue }
383
+ )
384
+ }
385
+
386
+ for targetY in 0..<256 {
387
+ let sourceY = (Float(targetY) + 0.5) * Float(sourceHeight) / 256 - 0.5
388
+ for targetX in 0..<256 {
389
+ let sourceX = (Float(targetX) + 0.5) * Float(sourceWidth) / 256 - 0.5
390
+ let rgb = try sampleRGB(sourceX, sourceY)
391
+ let offset = (targetY * 256 + targetX) * 3
392
+ input[offset] = rgb.red / 255
393
+ input[offset + 1] = rgb.green / 255
394
+ input[offset + 2] = rgb.blue / 255
395
+ }
396
+ }
397
+
398
+ let result = try process(input: input)
399
+ return [
400
+ "neuralNetworkScore": result.neuralNetworkScore,
401
+ "laplacianScore": result.laplacianScore,
402
+ "combinedScore": result.combinedScore,
403
+ "confidence": result.confidence
404
+ ] as NSDictionary
405
+ }
406
+
407
+ private class func calculateLaplacianScore(_ input: UnsafeBufferPointer<Float>) -> Int {
194
408
  let width = 256
195
409
  let height = 256
196
- var grey = [Int](repeating: 0, count: width * height)
197
410
  for index in 0..<(width * height) {
198
411
  let offset = index * 3
199
- grey[index] = Int(
412
+ grayBuffer[index] = Int(
200
413
  (0.299 * input[offset] + 0.587 * input[offset + 1] + 0.114 * input[offset + 2]) * 255
201
414
  )
202
415
  }
203
416
 
204
- let kernel = [[0, 1, 0], [1, -4, 1], [0, 1, 0]]
205
417
  var score = 0
206
418
  for y in 0..<(height - 2) {
419
+ let row = y * width
207
420
  for x in 0..<(width - 2) {
208
- var result = 0
209
- for ky in 0..<3 {
210
- for kx in 0..<3 {
211
- result += grey[(y + ky) * width + x + kx] * kernel[ky][kx]
212
- }
213
- }
421
+ let center = row + x + width + 1
422
+ let result = grayBuffer[center - width] + grayBuffer[center - 1] -
423
+ 4 * grayBuffer[center] + grayBuffer[center + 1] + grayBuffer[center + width]
214
424
  if result > 50 { score += 1 }
215
425
  }
216
426
  }
@@ -91,6 +91,33 @@ RCT_REMAP_METHOD(checkModelStatus,
91
91
  resolve(result);
92
92
  }
93
93
 
94
+ RCT_REMAP_METHOD(processFrame,
95
+ processFrameWithFrameData:(NSArray *)frameData
96
+ width:(nonnull NSNumber *)width
97
+ height:(nonnull NSNumber *)height
98
+ rowStrides:(NSArray *)rowStrides
99
+ pixelStrides:(NSArray *)pixelStrides
100
+ resolver:(RCTPromiseResolveBlock)resolve
101
+ rejecter:(RCTPromiseRejectBlock)reject)
102
+ {
103
+ Class managerClass = NSClassFromString(@"FaceAntiSpoofManager");
104
+ SEL selector = NSSelectorFromString(@"processFrameWithFrameData:width:height:rowStrides:pixelStrides:error:");
105
+ if (managerClass == Nil || ![managerClass respondsToSelector:selector]) {
106
+ reject(@"PROCESS_ERROR", @"Face anti-spoofing frame processor is unavailable", nil);
107
+ return;
108
+ }
109
+
110
+ NSError *error = nil;
111
+ NSDictionary *(*processFrame)(id, SEL, NSArray *, NSNumber *, NSNumber *, NSArray *, NSArray *, NSError **) =
112
+ (NSDictionary *(*)(id, SEL, NSArray *, NSNumber *, NSNumber *, NSArray *, NSArray *, NSError **))objc_msgSend;
113
+ NSDictionary *result = processFrame(managerClass, selector, frameData, width, height, rowStrides, pixelStrides, &error);
114
+ if (error != nil || result == nil) {
115
+ reject(@"PROCESS_ERROR", @"Failed to process camera frame", error);
116
+ return;
117
+ }
118
+ resolve(result);
119
+ }
120
+
94
121
  RCT_REMAP_METHOD(isAvailable,
95
122
  isAvailableWithResolver:(RCTPromiseResolveBlock)resolve
96
123
  rejecter:(RCTPromiseRejectBlock)reject)
@@ -103,14 +130,14 @@ RCT_REMAP_METHOD(testMethod,
103
130
  testMethodWithResolver:(RCTPromiseResolveBlock)resolve
104
131
  rejecter:(RCTPromiseRejectBlock)reject)
105
132
  {
106
- resolve(@"iOS native module is working!");
133
+ resolve(@"Native module is working!");
107
134
  }
108
135
 
109
136
  RCT_REMAP_METHOD(getModuleInfo,
110
137
  getModuleInfoWithResolver:(RCTPromiseResolveBlock)resolve
111
138
  rejecter:(RCTPromiseRejectBlock)reject)
112
139
  {
113
- NSDictionary *info = @{ @"name": @"FaceAntiSpoof", @"methods": @[@"initialize", @"checkModelStatus", @"isAvailable", @"testMethod", @"getModuleInfo", @"install", @"cleanup", @"getAccelerator"], @"accelerators": @[@"GPU", @"CPU"] };
140
+ NSDictionary *info = @{ @"name": @"FaceAntiSpoof", @"methods": @[@"initialize", @"checkModelStatus", @"processFrame", @"isAvailable", @"testMethod", @"getModuleInfo", @"install", @"cleanup", @"getAccelerator"], @"accelerators": @[@"GPU", @"CPU"] };
114
141
  resolve(info);
115
142
  }
116
143
 
@@ -16,8 +16,10 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
16
16
  private let queue = DispatchQueue(label: "com.faceantispoof.output", qos: .userInitiated)
17
17
  private let options: SpoofDetectorOutputOptions
18
18
  private let delegate: SpoofDetectorDelegate
19
+ private let faceDetectionRequest = VNDetectFaceLandmarksRequest()
19
20
  private let stateLock = NSLock()
20
21
  private let targetSize = 256
22
+ private var modelInput = [Float](repeating: 0, count: 256 * 256 * 3)
21
23
  private var isBusy = false
22
24
  private var isDisposed = false
23
25
  private var captured = false
@@ -78,7 +80,7 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
78
80
 
79
81
  func resetState() {
80
82
  queue.async { [weak self] in
81
- guard let self else { return }
83
+ guard let self, self.isActive() else { return }
82
84
  self.stateLock.lock()
83
85
  self.captured = false
84
86
  self.stableCount = 0
@@ -90,6 +92,12 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
90
92
  }
91
93
  }
92
94
 
95
+ private func isActive() -> Bool {
96
+ stateLock.lock()
97
+ defer { stateLock.unlock() }
98
+ return !isDisposed
99
+ }
100
+
93
101
  private func process(_ sampleBuffer: CMSampleBuffer) {
94
102
  stateLock.lock()
95
103
  guard !isDisposed, !isBusy else {
@@ -98,40 +106,52 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
98
106
  }
99
107
  isBusy = true
100
108
  stateLock.unlock()
101
-
102
- guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
109
+ defer {
103
110
  stateLock.lock()
104
111
  isBusy = false
105
112
  stateLock.unlock()
113
+ }
114
+
115
+ guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
106
116
  options.onError?(RuntimeError.error(withMessage: "Failed to create RGB frame input."))
107
117
  return
108
118
  }
109
119
 
110
- CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly)
120
+ let lockResult = CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly)
121
+ guard lockResult == kCVReturnSuccess else {
122
+ options.onError?(RuntimeError.error(withMessage: "Failed to lock camera frame buffer (\(lockResult))."))
123
+ return
124
+ }
111
125
  defer {
112
126
  CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly)
113
127
  }
114
128
 
115
- let faces = detectFaces(pixelBuffer)
129
+ let faces: [DetectedFace]
130
+ do {
131
+ faces = try detectFaces(pixelBuffer)
132
+ } catch {
133
+ invalidateLiveEvidence()
134
+ options.onError?(error)
135
+ return
136
+ }
137
+ guard isActive() else { return }
116
138
  processDetectedFaces(faces)
117
139
 
118
- guard shouldProcessFrame(pixelBuffer), faces.count == 1,
119
- let input = makeRGBInput(from: pixelBuffer, face: faces[0]) else {
140
+ guard shouldProcessFrame(pixelBuffer), faces.count == 1 else {
120
141
  invalidateLiveEvidence()
121
- stateLock.lock()
122
- isBusy = false
123
- stateLock.unlock()
124
142
  return
125
143
  }
126
-
127
- defer {
128
- stateLock.lock()
129
- isBusy = false
130
- stateLock.unlock()
144
+ guard makeRGBInput(from: pixelBuffer, face: faces[0], into: &modelInput) else {
145
+ invalidateLiveEvidence()
146
+ options.onError?(RuntimeError.error(withMessage: "Failed to prepare the face image for inference."))
147
+ return
131
148
  }
132
149
 
133
150
  do {
134
- let result = try FaceAntiSpoofManager.process(input: input)
151
+ let result = try modelInput.withUnsafeBufferPointer {
152
+ try FaceAntiSpoofManager.process(input: $0)
153
+ }
154
+ guard isActive() else { return }
135
155
  processAntiSpoofResult(
136
156
  AntiSpoofingResult(
137
157
  neuralNetworkScore: result.neuralNetworkScore,
@@ -155,47 +175,41 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
155
175
  }
156
176
  }
157
177
 
158
- private func detectFaces(_ pixelBuffer: CVPixelBuffer) -> [DetectedFace] {
159
- let request = VNDetectFaceLandmarksRequest()
160
- do {
161
- try VNImageRequestHandler(
162
- cvPixelBuffer: pixelBuffer,
163
- orientation: visionImageOrientation,
164
- options: [:]
165
- ).perform([request])
166
-
167
- let width = CVPixelBufferGetWidth(pixelBuffer)
168
- let height = CVPixelBufferGetHeight(pixelBuffer)
169
- let isQuarterTurn = outputOrientation == .right || outputOrientation == .left
170
- let orientedWidth = isQuarterTurn ? height : width
171
- let orientedHeight = isQuarterTurn ? width : height
172
- return (request.results ?? []).compactMap { observation in
173
- guard isEligibleFace(observation, width: orientedWidth, height: orientedHeight),
174
- let landmarks = observation.landmarks,
175
- let leftEye = landmarkCenter(landmarks.leftEye, in: observation.boundingBox),
176
- let rightEye = landmarkCenter(landmarks.rightEye, in: observation.boundingBox) else {
177
- return nil
178
- }
179
- let leftEyePoint = CGPoint(
180
- x: leftEye.x * CGFloat(orientedWidth),
181
- y: leftEye.y * CGFloat(orientedHeight)
182
- )
183
- let rightEyePoint = CGPoint(
184
- x: rightEye.x * CGFloat(orientedWidth),
185
- y: rightEye.y * CGFloat(orientedHeight)
186
- )
187
- return DetectedFace(
188
- observation: observation,
189
- face: SpoofDetectedFace(
190
- bounds: makeBufferBounds(from: observation.boundingBox, width: width, height: height)
191
- ),
192
- leftEye: leftEyePoint,
193
- rightEye: rightEyePoint
194
- )
178
+ private func detectFaces(_ pixelBuffer: CVPixelBuffer) throws -> [DetectedFace] {
179
+ try VNImageRequestHandler(
180
+ cvPixelBuffer: pixelBuffer,
181
+ orientation: visionImageOrientation,
182
+ options: [:]
183
+ ).perform([faceDetectionRequest])
184
+
185
+ let width = CVPixelBufferGetWidth(pixelBuffer)
186
+ let height = CVPixelBufferGetHeight(pixelBuffer)
187
+ let isQuarterTurn = outputOrientation == .right || outputOrientation == .left
188
+ let orientedWidth = isQuarterTurn ? height : width
189
+ let orientedHeight = isQuarterTurn ? width : height
190
+ return (faceDetectionRequest.results ?? []).compactMap { observation in
191
+ guard isEligibleFace(observation, width: orientedWidth, height: orientedHeight),
192
+ let landmarks = observation.landmarks,
193
+ let leftEye = landmarkCenter(landmarks.leftEye, in: observation.boundingBox),
194
+ let rightEye = landmarkCenter(landmarks.rightEye, in: observation.boundingBox) else {
195
+ return nil
195
196
  }
196
- } catch {
197
- options.onError?(error)
198
- return []
197
+ let leftEyePoint = CGPoint(
198
+ x: leftEye.x * CGFloat(orientedWidth),
199
+ y: leftEye.y * CGFloat(orientedHeight)
200
+ )
201
+ let rightEyePoint = CGPoint(
202
+ x: rightEye.x * CGFloat(orientedWidth),
203
+ y: rightEye.y * CGFloat(orientedHeight)
204
+ )
205
+ return DetectedFace(
206
+ observation: observation,
207
+ face: SpoofDetectedFace(
208
+ bounds: makeBufferBounds(from: observation.boundingBox, width: width, height: height)
209
+ ),
210
+ leftEye: leftEyePoint,
211
+ rightEye: rightEyePoint
212
+ )
199
213
  }
200
214
  }
201
215
 
@@ -329,55 +343,103 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
329
343
  return average >= 24 && average <= 220
330
344
  }
331
345
 
332
- private func makeRGBInput(from pixelBuffer: CVPixelBuffer, face: DetectedFace) -> [Float]? {
346
+ private func makeRGBInput(
347
+ from pixelBuffer: CVPixelBuffer,
348
+ face: DetectedFace,
349
+ into result: inout [Float]
350
+ ) -> Bool {
333
351
  guard CVPixelBufferGetPixelFormatType(pixelBuffer) == kCVPixelFormatType_32BGRA,
334
- let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else { return nil }
352
+ let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer),
353
+ result.count == targetSize * targetSize * 3 else { return false }
335
354
 
336
355
  let sourceWidth = CVPixelBufferGetWidth(pixelBuffer)
337
356
  let sourceHeight = CVPixelBufferGetHeight(pixelBuffer)
338
357
  let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
339
- let bytes = baseAddress.assumingMemoryBound(to: UInt8.self)
340
- var result = [Float](repeating: 0, count: targetSize * targetSize * 3)
341
358
  let isQuarterTurn = outputOrientation == .right || outputOrientation == .left
342
359
  let orientedWidth = isQuarterTurn ? sourceHeight : sourceWidth
343
360
  let orientedHeight = isQuarterTurn ? sourceWidth : sourceHeight
344
361
  let box = face.observation.boundingBox
345
362
  let faceWidth = box.width * CGFloat(orientedWidth)
346
363
  let faceHeight = box.height * CGFloat(orientedHeight)
347
- let cropSide = min(min(orientedWidth, orientedHeight), max(1, Int((max(faceWidth, faceHeight) * 1.4).rounded())))
364
+ let cropSide = min(
365
+ min(orientedWidth, orientedHeight),
366
+ max(1, Int(max(faceWidth, faceHeight) * 1.4))
367
+ )
348
368
  let halfSide = CGFloat(cropSide) / 2
349
369
  let centerX = min(max(box.midX * CGFloat(orientedWidth), halfSide), CGFloat(orientedWidth) - halfSide)
350
370
  let centerY = min(max((1 - box.midY) * CGFloat(orientedHeight), halfSide), CGFloat(orientedHeight) - halfSide)
351
- let eyeAngle = atan2(face.rightEye.y - face.leftEye.y, face.rightEye.x - face.leftEye.x)
352
- let cosine = cos(eyeAngle)
353
- let sine = sin(eyeAngle)
371
+ let cropLeft = min(orientedWidth - cropSide, max(0, Int(centerX - halfSide)))
372
+ let cropTop = min(orientedHeight - cropSide, max(0, Int(centerY - halfSide)))
373
+ let cropRight = cropLeft + cropSide - 1
374
+ let cropBottom = cropTop + cropSide - 1
375
+ let cropCenter = CGFloat(cropSide - 1) / 2
376
+ let rawEyeAngle = atan2(face.rightEye.y - face.leftEye.y, face.rightEye.x - face.leftEye.x)
377
+ let eyeAngle = abs(rawEyeAngle * 180 / .pi) >= 0.5 ? rawEyeAngle : 0
378
+ let cosine = Float(cos(eyeAngle))
379
+ let sine = Float(sin(eyeAngle))
380
+ let bytes = baseAddress.assumingMemoryBound(to: UInt8.self)
381
+ let cropCenterFloat = Float(cropCenter)
382
+ let cropLeftFloat = Float(cropLeft)
383
+ let cropTopFloat = Float(cropTop)
384
+ let cropRightFloat = Float(cropRight)
385
+ let cropBottomFloat = Float(cropBottom)
386
+ let sourceMaxX = Float(sourceWidth - 1)
387
+ let sourceMaxY = Float(sourceHeight - 1)
388
+ let cropOriginX = cropLeftFloat + cropCenterFloat
389
+ let cropOriginY = cropTopFloat + cropCenterFloat
390
+ let sampleScale = Float(cropSide) / Float(targetSize)
354
391
 
355
392
  for targetY in 0..<targetSize {
356
- let cropY = (CGFloat(targetY) + 0.5) * CGFloat(cropSide) / CGFloat(targetSize) - halfSide
393
+ let relativeY = (Float(targetY) + 0.5) * sampleScale - 0.5 - cropCenterFloat
394
+ let rowBaseX = cropOriginX - sine * relativeY
395
+ let rowBaseY = cropOriginY + cosine * relativeY
357
396
  for targetX in 0..<targetSize {
358
- let cropX = (CGFloat(targetX) + 0.5) * CGFloat(cropSide) / CGFloat(targetSize) - halfSide
359
- let orientedX = min(orientedWidth - 1, max(0, Int((centerX + cosine * cropX - sine * cropY).rounded())))
360
- let orientedY = min(orientedHeight - 1, max(0, Int((centerY + sine * cropX + cosine * cropY).rounded())))
361
- let sourcePoint: (x: Int, y: Int)
397
+ let relativeX = (Float(targetX) + 0.5) * sampleScale - 0.5 - cropCenterFloat
398
+ let orientedX = min(cropRightFloat, max(cropLeftFloat, rowBaseX + cosine * relativeX))
399
+ let orientedY = min(cropBottomFloat, max(cropTopFloat, rowBaseY + sine * relativeX))
400
+ let sourceX: Float
401
+ let sourceY: Float
362
402
  switch outputOrientation {
363
403
  case .right:
364
- sourcePoint = (orientedY, sourceHeight - 1 - orientedX)
404
+ sourceX = orientedY
405
+ sourceY = Float(sourceHeight - 1) - orientedX
365
406
  case .down:
366
- sourcePoint = (sourceWidth - 1 - orientedX, sourceHeight - 1 - orientedY)
407
+ sourceX = sourceMaxX - orientedX
408
+ sourceY = sourceMaxY - orientedY
367
409
  case .left:
368
- sourcePoint = (sourceWidth - 1 - orientedY, orientedX)
410
+ sourceX = sourceMaxX - orientedY
411
+ sourceY = orientedX
369
412
  default:
370
- sourcePoint = (orientedX, orientedY)
413
+ sourceX = orientedX
414
+ sourceY = orientedY
371
415
  }
372
416
 
373
- let source = sourcePoint.y * bytesPerRow + sourcePoint.x * 4
374
417
  let destination = (targetY * targetSize + targetX) * 3
375
- result[destination] = Float(bytes[source + 2]) / 255
376
- result[destination + 1] = Float(bytes[source + 1]) / 255
377
- result[destination + 2] = Float(bytes[source]) / 255
418
+ let boundedX = min(sourceMaxX, max(0, sourceX))
419
+ let boundedY = min(sourceMaxY, max(0, sourceY))
420
+ let x0 = Int(boundedX)
421
+ let y0 = Int(boundedY)
422
+ let x1 = min(x0 + 1, sourceWidth - 1)
423
+ let y1 = min(y0 + 1, sourceHeight - 1)
424
+ let xWeight = boundedX - Float(x0)
425
+ let yWeight = boundedY - Float(y0)
426
+ let topLeft = y0 * bytesPerRow + x0 * 4
427
+ let topRight = y0 * bytesPerRow + x1 * 4
428
+ let bottomLeft = y1 * bytesPerRow + x0 * 4
429
+ let bottomRight = y1 * bytesPerRow + x1 * 4
430
+
431
+ let topBlue = Float(bytes[topLeft]) * (1 - xWeight) + Float(bytes[topRight]) * xWeight
432
+ let bottomBlue = Float(bytes[bottomLeft]) * (1 - xWeight) + Float(bytes[bottomRight]) * xWeight
433
+ let topGreen = Float(bytes[topLeft + 1]) * (1 - xWeight) + Float(bytes[topRight + 1]) * xWeight
434
+ let bottomGreen = Float(bytes[bottomLeft + 1]) * (1 - xWeight) + Float(bytes[bottomRight + 1]) * xWeight
435
+ let topRed = Float(bytes[topLeft + 2]) * (1 - xWeight) + Float(bytes[topRight + 2]) * xWeight
436
+ let bottomRed = Float(bytes[bottomLeft + 2]) * (1 - xWeight) + Float(bytes[bottomRight + 2]) * xWeight
437
+ result[destination] = (topRed * (1 - yWeight) + bottomRed * yWeight) / 255
438
+ result[destination + 1] = (topGreen * (1 - yWeight) + bottomGreen * yWeight) / 255
439
+ result[destination + 2] = (topBlue * (1 - yWeight) + bottomBlue * yWeight) / 255
378
440
  }
379
441
  }
380
- return result
442
+ return true
381
443
  }
382
444
 
383
445
  private func isEligibleFace(_ face: VNFaceObservation, width: Int, height: Int) -> Bool {
@@ -30,7 +30,7 @@ namespace VisionCameraSpoofDetector { class HybridSpoofDetectorFactorySpec_cxx;
30
30
  // Include C++ defined types
31
31
  #include "AntiSpoofingResult.hpp"
32
32
  #include "HybridSpoofDetectorFactorySpec.hpp"
33
- #include "Size.hpp"
33
+ #include "SpoofDetectorSize.hpp"
34
34
  #include "SpoofDetectedFace.hpp"
35
35
  #include "SpoofDetectedFaceBounds.hpp"
36
36
  #include <NitroModules/Result.hpp>
@@ -26,7 +26,7 @@ namespace margelo::nitro::camera::spoofdetector { struct SpoofDetectorOutputOpti
26
26
  // Include C++ defined types
27
27
  #include "AntiSpoofingResult.hpp"
28
28
  #include "HybridSpoofDetectorFactorySpec.hpp"
29
- #include "Size.hpp"
29
+ #include "SpoofDetectorSize.hpp"
30
30
  #include "SpoofDetectedFace.hpp"
31
31
  #include "SpoofDetectedFaceBounds.hpp"
32
32
  #include "SpoofDetectorOutputOptions.hpp"
@@ -28,7 +28,7 @@ namespace margelo::nitro::camera::spoofdetector { struct SpoofDetectedFaceBounds
28
28
  #include <memory>
29
29
  #include <VisionCamera/HybridCameraOutputSpec.hpp>
30
30
  #include "SpoofDetectorOutputOptions.hpp"
31
- #include "Size.hpp"
31
+ #include "SpoofDetectorSize.hpp"
32
32
  #include <optional>
33
33
  #include "AntiSpoofingResult.hpp"
34
34
  #include <functional>
@@ -82,7 +82,6 @@ public extension SpoofDetectorOutputOptions {
82
82
  }())
83
83
  }
84
84
 
85
- @inline(__always)
86
85
  @inline(__always)
87
86
  var antispoofLevel: Double? {
88
87
  return { () -> Double? in
@@ -0,0 +1,7 @@
1
+ ///
2
+ /// SpoofDetectorSize.hpp
3
+ ///
4
+
5
+ #pragma once
6
+
7
+ #include "Size.hpp"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-vision-camera-spoof-detector",
3
- "version": "1.3.9",
3
+ "version": "1.3.11",
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": {