react-native-vision-camera-spoof-detector 1.1.11 → 1.1.15

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 (30) hide show
  1. package/VisionCameraSpoofDetector.podspec +41 -0
  2. package/ios/FaceAntiSpoofManager.swift +106 -4
  3. package/ios/FaceAntiSpoofModule.m +38 -51
  4. package/ios/HybridSpoofDetectorFactory.swift +10 -0
  5. package/ios/HybridSpoofDetectorOutput.swift +164 -0
  6. package/nitro.json +4 -0
  7. package/nitrogen/generated/ios/VisionCameraSpoofDetector+autolinking.rb +62 -0
  8. package/nitrogen/generated/ios/VisionCameraSpoofDetector-Swift-Cxx-Bridge.cpp +60 -0
  9. package/nitrogen/generated/ios/VisionCameraSpoofDetector-Swift-Cxx-Bridge.hpp +151 -0
  10. package/nitrogen/generated/ios/VisionCameraSpoofDetector-Swift-Cxx-Umbrella.hpp +60 -0
  11. package/nitrogen/generated/ios/VisionCameraSpoofDetectorAutolinking.mm +33 -0
  12. package/nitrogen/generated/ios/VisionCameraSpoofDetectorAutolinking.swift +26 -0
  13. package/nitrogen/generated/ios/c++/HybridSpoofDetectorFactorySpecSwift.cpp +11 -0
  14. package/nitrogen/generated/ios/c++/HybridSpoofDetectorFactorySpecSwift.hpp +97 -0
  15. package/nitrogen/generated/ios/swift/AntiSpoofingResult.swift +54 -0
  16. package/nitrogen/generated/ios/swift/Func_void_AntiSpoofingResult.swift +46 -0
  17. package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +46 -0
  18. package/nitrogen/generated/ios/swift/HybridSpoofDetectorFactorySpec.swift +56 -0
  19. package/nitrogen/generated/ios/swift/HybridSpoofDetectorFactorySpec_cxx.swift +142 -0
  20. package/nitrogen/generated/ios/swift/Size.swift +34 -0
  21. package/nitrogen/generated/ios/swift/SpoofDetectorOutputOptions.swift +74 -0
  22. package/package.json +8 -3
  23. package/src/specs/SpoofDetectorFactory.nitro.ts +1 -0
  24. package/ios/FaceAntiSpoofFrameProcessor.swift +0 -301
  25. package/ios/FaceAntiSpoofJSI.h +0 -12
  26. package/ios/FaceAntiSpoofJSI.mm +0 -92
  27. package/ios/FaceAntiSpoofPluginRegister.m +0 -84
  28. package/ios/models/FaceAntiSpoofing.tflite +0 -0
  29. package/react-native-vision-camera-spoof-detector.podspec +0 -22
  30. /package/{ios/models → lib/assets}/model_spec.json +0 -0
