react-native-vision-camera-spoof-detector 1.2.8 → 1.2.9

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.
@@ -7,4 +7,8 @@ final class HybridSpoofDetectorFactory: HybridSpoofDetectorFactorySpec {
7
7
  {
8
8
  return HybridSpoofDetectorOutput(options: options)
9
9
  }
10
+
11
+ func resetSpoofDetectorOutput(output: any HybridCameraOutputSpec) throws {
12
+ (output as? HybridSpoofDetectorOutput)?.resetState()
13
+ }
10
14
  }
@@ -6,6 +6,13 @@ import Vision
6
6
  import VisionCamera
7
7
 
8
8
  final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutput {
9
+ private struct DetectedFace {
10
+ let observation: VNFaceObservation
11
+ let face: SpoofDetectedFace
12
+ let leftEye: CGPoint
13
+ let rightEye: CGPoint
14
+ }
15
+
9
16
  private let queue = DispatchQueue(label: "com.faceantispoof.output", qos: .userInitiated)
10
17
  private let options: SpoofDetectorOutputOptions
11
18
  private let delegate: SpoofDetectorDelegate
@@ -13,8 +20,6 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
13
20
  private let targetSize = 256
14
21
  private var isBusy = false
15
22
  private var isDisposed = false
16
- private var frameCounter = 0
17
- private var lastFrameBrightness: Float = 0
18
23
  private var captured = false
19
24
  private var stableCount = 0
20
25
  private var lastFaceBounds: SpoofDetectedFaceBounds?
@@ -25,12 +30,12 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
25
30
  private var lastFacesUpdateAt = 0.0
26
31
  private var lastResultUpdateAt = 0.0
27
32
 
28
- private var antispoofLevel: Double { options.antispoofLevel ?? 0.8 }
29
- private var stableFrames: Int { max(1, Int(options.stableFrames ?? 1)) }
30
- private var requiredLiveFrames: Int { max(1, Int(options.requiredLiveFrames ?? 1)) }
33
+ private var antispoofLevel: Double { options.antispoofLevel ?? 0.4 }
34
+ private var stableFrames: Int { max(1, Int(options.stableFrames ?? 3)) }
35
+ private var requiredLiveFrames: Int { max(1, Int(options.requiredLiveFrames ?? 3)) }
31
36
  private var laplacianThreshold: Double { options.laplacianThreshold ?? 2000 }
32
37
  private var maxNeuralSpoofScore: Double { options.maxNeuralSpoofScore ?? 0.1 }
33
- private var uiUpdateInterval: Double { max(0, options.uiUpdateIntervalMs ?? 500) / 1000 }
38
+ private var uiUpdateInterval: Double { max(0, options.uiUpdateIntervalMs ?? 100) / 1000 }
34
39
  private var isLowMemoryDevice: Bool {
35
40
  ProcessInfo.processInfo.physicalMemory <= 4 * 1024 * 1024 * 1024
36
41
  }
@@ -130,12 +135,12 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
130
135
  CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly)
131
136
  }
132
137
 
133
- if options.onFacesDetected != nil || options.onStableFaceDetected != nil {
134
- processDetectedFaces(detectFaces(pixelBuffer))
135
- }
138
+ let faces = detectFaces(pixelBuffer)
139
+ processDetectedFaces(faces.map(\.face))
136
140
 
137
- guard shouldProcessFrame(pixelBuffer),
138
- let input = makeRGBInput(from: pixelBuffer) else {
141
+ guard shouldProcessFrame(pixelBuffer), faces.count == 1,
142
+ let input = makeRGBInput(from: pixelBuffer, face: faces[0]) else {
143
+ invalidateLiveEvidence()
139
144
  stateLock.lock()
140
145
  isBusy = false
141
146
  stateLock.unlock()
@@ -161,6 +166,7 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
161
166
  )
162
167
  )
163
168
  } catch {
169
+ invalidateLiveEvidence()
164
170
  options.onError?(error)
165
171
  }
166
172
  }
@@ -174,8 +180,8 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
174
180
  }
175
181
  }
176
182
 
