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,1161 @@
1
+ import AudioToolbox
2
+ import AVFoundation
3
+ import CoreGraphics
4
+ import Foundation
5
+ import os
6
+ import React
7
+ import UIKit
8
+
9
+ /// Port of `FaceCameraView.kt`.
10
+ ///
11
+ /// AVFoundation replaces CameraX, but the state machine, guards, event
12
+ /// payloads, error codes and tuning constants are identical to the Android
13
+ /// view so both platforms behave the same for the same user.
14
+ @objc(FaceCameraView)
15
+ final class FaceCameraView: UIView {
16
+
17
+ private enum Constants {
18
+ /// Averaging a short burst reduces capture-to-capture variation from
19
+ /// sensor noise, expression changes and small landmark shifts.
20
+ ///
21
+ /// Two, not three: each extra sample is a full shutter round trip plus a
22
+ /// detect + align + embed, and the shutter for sample N+1 only fires after
23
+ /// sample N's inference finishes — so the third sample was costing roughly
24
+ /// a third of the entire post-liveness wait for a third averaging term.
25
+ /// Averaging is retained because the matcher's score boundaries were
26
+ /// calibrated against averaged embeddings; dropping to a single sample
27
+ /// would shift that distribution and wants a labelled re-validation first.
28
+ /// Must stay equal to Android's IDENTITY_CAPTURE_BURST_SIZE.
29
+ static let identityCaptureBurstSize = 2
30
+
31
+ /// Perceived-brightness band (0-255). Below ENTER the screen is driven
32
+ /// to full brightness to light the user's face; it only drops back once
33
+ /// the frame recovers past EXIT, so the boost does not flicker.
34
+ static let lowLightEnter: Float = 62
35
+ static let lowLightExit: Float = 92
36
+ /// Minimum time the opposite boost state must persist before it is
37
+ /// actually applied. See the note on `pendingBoostState` below.
38
+ static let lowLightDebounceSeconds: CFTimeInterval = 0.6
39
+
40
+ /// CameraX's ImageAnalysis default is 640x480; matching it keeps the
41
+ /// framing gates and anti-spoof crops comparable across platforms.
42
+ static let analysisMaxSide = 640
43
+
44
+ static let faceEmitIntervalMs: Double = 200
45
+ }
46
+
47
+ private final class CaptureBurstState {
48
+ var sampleCount = 0
49
+ var embeddingSum: [Float]?
50
+ var captureURL: URL?
51
+ var width = 0
52
+ var height = 0
53
+ var faceCount = 0
54
+ }
55
+
56
+ // MARK: - Events
57
+
58
+ @objc var onFaceState: RCTDirectEventBlock?
59
+ @objc var onLiveness: RCTDirectEventBlock?
60
+ @objc var onCapture: RCTDirectEventBlock?
61
+ @objc var onError: RCTDirectEventBlock?
62
+ @objc var onCameraState: RCTDirectEventBlock?
63
+
64
+ // MARK: - Views / pipeline
65
+
66
+ /// Layer-backed host for the capture preview.
67
+ ///
68
+ /// A bare `AVCaptureVideoPreviewLayer` added with `addSublayer` has to be
69
+ /// resized by hand, and assigning `.frame` to a raw `CALayer` implicitly
70
+ /// animates over ~0.25s whenever it happens inside an animation
71
+ /// transaction — which is exactly what React Native's modal presentation
72
+ /// and its re-renders produce. The layer then sweeps out from x=0, showing
73
+ /// a left-anchored strip of camera against the white background, restarting
74
+ /// on every layout pass. Backing it with a UIView hands geometry to UIKit
75
+ /// and removes the implicit animation entirely.
76
+ private final class PreviewView: UIView {
77
+ override class var layerClass: AnyClass { AVCaptureVideoPreviewLayer.self }
78
+ var previewLayer: AVCaptureVideoPreviewLayer {
79
+ // swiftlint:disable:next force_cast
80
+ layer as! AVCaptureVideoPreviewLayer
81
+ }
82
+ }
83
+
84
+ private let previewView = PreviewView()
85
+ private var previewLayer: AVCaptureVideoPreviewLayer { previewView.previewLayer }
86
+ private let overlayView = FaceOverlayView(frame: .zero)
87
+ private let voice = LivenessVoice()
88
+ private let session = AVCaptureSession()
89
+ private let sessionQueue = DispatchQueue(label: "com.facematch.sdk.session")
90
+ private let analysisQueue = DispatchQueue(label: "com.facematch.sdk.analysis")
91
+ private let captureQueue = DispatchQueue(label: "com.facematch.sdk.capture")
92
+ private static let warmUpQueue = DispatchQueue(label: "com.facematch.sdk.warmup", qos: .userInitiated)
93
+ private let livenessDetector = LivenessDetector()
94
+ private let analyzer: FaceFrameAnalyzer
95
+
96
+ private var videoOutput: AVCaptureVideoDataOutput?
97
+ private var photoOutput: AVCapturePhotoOutput?
98
+ private var videoInput: AVCaptureDeviceInput?
99
+ private var softwareRotationDegrees = 0
100
+ private let rotationLock = NSLock()
101
+ /// Read on the main thread, consumed on the session queue.
102
+ private var cachedRotationAngle: CGFloat = 90
103
+
104
+ // MARK: - State
105
+
106
+ private var requestedStart = false
107
+ private var cameraStartPending = false
108
+ private var cameraStartGeneration: Int64 = 0
109
+ private var cameraStarted = false
110
+ private var requireLivenessFlag = true
111
+ private var autoCaptureOnLivenessFlag = false
112
+ private var autoCaptureTriggered = false
113
+ private var captureInProgress = false
114
+ private var brightenOnLowLightFlag = true
115
+ private var smoothedLuma: Float = -1
116
+ private var screenBoosted = false
117
+ private var originalBrightness: CGFloat?
118
+ /// The debounce state for `applyScreenBoost`. Turning the head is exactly
119
+ /// when the framed background changes the most (a window, then a wall,
120
+ /// then a lamp), which can legitimately swing the smoothed luminance
121
+ /// across the hysteresis band several times in a couple of seconds even
122
+ /// though the room itself has not gotten brighter or darker. Each flip
123
+ /// calls `UIScreen.main.brightness =`, which is a synchronous round trip
124
+ /// to the system UI process and is expensive enough that doing it several
125
+ /// times a second visibly stalls the main thread — right when React
126
+ /// Native is also handling a burst of onFaceState/onLiveness updates for
127
+ /// the same head turn. The two together tore the composited frame. A
128
+ /// target state now has to hold for `lowLightDebounceSeconds` before it is
129
+ /// actually applied, so a brief pan across the room no longer toggles the
130
+ /// backlight at all; only a genuinely sustained lighting change does.
131
+ private var pendingBoostState: Bool?
132
+ private var pendingBoostSince: CFTimeInterval = 0
133
+ private var voiceLanguage = "none"
134
+ private var antiSpoofThresholdValue = AntiSpoofHelper.defaultThreshold
135
+ private var lastAntiSpoofStatus: AntiSpoofStatus?
136
+ private var lastFaceCount = 0
137
+ private var livenessProgress: LivenessProgress
138
+ private var lastLivenessSignature = ""
139
+ private var lastAntiSpoofErrorSignature = ""
140
+ private var lastFaceEmitAt: Double = 0
141
+ private var analysisBusy = false
142
+ private var burstDelegate: PhotoCaptureDelegate?
143
+ #if DEBUG
144
+ private var frameCounter = 0
145
+ private static let debugLog = OSLog(subsystem: "com.facematch.sdk", category: "Camera")
146
+ #endif
147
+
148
+ // MARK: - Init
149
+
150
+ /// Bump this string with every native change under investigation. Printed
151
+ /// once per camera session — if this line is missing or shows the wrong
152
+ /// value in Xcode's console, the running binary predates the fix being
153
+ /// tested, full stop.
154
+ private static let buildMarker = "FaceCameraView build 2026-09-15-a (rotation-source-fix + hold-last-step + brightness-debounce + EXIF-bake-in)"
155
+ /// Always compiled — unlike `debugLog` below, not gated by `#if DEBUG` —
156
+ /// so the marker prints in a Release build too.
157
+ private static let alwaysLog = OSLog(subsystem: "com.facematch.sdk", category: "Build")
158
+ /// Also unconditional. `PhotoCaptureDelegate` is a free-standing class so
159
+ /// this cannot be a plain instance property of `FaceCameraView`.
160
+ fileprivate static let captureLog = OSLog(subsystem: "com.facematch.sdk", category: "Capture")
161
+
162
+ override init(frame: CGRect) {
163
+ analyzer = FaceFrameAnalyzer(
164
+ // Resolved on each call rather than captured: this closure only runs
165
+ // on the analysis queue, so the first touch of FaceMatchEngine (which
166
+ // loads ~15 MB of ONNX models) never lands on the main thread.
167
+ classifyAntiSpoof: { image, bounds, threshold in
168
+ FaceMatchEngine.shared.classifyAntiSpoof(
169
+ image,
170
+ faceBounds: bounds,
171
+ threshold: threshold
172
+ )
173
+ }
174
+ )
175
+ livenessProgress = LivenessProgress(
176
+ currentAction: nil,
177
+ completedActions: [],
178
+ isComplete: false,
179
+ promptKey: .positionFace
180
+ )
181
+ super.init(frame: frame)
182
+
183
+ previewLayer.session = session
184
+ previewLayer.videoGravity = .resizeAspectFill
185
+ addSubview(previewView)
186
+ addSubview(overlayView)
187
+
188
+ NotificationCenter.default.addObserver(
189
+ self,
190
+ selector: #selector(handleWillResignActive),
191
+ name: UIApplication.willResignActiveNotification,
192
+ object: nil
193
+ )
194
+ NotificationCenter.default.addObserver(
195
+ self,
196
+ selector: #selector(handleDidBecomeActive),
197
+ name: UIApplication.didBecomeActiveNotification,
198
+ object: nil
199
+ )
200
+ NotificationCenter.default.addObserver(
201
+ self,
202
+ selector: #selector(handleSessionRuntimeError(_:)),
203
+ name: .AVCaptureSessionRuntimeError,
204
+ object: session
205
+ )
206
+ }
207
+
208
+ required init?(coder: NSCoder) {
209
+ fatalError("init(coder:) is not supported")
210
+ }
211
+
212
+ deinit {
213
+ NotificationCenter.default.removeObserver(self)
214
+ }
215
+
216
+ override func layoutSubviews() {
217
+ super.layoutSubviews()
218
+ // No bringSubviewToFront here: the overlay is added last in init so it
219
+ // is already on top, and reordering during layout re-dirties the view
220
+ // hierarchy and can spin the layout pass.
221
+ // Belt and braces: layoutSubviews can itself run inside an animation
222
+ // block, which would animate these frames too.
223
+ CATransaction.begin()
224
+ CATransaction.setDisableActions(true)
225
+ previewView.frame = bounds
226
+ overlayView.frame = bounds
227
+ CATransaction.commit()
228
+ // The preview connection's angle depends on the layer's orientation in
229
+ // its window, which is not settled when the session is configured.
230
+ refreshPreviewRotation()
231
+ }
232
+
233
+ override func removeFromSuperview() {
234
+ dispose()
235
+ super.removeFromSuperview()
236
+ }
237
+
238
+ // MARK: - Props
239
+
240
+ @objc func setRequireLiveness(_ value: Bool) { requireLivenessFlag = value }
241
+
242
+ @objc func setAutoCaptureOnLiveness(_ value: Bool) { autoCaptureOnLivenessFlag = value }
243
+
244
+ @objc func setBrightenOnLowLight(_ value: Bool) {
245
+ brightenOnLowLightFlag = value
246
+ if !value { applyScreenBoost(false) }
247
+ }
248
+
249
+ @objc func setAntiSpoofThreshold(_ value: Float) {
250
+ antiSpoofThresholdValue = AntiSpoofHelper.sanitizeThreshold(value)
251
+ analyzer.setAntiSpoofThreshold(antiSpoofThresholdValue)
252
+ }
253
+
254
+ /// "en", "hi" or "none" — controls the spoken liveness instructions.
255
+ @objc func setVoiceLanguage(_ value: String) {
256
+ switch value.lowercased() {
257
+ case "hi", "hi-in", "hindi": voiceLanguage = "hi"
258
+ case "en", "en-in", "en-us", "english": voiceLanguage = "en"
259
+ default: voiceLanguage = "none"
260
+ }
261
+ voice.setLanguage(voiceLanguage)
262
+ }
263
+
264
+ /// "female" (default) or "male" — preferred India voice for the spoken guidance.
265
+ @objc func setVoiceGender(_ value: String) {
266
+ voice.setGender(value)
267
+ }
268
+
269
+ @objc func setAutoStart(_ value: Bool) {
270
+ if value { startCamera() } else { stopCamera() }
271
+ }
272
+
273
+ // MARK: - Commands
274
+
275
+ @objc func startCamera() {
276
+ os_log("%{public}@", log: Self.alwaysLog, type: .fault, Self.buildMarker)
277
+ requestedStart = true
278
+ smoothedLuma = -1
279
+ // Build the ONNX sessions ahead of the first frame, off the main thread.
280
+ FaceCameraView.warmUpQueue.async { _ = FaceMatchEngine.shared.isReady }
281
+ // A camera flow must not let the display dim or lock mid-liveness.
282
+ UIApplication.shared.isIdleTimerDisabled = true
283
+ // Configuration is asynchronous. React may request a start from both the
284
+ // autoStart prop and the imperative command (or a foreground resume)
285
+ // before it completes; without a pending guard each callback would add
286
+ // another input/output set to the session.
287
+ if cameraStarted || cameraStartPending { return }
288
+
289
+ switch AVCaptureDevice.authorizationStatus(for: .video) {
290
+ case .authorized:
291
+ beginConfiguration()
292
+ case .notDetermined:
293
+ cameraStartPending = true
294
+ AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
295
+ DispatchQueue.main.async {
296
+ guard let self else { return }
297
+ self.cameraStartPending = false
298
+ if granted {
299
+ self.beginConfiguration()
300
+ } else {
301
+ self.emitError("E_CAMERA_PERMISSION", "Camera permission has not been granted")
302
+ }
303
+ }
304
+ }
305
+ default:
306
+ emitError("E_CAMERA_PERMISSION", "Camera permission has not been granted")
307
+ }
308
+ }
309
+
310
+ private func beginConfiguration() {
311
+ cameraStartPending = true
312
+ cameraStartGeneration += 1
313
+ let startGeneration = cameraStartGeneration
314
+
315
+ // UIKit must be read on the main thread, and beginConfiguration() is
316
+ // always called from there; the session queue uses the cached value.
317
+ cachedRotationAngle = interfaceRotationAngle()
318
+
319
+ sessionQueue.async { [weak self] in
320
+ guard let self else { return }
321
+
322
+ var failure: FaceMatchError?
323
+ self.session.beginConfiguration()
324
+ do {
325
+ self.session.sessionPreset = .photo
326
+
327
+ guard let device = AVCaptureDevice.default(
328
+ .builtInWideAngleCamera,
329
+ for: .video,
330
+ position: .front
331
+ ) else {
332
+ throw FaceMatchError("E_CAMERA_START", "No front camera is available")
333
+ }
334
+
335
+ if self.videoInput == nil {
336
+ let input = try AVCaptureDeviceInput(device: device)
337
+ guard self.session.canAddInput(input) else {
338
+ throw FaceMatchError("E_CAMERA_START", "Unable to attach the front camera")
339
+ }
340
+ self.session.addInput(input)
341
+ self.videoInput = input
342
+ }
343
+
344
+ if self.videoOutput == nil {
345
+ let output = AVCaptureVideoDataOutput()
346
+ output.alwaysDiscardsLateVideoFrames = true
347
+ // Pixel format only. kCVPixelBufferWidthKey/HeightKey throw
348
+ // NSInvalidArgumentException unless the size matches both the
349
+ // connection's orientation and the active format's aspect
350
+ // ratio, so the downscale is done in Core Image instead (see
351
+ // ImageUtils.analysisImage). With the `.photo` preset and
352
+ // automaticallyConfiguresOutputBufferDimensions left at its
353
+ // default, these buffers already arrive preview-sized.
354
+ output.videoSettings = [
355
+ kCVPixelBufferPixelFormatTypeKey as String:
356
+ Int(kCVPixelFormatType_32BGRA)
357
+ ]
358
+ output.setSampleBufferDelegate(self, queue: self.analysisQueue)
359
+ guard self.session.canAddOutput(output) else {
360
+ throw FaceMatchError("E_CAMERA_START", "Unable to attach the analysis output")
361
+ }
362
+ self.session.addOutput(output)
363
+ self.videoOutput = output
364
+ }
365
+
366
+ if self.photoOutput == nil {
367
+ let output = AVCapturePhotoOutput()
368
+ guard self.session.canAddOutput(output) else {
369
+ throw FaceMatchError("E_CAMERA_START", "Unable to attach the photo output")
370
+ }
371
+ self.session.addOutput(output)
372
+ output.maxPhotoQualityPrioritization = .quality
373
+ self.photoOutput = output
374
+ }
375
+
376
+ // Unconditionally, outside the creation branch above: videoOutput
377
+ // survives stopCameraPipeline(), so a restart skips that branch —
378
+ // and `capture()` detaches this delegate for the duration of the
379
+ // burst. Without re-attaching here, a retake after a successful
380
+ // capture would come back with per-frame analysis dead and
381
+ // liveness never advancing.
382
+ self.videoOutput?.setSampleBufferDelegate(self, queue: self.analysisQueue)
383
+ } catch {
384
+ failure = FaceMatchError(
385
+ FaceMatchError.code(of: error),
386
+ FaceMatchError.message(of: error)
387
+ )
388
+ }
389
+ self.session.commitConfiguration()
390
+
391
+ if let failure {
392
+ DispatchQueue.main.async {
393
+ self.cameraStartPending = false
394
+ self.emitError(failure.code, failure.message)
395
+ }
396
+ return
397
+ }
398
+
399
+ // A stop/background/dispose invalidates a configuration that was
400
+ // still running. A later start gets its own generation.
401
+ guard startGeneration == self.cameraStartGeneration else { return }
402
+
403
+ self.configureConnections()
404
+ if !self.session.isRunning { self.session.startRunning() }
405
+
406
+ DispatchQueue.main.async {
407
+ self.cameraStartPending = false
408
+ guard startGeneration == self.cameraStartGeneration, self.requestedStart else {
409
+ self.sessionQueue.async { self.session.stopRunning() }
410
+ return
411
+ }
412
+ self.cameraStarted = true
413
+ self.overlayView.isHidden = false
414
+ self.refreshPreviewRotation()
415
+ self.emitCameraState("started")
416
+ }
417
+ }
418
+ }
419
+
420
+ /// Portrait-upright frames, with the preview mirrored like every other
421
+ /// front-facing camera and the captured pixels deliberately not mirrored.
422
+ /// Portrait-upright frames, with the preview mirrored like every other
423
+ /// front-facing camera and the captured pixels deliberately not mirrored.
424
+ ///
425
+ /// The rotation angle is never hardcoded: `AVCaptureVideoDataOutput` does
426
+ /// physically rotate buffers, but the connection's starting angle is
427
+ /// device-dependent (0 on most devices, 180 for the front camera on the
428
+ /// Spring 2024 iPads), and iPad also allows landscape. A wrong angle hands
429
+ /// ML Kit an upside-down face, which it will not detect at all.
430
+ private func configureConnections() {
431
+ let captureAngle = cachedRotationAngle
432
+ let previewAngle = captureAngle
433
+
434
+ if let connection = videoOutput?.connection(with: .video) {
435
+ // If the connection cannot rotate, the analysis path does it in
436
+ // software instead so ML Kit always receives an upright frame.
437
+ let applied = apply(angle: captureAngle, to: connection)
438
+ setSoftwareRotation(applied ? 0 : Int(captureAngle.rounded()))
439
+ if connection.isVideoMirroringSupported {
440
+ connection.automaticallyAdjustsVideoMirroring = false
441
+ connection.isVideoMirrored = false
442
+ }
443
+ }
444
+ if let connection = photoOutput?.connection(with: .video) {
445
+ _ = apply(angle: captureAngle, to: connection)
446
+ if connection.isVideoMirroringSupported {
447
+ connection.automaticallyAdjustsVideoMirroring = false
448
+ // Keep the saved/inference image in the sensor's natural
449
+ // orientation. Mirroring the captured pixels made them less
450
+ // comparable with ordinary reference photos.
451
+ connection.isVideoMirrored = false
452
+ }
453
+ }
454
+ DispatchQueue.main.async { [weak self] in
455
+ guard let self, let connection = self.previewLayer.connection else { return }
456
+ _ = self.apply(angle: previewAngle, to: connection)
457
+ if connection.isVideoMirroringSupported {
458
+ connection.automaticallyAdjustsVideoMirroring = false
459
+ connection.isVideoMirrored = true
460
+ }
461
+ }
462
+ }
463
+
464
+ /// - Returns: whether the connection accepted the rotation.
465
+ private func apply(angle: CGFloat, to connection: AVCaptureConnection) -> Bool {
466
+ if #available(iOS 17.0, *) {
467
+ guard connection.isVideoRotationAngleSupported(angle) else { return false }
468
+ connection.videoRotationAngle = angle
469
+ return true
470
+ }
471
+ guard connection.isVideoOrientationSupported else { return false }
472
+ connection.videoOrientation = Self.legacyOrientation(for: angle)
473
+ return true
474
+ }
475
+
476
+ /// Interface-relative angle — the analogue of CameraX's
477
+ /// `setTargetRotation(display.rotation)`.
478
+ ///
479
+ /// Deliberately **not** `AVCaptureDevice.RotationCoordinator`: every angle
480
+ /// it reports is *horizon-level*, meaning gravity-derived, so it changes
481
+ /// continuously while the device is being moved. Re-applying it from
482
+ /// `layoutSubviews` reconfigured the preview connection many times a second
483
+ /// during a head turn, and each reconfiguration drops the preview layer's
484
+ /// contents — the screen flickered white until the motion settled.
485
+ ///
486
+ /// The interface orientation is stable (and locked to portrait on iPhone),
487
+ /// so the preview and the analysis frames stay put while the user moves.
488
+ ///
489
+ /// Must be called on the main thread.
490
+ private func interfaceRotationAngle() -> CGFloat {
491
+ let scene = window?.windowScene
492
+ ?? UIApplication.shared.connectedScenes
493
+ .compactMap { $0 as? UIWindowScene }
494
+ .first { $0.activationState == .foregroundActive }
495
+
496
+ switch scene?.interfaceOrientation ?? .portrait {
497
+ case .portraitUpsideDown: return 270
498
+ case .landscapeLeft: return 180
499
+ case .landscapeRight: return 0
500
+ default: return 90
501
+ }
502
+ }
503
+
504
+ private static func legacyOrientation(for angle: CGFloat) -> AVCaptureVideoOrientation {
505
+ switch Int(angle.rounded()) % 360 {
506
+ case 0: return .landscapeRight
507
+ case 180: return .landscapeLeft
508
+ case 270: return .portraitUpsideDown
509
+ default: return .portrait
510
+ }
511
+ }
512
+
513
+ /// Cheap to call repeatedly — the preview layer rotates by transforming its
514
+ /// contents, unlike the data output which reconfigures the capture pipeline.
515
+ private func refreshPreviewRotation() {
516
+ guard let connection = previewLayer.connection else { return }
517
+ let angle = interfaceRotationAngle()
518
+ cachedRotationAngle = angle
519
+ if #available(iOS 17.0, *) {
520
+ guard connection.videoRotationAngle != angle else { return }
521
+ }
522
+ _ = apply(angle: angle, to: connection)
523
+ }
524
+
525
+ private func setSoftwareRotation(_ degrees: Int) {
526
+ rotationLock.lock()
527
+ softwareRotationDegrees = degrees
528
+ rotationLock.unlock()
529
+ }
530
+
531
+ private var currentSoftwareRotation: Int {
532
+ rotationLock.lock()
533
+ defer { rotationLock.unlock() }
534
+ return softwareRotationDegrees
535
+ }
536
+
537
+ @objc func stopCamera() {
538
+ requestedStart = false
539
+ stopCameraPipeline()
540
+ }
541
+
542
+ private func stopCameraPipeline() {
543
+ // Invalidate any configuration callback that has not run yet.
544
+ cameraStartGeneration += 1
545
+ cameraStartPending = false
546
+
547
+ sessionQueue.async { [weak self] in
548
+ guard let self else { return }
549
+ if self.session.isRunning { self.session.stopRunning() }
550
+ }
551
+
552
+ if cameraStarted { emitCameraState("stopped") }
553
+ cameraStarted = false
554
+ captureInProgress = false
555
+ lastAntiSpoofStatus = nil
556
+ lastFaceCount = 0
557
+ smoothedLuma = -1
558
+ pendingBoostState = nil
559
+ applyScreenBoost(false)
560
+ UIApplication.shared.isIdleTimerDisabled = false
561
+ voice.stop()
562
+ overlayView.reset()
563
+ }
564
+
565
+ @objc func startLiveness(_ actions: [String]?) {
566
+ livenessProgress = livenessDetector.reset(actions?.isEmpty == true ? nil : actions)
567
+ lastLivenessSignature = ""
568
+ autoCaptureTriggered = false
569
+ lastAntiSpoofStatus = nil
570
+ lastFaceCount = 0
571
+ lastAntiSpoofErrorSignature = ""
572
+ voice.resetSpokenHistory()
573
+ overlayView.reset()
574
+ emitLiveness(livenessProgress)
575
+ }
576
+
577
+ @objc func capture() {
578
+ if captureInProgress { return }
579
+ guard cameraStarted, let output = photoOutput else {
580
+ emitError("E_CAMERA_NOT_READY", "Camera is not ready")
581
+ return
582
+ }
583
+ if lastFaceCount > 1 {
584
+ emitError("E_MULTIPLE_FACES", "Multiple faces detected. Only one person is allowed")
585
+ return
586
+ }
587
+ if requireLivenessFlag && !livenessDetector.isComplete() {
588
+ emitError("E_LIVENESS_REQUIRED", "Complete all liveness actions before capture")
589
+ return
590
+ }
591
+ switch lastAntiSpoofStatus {
592
+ // A preview-frame score may fluctuate during the blink itself. Always
593
+ // take the photo after a valid blink and let extractLive() perform the
594
+ // definitive anti-spoof check on that exact image.
595
+ case .some(.spoof):
596
+ break
597
+ case .some(.error):
598
+ emitError("E_ANTI_SPOOF_MODEL", "Passive anti-spoofing is unavailable")
599
+ return
600
+ default:
601
+ break // The captured high-resolution image is checked again below.
602
+ }
603
+ captureInProgress = true
604
+ // Liveness is settled and every gate above has passed, so per-frame
605
+ // analysis has nothing left to decide. Detaching it for the duration of
606
+ // the burst hands the whole CPU — and the ONNX session the anti-spoof
607
+ // re-check needs — to the capture pipeline instead of competing with it.
608
+ setAnalysisPaused(true)
609
+ captureBurst(output, state: CaptureBurstState())
610
+ }
611
+
612
+ /// Detach or re-attach the video-data delegate that drives per-frame analysis.
613
+ /// Re-attaching after a failed burst keeps liveness guidance alive for a retry.
614
+ private func setAnalysisPaused(_ paused: Bool) {
615
+ sessionQueue.async { [weak self] in
616
+ guard let self, let output = self.videoOutput else { return }
617
+ if paused {
618
+ output.setSampleBufferDelegate(nil, queue: nil)
619
+ } else {
620
+ output.setSampleBufferDelegate(self, queue: self.analysisQueue)
621
+ }
622
+ }
623
+ }
624
+
625
+ // MARK: - Capture burst
626
+
627
+ private func captureBurst(_ output: AVCapturePhotoOutput, state: CaptureBurstState) {
628
+ let settings = AVCapturePhotoSettings()
629
+ // .balanced, not .quality: every consumer of this still is a downscale —
630
+ // a 112x112 aligned crop for the embedding, an 80x80 crop for anti-spoof,
631
+ // and a compressed upload — so the extra multi-frame ISP work .quality
632
+ // requests is discarded, while its shutter latency is paid per burst
633
+ // sample. .speed is deliberately not used: it can return a frame with
634
+ // visibly less noise reduction, which does reach the embedding.
635
+ settings.photoQualityPrioritization = .balanced
636
+ settings.isHighResolutionPhotoEnabled = false
637
+ // No shutter click: the capture fires on its own the moment liveness
638
+ // completes, so a camera sound (twice, once per burst sample) is only
639
+ // startling. iOS 18+ supports suppression officially; older versions
640
+ // fall back to PhotoCaptureDelegate's willCapture workaround. Regions
641
+ // that legally require the sound (e.g. Japan, Korea) still play it.
642
+ if #available(iOS 18.0, *), output.isShutterSoundSuppressionSupported {
643
+ settings.isShutterSoundSuppressionEnabled = true
644
+ }
645
+
646
+ let delegate = PhotoCaptureDelegate { [weak self] image, error in
647
+ guard let self else { return }
648
+ if let error {
649
+ self.captureInProgress = false
650
+ self.setAnalysisPaused(false)
651
+ self.cleanupFailedBurst(state)
652
+ self.emitError("E_CAPTURE", FaceMatchError.message(of: error))
653
+ return
654
+ }
655
+ guard let image else {
656
+ self.captureInProgress = false
657
+ self.setAnalysisPaused(false)
658
+ self.cleanupFailedBurst(state)
659
+ self.emitError("E_CAPTURE", "Unable to read captured image")
660
+ return
661
+ }
662
+ self.processCaptureSample(output, image: image, state: state)
663
+ }
664
+ burstDelegate = delegate
665
+ output.capturePhoto(with: settings, delegate: delegate)
666
+ }
667
+
668
+ private func processCaptureSample(
669
+ _ output: AVCapturePhotoOutput,
670
+ image: CGImage,
671
+ state: CaptureBurstState
672
+ ) {
673
+ captureQueue.async { [weak self] in
674
+ guard let self else { return }
675
+ do {
676
+ // Re-check the exact first image for liveness. The remaining
677
+ // images are taken immediately in the same verified burst and
678
+ // contribute identity embeddings only.
679
+ let extraction = state.sampleCount == 0
680
+ ? try FaceMatchEngine.shared.extractLive(
681
+ image,
682
+ threshold: self.antiSpoofThresholdValue
683
+ )
684
+ : try FaceMatchEngine.shared.extract(image)
685
+
686
+ if state.sampleCount == 0 {
687
+ let url = try PrivateCaptureStore.create()
688
+ guard let data = ImageUtils.jpegData(from: image, quality: 0.95) else {
689
+ throw FaceMatchError("E_CAPTURE_FILE", "Unable to encode the captured image")
690
+ }
691
+ try data.write(to: url, options: .atomic)
692
+ state.captureURL = url
693
+ state.width = image.width
694
+ state.height = image.height
695
+ state.faceCount = extraction.faceCount
696
+ state.embeddingSum = extraction.embedding
697
+ } else {
698
+ guard var sum = state.embeddingSum else {
699
+ throw FaceMatchError("E_EMBEDDING", "Could not aggregate face embeddings")
700
+ }
701
+ for index in extraction.embedding.indices {
702
+ sum[index] += extraction.embedding[index]
703
+ }
704
+ state.embeddingSum = sum
705
+ }
706
+ state.sampleCount += 1
707
+
708
+ if state.sampleCount < Constants.identityCaptureBurstSize {
709
+ DispatchQueue.main.async {
710
+ guard self.cameraStarted, self.photoOutput === output else {
711
+ self.cleanupFailedBurst(state)
712
+ self.captureInProgress = false
713
+ self.setAnalysisPaused(false)
714
+ self.emitError("E_CAMERA_NOT_READY", "Camera stopped during capture")
715
+ return
716
+ }
717
+ self.captureBurst(output, state: state)
718
+ }
719
+ return
720
+ }
721
+
722
+ guard let sum = state.embeddingSum else {
723
+ throw FaceMatchError("E_EMBEDDING", "Could not aggregate face embeddings")
724
+ }
725
+ let identityEmbedding = try Self.normalizeSum(sum)
726
+ guard let url = state.captureURL else {
727
+ throw FaceMatchError("E_CAPTURE_FILE", "Capture file is unavailable")
728
+ }
729
+
730
+ let payload: [String: Any] = [
731
+ "uri": url.absoluteString,
732
+ "width": state.width,
733
+ "height": state.height,
734
+ "faceCount": state.faceCount,
735
+ "embedding": identityEmbedding.map { Double($0) }
736
+ ]
737
+ DispatchQueue.main.async {
738
+ self.onCapture?(payload)
739
+ self.requestedStart = false
740
+ self.stopCameraPipeline()
741
+ }
742
+ } catch {
743
+ let code = (error as? FaceMatchError)?.code ?? "E_CAPTURE_PROCESSING"
744
+ // Sample 0 is the one that went through extractLive(), so a failure
745
+ // here is the exact frame auto-capture took the instant liveness
746
+ // completed. The frame is written out under #if DEBUG only: in a
747
+ // release build this persisted a full-resolution biometric image to
748
+ // Documents/, outside everything PrivateCaptureStore manages, where
749
+ // it survived logout and was readable by anyone who downloaded the
750
+ // app container. Encoding it also cost 250-500 ms on the retry path
751
+ // the user was already waiting through.
752
+ #if DEBUG
753
+ let savedPath = state.sampleCount == 0
754
+ ? FaceCameraView.saveFailureDiagnostic(image, code: code)
755
+ : nil
756
+ os_log(
757
+ "%{public}@",
758
+ log: FaceCameraView.captureLog,
759
+ type: .fault,
760
+ "capture FAILED: sample=\(state.sampleCount) code=\(code) "
761
+ + "message=\(FaceMatchError.message(of: error)) "
762
+ + "image=\(image.width)x\(image.height) "
763
+ + "savedTo=\(savedPath ?? "n/a - see code above")"
764
+ )
765
+ #else
766
+ // Dimensions and code only — no image, no biometric content.
767
+ os_log(
768
+ "%{public}@",
769
+ log: FaceCameraView.captureLog,
770
+ type: .error,
771
+ "capture FAILED: sample=\(state.sampleCount) code=\(code) "
772
+ + "image=\(image.width)x\(image.height)"
773
+ )
774
+ #endif
775
+ self.cleanupFailedBurst(state)
776
+ DispatchQueue.main.async {
777
+ self.captureInProgress = false
778
+ self.setAnalysisPaused(false)
779
+ self.emitError(code, FaceMatchError.message(of: error))
780
+ }
781
+ }
782
+ }
783
+ }
784
+
785
+ #if DEBUG
786
+ /// Writes the exact frame that failed detection to a fixed, overwritten
787
+ /// path so it survives to be pulled off the device afterwards (Xcode ->
788
+ /// Devices and Simulators -> select the app -> gear icon -> Download
789
+ /// Container, then Documents/facematch-debug/last-capture-failure.jpg).
790
+ ///
791
+ /// DEBUG only. This writes an unencrypted biometric image outside
792
+ /// PrivateCaptureStore's lifecycle, so it must never ship in a release build.
793
+ private static func saveFailureDiagnostic(_ image: CGImage, code: String) -> String? {
794
+ guard let data = ImageUtils.jpegData(from: image, quality: 0.92) else { return nil }
795
+ let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
796
+ let dir = documents.appendingPathComponent("facematch-debug", isDirectory: true)
797
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
798
+ let url = dir.appendingPathComponent("last-capture-failure.jpg")
799
+ do {
800
+ try data.write(to: url, options: .atomic)
801
+ return url.path
802
+ } catch {
803
+ return nil
804
+ }
805
+ }
806
+ #endif
807
+
808
+ private static func normalizeSum(_ sum: [Float]) throws -> [Float] {
809
+ let norm = Float(sum.reduce(0.0) { $0 + Double($1) * Double($1) }.squareRoot())
810
+ guard norm.isFinite, norm >= 1e-6 else {
811
+ throw FaceMatchError("E_EMBEDDING", "Could not aggregate face embeddings")
812
+ }
813
+ return sum.map { $0 / norm }
814
+ }
815
+
816
+ private func cleanupFailedBurst(_ state: CaptureBurstState) {
817
+ if let url = state.captureURL {
818
+ try? FileManager.default.removeItem(at: url)
819
+ }
820
+ state.captureURL = nil
821
+ }
822
+
823
+ // MARK: - Frame handling
824
+
825
+ private func onFaceFrame(_ frame: FaceFrameResult) {
826
+ #if DEBUG
827
+ let hitchStart = CACurrentMediaTime()
828
+ defer {
829
+ // Anything over one 60Hz frame here stalls UIKit and React Native's
830
+ // mounting for the same tick, which is what tears the screen.
831
+ let elapsedMs = (CACurrentMediaTime() - hitchStart) * 1000
832
+ if elapsedMs > 16 {
833
+ Self.log(String(format: "MAIN-THREAD HITCH %.1fms in onFaceFrame", elapsedMs))
834
+ }
835
+ }
836
+ #endif
837
+ lastFaceCount = frame.faceCount
838
+ lastAntiSpoofStatus = frame.antiSpoof?.status
839
+ let wasComplete = livenessProgress.isComplete
840
+ let progress = livenessDetector.update(frame)
841
+ livenessProgress = progress
842
+ overlayView.update(frame: frame, progress: progress)
843
+
844
+ // Low-light detection: exponentially smooth the per-frame brightness and
845
+ // apply a hysteresis band before boosting the screen.
846
+ smoothedLuma = smoothedLuma < 0
847
+ ? frame.luminance
848
+ : smoothedLuma * 0.8 + frame.luminance * 0.2
849
+ let lowLight: Bool
850
+ if smoothedLuma < Constants.lowLightEnter {
851
+ lowLight = true
852
+ } else if smoothedLuma > Constants.lowLightExit {
853
+ lowLight = false
854
+ } else {
855
+ lowLight = screenBoosted
856
+ }
857
+ if brightenOnLowLightFlag { debounceScreenBoost(lowLight) }
858
+
859
+ let now = Date.timeIntervalSinceReferenceDate * 1000
860
+ if now - lastFaceEmitAt >= Constants.faceEmitIntervalMs {
861
+ lastFaceEmitAt = now
862
+ var payload: [String: Any] = [
863
+ "lowLight": lowLight,
864
+ "luminance": Double(smoothedLuma),
865
+ "hasFace": frame.hasFace,
866
+ "faceCount": frame.faceCount,
867
+ "hasMultipleFaces": frame.hasMultipleFaces,
868
+ "isPositioned": frame.isPositioned,
869
+ "isGoodPose": frame.isGoodPose,
870
+ "yaw": Double(frame.yaw),
871
+ "pitch": Double(frame.pitch),
872
+ "roll": Double(frame.roll)
873
+ ]
874
+ if let left = frame.leftEyeOpenProbability {
875
+ payload["leftEyeOpenProbability"] = Double(left)
876
+ }
877
+ if let right = frame.rightEyeOpenProbability {
878
+ payload["rightEyeOpenProbability"] = Double(right)
879
+ }
880
+ if let antiSpoof = frame.antiSpoof {
881
+ payload["antiSpoofStatus"] = antiSpoof.status.rawValue
882
+ if let score = antiSpoof.realScore {
883
+ payload["antiSpoofRealScore"] = Double(score)
884
+ }
885
+ payload["antiSpoofThreshold"] = Double(antiSpoof.threshold)
886
+ }
887
+ onFaceState?(payload)
888
+ }
889
+
890
+ if let antiSpoof = frame.antiSpoof {
891
+ let errorSignature = "\(antiSpoof.status)|\(antiSpoof.errorMessage ?? "")"
892
+ switch antiSpoof.status {
893
+ case .real:
894
+ break
895
+ // Motion and lighting can make individual analysis frames fluctuate.
896
+ // Liveness pauses through its one guidance message; the exact
897
+ // captured image remains fail-closed.
898
+ case .spoof:
899
+ break
900
+ case .error:
901
+ if errorSignature != lastAntiSpoofErrorSignature {
902
+ lastAntiSpoofErrorSignature = errorSignature
903
+ emitError(
904
+ "E_ANTI_SPOOF_MODEL",
905
+ antiSpoof.errorMessage ?? "Passive anti-spoofing is unavailable"
906
+ )
907
+ }
908
+ }
909
+ }
910
+
911
+ let signature = "\(progress.promptKey.rawValue)|\(progress.completedActions.count)|\(progress.isComplete)"
912
+ if signature != lastLivenessSignature {
913
+ lastLivenessSignature = signature
914
+ emitLiveness(progress)
915
+ }
916
+
917
+ if !wasComplete && progress.isComplete && autoCaptureOnLivenessFlag && !autoCaptureTriggered {
918
+ autoCaptureTriggered = true
919
+ DispatchQueue.main.async { [weak self] in self?.capture() }
920
+ }
921
+ }
922
+
923
+ // MARK: - Emission
924
+
925
+ private func emitLiveness(_ progress: LivenessProgress) {
926
+ let prompt = progress.promptKey
927
+ var payload: [String: Any] = [
928
+ "promptKey": prompt.rawValue,
929
+ "promptEn": prompt.en,
930
+ "promptHi": prompt.hi,
931
+ "instruction": prompt.en,
932
+ "isComplete": progress.isComplete,
933
+ "stepIndex": progress.stepIndex,
934
+ "stepCount": progress.stepCount,
935
+ "actionProgress": Double(progress.actionProgress),
936
+ "completedActions": progress.completedActions.map { $0.rawValue }
937
+ ]
938
+ if let action = progress.currentAction {
939
+ payload["currentAction"] = action.rawValue
940
+ }
941
+ onLiveness?(payload)
942
+
943
+ if voiceLanguage != "none" && prompt.spoken {
944
+ voice.speak(key: prompt.rawValue, text: prompt.localized(voiceLanguage))
945
+ }
946
+ }
947
+
948
+ private func emitCameraState(_ state: String) {
949
+ onCameraState?(["state": state])
950
+ }
951
+
952
+ private func emitError(_ code: String, _ message: String) {
953
+ onError?(["code": code, "message": message])
954
+ }
955
+
956
+ // MARK: - Screen brightness
957
+
958
+ /// Drive the screen to full brightness (or release the override) so the
959
+ /// front camera has enough light on the user's face in a dim room.
960
+ private func debounceScreenBoost(_ target: Bool) {
961
+ if target == screenBoosted {
962
+ pendingBoostState = nil
963
+ return
964
+ }
965
+ let now = CACurrentMediaTime()
966
+ if pendingBoostState != target {
967
+ pendingBoostState = target
968
+ pendingBoostSince = now
969
+ return
970
+ }
971
+ if now - pendingBoostSince >= Constants.lowLightDebounceSeconds {
972
+ applyScreenBoost(target)
973
+ pendingBoostState = nil
974
+ }
975
+ }
976
+
977
+ private func applyScreenBoost(_ boost: Bool) {
978
+ if boost == screenBoosted { return }
979
+ screenBoosted = boost
980
+ DispatchQueue.main.async {
981
+ if boost {
982
+ if self.originalBrightness == nil {
983
+ self.originalBrightness = UIScreen.main.brightness
984
+ }
985
+ UIScreen.main.brightness = 1.0
986
+ } else if let original = self.originalBrightness {
987
+ UIScreen.main.brightness = original
988
+ self.originalBrightness = nil
989
+ }
990
+ }
991
+ }
992
+
993
+ // MARK: - Lifecycle
994
+
995
+ @objc private func handleDidBecomeActive() {
996
+ if requestedStart { startCamera() }
997
+ }
998
+
999
+ @objc private func handleWillResignActive() {
1000
+ stopCameraPipeline()
1001
+ }
1002
+
1003
+ /// A media-services reset (or a transient device error) stops the session
1004
+ /// without any other signal, leaving the camera box frozen or black until
1005
+ /// the screen was reopened. Rebuild the pipeline if the camera is wanted.
1006
+ @objc private func handleSessionRuntimeError(_ notification: Notification) {
1007
+ DispatchQueue.main.async { [weak self] in
1008
+ guard let self, self.requestedStart else { return }
1009
+ self.stopCameraPipeline()
1010
+ self.sessionQueue.async { [weak self] in
1011
+ guard let self else { return }
1012
+ self.session.beginConfiguration()
1013
+ self.session.inputs.forEach { self.session.removeInput($0) }
1014
+ self.session.commitConfiguration()
1015
+ self.videoInput = nil
1016
+ DispatchQueue.main.async {
1017
+ if self.requestedStart { self.startCamera() }
1018
+ }
1019
+ }
1020
+ }
1021
+ }
1022
+
1023
+ #if DEBUG
1024
+ /// Diagnostics for the analysis loop. Debug builds only — the release build
1025
+ /// never logs anything derived from a camera frame.
1026
+ fileprivate static func log(_ message: String) {
1027
+ os_log("%{public}@", log: debugLog, type: .info, message)
1028
+ }
1029
+ #endif
1030
+
1031
+ func dispose() {
1032
+ requestedStart = false
1033
+ stopCameraPipeline()
1034
+ applyScreenBoost(false)
1035
+ voice.shutdown()
1036
+ overlayView.stopAnimating()
1037
+ sessionQueue.async { [session] in
1038
+ session.beginConfiguration()
1039
+ session.inputs.forEach { session.removeInput($0) }
1040
+ session.outputs.forEach { session.removeOutput($0) }
1041
+ session.commitConfiguration()
1042
+ }
1043
+ videoOutput?.setSampleBufferDelegate(nil, queue: nil)
1044
+ videoOutput = nil
1045
+ photoOutput = nil
1046
+ videoInput = nil
1047
+ NotificationCenter.default.removeObserver(self)
1048
+ }
1049
+ }
1050
+
1051
+ // MARK: - Analysis
1052
+
1053
+ extension FaceCameraView: AVCaptureVideoDataOutputSampleBufferDelegate {
1054
+ func captureOutput(
1055
+ _ output: AVCaptureOutput,
1056
+ didOutput sampleBuffer: CMSampleBuffer,
1057
+ from connection: AVCaptureConnection
1058
+ ) {
1059
+ // Keep-only-latest: drop frames that arrive while one is in flight.
1060
+ if analysisBusy { return }
1061
+ guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
1062
+
1063
+ analysisBusy = true
1064
+ defer { analysisBusy = false }
1065
+
1066
+ // Convert and downscale in one Core Image pass; the framing gates and
1067
+ // the anti-spoof crop then see the same resolution CameraX delivers.
1068
+ guard let converted = ImageUtils.analysisImage(
1069
+ from: pixelBuffer,
1070
+ maxSide: Constants.analysisMaxSide
1071
+ ) else {
1072
+ #if DEBUG
1073
+ Self.log("frame dropped: could not convert the pixel buffer")
1074
+ #endif
1075
+ return
1076
+ }
1077
+
1078
+ // Non-zero only when the connection refused the rotation; ML Kit finds
1079
+ // upright faces only, so the frame must be corrected either way.
1080
+ let rotation = currentSoftwareRotation
1081
+ let image = rotation == 0 ? converted : ImageUtils.rotate(converted, degrees: rotation)
1082
+
1083
+ let result = analyzer.analyze(image)
1084
+
1085
+ #if DEBUG
1086
+ frameCounter += 1
1087
+ if frameCounter == 1 || frameCounter % 30 == 0 {
1088
+ Self.log(String(
1089
+ format: "frame %d: %dx%d luma=%.0f faces=%d spoof=%@",
1090
+ frameCounter,
1091
+ image.width,
1092
+ image.height,
1093
+ result.luminance,
1094
+ result.faceCount,
1095
+ result.antiSpoof.map { "\($0.status.rawValue)" } ?? "n/a"
1096
+ ))
1097
+ }
1098
+ #endif
1099
+
1100
+ DispatchQueue.main.async { [weak self] in
1101
+ self?.onFaceFrame(result)
1102
+ }
1103
+ }
1104
+ }
1105
+
1106
+ // MARK: - Photo delegate
1107
+
1108
+ /// `AVCapturePhotoOutput` only retains its delegate for the duration of one
1109
+ /// capture, so the view holds a strong reference for the burst.
1110
+ private final class PhotoCaptureDelegate: NSObject, AVCapturePhotoCaptureDelegate {
1111
+ private let completion: (CGImage?, Error?) -> Void
1112
+
1113
+ init(completion: @escaping (CGImage?, Error?) -> Void) {
1114
+ self.completion = completion
1115
+ }
1116
+
1117
+ /// Pre-iOS 18 shutter-sound suppression: disposing the system shutter sound
1118
+ /// (1108) just before the exposure stops AVFoundation from playing it.
1119
+ /// Unneeded where `isShutterSoundSuppressionEnabled` is honoured.
1120
+ func photoOutput(
1121
+ _ output: AVCapturePhotoOutput,
1122
+ willCapturePhotoFor resolvedSettings: AVCaptureResolvedPhotoSettings
1123
+ ) {
1124
+ if #available(iOS 18.0, *), output.isShutterSoundSuppressionSupported { return }
1125
+ AudioServicesDisposeSystemSoundID(1108)
1126
+ }
1127
+
1128
+ func photoOutput(
1129
+ _ output: AVCapturePhotoOutput,
1130
+ didFinishProcessingPhoto photo: AVCapturePhoto,
1131
+ error: Error?
1132
+ ) {
1133
+ if let error {
1134
+ DispatchQueue.main.async { self.completion(nil, error) }
1135
+ return
1136
+ }
1137
+ guard let raw = photo.cgImageRepresentation() else {
1138
+ DispatchQueue.main.async { self.completion(nil, nil) }
1139
+ return
1140
+ }
1141
+
1142
+ // The photo output records orientation as an EXIF tag rather than
1143
+ // rotating the buffer, so bake it in before anything downstream sees
1144
+ // the image — ML Kit does not detect sideways faces.
1145
+ let rawValue = photo.metadata[kCGImagePropertyOrientation as String] as? UInt32
1146
+ let orientation = rawValue.flatMap(CGImagePropertyOrientation.init) ?? .up
1147
+ let upright = ImageUtils.normalized(raw, orientation: orientation)
1148
+
1149
+ // DEBUG only, and no longer .fault: this fired for every photo in every
1150
+ // burst, and a fault-level entry is persisted and surfaced as a crash-class
1151
+ // signal — for what is ordinary success bookkeeping.
1152
+ #if DEBUG
1153
+ let message = "capture: raw=\(raw.width)x\(raw.height) "
1154
+ + "exifOrientation=\(orientation)(rawTag=\(rawValue.map(String.init) ?? "nil")) "
1155
+ + "upright=\(upright.width)x\(upright.height)"
1156
+ os_log("%{public}@", log: FaceCameraView.captureLog, type: .info, message)
1157
+ #endif
1158
+
1159
+ DispatchQueue.main.async { self.completion(upright, nil) }
1160
+ }
1161
+ }