@@ -0,0 +1,142 @@
1
+ ///
2
+ /// HybridSpoofDetectorFactorySpec_cxx.swift
3
+ /// This file was generated by nitrogen. DO NOT MODIFY THIS FILE.
4
+ /// https://github.com/mrousavy/nitro
5
+ /// Copyright © Marc Rousavy @ Margelo
6
+ ///
7
+
8
+ import NitroModules
9
+ import VisionCamera
10
+
11
+ /**
12
+ * A class implementation that bridges HybridSpoofDetectorFactorySpec over to C++.
13
+ * In C++, we cannot use Swift protocols - so we need to wrap it in a class to make it strongly defined.
14
+ *
15
+ * Also, some Swift types need to be bridged with special handling:
16
+ * - Enums need to be wrapped in Structs, otherwise they cannot be accessed bi-directionally (Swift bug: https://github.com/swiftlang/swift/issues/75330)
17
+ * - Other HybridObjects need to be wrapped/unwrapped from the Swift TCxx wrapper
18
+ * - Throwing methods need to be wrapped with a Result<T, Error> type, as exceptions cannot be propagated to C++
19
+ */
20
+ open class HybridSpoofDetectorFactorySpec_cxx {
21
+ /**
22
+ * The Swift <> C++ bridge's namespace (`margelo::nitro::camera::spoofdetector::bridge::swift`)
23
+ * from `VisionCameraSpoofDetector-Swift-Cxx-Bridge.hpp`.
24
+ * This contains specialized C++ templates, and C++ helper functions that can be accessed from Swift.
25
+ */
26
+ public typealias bridge = margelo.nitro.camera.spoofdetector.bridge.swift
27
+
28
+ /**
29
+ * Holds an instance of the `HybridSpoofDetectorFactorySpec` Swift protocol.
30
+ */
31
+ private var __implementation: any HybridSpoofDetectorFactorySpec
32
+
33
+ /**
34
+ * Holds a weak pointer to the C++ class that wraps the Swift class.
35
+ */
36
+ private var __cxxPart: bridge.std__weak_ptr_HybridSpoofDetectorFactorySpec_
37
+
38
+ /**
39
+ * Create a new `HybridSpoofDetectorFactorySpec_cxx` that wraps the given `HybridSpoofDetectorFactorySpec`.
40
+ * All properties and methods bridge to C++ types.
41
+ */
42
+ public init(_ implementation: any HybridSpoofDetectorFactorySpec) {
43
+ self.__implementation = implementation
44
+ self.__cxxPart = .init()
45
+ /* no base class */
46
+ }
47
+
48
+ /**
49
+ * Get the actual `HybridSpoofDetectorFactorySpec` instance this class wraps.
50
+ */
51
+ @inline(__always)
52
+ public func getHybridSpoofDetectorFactorySpec() -> any HybridSpoofDetectorFactorySpec {
53
+ return __implementation
54
+ }
55
+
56
+ /**
57
+ * Casts this instance to a retained unsafe raw pointer.
58
+ * This acquires one additional strong reference on the object!
59
+ */
60
+ public func toUnsafe() -> UnsafeMutableRawPointer {
61
+ return Unmanaged.passRetained(self).toOpaque()
62
+ }
63
+
64
+ /**
65
+ * Casts an unsafe pointer to a `HybridSpoofDetectorFactorySpec_cxx`.
66
+ * The pointer has to be a retained opaque `Unmanaged<HybridSpoofDetectorFactorySpec_cxx>`.
67
+ * This removes one strong reference from the object!
68
+ */
69
+ public class func fromUnsafe(_ pointer: UnsafeMutableRawPointer) -> HybridSpoofDetectorFactorySpec_cxx {
70
+ return Unmanaged<HybridSpoofDetectorFactorySpec_cxx>.fromOpaque(pointer).takeRetainedValue()
71
+ }
72
+
73
+ /**
74
+ * Gets (or creates) the C++ part of this Hybrid Object.
75
+ * The C++ part is a `std::shared_ptr<HybridSpoofDetectorFactorySpec>`.
76
+ */
77
+ public func getCxxPart() -> bridge.std__shared_ptr_HybridSpoofDetectorFactorySpec_ {
78
+ let cachedCxxPart = self.__cxxPart.lock()
79
+ if Bool(fromCxx: cachedCxxPart) {
80
+ return cachedCxxPart
81
+ } else {
82
+ let newCxxPart = bridge.create_std__shared_ptr_HybridSpoofDetectorFactorySpec_(self.toUnsafe())
83
+ __cxxPart = bridge.weakify_std__shared_ptr_HybridSpoofDetectorFactorySpec_(newCxxPart)
84
+ return newCxxPart
85
+ }
86
+ }
87
+
88
+
89
+
90
+ /**
91
+ * Get the memory size of the Swift class (plus size of any other allocations)
92
+ * so the JS VM can properly track it and garbage-collect the JS object if needed.
93
+ */
94
+ @inline(__always)
95
+ public var memorySize: Int {
96
+ return MemoryHelper.getSizeOf(self.__implementation) + self.__implementation.memorySize
97
+ }
98
+
99
+ /**
100
+ * Compares this object with the given [other] object for reference equality.
101
+ */
102
+ @inline(__always)
103
+ public func equals(other: HybridSpoofDetectorFactorySpec_cxx) -> Bool {
104
+ return self.__implementation === other.__implementation
105
+ }
106
+
107
+ /**
108
+ * Call dispose() on the Swift class.
109
+ * This _may_ be called manually from JS.
110
+ */
111
+ @inline(__always)
112
+ public func dispose() {
113
+ self.__implementation.dispose()
114
+ }
115
+
116
+ /**
117
+ * Call toString() on the Swift class.
118
+ */
119
+ @inline(__always)
120
+ public func toString() -> String {
121
+ return self.__implementation.toString()
122
+ }
123
+
124
+ // Properties
125
+
126
+
127
+ // Methods
128
+ @inline(__always)
129
+ public final func createSpoofDetectorOutput(options: SpoofDetectorOutputOptions) -> bridge.Result_std__shared_ptr_margelo__nitro__camera__HybridCameraOutputSpec__ {
130
+ do {
131
+ let __result = try self.__implementation.createSpoofDetectorOutput(options: options)
132
+ let __resultCpp = { () -> bridge.std__shared_ptr_margelo__nitro__camera__HybridCameraOutputSpec_ in
133
+ let __cxxWrapped = __result.getCxxWrapper()
134
+ return __cxxWrapped.getCxxPart()
135
+ }()
136
+ return bridge.create_Result_std__shared_ptr_margelo__nitro__camera__HybridCameraOutputSpec__(__resultCpp)
137
+ } catch (let __error) {
138
+ let __exceptionPtr = __error.toCpp()
139
+ return bridge.create_Result_std__shared_ptr_margelo__nitro__camera__HybridCameraOutputSpec__(__exceptionPtr)
140
+ }
141
+ }
142
+ }
@@ -0,0 +1,34 @@
1
+ ///
2
+ /// Size.swift
3
+ /// This file was generated by nitrogen. DO NOT MODIFY THIS FILE.
4
+ /// https://github.com/mrousavy/nitro
5
+ /// Copyright © Marc Rousavy @ Margelo
6
+ ///
7
+
8
+ import NitroModules
9
+
10
+ /**
11
+ * Represents an instance of `Size`, backed by a C++ struct.
12
+ */
13
+ public typealias Size = margelo.nitro.camera.spoofdetector.Size
14
+
15
+ public extension Size {
16
+ private typealias bridge = margelo.nitro.camera.spoofdetector.bridge.swift
17
+
18
+ /**
19
+ * Create a new instance of `Size`.
20
+ */
21
+ init(width: Double, height: Double) {
22
+ self.init(width, height)
23
+ }
24
+
25
+ @inline(__always)
26
+ var width: Double {
27
+ return self.__width
28
+ }
29
+
30
+ @inline(__always)
31
+ var height: Double {
32
+ return self.__height
33
+ }
34
+ }
@@ -0,0 +1,74 @@
1
+ ///
2
+ /// SpoofDetectorOutputOptions.swift
3
+ /// This file was generated by nitrogen. DO NOT MODIFY THIS FILE.
4
+ /// https://github.com/mrousavy/nitro
5
+ /// Copyright © Marc Rousavy @ Margelo
6
+ ///
7
+
8
+ import NitroModules
9
+
10
+ /**
11
+ * Represents an instance of `SpoofDetectorOutputOptions`, backed by a C++ struct.
12
+ */
13
+ public typealias SpoofDetectorOutputOptions = margelo.nitro.camera.spoofdetector.SpoofDetectorOutputOptions
14
+
15
+ public extension SpoofDetectorOutputOptions {
16
+ private typealias bridge = margelo.nitro.camera.spoofdetector.bridge.swift
17
+
18
+ /**
19
+ * Create a new instance of `SpoofDetectorOutputOptions`.
20
+ */
21
+ init(targetResolution: Size?, onResult: @escaping (_ result: AntiSpoofingResult) -> Void, onError: ((_ error: Error) -> Void)?) {
22
+ self.init({ () -> bridge.std__optional_Size_ in
23
+ if let __unwrappedValue = targetResolution {
24
+ return bridge.create_std__optional_Size_(__unwrappedValue)
25
+ } else {
26
+ return .init()
27
+ }
28
+ }(), { () -> bridge.Func_void_AntiSpoofingResult in
29
+ let __closureWrapper = Func_void_AntiSpoofingResult(onResult)
30
+ return bridge.create_Func_void_AntiSpoofingResult(__closureWrapper.toUnsafe())
31
+ }(), { () -> bridge.std__optional_std__function_void_const_std__exception_ptr_____error______ in
32
+ if let __unwrappedValue = onError {
33
+ return bridge.create_std__optional_std__function_void_const_std__exception_ptr_____error______({ () -> bridge.Func_void_std__exception_ptr in
34
+ let __closureWrapper = Func_void_std__exception_ptr(__unwrappedValue)
35
+ return bridge.create_Func_void_std__exception_ptr(__closureWrapper.toUnsafe())
36
+ }())
37
+ } else {
38
+ return .init()
39
+ }
40
+ }())
41
+ }
42
+
43
+ @inline(__always)
44
+ var targetResolution: Size? {
45
+ return self.__targetResolution.value
46
+ }
47
+
48
+ @inline(__always)
49
+ var onResult: (_ result: AntiSpoofingResult) -> Void {
50
+ return { () -> (AntiSpoofingResult) -> Void in
51
+ let __wrappedFunction = bridge.wrap_Func_void_AntiSpoofingResult(self.__onResult)
52
+ return { (__result: AntiSpoofingResult) -> Void in
53
+ __wrappedFunction.call(__result)
54
+ }
55
+ }()
56
+ }
57
+
58
+ @inline(__always)
59
+ var onError: ((_ error: Error) -> Void)? {
60
+ return { () -> ((_ error: Error) -> Void)? in
61
+ if bridge.has_value_std__optional_std__function_void_const_std__exception_ptr_____error______(self.__onError) {
62
+ let __unwrapped = bridge.get_std__optional_std__function_void_const_std__exception_ptr_____error______(self.__onError)
63
+ return { () -> (Error) -> Void in
64
+ let __wrappedFunction = bridge.wrap_Func_void_std__exception_ptr(__unwrapped)
65
+ return { (__error: Error) -> Void in
66
+ __wrappedFunction.call(__error.toCpp())
67
+ }
68
+ }()
69
+ } else {
70
+ return nil
71
+ }
72
+ }()
73
+ }
74
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-vision-camera-spoof-detector",
3
- "version": "1.1.11",
3
+ "version": "1.1.15",
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": {
@@ -27,18 +27,22 @@
27
27
  "react-native": "index.js",
28
28
  "types": "index.d.ts",
29
29
  "files": [
30
- "android/",
30
+ "android/build.gradle",
31
+ "android/CMakeLists.txt",
32
+ "android/fix-prefab.gradle",
33
+ "android/src/",
31
34
  "lib/",
32
35
  "src/",
33
36
  "nitrogen/",
34
37
  "nitro.json",
35
38
  "ios/",
36
39
  ".npmignore",
40
+ ".gitignore",
37
41
  "CHANGELOG.md",
38
42
  "index.d.ts",
39
43
  "index.js",
40
44
  "LICENSE",
41
- "react-native-vision-camera-spoof-detector.podspec",
45
+ "VisionCameraSpoofDetector.podspec",
42
46
  "README.md"
43
47
  ],
44
48
  "keywords": [
@@ -63,6 +67,7 @@
63
67
  "react-native": ">=0.60.0",
64
68
  "react-native-vision-camera": "^5.0.0",
65
69
  "react-native-vision-camera-worklets": "^5.0.0",
70
+ "react-native-nitro-modules": "^0.37.1",
66
71
  "react-native-worklets": "^0.12.0"
67
72
  },
68
73
  "peerDependenciesMeta": {
@@ -17,6 +17,7 @@ export interface SpoofDetectorOutputOptions {
17
17
  }
18
18
 
19
19
  export interface SpoofDetectorFactory extends HybridObject<{
20
+ ios: 'swift'
20
21
  android: 'kotlin'
21
22
  }> {
22
23
  createSpoofDetectorOutput(options: SpoofDetectorOutputOptions): CameraOutput
@@ -1,301 +0,0 @@
1
- import Foundation
2
-
3
- #if canImport(VisionCamera)
4
- import VisionCamera
5
- import AVFoundation
6
- import CoreImage
7
- import UIKit
8
- import Accelerate
9
-
10
- #if canImport(TensorFlowLite)
11
- import TensorFlowLite
12
- #endif
13
-
14
- typealias FaceAntiSpoofFrameType = VisionCamera.Frame
15
- typealias FaceAntiSpoofProxyType = VisionCamera.VisionCameraProxyHolder
16
- typealias FaceAntiSpoofPluginBase = VisionCamera.FrameProcessorPlugin
17
-
18
- @objc(FaceAntiSpoofFrameProcessor)
19
- class FaceAntiSpoofFrameProcessor: FaceAntiSpoofPluginBase {
20
- private weak var proxyHolder: FaceAntiSpoofProxyType?
21
-
22
- // Processing state
23
- private let processingQueue = DispatchQueue(label: "com.faceantispoof.processing", qos: .userInitiated)
24
- private var isProcessing: Bool = false
25
- private var latestResult: [String: Any] = ["error": "Not initialized", "isLive": false, "label": "Not Initialized"]
26
- private static let INPUT_IMAGE_SIZE: Int = 256
27
- private static let BASE_THRESHOLD: Float = 0.2
28
- private static let LAPLACE_THRESHOLD: Int = 50
29
- private static let LAPLACIAN_THRESHOLD: Int = 4000
30
-
31
- #if canImport(TensorFlowLite)
32
- // Interpreter is provided by FaceAntiSpoofManager.sharedInterpreter
33
- #endif
34
-
35
- override init(
36
- proxy: FaceAntiSpoofProxyType,
37
- options: [AnyHashable : Any]! = [:]
38
- ) {
39
- #if canImport(VisionCamera)
40
- super.init(proxy: proxy, options: options)
41
- #else
42
- super.init(proxy: proxy, options: options as NSDictionary?)
43
- #endif
44
- self.proxyHolder = proxy
45
-
46
- #if canImport(TensorFlowLite)
47
- let managerInited = FaceAntiSpoofManager.initializeModel()
48
- if managerInited {
49
- NSLog("[FaceAntiSpoof] Manager initialized model")
50
- } else {
51
- NSLog("[FaceAntiSpoof] Manager failed to initialize model; running stub")
52
- }
53
- #else
54
- NSLog("[FaceAntiSpoof] TensorFlowLite not available; running stub")
55
- #endif
56
- }
57
-
58
- deinit {
59
- NSLog("[FaceAntiSpoof] deinit - releasing resources")
60
- self.proxyHolder = nil
61
- }
62
-
63
- override func callback(
64
- _ frame: FaceAntiSpoofFrameType,
65
- withArguments arguments: [AnyHashable : Any]?
66
- ) -> Any {
67
- #if canImport(TensorFlowLite)
68
- guard FaceAntiSpoofManager.isModelLoaded() else {
69
- return ["error": "Model not loaded", "isLive": false, "label": "stub"]
70
- }
71
-
72
- let sampleBuffer = frame.buffer
73
- guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
74
- return ["error": "No pixel buffer", "isLive": false, "label": "stub"]
75
- }
76
-
77
- let width = CVPixelBufferGetWidth(pixelBuffer)
78
- let height = CVPixelBufferGetHeight(pixelBuffer)
79
-
80
- // If processing already in flight, return latest cached result immediately
81
- var shouldReturnLatest = false
82
- objc_sync_enter(self)
83
- if isProcessing {
84
- shouldReturnLatest = true
85
- } else {
86
- isProcessing = true
87
- }
88
- objc_sync_exit(self)
89
-
90
- if shouldReturnLatest {
91
- return latestResult
92
- }
93
-
94
- // Capture a small, resized RGB float snapshot synchronously while the pixel buffer is valid
95
- let targetSize = CGSize(width: Self.INPUT_IMAGE_SIZE, height: Self.INPUT_IMAGE_SIZE)
96
- guard let rgbInput = Self.rgbFloatData(from: pixelBuffer, orientation: frame.orientation, size: targetSize) else {
97
- objc_sync_enter(self)
98
- isProcessing = false
99
- objc_sync_exit(self)
100
- latestResult = ["error": "Failed to create RGB snapshot", "isLive": false, "label": "error"]
101
- return latestResult
102
- }
103
-
104
- // Offload heavy model work to a background queue
105
- processingQueue.async { [weak self] in
106
- guard let self = self else { return }
107
- defer {
108
- objc_sync_enter(self)
109
- self.isProcessing = false
110
- objc_sync_exit(self)
111
- }
112
-
113
- guard let interpreter = FaceAntiSpoofManager.sharedInterpreter else {
114
- self.latestResult = ["error": "Interpreter not available", "isLive": false, "label": "error"]
115
- return
116
- }
117
-
118
- do {
119
- // Prepare input Data (Float32 little-endian)
120
- var inputFloats = rgbInput
121
- let inputData = Data(bytes: &inputFloats, count: inputFloats.count * MemoryLayout<Float>.size)
122
-
123
- try interpreter.copy(inputData, toInputAt: 0)
124
- try interpreter.invoke()
125
-
126
- // Read outputs (assume indices 0 and 1 correspond to clssPred and leafNodeMask)
127
- let out0 = try interpreter.output(at: 0)
128
- let out1 = try interpreter.output(at: 1)
129
-
130
- let clssPred: [Float] = out0.data.withUnsafeBytes { ptr in
131
- let floatPtr = ptr.bindMemory(to: Float.self)
132
- return Array(floatPtr)
133
- }
134
- let leafMask: [Float] = out1.data.withUnsafeBytes { ptr in
135
- let floatPtr = ptr.bindMemory(to: Float.self)
136
- return Array(floatPtr)
137
- }
138
-
139
- // Compute neural network score similar to Android leafScore1
140
- let count = min(clssPred.count, leafMask.count)
141
- var nnScore: Float = 0.0
142
- for i in 0..<count {
143
- nnScore += abs(clssPred[i]) * leafMask[i]
144
- }
145
-
146
- // Laplacian score computed from the RGB snapshot (resized)
147
- let lapScore = Self.calculateLaplacianScore(from: rgbInput, width: Self.INPUT_IMAGE_SIZE, height: Self.INPUT_IMAGE_SIZE)
148
-
149
- let combined = Self.calculateCombinedScore(neuralScore: nnScore, laplacianScore: lapScore)
150
- let confidence = Self.calculateConfidence(neuralScore: nnScore, laplacianScore: lapScore)
151
- let isLive = nnScore < Self.BASE_THRESHOLD && lapScore > Self.LAPLACIAN_THRESHOLD
152
-
153
- self.latestResult = [
154
- "neuralNetworkScore": Double(nnScore),
155
- "laplacianScore": lapScore,
156
- "combinedScore": Double(combined),
157
- "confidence": Double(confidence),
158
- "isLive": isLive,
159
- "label": isLive ? "live" : "spoof",
160
- "width": width,
161
- "height": height
162
- ]
163
- } catch {
164
- self.latestResult = ["error": "Processing error: \(error)", "isLive": false, "label": "error"]
165
- }
166
- }
167
-
168
- // Return latest result immediately (may be previous or initial)
169
- return latestResult
170
- #else
171
- return ["error": "TensorFlowLite not available", "isLive": false, "label": "stub"]
172
- #endif
173
- }
174
-
175
- // MARK: - Helpers
176
- #if canImport(TensorFlowLite)
177
- private static func floatArray(from data: Data) -> [Float] {
178
- let count = data.count / MemoryLayout<Float>.size
179
- return data.withUnsafeBytes { buffer -> [Float] in
180
- let ptr = buffer.bindMemory(to: Float.self)
181
- return Array(UnsafeBufferPointer(start: ptr.baseAddress, count: count))
182
- }
183
- }
184
-
185
- private static let sharedCIContext: CIContext = CIContext(options: nil)
186
-
187
- private static func rgbFloatData(from pixelBuffer: CVPixelBuffer, orientation: UIImage.Orientation, size: CGSize) -> [Float]? {
188
- CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly)
189
- defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly) }
190
-
191
- let image = CIImage(cvPixelBuffer: pixelBuffer)
192
- let exifOrientation: CGImagePropertyOrientation
193
- switch orientation {
194
- case .up, .upMirrored:
195
- exifOrientation = .up
196
- case .right, .rightMirrored:
197
- exifOrientation = .right
198
- case .down, .downMirrored:
199
- exifOrientation = .down
200
- case .left, .leftMirrored:
201
- exifOrientation = .left
202
- @unknown default:
203
- exifOrientation = .up
204
- }
205
- let ciImage = image.oriented(forExifOrientation: Int32(exifOrientation.rawValue))
206
- let context = Self.sharedCIContext
207
- guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else { return nil }
208
-
209
- let width = Int(size.width)
210
- let height = Int(size.height)
211
- let colorSpace = CGColorSpaceCreateDeviceRGB()
212
- var rawData = [UInt8](repeating: 0, count: width * height * 4)
213
- rawData.withUnsafeMutableBytes { ptr in
214
- if let base = ptr.baseAddress {
215
- let bytesPerRow = width * 4
216
- if let ctx = CGContext(data: base,
217
- width: width,
218
- height: height,
219
- bitsPerComponent: 8,
220
- bytesPerRow: bytesPerRow,
221
- space: colorSpace,
222
- bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) {
223
- ctx.interpolationQuality = .high
224
- ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
225
- }
226
- }
227
- }
228
-
229
- var floatData = [Float](repeating: 0, count: width * height * 3)
230
- var idx = 0
231
- for y in 0..<height {
232
- for x in 0..<width {
233
- let pixelIndex = (y * width + x) * 4
234
- let r = Float(rawData[pixelIndex]) / 255.0
235
- let g = Float(rawData[pixelIndex + 1]) / 255.0
236
- let b = Float(rawData[pixelIndex + 2]) / 255.0
237
- floatData[idx] = r
238
- floatData[idx + 1] = g
239
- floatData[idx + 2] = b
240
- idx += 3
241
- }
242
- }
243
- return floatData
244
- }
245
-
246
- private static func calculateLaplacianScore(from rgbData: [Float], width: Int, height: Int) -> Int {
247
- var grey = [Int](repeating: 0, count: width * height)
248
- var i = 0
249
- for y in 0..<height {
250
- for x in 0..<width {
251
- let base = (y * width + x) * 3
252
- let r = Int((rgbData[base] * 255).rounded())
253
- let g = Int((rgbData[base + 1] * 255).rounded())
254
- let b = Int((rgbData[base + 2] * 255).rounded())
255
- let value = Int(0.299 * Float(r) + 0.587 * Float(g) + 0.114 * Float(b))
256
- grey[i] = value
257
- i += 1
258
- }
259
- }
260
-
261
- let laplace = [[0,1,0],[1,-4,1],[0,1,0]]
262
- let size = 3
263
- var score = 0
264
- let threshold = Self.LAPLACE_THRESHOLD
265
- for y in 0..<(height - size + 1) {
266
- for x in 0..<(width - size + 1) {
267
- var result = 0
268
- for ky in 0..<size {
269
- for kx in 0..<size {
270
- result += grey[(y + ky) * width + (x + kx)] * laplace[ky][kx]
271
- }
272
- }
273
- if result > threshold {
274
- score += 1
275
- }
276
- }
277
- }
278
- return score
279
- }
280
-
281
- private static func calculateCombinedScore(neuralScore: Float, laplacianScore: Int) -> Float {
282
- let normalizedNeural = min(max(neuralScore, 0), 1)
283
- let normalizedLaplacian = min(max(Float(laplacianScore) / Float(Self.LAPLACIAN_THRESHOLD), 0), 1)
284
- let neuralWeight: Float = 0.6
285
- let laplacianWeight: Float = 0.4
286
- let invertedNeural = 1.0 - normalizedNeural
287
- return (invertedNeural * neuralWeight) + (normalizedLaplacian * laplacianWeight)
288
- }
289
-
290
- private static func calculateConfidence(neuralScore: Float, laplacianScore: Int) -> Float {
291
- let neuralConfidence = min(max(neuralScore, 0), 1)
292
- let laplacianConfidence = min(max(Float(laplacianScore) / Float(Self.LAPLACIAN_THRESHOLD), 0), 1)
293
- let invertedNeural = 1.0 - neuralConfidence
294
- return (invertedNeural * 0.6 + laplacianConfidence * 0.4)
295
- }
296
- #endif
297
- }
298
-
299
- #endif
300
-
301
-
@@ -1,12 +0,0 @@
1
- // Simple header for JSI install stub
2
- #import <Foundation/Foundation.h>
3
-
4
- #ifdef __cplusplus
5
- extern "C" {
6
- #endif
7
-
8
- void FaceAntiSpoofJSI_install(void *runtimePtr);
9
-
10
- #ifdef __cplusplus
11
- }
12
- #endif