177
- private func detectFaces(_ pixelBuffer: CVPixelBuffer) -> [SpoofDetectedFace] {
178
- let request = VNDetectFaceRectanglesRequest()
183
+ private func detectFaces(_ pixelBuffer: CVPixelBuffer) -> [DetectedFace] {
184
+ let request = VNDetectFaceLandmarksRequest()
179
185
  do {
180
186
  try VNImageRequestHandler(
181
187
  cvPixelBuffer: pixelBuffer,
@@ -185,13 +191,31 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
185
191
 
186
192
  let width = CVPixelBufferGetWidth(pixelBuffer)
187
193
  let height = CVPixelBufferGetHeight(pixelBuffer)
188
- return (request.results ?? []).map { observation in
189
- SpoofDetectedFace(
190
- bounds: makeBufferBounds(
191
- from: observation.boundingBox,
192
- width: width,
193
- height: height
194
- )
194
+ let isQuarterTurn = outputOrientation == .right || outputOrientation == .left
195
+ let orientedWidth = isQuarterTurn ? height : width
196
+ let orientedHeight = isQuarterTurn ? width : height
197
+ return (request.results ?? []).compactMap { observation in
198
+ guard isEligibleFace(observation, width: orientedWidth, height: orientedHeight),
199
+ let landmarks = observation.landmarks,
200
+ let leftEye = landmarkCenter(landmarks.leftEye, in: observation.boundingBox),
201
+ let rightEye = landmarkCenter(landmarks.rightEye, in: observation.boundingBox) else {
202
+ return nil
203
+ }
204
+ let leftEyePoint = CGPoint(
205
+ x: leftEye.x * CGFloat(orientedWidth),
206
+ y: leftEye.y * CGFloat(orientedHeight)
207
+ )
208
+ let rightEyePoint = CGPoint(
209
+ x: rightEye.x * CGFloat(orientedWidth),
210
+ y: rightEye.y * CGFloat(orientedHeight)
211
+ )
212
+ return DetectedFace(
213
+ observation: observation,
214
+ face: SpoofDetectedFace(
215
+ bounds: makeBufferBounds(from: observation.boundingBox, width: width, height: height)
216
+ ),
217
+ leftEye: leftEyePoint,
218
+ rightEye: rightEyePoint
195
219
  )
196
220
  }
197
221
  } catch {
@@ -221,7 +245,6 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
221
245
  lastFacesUpdateAt = now
222
246
  options.onFacesDetected?(faces)
223
247
  }
224
- notifyStableFaceIfReady()
225
248
  }
226
249
 
227
250
  private func processAntiSpoofResult(_ result: AntiSpoofingResult) {
@@ -230,19 +253,12 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
230
253
  consecutiveLiveFrames = 0
231
254
  isLive = false
232
255
  } else {
233
- let targetPercent = Int((antispoofLevel * 100).rounded())
234
- let currentPercent = Int((result.confidence * 100).rounded())
235
- let combinedPercent = Int((result.combinedScore * 100).rounded())
236
- let meetsConfidence = currentPercent >= targetPercent ||
237
- result.confidence >= antispoofLevel ||
238
- combinedPercent >= targetPercent ||
239
- result.combinedScore >= antispoofLevel
240
- let meetsLaplacian = result.laplacianScore == 0 ||
241
- result.laplacianScore >= laplacianThreshold
256
+ let meetsConfidence = result.confidence >= antispoofLevel
257
+ let meetsLaplacian = result.laplacianScore >= laplacianThreshold
242
258
  if meetsConfidence && meetsLaplacian {
243
259
  consecutiveLiveFrames = min(requiredLiveFrames, consecutiveLiveFrames + 1)
244
260
  } else {
245
- consecutiveLiveFrames = max(0, consecutiveLiveFrames - 1)
261
+ consecutiveLiveFrames = 0
246
262
  }
247
263
  isLive = consecutiveLiveFrames >= requiredLiveFrames
248
264
  }
@@ -298,9 +314,6 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
298
314
  }
299
315
 
300
316
  private func shouldProcessFrame(_ pixelBuffer: CVPixelBuffer) -> Bool {
301
- frameCounter += 1
302
- guard frameCounter % 3 == 0 else { return false }
303
-
304
317
  let width = CVPixelBufferGetWidth(pixelBuffer)
305
318
  let height = CVPixelBufferGetHeight(pixelBuffer)
306
319
  let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
@@ -308,7 +321,6 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
308
321
  let bytes = baseAddress.assumingMemoryBound(to: UInt8.self)
309
322
  let sampleStep = max(1, min(width, height) / 32)
310
323
  var brightnessSum: Float = 0
311
- var brightnessSquaredSum: Float = 0
312
324
  var sampleCount: Float = 0
313
325
 
314
326
  for y in stride(from: 0, to: height, by: sampleStep) {
@@ -319,23 +331,16 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
319
331
  let red = Float(bytes[offset + 2])
320
332
  let luma = 0.299 * red + 0.587 * green + 0.114 * blue
321
333
  brightnessSum += luma
322
- brightnessSquaredSum += luma * luma
323
334
  sampleCount += 1
324
335
  }
325
336
  }
326
337
 
327
338
  guard sampleCount > 0 else { return false }
328
339
  let average = brightnessSum / sampleCount
329
- let variance = (brightnessSquaredSum / sampleCount) - (average * average)
330
- let brightnessDelta = abs(average - lastFrameBrightness)
331
- let isFirstSample = lastFrameBrightness == 0
332
- lastFrameBrightness = average
333
-
334
- return average >= 24 && average <= 220 && variance >= 1500 &&
335
- (isFirstSample || brightnessDelta >= 8)
340
+ return average >= 24 && average <= 220
336
341
  }
337
342
 
338
- private func makeRGBInput(from pixelBuffer: CVPixelBuffer) -> [Float]? {
343
+ private func makeRGBInput(from pixelBuffer: CVPixelBuffer, face: DetectedFace) -> [Float]? {
339
344
  guard CVPixelBufferGetPixelFormatType(pixelBuffer) == kCVPixelFormatType_32BGRA,
340
345
  let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else { return nil }
341
346
 
@@ -347,11 +352,23 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
347
352
  let isQuarterTurn = outputOrientation == .right || outputOrientation == .left
348
353
  let orientedWidth = isQuarterTurn ? sourceHeight : sourceWidth
349
354
  let orientedHeight = isQuarterTurn ? sourceWidth : sourceHeight
355
+ let box = face.observation.boundingBox
356
+ let faceWidth = box.width * CGFloat(orientedWidth)
357
+ let faceHeight = box.height * CGFloat(orientedHeight)
358
+ let cropSide = min(min(orientedWidth, orientedHeight), max(1, Int((max(faceWidth, faceHeight) * 1.4).rounded())))
359
+ let halfSide = CGFloat(cropSide) / 2
360
+ let centerX = min(max(box.midX * CGFloat(orientedWidth), halfSide), CGFloat(orientedWidth) - halfSide)
361
+ let centerY = min(max((1 - box.midY) * CGFloat(orientedHeight), halfSide), CGFloat(orientedHeight) - halfSide)
362
+ let eyeAngle = atan2(face.rightEye.y - face.leftEye.y, face.rightEye.x - face.leftEye.x)
363
+ let cosine = cos(eyeAngle)
364
+ let sine = sin(eyeAngle)
350
365
 
351
366
  for targetY in 0..<targetSize {
352
- let orientedY = min(orientedHeight - 1, targetY * orientedHeight / targetSize)
367
+ let cropY = (CGFloat(targetY) + 0.5) * CGFloat(cropSide) / CGFloat(targetSize) - halfSide
353
368
  for targetX in 0..<targetSize {
354
- let orientedX = min(orientedWidth - 1, targetX * orientedWidth / targetSize)
369
+ let cropX = (CGFloat(targetX) + 0.5) * CGFloat(cropSide) / CGFloat(targetSize) - halfSide
370
+ let orientedX = min(orientedWidth - 1, max(0, Int((centerX + cosine * cropX - sine * cropY).rounded())))
371
+ let orientedY = min(orientedHeight - 1, max(0, Int((centerY + sine * cropX + cosine * cropY).rounded())))
355
372
  let sourcePoint: (x: Int, y: Int)
356
373
  switch outputOrientation {
357
374
  case .right:
@@ -373,6 +390,40 @@ final class HybridSpoofDetectorOutput: HybridCameraOutputSpec, NativeCameraOutpu
373
390
  }
374
391
  return result
375
392
  }
393
+
394
+ private func isEligibleFace(_ face: VNFaceObservation, width: Int, height: Int) -> Bool {
395
+ guard width > 0, height > 0 else { return false }
396
+ let box = face.boundingBox
397
+ let marginX: CGFloat = 0.02
398
+ let marginY: CGFloat = 0.02
399
+ guard box.minX >= marginX, box.maxX <= 1 - marginX,
400
+ box.minY >= marginY, box.maxY <= 1 - marginY,
401
+ box.width >= 0.18, box.height >= 0.18,
402
+ abs(face.yaw?.doubleValue ?? 0) <= 25 * .pi / 180,
403
+ abs(face.roll?.doubleValue ?? 0) <= 25 * .pi / 180,
404
+ let landmarks = face.landmarks,
405
+ landmarks.leftEye != nil, landmarks.rightEye != nil,
406
+ landmarks.nose != nil, landmarks.outerLips != nil else {
407
+ return false
408
+ }
409
+ return true
410
+ }
411
+
412
+ private func landmarkCenter(_ landmark: VNFaceLandmarkRegion2D?, in box: CGRect) -> CGPoint? {
413
+ guard let points = landmark?.normalizedPoints, !points.isEmpty else { return nil }
414
+ let average = points.reduce(CGPoint.zero) { partial, point in
415
+ CGPoint(x: partial.x + point.x, y: partial.y + point.y)
416
+ }
417
+ let normalizedX = box.minX + average.x / CGFloat(points.count) * box.width
418
+ let normalizedY = 1 - (box.minY + average.y / CGFloat(points.count) * box.height)
419
+ return CGPoint(x: normalizedX, y: normalizedY)
420
+ }
421
+
422
+ private func invalidateLiveEvidence() {
423
+ consecutiveLiveFrames = 0
424
+ isLive = false
425
+ lastSpoofResult = nil
426
+ }
376
427
  }
377
428
 
378
429
  private final class SpoofDetectorDelegate: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-vision-camera-spoof-detector",
3
- "version": "1.2.8",
3
+ "version": "1.2.9",
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": {