SPB Git

Repository Public

CameraController.swift 22.7 KB 513 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr Identity9// File             : sdk/swift/Sources/MacLustrIdentityUI/CameraController.swift10// Module           : MacLustrIdentityUI11// Repository       : https://git.spboucher.ai/maclustr-identity12// Project Website  : https://identity.spboucher.ai13// Created          : 2026-12-0114// Last Modified    : 2026-12-0115//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: admin@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788// AVFoundation capture session shared by the document and selfie screens. Frames stay in memory.89import AVFoundation90import CoreImage91import SwiftUI92import MacLustrIdentityCore9394/// A value protected by a lock, for state shared between the main thread and the capture queues.95final class Locked<Value>: @unchecked Sendable {96    private var value: Value97    private let lock = NSLock()98    init(_ value: Value) { self.value = value }99    func get() -> Value { lock.lock(); defer { lock.unlock() }; return value }100    func set(_ new: Value) { lock.lock(); value = new; lock.unlock() }101    func with<T>(_ body: (inout Value) -> T) -> T { lock.lock(); defer { lock.unlock() }; return body(&value) }102}103104final class CameraController: NSObject, ObservableObject, @unchecked Sendable {105    enum Purpose { case document, selfie }106    enum Status: Equatable { case idle, running, interrupted, failed }107108    /// Updated on the main thread.109    @Published private(set) var status: Status = .idle110111    let purpose: Purpose112    let session = AVCaptureSession()113    /// The preview layer is owned here so that rotation can follow it before the view exists.114    let previewLayer: AVCaptureVideoPreviewLayer115116    /// Called on the frame queue for every delivered frame: pixel buffer (upright, unmirrored) and its timestamp in seconds.117    let onFrame = Locked<((CVPixelBuffer, TimeInterval) -> Void)?>(nil)118119    private let sessionQueue = DispatchQueue(label: "ai.spboucher.maclustr.identity.camera.session")120    private let frameQueue = DispatchQueue(label: "ai.spboucher.maclustr.identity.camera.frames", qos: .userInitiated)121    private let videoOutput = AVCaptureVideoDataOutput()122    private let photoOutput = AVCapturePhotoOutput()123    private var hasPhotoOutput = false124    private var configured = false125    private var wantsRunning = false126    private var device: AVCaptureDevice?127    private var rotationObservation: NSKeyValueObservation?128    private var rotationCoordinator: AnyObject?129    private let latestFrame = Locked<CVPixelBuffer?>(nil)130    private let photoContinuation = Locked<CheckedContinuation<Data, Error>?>(nil)131    private var observers: [NSObjectProtocol] = []132133    init(purpose: Purpose) {134        self.purpose = purpose135        previewLayer = AVCaptureVideoPreviewLayer(session: session)136        previewLayer.videoGravity = .resizeAspectFill137        super.init()138        let nc = NotificationCenter.default139        #if os(iOS)140        observers.append(nc.addObserver(forName: AVCaptureSession.wasInterruptedNotification, object: session, queue: .main) { [weak self] _ in self?.status = .interrupted })141        observers.append(nc.addObserver(forName: AVCaptureSession.interruptionEndedNotification, object: session, queue: .main) { [weak self] _ in142            guard let self else { return }143            self.status = self.session.isRunning ? .running : .idle144        })145        #endif146        observers.append(nc.addObserver(forName: AVCaptureSession.runtimeErrorNotification, object: session, queue: .main) { [weak self] _ in147            guard let self else { return }148            self.status = .failed149            // Media services reset and similar errors are usually cured by restarting the session.150            if self.wantsRunning { self.start() }151        })152    }153154    deinit {155        observers.forEach(NotificationCenter.default.removeObserver)156        rotationObservation?.invalidate()157        let session = self.session158        if session.isRunning { sessionQueue.async { session.stopRunning() } }159    }160161    // MARK: Availability and permission162163    static func device(for purpose: Purpose) -> AVCaptureDevice? {164        #if os(iOS)165        if purpose == .selfie { return AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front) }166        // Virtual multi-camera devices switch to the ultra-wide lens for close subjects, which helps focusing on a card.167        for type in [AVCaptureDevice.DeviceType.builtInTripleCamera, .builtInDualWideCamera, .builtInWideAngleCamera] {168            if let d = AVCaptureDevice.default(type, for: .video, position: .back) { return d }169        }170        return nil171        #else172        return AVCaptureDevice.default(for: .video)173        #endif174    }175176    static func hasCamera(_ purpose: Purpose) -> Bool { device(for: purpose) != nil }177178    /// The host app must declare why it uses the camera, otherwise the system terminates it on the first access.179    static var usageDescriptionIsDeclared: Bool {180        Bundle.main.object(forInfoDictionaryKey: "NSCameraUsageDescription") != nil181    }182183    static var authorization: AVAuthorizationStatus { AVCaptureDevice.authorizationStatus(for: .video) }184185    // MARK: Lifecycle186187    func start() {188        wantsRunning = true189        sessionQueue.async { [weak self] in190            guard let self else { return }191            if !self.configured {192                self.configure()193                // After the configuration is committed: the active format is then the one the photo preset selected.194                if self.configured { self.applyPhotoDimensions() }195            }196            guard self.configured else { return self.publish(.failed) }197            if !self.session.isRunning { self.session.startRunning() }198            self.publish(self.session.isRunning ? .running : .failed)199        }200    }201202    func stop() {203        wantsRunning = false204        latestFrame.set(nil)205        sessionQueue.async { [weak self] in206            guard let self else { return }207            if self.session.isRunning { self.session.stopRunning() }208            self.publish(.idle)209        }210    }211212    private func publish(_ s: Status) {213        DispatchQueue.main.async { [weak self] in214            guard let self, self.status != s else { return }215            // A stop requested meanwhile wins over a late "running".216            if s == .running, !self.wantsRunning { return }217            self.status = s218        }219    }220221    private func configure() {222        guard let device = CameraController.device(for: purpose), let input = try? AVCaptureDeviceInput(device: device) else { return }223        session.beginConfiguration()224        defer { session.commitConfiguration() }225        if purpose == .document, session.canSetSessionPreset(.photo) {226            session.sessionPreset = .photo227        } else if session.canSetSessionPreset(.hd1280x720) {228            session.sessionPreset = .hd1280x720229        } else {230            session.sessionPreset = .high231        }232        guard session.canAddInput(input) else { return }233        session.addInput(input)234235        videoOutput.alwaysDiscardsLateVideoFrames = true236        let wanted = [kCVPixelFormatType_420YpCbCr8BiPlanarFullRange, kCVPixelFormatType_32BGRA]237        if let format = wanted.first(where: { videoOutput.availableVideoPixelFormatTypes.contains($0) }) {238            videoOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: format]239        }240        videoOutput.setSampleBufferDelegate(self, queue: frameQueue)241        guard session.canAddOutput(videoOutput) else { return }242        session.addOutput(videoOutput)243        if purpose == .document, session.canAddOutput(photoOutput) {244            session.addOutput(photoOutput)245            hasPhotoOutput = true246            // The document is a full-resolution still photo, never a video frame: a 1080p frame is too small for a247            // licence barcode (PDF417). Quality is preferred over shutter speed.248            photoOutput.maxPhotoQualityPrioritization = .quality249        }250251        if (try? device.lockForConfiguration()) != nil {252            if device.isFocusModeSupported(.continuousAutoFocus) { device.focusMode = .continuousAutoFocus }253            if device.isExposureModeSupported(.continuousAutoExposure) { device.exposureMode = .continuousAutoExposure }254            #if os(iOS)255            if purpose == .document, device.isAutoFocusRangeRestrictionSupported { device.autoFocusRangeRestriction = .near }256            #endif257            device.unlockForConfiguration()258        }259260        // Uploaded frames are never mirrored; only the selfie preview is, like a mirror.261        if let c = videoOutput.connection(with: .video), c.isVideoMirroringSupported {262            c.automaticallyAdjustsVideoMirroring = false263            c.isVideoMirrored = false264        }265        if let c = previewLayer.connection, c.isVideoMirroringSupported {266            c.automaticallyAdjustsVideoMirroring = false267            c.isVideoMirrored = purpose == .selfie268        }269        self.device = device270        configureRotation(device)271        configured = true272    }273274    /// Keeps frames, photos and preview upright for the current interface orientation.275    private func configureRotation(_ device: AVCaptureDevice) {276        if #available(iOS 17.0, macOS 14.0, *) {277            let coordinator = AVCaptureDevice.RotationCoordinator(device: device, previewLayer: previewLayer)278            rotationCoordinator = coordinator279            applyRotation(coordinator.videoRotationAngleForHorizonLevelPreview)280            rotationObservation = coordinator.observe(\.videoRotationAngleForHorizonLevelPreview, options: [.new]) { [weak self] coordinator, _ in281                let angle = coordinator.videoRotationAngleForHorizonLevelPreview282                self?.sessionQueue.async { self?.applyRotation(angle) }283            }284        } else {285            #if os(iOS)286            // iOS 16: portrait only.287            for c in connections where c.isVideoOrientationSupported { c.videoOrientation = .portrait }288            #endif289        }290    }291292    private var connections: [AVCaptureConnection] {293        [videoOutput.connection(with: .video), hasPhotoOutput ? photoOutput.connection(with: .video) : nil, previewLayer.connection].compactMap { $0 }294    }295296    @available(iOS 17.0, macOS 14.0, *)297    private func applyRotation(_ angle: CGFloat) {298        for c in connections where c.isVideoRotationAngleSupported(angle) { c.videoRotationAngle = angle }299    }300301    /// Asks the photo output for a still large enough for the service. Only a size listed by the active format is ever set.302    private func applyPhotoDimensions() {303        guard hasPhotoOutput, let device else { return }304        let supported = device.activeFormat.supportedMaxPhotoDimensions305        guard let wanted = CameraController.photoDimensions(for: supported.map { ($0.width, $0.height) }),306              let match = supported.first(where: { $0.width == wanted.0 && $0.height == wanted.1 }) else { return }307        photoOutput.maxPhotoDimensions = match308    }309310    /// Picks the still-photo size among those the camera format supports: the smallest one whose long side reaches311    /// what the service keeps (3600 px), so that nothing useful is lost and no 48 MP image is processed for nothing;312    /// when none reaches it, the largest available.313    static func photoDimensions(for supported: [(Int32, Int32)], wantedLongSide: Int32 = Int32(ImageUtilities.documentMaxSide)) -> (Int32, Int32)? {314        let sorted = supported.sorted { Int64($0.0) * Int64($0.1) < Int64($1.0) * Int64($1.1) }315        return sorted.first { max($0.0, $0.1) >= wantedLongSide } ?? sorted.last316    }317318    // MARK: Still capture319320    /// Captures a still image and returns its encoded data, in memory. Falls back to the latest video frame321    /// when the device has no photo output.322    func captureStill() async throws -> Data {323        if hasPhotoOutput, photoOutput.connection(with: .video)?.isActive == true {324            return try await withCheckedThrowingContinuation { continuation in325                let pending = photoContinuation.with { current -> Bool in326                    if current != nil { return true }327                    current = continuation328                    return false329                }330                if pending { return continuation.resume(throwing: IdentityError.captureFailed("capture already in progress")) }331                sessionQueue.async { [self] in332                    let settings: AVCapturePhotoSettings333                    if photoOutput.availablePhotoCodecTypes.contains(.jpeg) {334                        settings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg])335                    } else {336                        settings = AVCapturePhotoSettings()337                    }338                    settings.maxPhotoDimensions = photoOutput.maxPhotoDimensions339                    settings.photoQualityPrioritization = photoOutput.maxPhotoQualityPrioritization340                    settings.flashMode = .off                // a flash puts a glare on a laminated card341                    photoOutput.capturePhoto(with: settings, delegate: self)342                }343            }344        }345        // No photo output (rare: a camera that only streams). The frame is sent at its full size; the review screen warns346        // the person when it is too small for a barcode.347        guard let frame = latestFrame.get(), let jpeg = ImageUtilities.jpegData(from: frame, maxShortSide: 4000, quality: ImageUtilities.documentQuality, context: ImageUtilities.makeContext()) else {348            throw IdentityError.captureFailed("no frame")349        }350        return jpeg351    }352}353354extension CameraController: AVCaptureVideoDataOutputSampleBufferDelegate {355    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {356        guard let buffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }357        latestFrame.set(buffer)358        onFrame.get()?(buffer, CMSampleBufferGetPresentationTimeStamp(sampleBuffer).seconds)359    }360}361362extension CameraController: AVCapturePhotoCaptureDelegate {363    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {364        let continuation = photoContinuation.with { current -> CheckedContinuation<Data, Error>? in365            defer { current = nil }366            return current367        }368        if let data = photo.fileDataRepresentation(), error == nil {369            continuation?.resume(returning: data)370        } else {371            continuation?.resume(throwing: IdentityError.captureFailed("photo capture failed"))372        }373    }374}375376// MARK: - Preview377378#if os(iOS)379struct CameraPreview: UIViewRepresentable {380    let controller: CameraController381382    final class PreviewView: UIView {383        var previewLayer: AVCaptureVideoPreviewLayer? {384            didSet {385                oldValue?.removeFromSuperlayer()386                if let previewLayer { layer.addSublayer(previewLayer) }387            }388        }389390        override func layoutSubviews() {391            super.layoutSubviews()392            CATransaction.begin()393            CATransaction.setDisableActions(true)394            previewLayer?.frame = bounds395            CATransaction.commit()396        }397    }398399    func makeUIView(context: Context) -> PreviewView {400        let v = PreviewView()401        v.backgroundColor = .black402        v.previewLayer = controller.previewLayer403        v.isAccessibilityElement = false404        return v405    }406407    func updateUIView(_ view: PreviewView, context: Context) {408        if view.previewLayer !== controller.previewLayer { view.previewLayer = controller.previewLayer }409    }410}411#else412struct CameraPreview: NSViewRepresentable {413    let controller: CameraController414415    final class PreviewView: NSView {416        var previewLayer: AVCaptureVideoPreviewLayer? {417            didSet {418                oldValue?.removeFromSuperlayer()419                if let previewLayer { layer?.addSublayer(previewLayer) }420            }421        }422423        override func layout() {424            super.layout()425            CATransaction.begin()426            CATransaction.setDisableActions(true)427            previewLayer?.frame = bounds428            CATransaction.commit()429        }430    }431432    func makeNSView(context: Context) -> PreviewView {433        let v = PreviewView()434        v.wantsLayer = true435        v.layer?.backgroundColor = NSColor.black.cgColor436        v.previewLayer = controller.previewLayer437        return v438    }439440    func updateNSView(_ view: PreviewView, context: Context) {441        if view.previewLayer !== controller.previewLayer { view.previewLayer = controller.previewLayer }442    }443}444#endif445446// MARK: - Permission gate447448/// Shows the content only once the camera is authorised and present; otherwise explains, asks, or links to the settings.449struct CameraGate<Content: View, Fallback: View>: View {450    let purpose: CameraController.Purpose451    @ViewBuilder var content: () -> Content452    /// Shown when the device has no camera for this purpose.453    @ViewBuilder var unavailable: () -> Fallback454455    @Environment(\.identityLanguage) private var lang456    @Environment(\.scenePhase) private var scenePhase457    @State private var authorization = CameraController.authorization458459    var body: some View {460        Group {461            if !CameraController.hasCamera(purpose) || !CameraController.usageDescriptionIsDeclared {462                unavailable()463            } else {464                switch authorization {465                case .authorized:466                    content()467                case .notDetermined:468                    StepLayout {469                        Image(systemName: "camera").font(.largeTitle).foregroundStyle(Color.accentColor).accessibilityHidden(true)470                        Text(IdentityString.cameraPromptTitle.text(lang)).font(.title2.bold()).accessibilityAddTraits(.isHeader)471                        Text(IdentityString.cameraPromptBody.text(lang)).fixedSize(horizontal: false, vertical: true)472                    } actions: {473                        Button(IdentityString.cameraAllow.text(lang)) {474                            AVCaptureDevice.requestAccess(for: .video) { _ in475                                DispatchQueue.main.async { authorization = CameraController.authorization }476                            }477                        }478                        .buttonStyle(PrimaryButtonStyle())479                    }480                default:481                    StepLayout {482                        Image(systemName: "camera.badge.ellipsis").font(.largeTitle).foregroundStyle(.secondary).accessibilityHidden(true)483                        Text(IdentityString.cameraDeniedTitle.text(lang)).font(.title2.bold()).accessibilityAddTraits(.isHeader)484                        Text(IdentityString.cameraDeniedBody.text(lang)).fixedSize(horizontal: false, vertical: true)485                    } actions: {486                        Button(IdentityString.cameraOpenSettings.text(lang)) { CameraGate.openSettings() }487                            .buttonStyle(PrimaryButtonStyle())488                    }489                }490            }491        }492        // Coming back from the settings: read the authorisation again.493        .onChange(of: scenePhase) { phase in494            if phase == .active { authorization = CameraController.authorization }495        }496        .onAppear {497            #if DEBUG498            if !CameraController.usageDescriptionIsDeclared {499                print("MacLustrIdentity: add NSCameraUsageDescription to the app's Info.plist; the camera is disabled until then.")500            }501            #endif502        }503    }504505    static func openSettings() {506        #if os(iOS)507        if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) }508        #else509        if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Camera") { NSWorkspace.shared.open(url) }510        #endif511    }512}513
Files main
Menu

Theme