SPB Git

Repository Public License

CameraBackend.swift 9.0 KB 235 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Camera9// File             : App/Sources/Core/CameraSession/CameraBackend.swift10// Description      : The hardware boundary. Everything the interface can ask of11//                    a camera goes through CameraBackend; the device12//                    implementation maps each call onto AVFoundation, the13//                    simulator implementation onto the synthetic scene.14// Module           : Core15// Repository       : https://git.spboucher.ai/orix-camera16// Project Website  : https://www.orixlab.dev17// Created          : 2026-11-2118// Last Modified    : 2026-11-2119//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : Proprietary, all rights reserved (see license file)85// License File     : LICENSE86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import CoreGraphics94import CoreMedia95import Foundation96import ORIXImaging97import QuartzCore9899nonisolated enum ControlMode: String, Sendable, Codable { case auto, manual, locked }100101nonisolated enum FlashSetting: String, Sendable, Codable, CaseIterable { case off, auto, on }102103nonisolated enum PhotoFormat: String, Sendable, Codable, CaseIterable {104    case heic, jpeg, raw, rawPlusHEIC, proRAW105    var isRAW: Bool { self == .raw || self == .rawPlusHEIC || self == .proRAW }106    var title: String {107        switch self {108        case .heic: "HEIC"109        case .jpeg: "JPEG"110        case .raw: "RAW"111        case .rawPlusHEIC: "RAW+HEIC"112        case .proRAW: "ProRAW"113        }114    }115}116117nonisolated enum PressureLevel: String, Sendable { case nominal, fair, serious, critical, shutdown }118119/// Values read back from the camera several times per second. These are hardware readings, not requests.120nonisolated struct LiveCameraState: Sendable, Equatable {121    var iso: Double = 0122    var exposureDuration: Double = 0123    var exposureBias: Double = 0124    /// Metered offset from the target exposure, in stops (meaningful in manual exposure).125    var exposureOffset: Double = 0126    var exposureMode: ControlMode = .auto127    var lensPosition: Double = 0128    var focusMode: ControlMode = .auto129    var isAdjustingFocus = false130    var isAdjustingExposure = false131    var temperature: Double = 0132    var tint: Double = 0133    var whiteBalanceMode: ControlMode = .auto134    var zoom: Double = 1135    var torchOn = false136    var activeWidth = 0137    var activeHeight = 0138    var activeFrameRate: Double = 0139    var stabilizationActive = false140}141142nonisolated enum CameraEvent: Sendable {143    case state(LiveCameraState)144    case interrupted(String)145    case interruptionEnded146    case runtimeError(String)147    case pressure(PressureLevel)148    /// Clockwise degrees to rotate sensor frames for display, and for horizon-level capture.149    case rotation(preview: Double, capture: Double)150}151152nonisolated enum CapturePurpose: Sendable, Equatable {153    case photo154    case video(VideoFormatOption, audio: Bool, stabilization: Bool)155}156157nonisolated struct PhotoRequest: Sendable {158    var format: PhotoFormat = .heic159    var flash: FlashSetting = .off160    /// Favour shot-to-shot speed (bursts). Bayer RAW always uses speed: AVFoundation requires it.161    var prioritizeSpeed = false162    /// Requested still size; nil = the largest the output offers.163    var maxWidth: Int?164    var maxHeight: Int?165}166167nonisolated struct CapturedPhoto: Sendable {168    var processed: Data?169    var processedExtension = "heic"170    var raw: Data?171    var isProRAW = false172    var width = 0173    var height = 0174}175176nonisolated enum CameraError: Error, Equatable, LocalizedError {177    case notAuthorized, noCamera, configurationFailed(String), captureFailed(String), unsupported(String), busy178179    var errorDescription: String? {180        switch self {181        case .notAuthorized: String(localized: "Camera access is not allowed.")182        case .noCamera: String(localized: "No camera is available.")183        case .configurationFailed(let why): String(localized: "The camera could not be configured: \(why)")184        case .captureFailed(let why): String(localized: "The capture failed: \(why)")185        case .unsupported(let what): what186        case .busy: String(localized: "The camera is busy.")187        }188    }189}190191nonisolated enum AccessState: Sendable { case undetermined, granted, denied }192193/// Receives media on the capture queues. Implementations must be fast and thread-safe.194nonisolated protocol CameraMediaReceiver: AnyObject, Sendable {195    func receive(_ frame: Frame)196    func receiveAudio(_ sampleBuffer: CMSampleBuffer)197    func frameDropped()198}199200nonisolated protocol CameraBackend: AnyObject, Sendable {201    var receiver: (any CameraMediaReceiver)? { get set }202    var events: AsyncStream<CameraEvent> { get }203204    func cameraAccess() -> AccessState205    func requestCameraAccess() async -> Bool206    func microphoneAccess() -> AccessState207    func requestMicrophoneAccess() async -> Bool208209    func lenses() -> [LensDescriptor]210    /// (Re)configures the session for a lens and purpose and starts it. Returns what that configuration can do.211    func configure(lensID: String?, purpose: CapturePurpose) async throws -> CameraCapabilities212    func stop() async213    /// The layer showing the preview, so the system can report the rotation that keeps it horizon-level.214    @MainActor func attachPreviewLayer(_ layer: CALayer)215216    func setExposureAuto()217    func setExposureLocked()218    func setExposureManual(iso: Double, duration: Double)219    func setExposureBias(_ bias: Double)220    func setFocusAuto()221    func setFocusLocked()222    func setFocusManual(lensPosition: Double)223    /// `point` is in sensor space (normalized, origin top-left of the unrotated frame).224    func focusAndExpose(at point: CGPoint, expose: Bool)225    func setWhiteBalanceAuto()226    func setWhiteBalanceLocked()227    func setWhiteBalance(temperature: Double, tint: Double)228    func setZoom(_ factor: Double)229    func setTorch(_ on: Bool)230231    func capturePhoto(_ request: PhotoRequest) async throws -> CapturedPhoto232    /// An exposure bracket (processed images, one per bias, in order).233    func captureBracket(biases: [Double]) async throws -> [Data]234}235
Files main
Menu

Theme