SPB Git

Repository Public

CameraController.swift 11.2 KB 252 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVault/Features/Scanner/CameraController.swift8// Module           : SPVault9// Repository       : https://git.spboucher.ai/sp-id-card-vault10// Project Website  : Not specified11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041@preconcurrency import AVFoundation42import CoreImage43import Foundation44import SwiftUI45import UIKit4647/// What one analysed video frame says about the card in view.48struct LiveAnalysis: Sendable {49    var quad: CardQuad?50    var report: QualityReport51    /// Size of the (upright) video frame, to place the overlay on the preview.52    var frameSize: CGSize53}5455enum CameraError: Error, Equatable {56    case unavailable57    case captureFailed58}5960/// The capture session: live frames for detection and quality hints, and61/// high-resolution stills. Photographs are handed over as in-memory `CGImage`s;62/// nothing is written to disk and nothing is added to the Photos library.63final class CameraController: NSObject, @unchecked Sendable {64    let session = AVCaptureSession()6566    private let sessionQueue = DispatchQueue(label: "ai.spboucher.idcardvault.camera.session")67    private let videoQueue = DispatchQueue(label: "ai.spboucher.idcardvault.camera.video", qos: .userInitiated)68    private let photoOutput = AVCapturePhotoOutput()69    private let videoOutput = AVCaptureVideoDataOutput()70    private var device: AVCaptureDevice?71    private var isConfigured = false7273    private let lock = NSLock()74    private var analysisHandler: (@MainActor @Sendable (LiveAnalysis) -> Void)?75    private var photoHandler: (@MainActor @Sendable (Result<CapturedStill, CameraError>) -> Void)?76    private var isAnalysing = false77    private var lastAnalysis = Date.distantPast78    private var isPaused = false7980    /// Minimum time between two analysed frames.81    private let analysisInterval: TimeInterval = 0.18283    func setAnalysisHandler(_ handler: (@MainActor @Sendable (LiveAnalysis) -> Void)?) {84        lock.withLock { analysisHandler = handler }85    }8687    /// Stops or resumes frame analysis without stopping the preview.88    func setPaused(_ paused: Bool) {89        lock.withLock { isPaused = paused }90    }9192    func start(completion: @escaping @MainActor @Sendable (Bool) -> Void) {93        sessionQueue.async { [self] in94            let ready = configureIfNeeded()95            if ready, !session.isRunning { session.startRunning() }96            Task { @MainActor in completion(ready) }97        }98    }99100    func stop() {101        sessionQueue.async { [self] in102            if session.isRunning { session.stopRunning() }103        }104    }105106    private func configureIfNeeded() -> Bool {107        if isConfigured { return true }108        guard let camera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back),109              let input = try? AVCaptureDeviceInput(device: camera) else { return false }110        session.beginConfiguration()111        defer { session.commitConfiguration() }112        session.sessionPreset = .photo113        guard session.canAddInput(input), session.canAddOutput(photoOutput), session.canAddOutput(videoOutput) else { return false }114        session.addInput(input)115        session.addOutput(photoOutput)116        videoOutput.alwaysDiscardsLateVideoFrames = true117        videoOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]118        videoOutput.setSampleBufferDelegate(self, queue: videoQueue)119        session.addOutput(videoOutput)120121        // Upright (portrait) frames and photographs.122        for output in [photoOutput, videoOutput] as [AVCaptureOutput] {123            if let connection = output.connection(with: .video), connection.isVideoRotationAngleSupported(90) {124                connection.videoRotationAngle = 90125            }126        }127        // The largest still up to 12 MP: ample for a card, without 48 MP memory spikes.128        let dimensions = camera.activeFormat.supportedMaxPhotoDimensions129        if let best = dimensions.filter({ max($0.width, $0.height) <= 4100 }).max(by: { $0.width * $0.height < $1.width * $1.height })130            ?? dimensions.min(by: { $0.width * $0.height < $1.width * $1.height }) {131            photoOutput.maxPhotoDimensions = best132        }133        photoOutput.maxPhotoQualityPrioritization = .quality134135        if (try? camera.lockForConfiguration()) != nil {136            if camera.isFocusModeSupported(.continuousAutoFocus) { camera.focusMode = .continuousAutoFocus }137            if camera.isAutoFocusRangeRestrictionSupported { camera.autoFocusRangeRestriction = .near }138            if camera.isExposureModeSupported(.continuousAutoExposure) { camera.exposureMode = .continuousAutoExposure }139            camera.unlockForConfiguration()140        }141        device = camera142        isConfigured = true143        return true144    }145146    var hasTorch: Bool { AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)?.hasTorch ?? false }147148    func setTorch(_ on: Bool) {149        sessionQueue.async { [self] in150            guard let device, device.hasTorch, (try? device.lockForConfiguration()) != nil else { return }151            device.torchMode = on ? .on : .off152            device.unlockForConfiguration()153        }154    }155156    /// Focus and expose on a point of the preview (normalised device coordinates).157    func focus(at devicePoint: CGPoint) {158        sessionQueue.async { [self] in159            guard let device, (try? device.lockForConfiguration()) != nil else { return }160            if device.isFocusPointOfInterestSupported { device.focusPointOfInterest = devicePoint; device.focusMode = .continuousAutoFocus }161            if device.isExposurePointOfInterestSupported { device.exposurePointOfInterest = devicePoint; device.exposureMode = .continuousAutoExposure }162            device.unlockForConfiguration()163        }164    }165166    func capturePhoto(completion: @escaping @MainActor @Sendable (Result<CapturedStill, CameraError>) -> Void) {167        sessionQueue.async { [self] in168            guard isConfigured, session.isRunning else {169                Task { @MainActor in completion(.failure(.unavailable)) }170                return171            }172            lock.withLock { photoHandler = completion }173            let settings = AVCapturePhotoSettings()174            settings.maxPhotoDimensions = photoOutput.maxPhotoDimensions175            settings.photoQualityPrioritization = .quality176            settings.flashMode = .off177            photoOutput.capturePhoto(with: settings, delegate: self)178        }179    }180}181182extension CameraController: AVCaptureVideoDataOutputSampleBufferDelegate {183    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {184        let (handler, proceed): ((@MainActor @Sendable (LiveAnalysis) -> Void)?, Bool) = lock.withLock {185            guard !isPaused, !isAnalysing, Date().timeIntervalSince(lastAnalysis) >= analysisInterval else { return (nil, false) }186            isAnalysing = true187            return (analysisHandler, true)188        }189        guard proceed else { return }190        defer { lock.withLock { isAnalysing = false; lastAnalysis = Date() } }191        guard let handler, let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }192        let quad = CardDetector.detect(in: pixelBuffer)?.quad193        let report = QualityAnalyzer.analyze(pixelBuffer, quad: quad)194        let analysis = LiveAnalysis(quad: quad, report: report,195                                    frameSize: CGSize(width: CVPixelBufferGetWidth(pixelBuffer), height: CVPixelBufferGetHeight(pixelBuffer)))196        Task { @MainActor in handler(analysis) }197    }198}199200extension CameraController: AVCapturePhotoCaptureDelegate {201    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {202        let handler = lock.withLock { () -> (@MainActor @Sendable (Result<CapturedStill, CameraError>) -> Void)? in203            defer { photoHandler = nil }204            return photoHandler205        }206        guard let handler else { return }207        var result: Result<CapturedStill, CameraError> = .failure(.captureFailed)208        if error == nil, let raw = photo.cgImageRepresentation() {209            let orientation = (photo.metadata[kCGImagePropertyOrientation as String] as? UInt32).flatMap(CGImagePropertyOrientation.init(rawValue:)) ?? .up210            let upright = ImageAdjustments.upright(raw, orientation: orientation)211            result = .success(CapturedStill(image: ImageAdjustments.limited(upright, longEdge: 4032)))212        }213        Task { @MainActor in handler(result) }214    }215}216217/// Camera preview layer hosted in SwiftUI.218struct CameraPreview: UIViewRepresentable {219    let session: AVCaptureSession220    var onTap: ((CGPoint) -> Void)?221222    final class PreviewView: UIView {223        override class var layerClass: AnyClass { AVCaptureVideoPreviewLayer.self }224        var previewLayer: AVCaptureVideoPreviewLayer { layer as! AVCaptureVideoPreviewLayer }225        var onTap: ((CGPoint) -> Void)?226227        @objc func tapped(_ recognizer: UITapGestureRecognizer) {228            let point = recognizer.location(in: self)229            onTap?(previewLayer.captureDevicePointConverted(fromLayerPoint: point))230        }231232        override func layoutSubviews() {233            super.layoutSubviews()234            if let connection = previewLayer.connection, connection.isVideoRotationAngleSupported(90) { connection.videoRotationAngle = 90 }235        }236    }237238    func makeUIView(context: Context) -> PreviewView {239        let view = PreviewView()240        view.backgroundColor = .black241        view.previewLayer.session = session242        view.previewLayer.videoGravity = .resizeAspectFill243        view.addGestureRecognizer(UITapGestureRecognizer(target: view, action: #selector(PreviewView.tapped(_:))))244        view.onTap = onTap245        return view246    }247248    func updateUIView(_ view: PreviewView, context: Context) {249        view.onTap = onTap250    }251}252
Files main
Menu

Theme