react-native-face-match-sdk 0.0.0-stage → 1.0.3

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 (59) hide show
  1. package/FaceMatch.podspec +55 -0
  2. package/LICENSE +21 -0
  3. package/README.md +190 -2
  4. package/android/build.gradle +59 -0
  5. package/android/consumer-rules.pro +5 -0
  6. package/android/src/main/AndroidManifest.xml +11 -0
  7. package/android/src/main/java/com/facematch/sdk/AntiSpoofHelper.kt +216 -0
  8. package/android/src/main/java/com/facematch/sdk/BitmapUtils.kt +138 -0
  9. package/android/src/main/java/com/facematch/sdk/CameraFrameView.kt +75 -0
  10. package/android/src/main/java/com/facematch/sdk/FaceAlignmentHelper.kt +156 -0
  11. package/android/src/main/java/com/facematch/sdk/FaceCameraView.kt +628 -0
  12. package/android/src/main/java/com/facematch/sdk/FaceCameraViewManager.kt +79 -0
  13. package/android/src/main/java/com/facematch/sdk/FaceCandidateFilter.kt +65 -0
  14. package/android/src/main/java/com/facematch/sdk/FaceDetectionHelper.kt +225 -0
  15. package/android/src/main/java/com/facematch/sdk/FaceEmbeddingHelper.kt +242 -0
  16. package/android/src/main/java/com/facematch/sdk/FaceFrameAnalyzer.kt +228 -0
  17. package/android/src/main/java/com/facematch/sdk/FaceMatchModule.kt +249 -0
  18. package/android/src/main/java/com/facematch/sdk/FaceMatchPackage.kt +14 -0
  19. package/android/src/main/java/com/facematch/sdk/FaceMatchRuntime.kt +138 -0
  20. package/android/src/main/java/com/facematch/sdk/FaceMatcherHelper.kt +92 -0
  21. package/android/src/main/java/com/facematch/sdk/FaceOverlayView.kt +236 -0
  22. package/android/src/main/java/com/facematch/sdk/LivenessDetector.kt +483 -0
  23. package/android/src/main/java/com/facematch/sdk/LivenessPrompts.kt +137 -0
  24. package/android/src/main/java/com/facematch/sdk/LivenessVoice.kt +270 -0
  25. package/android/src/main/java/com/facematch/sdk/PrivateCaptureStore.kt +50 -0
  26. package/ios/Sources/AntiSpoofHelper.swift +239 -0
  27. package/ios/Sources/FaceAlignmentHelper.swift +169 -0
  28. package/ios/Sources/FaceCameraView.swift +1161 -0
  29. package/ios/Sources/FaceCameraViewManager.m +28 -0
  30. package/ios/Sources/FaceCameraViewManager.swift +57 -0
  31. package/ios/Sources/FaceCandidateFilter.swift +62 -0
  32. package/ios/Sources/FaceDetectionHelper.swift +283 -0
  33. package/ios/Sources/FaceEmbeddingHelper.swift +188 -0
  34. package/ios/Sources/FaceFrameAnalyzer.swift +179 -0
  35. package/ios/Sources/FaceFrameResult.swift +96 -0
  36. package/ios/Sources/FaceMatchBundle.swift +26 -0
  37. package/ios/Sources/FaceMatchEngine.swift +136 -0
  38. package/ios/Sources/FaceMatchError.swift +40 -0
  39. package/ios/Sources/FaceMatchModule.m +55 -0
  40. package/ios/Sources/FaceMatchModule.swift +288 -0
  41. package/ios/Sources/FaceMatcherHelper.swift +107 -0
  42. package/ios/Sources/FaceOverlayView.swift +285 -0
  43. package/ios/Sources/ImageUtils.swift +322 -0
  44. package/ios/Sources/LivenessDetector.swift +505 -0
  45. package/ios/Sources/LivenessPrompts.swift +121 -0
  46. package/ios/Sources/LivenessVoice.swift +229 -0
  47. package/ios/Sources/OnnxRuntime/ORTShim.h +91 -0
  48. package/ios/Sources/OnnxRuntime/ORTShim.mm +260 -0
  49. package/ios/Sources/PrivateCaptureStore.swift +71 -0
  50. package/ios/Sources/VisionFaceFallback.swift +95 -0
  51. package/ios/onnxruntime-c.podspec +47 -0
  52. package/models/anti_spoof_minifasnet_v2.onnx +0 -0
  53. package/models/w600k_mbf.onnx +0 -0
  54. package/package.json +47 -4
  55. package/react-native.config.js +16 -0
  56. package/src/FaceCameraView.tsx +75 -0
  57. package/src/FaceMatch.ts +66 -0
  58. package/src/index.ts +4 -0
  59. package/src/types.ts +87 -0
