SPB Git

Repository Public

SelfieCaptureView.swift 17.5 KB 413 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/SelfieCaptureView.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// Selfie with a guided liveness challenge. Frames are unmirrored JPEG kept in memory until the upload.89import SwiftUI90import MacLustrIdentityCore9192/// Records and analyses frames on the camera queue while a challenge is running.93final class SelfieFrameProcessor: @unchecked Sendable {94    struct Progress: Equatable, Sendable {95        var instruction: LivenessInstruction96        var movement: Int97        var total: Int98        /// The movements are done; a few more frames are being recorded.99        var holding: Bool100    }101102    enum Outcome: Sendable { case finished([Data]), timedOut }103104    private struct Run {105        var guide: LivenessGuide106        var frames: [Data] = []107        var interval: TimeInterval108        var minFrames: Int109        var maxFrames: Int110        var startedAt: TimeInterval?111        var lastSample: TimeInterval = 0112        var lastProgress: Progress?113    }114115    private let run = Locked<Run?>(nil)116    private let context = ImageUtilities.makeContext()117    /// Longest duration of one attempt, well inside the 120 s validity of a challenge.118    private let timeout: TimeInterval = 40119    /// Upper bound of frames kept in memory during one attempt.120    private let hardLimit = 200121    var onProgress: (@Sendable (Progress) -> Void)?122    var onOutcome: (@Sendable (Outcome) -> Void)?123124    func begin(_ challenge: LivenessChallenge) {125        let minFrames = max(challenge.frames.min, 3)126        run.set(Run(guide: LivenessGuide(steps: challenge.steps, accessibleFrames: minFrames), interval: Double(max(challenge.frames.intervalMS, 100)) / 1000,127                    minFrames: minFrames, maxFrames: max(challenge.frames.max, minFrames)))128    }129130    /// Stops the attempt and releases its frames.131    func cancel() { run.set(nil) }132133    /// Called on the camera frame queue.134    func process(_ buffer: CVPixelBuffer, time: TimeInterval) {135        guard var r = run.get() else { return }136        if r.startedAt == nil { r.startedAt = time }137        guard time - r.lastSample >= r.interval else { return }138        r.lastSample = time139        if time - (r.startedAt ?? time) > timeout || r.frames.count >= hardLimit {140            finish(.timedOut)141            return142        }143        let short = Double(min(CVPixelBufferGetWidth(buffer), CVPixelBufferGetHeight(buffer)))144        let scale = min(1, Double(ImageUtilities.selfieShortSide) / short)145        let sample = VisionAnalysis.faceSample(in: buffer, uploadScale: scale)146        var index: Int?147        if let sample, sample.faceWidth >= r.guide.minFaceWidth,148           let jpeg = ImageUtilities.jpegData(from: buffer, maxShortSide: ImageUtilities.selfieShortSide, quality: 0.85, context: context) {149            r.frames.append(jpeg)150            index = r.frames.count - 1151        }152        let instruction = r.guide.update(sample, frameIndex: index)153        if r.guide.isDone, r.frames.count >= r.minFrames {154            let chosen = FrameSelector.select(count: r.frames.count, keyFrames: r.guide.keyFrames, max: r.maxFrames).map { r.frames[$0] }155            finish(.finished(chosen))156            return157        }158        let progress = Progress(instruction: instruction, movement: r.guide.currentMovement, total: r.guide.stepCount, holding: r.guide.isDone)159        let changed = progress != r.lastProgress160        r.lastProgress = progress161        // The attempt may have been cancelled from the main thread while this frame was analysed.162        let stillRunning = run.with { current -> Bool in163            guard current != nil else { return false }164            current = r165            return true166        }167        if stillRunning, changed {168            let callback = onProgress169            DispatchQueue.main.async { callback?(progress) }170        }171    }172173    private func finish(_ outcome: Outcome) {174        let wasRunning = run.with { current -> Bool in175            defer { current = nil }176            return current != nil177        }178        guard wasRunning else { return }179        let callback = onOutcome180        DispatchQueue.main.async { callback?(outcome) }181    }182}183184@MainActor185final class SelfieCaptureModel: ObservableObject {186    enum Phase: Equatable {187        case intro188        case accessibleIntro189        case preparing190        case capturing191        case uploading192        case problem(IdentityString)193    }194195    @Published var phase: Phase = .intro196    @Published var progress = SelfieFrameProcessor.Progress(instruction: .lookStraight, movement: 0, total: 0, holding: false)197198    let camera = CameraController(purpose: .selfie)199    private let processor = SelfieFrameProcessor()200    private var challenge: LivenessChallenge?201    private var accessible = false202    weak var flow: VerificationFlowModel?203204    init() {205        let processor = self.processor206        camera.onFrame.set { buffer, time in processor.process(buffer, time: time) }207        processor.onProgress = { [weak self] p in Task { @MainActor in self?.received(p) } }208        processor.onOutcome = { [weak self] o in Task { @MainActor in await self?.finished(o) } }209    }210211    func resume() { camera.start() }212213    /// Leaves the capture (background, interruption, screen dismissed): the attempt in progress is dropped.214    func pause(interrupted: Bool) {215        processor.cancel()216        camera.stop()217        if phase == .capturing || phase == .preparing {218            phase = interrupted ? .problem(.cameraInterrupted) : .intro219        }220    }221222    func begin(accessible: Bool) async {223        guard let flow, phase != .preparing, phase != .capturing, phase != .uploading else { return }224        self.accessible = accessible225        phase = .preparing226        do {227            let c = try await flow.requestChallenge(accessible: accessible)228            guard phase == .preparing else { return }       // interrupted meanwhile229            challenge = c230            progress = .init(instruction: .lookStraight, movement: 0, total: c.steps.count, holding: false)231            processor.begin(c)232            phase = .capturing233        } catch {234            if phase == .preparing { phase = .problem(IdentityString.forError(IdentityError.wrap(error))) }235        }236    }237238    func retry() async { await begin(accessible: accessible) }239240    private func received(_ p: SelfieFrameProcessor.Progress) {241        guard phase == .capturing else { return }242        progress = p243    }244245    private func finished(_ outcome: SelfieFrameProcessor.Outcome) async {246        guard phase == .capturing, let flow, let challenge else { return }247        switch outcome {248        case .timedOut:249            phase = .problem(.selfieTimeout)250        case .finished(let frames):251            phase = .uploading252            camera.stop()253            let ok = await flow.uploadSelfie(challengeID: challenge.challengeID, frames: frames)254            if !ok {255                camera.start()256                phase = .problem(flow.lastError.map(IdentityString.forError) ?? .errorGeneric)257            }258        }259    }260}261262struct SelfieCaptureView: View {263    @ObservedObject var flow: VerificationFlowModel264    @StateObject private var capture = SelfieCaptureModel()265    @Environment(\.identityLanguage) private var lang266    @Environment(\.scenePhase) private var scenePhase267    @Environment(\.accessibilityReduceMotion) private var reduceMotion268269    var body: some View {270        CameraGate(purpose: .selfie) {271            content272                .onAppear { capture.flow = flow; capture.resume() }273                .onDisappear { capture.pause(interrupted: false) }274                .onChange(of: scenePhase) { phase in275                    if phase == .active { capture.resume() } else { capture.pause(interrupted: true) }276                }277                .onChange(of: capture.camera.status) { status in278                    if status == .interrupted, capture.phase == .capturing || capture.phase == .preparing {279                        capture.pause(interrupted: true)280                        capture.resume()281                    }282                }283        } unavailable: {284            StepLayout {285                Text(IdentityString.selfieTitle.text(lang)).font(.title2.bold()).accessibilityAddTraits(.isHeader)286                NoticeView(kind: .info, text: IdentityString.selfieNoCamera.text(lang))287            } actions: { EmptyView() }288        }289    }290291    private var instructionText: String {292        switch capture.phase {293        case .capturing:294            return (capture.progress.holding ? IdentityString.selfieGuideHold : capture.progress.instruction.string).text(lang)295        case .preparing: return IdentityString.selfieGuideCenter.text(lang)296        case .uploading: return IdentityString.selfieUploading.text(lang)297        case .problem(let s): return s.text(lang)298        case .intro: return IdentityString.selfieIntro.text(lang)299        case .accessibleIntro: return IdentityString.selfieAccessibleBody.text(lang)300        }301    }302303    /// Arrow shown next to the instruction. The preview is mirrored, so the person's own left is on the left of the screen.304    private var arrow: String? {305        guard capture.phase == .capturing, !capture.progress.holding else { return nil }306        switch capture.progress.instruction {307        case .turnLeft: return "arrow.left"308        case .turnRight: return "arrow.right"309        case .backToCenter, .lookStraight: return "circle.dashed"310        default: return nil311        }312    }313314    private var content: some View {315        StepLayout {316            Text(IdentityString.selfieTitle.text(lang)).font(.title2.bold()).accessibilityAddTraits(.isHeader)317            ZStack {318                CameraPreview(controller: capture.camera)319                FaceOvalOverlay(active: capture.phase == .capturing && capture.progress.instruction != .noFace && capture.progress.instruction != .moveCloser)320                if capture.phase == .uploading || capture.phase == .preparing {321                    Color.black.opacity(0.45)322                    ProgressView().tint(.white)323                }324            }325            .aspectRatio(3.0 / 4.0, contentMode: .fit)326            .frame(maxHeight: 420)327            .frame(maxWidth: .infinity)328            .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))329            .accessibilityElement()330            .accessibilityLabel(IdentityString.a11yCameraPreview.text(lang))331332            HStack(alignment: .center, spacing: 10) {333                if let arrow {334                    Image(systemName: arrow).font(.title.weight(.semibold)).foregroundStyle(Color.accentColor).accessibilityHidden(true)335                }336                Text(instructionText)337                    .font(capture.phase == .capturing ? .title3.weight(.semibold) : .body)338                    .multilineTextAlignment(capture.phase == .capturing ? .center : .leading)339                    .fixedSize(horizontal: false, vertical: true)340            }341            .frame(maxWidth: .infinity, alignment: capture.phase == .capturing ? .center : .leading)342            .animation(reduceMotion ? nil : .easeInOut(duration: 0.2), value: capture.progress)343344            if capture.phase == .capturing, capture.progress.total > 0, capture.progress.movement > 0 {345                Text(IdentityString.selfieStepProgress.text(lang, capture.progress.movement, capture.progress.total))346                    .font(.subheadline)347                    .foregroundStyle(.secondary)348                    .frame(maxWidth: .infinity, alignment: .center)349            }350        } actions: {351            switch capture.phase {352            case .intro:353                Button(IdentityString.selfieStart.text(lang)) { Task { await capture.begin(accessible: false) } }354                    .buttonStyle(PrimaryButtonStyle())355                    .disabled(capture.camera.status != .running)356                Button(IdentityString.selfieAccessibleLink.text(lang)) { capture.phase = .accessibleIntro }357                    .buttonStyle(SecondaryButtonStyle())358                if flow.canChangeMethod {359                    Button(IdentityString.changeMethod.text(lang)) { flow.changeMethod() }360                        .buttonStyle(SecondaryButtonStyle())361                        .accessibilityIdentifier("mlid.changeMethod")362                }363            case .accessibleIntro:364                Button(IdentityString.selfieAccessibleStart.text(lang)) { Task { await capture.begin(accessible: true) } }365                    .buttonStyle(PrimaryButtonStyle())366                    .disabled(capture.camera.status != .running)367                Button(IdentityString.back.text(lang)) { capture.phase = .intro }368                    .buttonStyle(SecondaryButtonStyle())369            case .problem:370                Button(IdentityString.retry.text(lang)) { Task { await capture.retry() } }371                    .buttonStyle(PrimaryButtonStyle())372                    .disabled(capture.camera.status != .running)373                Button(IdentityString.selfieAccessibleLink.text(lang)) { capture.phase = .accessibleIntro }374                    .buttonStyle(SecondaryButtonStyle())375            case .preparing, .capturing, .uploading:376                EmptyView()377            }378        }379        .onChange(of: instructionText) { text in380            // Guidance is spoken as it changes; the first instruction of each phase too.381            Accessibility.announce(text)382        }383        .onChange(of: capture.progress.movement) { _ in Haptics.step() }384    }385}386387/// Oval guide for the face.388struct FaceOvalOverlay: View {389    var active: Bool390391    var body: some View {392        GeometryReader { geo in393            let w = min(geo.size.width * 0.68, geo.size.height * 0.62)394            Ellipse()395                .strokeBorder(active ? Color.accentColor : Color.white.opacity(0.9), lineWidth: active ? 4 : 2)396                .frame(width: w, height: w * 1.3)397                .position(x: geo.size.width / 2, y: geo.size.height * 0.47)398        }399        .allowsHitTesting(false)400        .accessibilityHidden(true)401    }402}403404enum Haptics {405    /// Light confirmation when a movement is recognised.406    @MainActor407    static func step() {408        #if os(iOS)409        UIImpactFeedbackGenerator(style: .light).impactOccurred()410        #endif411    }412}413
Files main
Menu

Theme