@@ -0,0 +1,322 @@
1
+ import CoreGraphics
2
+ import CoreImage
3
+ import CoreVideo
4
+ import Foundation
5
+ import ImageIO
6
+ import UIKit
7
+ import VideoToolbox
8
+
9
+ /// Port of `BitmapUtils.kt`.
10
+ ///
11
+ /// Pixels are handled as `UInt32` values packed `0xAARRGGBB`, exactly matching
12
+ /// Android's `Bitmap.getPixels()`, so every downstream bit-shift in
13
+ /// AntiSpoofHelper / FaceEmbeddingHelper ports over unchanged.
14
+ enum ImageUtils {
15
+ private static let maxSourceBytes: Int64 = 64 * 1024 * 1024
16
+ private static let maxDecodedDimension = 4096
17
+ private static let maxDecodedPixels = 8 * 1024 * 1024
18
+ /// Grid resolution for the coarse luminance sample (per axis).
19
+ private static let lumaSamples = 20
20
+
21
+ // MARK: - Decoding
22
+
23
+ /// Decodes a local image, applying EXIF orientation and the same size caps
24
+ /// as Android. Only `file://` URIs inside the app sandbox are accepted.
25
+ static func decode(uriString: String) throws -> CGImage {
26
+ guard !uriString.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
27
+ throw FaceMatchError("E_FACE_MATCH", "Image URI must not be empty")
28
+ }
29
+ let url = try validate(uriString: uriString)
30
+ try validateKnownSize(url)
31
+
32
+ guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else {
33
+ throw FaceMatchError("E_FACE_MATCH", "Unsupported or unreadable image")
34
+ }
35
+ let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]
36
+ let width = properties?[kCGImagePropertyPixelWidth] as? Int ?? 0
37
+ let height = properties?[kCGImagePropertyPixelHeight] as? Int ?? 0
38
+ guard width > 0, height > 0 else {
39
+ throw FaceMatchError("E_FACE_MATCH", "Unsupported or unreadable image")
40
+ }
41
+
42
+ // Cap the longest side so neither the per-side nor the total-pixel
43
+ // budget is exceeded, mirroring the inSampleSize loop on Android.
44
+ var maxPixelSize = max(width, height)
45
+ maxPixelSize = min(maxPixelSize, maxDecodedDimension)
46
+ if width * height > maxDecodedPixels {
47
+ let scale = (Double(maxDecodedPixels) / Double(width * height)).squareRoot()
48
+ maxPixelSize = min(maxPixelSize, Int((Double(max(width, height)) * scale).rounded(.down)))
49
+ }
50
+
51
+ let options: [CFString: Any] = [
52
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
53
+ // Bakes the EXIF orientation into the returned pixels.
54
+ kCGImageSourceCreateThumbnailWithTransform: true,
55
+ kCGImageSourceShouldCacheImmediately: true,
56
+ kCGImageSourceThumbnailMaxPixelSize: max(maxPixelSize, 1)
57
+ ]
58
+ guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else {
59
+ throw FaceMatchError("E_FACE_MATCH", "Unsupported or unreadable image")
60
+ }
61
+ return image
62
+ }
63
+
64
+ private static func validate(uriString: String) throws -> URL {
65
+ let url: URL
66
+ if let parsed = URL(string: uriString), parsed.scheme != nil {
67
+ guard parsed.isFileURL else {
68
+ throw FaceMatchError(
69
+ "E_FACE_MATCH",
70
+ "Only app-private file:// images are supported"
71
+ )
72
+ }
73
+ url = parsed
74
+ } else {
75
+ url = URL(fileURLWithPath: uriString)
76
+ }
77
+
78
+ let target = url.standardizedFileURL.resolvingSymlinksInPath()
79
+ let allowed = PrivateCaptureStore.allowedRoots().contains { root in
80
+ target.path == root.path || target.path.hasPrefix(root.path + "/")
81
+ }
82
+ guard allowed else {
83
+ throw FaceMatchError("E_FACE_MATCH", "File URI must point to app-private storage")
84
+ }
85
+ return target
86
+ }
87
+
88
+ private static func validateKnownSize(_ url: URL) throws {
89
+ let attributes = try? FileManager.default.attributesOfItem(atPath: url.path)
90
+ let length = (attributes?[.size] as? NSNumber)?.int64Value ?? -1
91
+ guard length <= 0 || length <= maxSourceBytes else {
92
+ throw FaceMatchError("E_FACE_MATCH", "Image file is too large")
93
+ }
94
+ }
95
+
96
+ // MARK: - Geometry
97
+
98
+ static func rotate(_ image: CGImage, degrees: Int) -> CGImage {
99
+ let normalized = ((degrees % 360) + 360) % 360
100
+ if normalized == 0 { return image }
101
+
102
+ let radians = CGFloat(normalized) * .pi / 180
103
+ let swapsAxes = normalized == 90 || normalized == 270
104
+ let width = swapsAxes ? image.height : image.width
105
+ let height = swapsAxes ? image.width : image.height
106
+
107
+ guard let context = makeContext(width: width, height: height) else { return image }
108
+ context.translateBy(x: CGFloat(width) / 2, y: CGFloat(height) / 2)
109
+ context.rotate(by: -radians)
110
+ context.translateBy(x: -CGFloat(image.width) / 2, y: -CGFloat(image.height) / 2)
111
+ context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
112
+ return context.makeImage() ?? image
113
+ }
114
+
115
+ /// Bakes an EXIF orientation into the pixels.
116
+ ///
117
+ /// `AVCapturePhotoOutput` does not physically rotate captured buffers — it
118
+ /// records the intended orientation as an EXIF tag — so a still handed
119
+ /// straight to ML Kit is sideways and detects nothing. This is the iOS
120
+ /// equivalent of Android's `rotateDegrees(image.imageInfo.rotationDegrees)`.
121
+ static func normalized(_ image: CGImage, orientation: CGImagePropertyOrientation) -> CGImage {
122
+ if orientation == .up { return image }
123
+
124
+ let uiOrientation: UIImage.Orientation
125
+ switch orientation {
126
+ case .up: uiOrientation = .up
127
+ case .upMirrored: uiOrientation = .upMirrored
128
+ case .down: uiOrientation = .down
129
+ case .downMirrored: uiOrientation = .downMirrored
130
+ case .leftMirrored: uiOrientation = .leftMirrored
131
+ case .right: uiOrientation = .right
132
+ case .rightMirrored: uiOrientation = .rightMirrored
133
+ case .left: uiOrientation = .left
134
+ @unknown default: uiOrientation = .up
135
+ }
136
+
137
+ // UIImage.draw(in:) applies the orientation while rasterising, which is
138
+ // the safest way to resolve all eight EXIF cases including the mirrored
139
+ // ones the front camera can produce.
140
+ let source = UIImage(cgImage: image, scale: 1, orientation: uiOrientation)
141
+ let format = UIGraphicsImageRendererFormat()
142
+ format.scale = 1
143
+ format.opaque = true
144
+ // .automatic picks extended range on wide-colour (P3) iPhones, which
145
+ // yields a 16-bit float CGImage that ML Kit cannot read — it reports no
146
+ // face at all. Force the plain 8-bit sRGB layout Android's ARGB_8888 uses.
147
+ format.preferredRange = .standard
148
+ let renderer = UIGraphicsImageRenderer(size: source.size, format: format)
149
+ let drawn = renderer.image { _ in
150
+ source.draw(in: CGRect(origin: .zero, size: source.size))
151
+ }
152
+ return drawn.cgImage ?? image
153
+ }
154
+
155
+ static func mirrorHorizontal(_ image: CGImage) -> CGImage {
156
+ guard let context = makeContext(width: image.width, height: image.height) else { return image }
157
+ context.translateBy(x: CGFloat(image.width), y: 0)
158
+ context.scaleBy(x: -1, y: 1)
159
+ context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
160
+ return context.makeImage() ?? image
161
+ }
162
+
163
+ /// Crops in top-left origin pixel coordinates, matching Android's `Rect`.
164
+ static func crop(_ image: CGImage, to rect: CGRect) -> CGImage? {
165
+ let bounds = CGRect(x: 0, y: 0, width: image.width, height: image.height)
166
+ let clamped = rect.integral.intersection(bounds)
167
+ guard clamped.width >= 1, clamped.height >= 1 else { return nil }
168
+ return image.cropping(to: clamped)
169
+ }
170
+
171
+ /// Returns `image` in canonical 8-bit BGRA device-RGB, redrawing only when
172
+ /// it is in some other layout (16-bit / float wide-colour, grayscale, CMYK,
173
+ /// indexed, ...). ML Kit on iOS silently detects nothing in those formats.
174
+ static func standardized(_ image: CGImage) -> CGImage {
175
+ let isStandard = image.bitsPerComponent == 8 &&
176
+ image.bitsPerPixel == 32 &&
177
+ image.colorSpace?.model == .rgb &&
178
+ !image.bitmapInfo.contains(.floatComponents)
179
+ if isStandard { return image }
180
+ guard let context = makeContext(width: image.width, height: image.height) else { return image }
181
+ context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
182
+ return context.makeImage() ?? image
183
+ }
184
+
185
+ static func scaled(_ image: CGImage, width: Int, height: Int) -> CGImage {
186
+ if image.width == width && image.height == height { return image }
187
+ guard width > 0, height > 0, let context = makeContext(width: width, height: height) else {
188
+ return image
189
+ }
190
+ context.interpolationQuality = .high
191
+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
192
+ return context.makeImage() ?? image
193
+ }
194
+
195
+ // MARK: - Pixels
196
+
197
+ /// Returns pixels packed `0xAARRGGBB` in row-major, top-left-origin order.
198
+ static func argbPixels(of image: CGImage) -> [UInt32] {
199
+ let width = image.width
200
+ let height = image.height
201
+ var pixels = [UInt32](repeating: 0, count: width * height)
202
+ pixels.withUnsafeMutableBytes { raw in
203
+ guard let base = raw.baseAddress,
204
+ let context = CGContext(
205
+ data: base,
206
+ width: width,
207
+ height: height,
208
+ bitsPerComponent: 8,
209
+ bytesPerRow: width * 4,
210
+ space: CGColorSpaceCreateDeviceRGB(),
211
+ // Little-endian + skipFirst lays bytes out as B,G,R,X,
212
+ // which reads back as 0x00RRGGBB.
213
+ bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue
214
+ | CGBitmapInfo.byteOrder32Little.rawValue
215
+ ) else { return }
216
+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
217
+ }
218
+ // Force opaque alpha so callers can rely on the top byte.
219
+ for index in pixels.indices { pixels[index] |= 0xFF00_0000 }
220
+ return pixels
221
+ }
222
+
223
+ static func image(fromARGB pixels: [UInt32], width: Int, height: Int) -> CGImage? {
224
+ guard width > 0, height > 0, pixels.count == width * height else { return nil }
225
+ var mutable = pixels
226
+ return mutable.withUnsafeMutableBytes { raw -> CGImage? in
227
+ guard let base = raw.baseAddress,
228
+ let context = CGContext(
229
+ data: base,
230
+ width: width,
231
+ height: height,
232
+ bitsPerComponent: 8,
233
+ bytesPerRow: width * 4,
234
+ space: CGColorSpaceCreateDeviceRGB(),
235
+ bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue
236
+ | CGBitmapInfo.byteOrder32Little.rawValue
237
+ ) else { return nil }
238
+ return context.makeImage()
239
+ }
240
+ }
241
+
242
+ /// Mean perceived brightness (0-255) sampled over a coarse grid, using the
243
+ /// same weights and stride as `FaceFrameAnalyzer.estimateLuminance`.
244
+ static func luminance(of image: CGImage) -> Float {
245
+ let width = image.width
246
+ let height = image.height
247
+ guard width > 0, height > 0 else { return 255 }
248
+ let pixels = argbPixels(of: image)
249
+
250
+ let stepX = max(width / lumaSamples, 1)
251
+ let stepY = max(height / lumaSamples, 1)
252
+ var sum = 0.0
253
+ var count = 0
254
+ var y = 0
255
+ while y < height {
256
+ var x = 0
257
+ let row = y * width
258
+ while x < width {
259
+ let pixel = pixels[row + x]
260
+ let r = Double((pixel >> 16) & 0xFF)
261
+ let g = Double((pixel >> 8) & 0xFF)
262
+ let b = Double(pixel & 0xFF)
263
+ sum += 0.299 * r + 0.587 * g + 0.114 * b
264
+ count += 1
265
+ x += stepX
266
+ }
267
+ y += stepY
268
+ }
269
+ return count == 0 ? 255 : Float(sum / Double(count))
270
+ }
271
+
272
+ // MARK: - Encoding / conversion
273
+
274
+ static func jpegData(from image: CGImage, quality: CGFloat) -> Data? {
275
+ UIImage(cgImage: image).jpegData(compressionQuality: quality)
276
+ }
277
+
278
+ static func cgImage(from pixelBuffer: CVPixelBuffer) -> CGImage? {
279
+ var image: CGImage?
280
+ let status = VTCreateCGImageFromCVPixelBuffer(pixelBuffer, options: nil, imageOut: &image)
281
+ return status == noErr ? image : nil
282
+ }
283
+
284
+ /// GPU-backed context reused across frames; creating one per frame is the
285
+ /// single most expensive thing an analysis loop can do.
286
+ private static let sharedCIContext = CIContext(options: [.useSoftwareRenderer: false])
287
+
288
+ /// Converts a camera pixel buffer straight to an analysis-sized CGImage.
289
+ ///
290
+ /// The session runs the `.photo` preset so stills keep full quality, which
291
+ /// means these buffers arrive at full sensor resolution. Scaling inside the
292
+ /// Core Image pipeline avoids ever materialising a full-resolution bitmap —
293
+ /// the equivalent of CameraX delivering 640x480 analysis frames directly.
294
+ static func analysisImage(from pixelBuffer: CVPixelBuffer, maxSide: Int) -> CGImage? {
295
+ var ciImage = CIImage(cvPixelBuffer: pixelBuffer)
296
+ let extent = ciImage.extent
297
+ guard extent.width > 0, extent.height > 0 else { return nil }
298
+
299
+ let longest = max(extent.width, extent.height)
300
+ if longest > CGFloat(maxSide) {
301
+ let scale = CGFloat(maxSide) / longest
302
+ ciImage = ciImage.transformed(by: CGAffineTransform(scaleX: scale, y: scale))
303
+ }
304
+ return sharedCIContext.createCGImage(ciImage, from: ciImage.extent)
305
+ }
306
+
307
+ private static func makeContext(width: Int, height: Int) -> CGContext? {
308
+ CGContext(
309
+ data: nil,
310
+ width: width,
311
+ height: height,
312
+ bitsPerComponent: 8,
313
+ bytesPerRow: 0,
314
+ space: CGColorSpaceCreateDeviceRGB(),
315
+ // Canonical BGRA. Every image here is opaque, so premultiplied and
316
+ // straight alpha are identical, but this is the layout ML Kit and
317
+ // UIKit expect from a UIImage.
318
+ bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue
319
+ | CGBitmapInfo.byteOrder32Little.rawValue
320
+ )
321
+ }
322
+ }