SPB Git

Repository Public License

VirtualCameraBackend.swift 17.1 KB 341 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/VirtualCameraBackend.swift10// Description      : Simulator-only camera. The iOS Simulator has no camera, so11//                    this backend feeds the real pipeline (monitor, histogram,12//                    peaking, zebras, recorder, accumulators, storage) with the13//                    procedural test scene and reacts to exposure, focus, white14//                    balance and zoom the way a camera would. It is a test15//                    double: it is compiled only for the simulator, and16//                    everything captured with it is marked synthetic.17// Module           : Core18// Repository       : https://git.spboucher.ai/orix-camera19// Project Website  : https://www.orixlab.dev20// Created          : 2026-11-2121// Last Modified    : 2026-11-2122//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author           : Simon-Pierre Boucher28// Position         : Professor of Finance29// Institution      : Université du Québec en Outaouais (UQO)30// Department       : Département des sciences administratives31// Organization     : SP Boucher32//33// Website          : https://spboucher.ai34// Git              : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General          : info@spboucher.ai41// Professional     : contact@spboucher.ai42// Direct           : simon@spboucher.ai43// Research         : research@spboucher.ai44// Development      : dev@spboucher.ai45// Support          : support@spboucher.ai46// Security/Admin   : admin@spboucher.ai47// Notifications    : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification   : Public74// Distribution     : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License          : Proprietary, all rights reserved (see license file)88// License File     : LICENSE89// Maintainer       : Simon-Pierre Boucher90// Technical Contact: dev@spboucher.ai91//92// =============================================================================93// END OF SP BOUCHER SOURCE HEADER94// =============================================================================9596#if targetEnvironment(simulator)97import CoreGraphics98import CoreMedia99import Foundation100import ImageIO101import ORIXImaging102import QuartzCore103import UIKit104import UniformTypeIdentifiers105106nonisolated final class VirtualCameraBackend: CameraBackend, @unchecked Sendable {107    private let queue = DispatchQueue(label: "ai.spboucher.orix.camera.virtual", qos: .userInteractive)108    private var timer: DispatchSourceTimer?109    private var scene: SyntheticScene?110    private var state = LiveCameraState()111    private var purpose: CapturePurpose = .photo112    private var lensID = "virtual.wide"113    private var start = CACurrentMediaTime()114    private var frameIndex: Int64 = 0115    private var portrait = true116    private let lock = NSLock()117    private weak var _receiver: (any CameraMediaReceiver)?118    private let continuation: AsyncStream<CameraEvent>.Continuation119    let events: AsyncStream<CameraEvent>120121    /// Nominal exposure of the scene: ISO 100 at 1/60 s renders it as drawn.122    private static let nominalExposure = 100.0 / 60.0123    /// The lens position at which the scene is in focus.124    private static let focusPlane = 0.72125126    private static let allLenses: [LensDescriptor] = [127        LensDescriptor(id: "virtual.ultrawide", position: .back, kind: "ultraWide", label: "0.5×", fieldOfView: 108, focalLength35mm: 13, aperture: 2.2),128        LensDescriptor(id: "virtual.wide", position: .back, kind: "wide", label: "1×", fieldOfView: 73.7, focalLength35mm: 24, aperture: 1.78),129        LensDescriptor(id: "virtual.tele", position: .back, kind: "telephoto", label: "3×", fieldOfView: 26.8, focalLength35mm: 77, aperture: 2.8),130        LensDescriptor(id: "virtual.front", position: .front, kind: "front", label: "1×", fieldOfView: 80, focalLength35mm: 21, aperture: 1.9),131    ]132133    var receiver: (any CameraMediaReceiver)? {134        get { lock.lock(); defer { lock.unlock() }; return _receiver }135        set { lock.lock(); _receiver = newValue; lock.unlock() }136    }137138    init() {139        (events, continuation) = AsyncStream.makeStream(of: CameraEvent.self, bufferingPolicy: .bufferingNewest(32))140        state.iso = 100; state.exposureDuration = 1.0 / 60; state.lensPosition = Self.focusPlane; state.temperature = 5500141    }142143    /// Simulated denial of camera access (UI tests of the permission screen).144    nonisolated(unsafe) static var simulateDenied = false145146    func cameraAccess() -> AccessState { Self.simulateDenied ? .denied : .granted }147    func requestCameraAccess() async -> Bool { !Self.simulateDenied }148    func microphoneAccess() -> AccessState { .granted }149    func requestMicrophoneAccess() async -> Bool { true }150    func lenses() -> [LensDescriptor] { Self.allLenses }151152    @MainActor func attachPreviewLayer(_ layer: CALayer) {153        // Frames are produced upright for the current interface orientation: no rotation is needed.154        let scene = (layer.delegate as? UIView)?.window?.windowScene155        let screen = UIScreen.main.bounds.size156        let isPortrait = scene.map { $0.effectiveGeometry.interfaceOrientation.isPortrait } ?? (screen.height >= screen.width)157        queue.async {158            if self.portrait != isPortrait { self.portrait = isPortrait; self.rebuildScene() }159        }160        continuation.yield(.rotation(preview: 0, capture: 0))161    }162163    private func streamSize() -> (Int, Int) {164        var size: (Int, Int)165        switch purpose {166        case .photo: size = (1440, 1080)167        case .video(let option, _, _): size = option.width >= 1920 ? (1920, 1080) : (option.width, option.height)   // the simulator renders 4K at 1080p168        }169        return portrait ? (size.1, size.0) : size170    }171172    private func rebuildScene() {173        let (w, h) = streamSize()174        scene = SyntheticScene(width: w, height: h)175        state.activeWidth = w; state.activeHeight = h176    }177178    func configure(lensID: String?, purpose: CapturePurpose) async throws -> CameraCapabilities {179        guard cameraAccess() == .granted else { throw CameraError.notAuthorized }180        return await withCheckedContinuation { continuation in181            queue.async {182                self.purpose = purpose183                self.lensID = lensID ?? self.lensID184                self.rebuildScene()185                var rate = 30.0186                if case .video(let option, _, _) = purpose { rate = min(option.frameRate, 60) }187                self.state.activeFrameRate = rate188                self.state.zoom = 1189                self.timer?.cancel()190                let timer = DispatchSource.makeTimerSource(queue: self.queue)191                timer.schedule(deadline: .now(), repeating: 1 / rate, leeway: .milliseconds(1))192                timer.setEventHandler { [weak self] in self?.tick() }193                timer.resume()194                self.timer = timer195                continuation.resume(returning: self.capabilities())196            }197        }198    }199200    private func capabilities() -> CameraCapabilities {201        let lens = Self.allLenses.first { $0.id == lensID } ?? Self.allLenses[1]202        var c = CameraCapabilities(lens: lens)203        c.minISO = 32; c.maxISO = 6400; c.minExposureDuration = 1.0 / 8000; c.maxExposureDuration = 1204        c.minExposureBias = -4; c.maxExposureBias = 4205        c.supportsManualExposure = true; c.supportsManualFocus = lens.position == .back206        c.supportsFocusPointOfInterest = true; c.supportsExposurePointOfInterest = true; c.supportsWhiteBalanceLock = true207        c.maxWhiteBalanceGain = 4; c.hasFlash = false; c.hasTorch = false; c.minZoom = 1; c.maxZoom = 10208        c.supportsBayerRAW = false; c.supportsProRAW = false; c.maxBracketCount = 3; c.supportsHEVCPhoto = true209        c.maxPhotoWidth = 4032; c.maxPhotoHeight = 3024210        c.videoFormats = [(3840, 2160, 30.0), (3840, 2160, 24), (1920, 1080, 60), (1920, 1080, 30), (1920, 1080, 24), (1280, 720, 30)].map { VideoFormatOption(width: $0.0, height: $0.1, frameRate: $0.2) }211        c.videoCodecs = VideoCodec.allCases.filter(\.isEncoderAvailable)212        c.isSynthetic = true213        return c214    }215216    func stop() async {217        await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in218            queue.async { self.timer?.cancel(); self.timer = nil; continuation.resume() }219        }220    }221222    // MARK: Simulated optics223224    private func controls(biasOverride: Double? = nil) -> SyntheticScene.Controls {225        var c = SyntheticScene.Controls()226        let bias = biasOverride ?? state.exposureBias227        if state.exposureMode == .manual {228            c.exposureGain = (state.iso * state.exposureDuration) / Self.nominalExposure * (biasOverride.map { pow(2, $0) } ?? 1)229        } else {230            c.exposureGain = pow(2, bias)231        }232        if state.whiteBalanceMode == .locked {233            // A higher Kelvin setting tells the camera the light is bluer, so it renders warmer.234            let k = (state.temperature - 5500) / 5500235            c.redGain = 1 + k * 0.55; c.blueGain = 1 - k * 0.55236            c.greenGain = 1 - state.tint / 150 * 0.25237        }238        c.defocus = state.focusMode == .manual ? min(1, abs(state.lensPosition - Self.focusPlane) * 1.6) : 0239        let lensZoom: Double = lensID == "virtual.tele" ? 3 : (lensID == "virtual.ultrawide" ? 1 : 1.35)240        c.zoom = state.zoom * (lensID == "virtual.ultrawide" ? 1 : lensZoom)241        return c242    }243244    private func tick() {245        guard let scene else { return }246        let time = CACurrentMediaTime() - start247        if state.exposureMode == .auto { state.iso = 100; state.exposureDuration = 1.0 / 60; state.exposureOffset = 0 } else {248            state.exposureOffset = log2(max((state.iso * state.exposureDuration) / Self.nominalExposure, 1e-6))249        }250        if state.whiteBalanceMode == .auto { state.temperature = 5500; state.tint = 0 }251        if state.focusMode == .auto { state.lensPosition = Self.focusPlane }252        guard let buffer = scene.render(time: time, controls: controls()) else { receiver?.frameDropped(); return }253        frameIndex += 1254        receiver?.receive(Frame(pixelBuffer: buffer, time: CACurrentMediaTime()))255        if frameIndex % 3 == 0 { continuation.yield(.state(state)) }256    }257258    // MARK: Controls259260    func setExposureAuto() { queue.async { self.state.exposureMode = .auto } }261    func setExposureLocked() { queue.async { self.state.exposureMode = .locked } }262    func setExposureManual(iso: Double, duration: Double) {263        queue.async {264            self.state.exposureMode = .manual265            self.state.iso = min(max(iso, 32), 6400)266            var seconds = min(max(duration, 1.0 / 8000), 1)267            if case .video(let option, _, _) = self.purpose { seconds = min(seconds, 1 / option.frameRate) }268            self.state.exposureDuration = seconds269        }270    }271    func setExposureBias(_ bias: Double) { queue.async { self.state.exposureBias = min(max(bias, -4), 4) } }272    func setFocusAuto() { queue.async { self.state.focusMode = .auto } }273    func setFocusLocked() { queue.async { self.state.focusMode = .manual } }274    func setFocusManual(lensPosition: Double) { queue.async { self.state.focusMode = .manual; self.state.lensPosition = min(max(lensPosition, 0), 1) } }275    func focusAndExpose(at point: CGPoint, expose: Bool) {276        queue.async {277            self.state.focusMode = .auto; self.state.isAdjustingFocus = true278            self.queue.asyncAfter(deadline: .now() + 0.35) { self.state.isAdjustingFocus = false }279        }280    }281    func setWhiteBalanceAuto() { queue.async { self.state.whiteBalanceMode = .auto } }282    func setWhiteBalanceLocked() { queue.async { self.state.whiteBalanceMode = .locked } }283    func setWhiteBalance(temperature: Double, tint: Double) {284        queue.async { self.state.whiteBalanceMode = .locked; self.state.temperature = min(max(temperature, 2000), 10000); self.state.tint = min(max(tint, -150), 150) }285    }286    func setZoom(_ factor: Double) { queue.async { self.state.zoom = min(max(factor, 1), 10) } }287    func setTorch(_ on: Bool) {}288289    // MARK: Capture290291    private func stillData(biasOverride: Double? = nil, width: Int, height: Int) -> Data? {292        let (w, h) = portrait ? (min(width, height), max(width, height)) : (max(width, height), min(width, height))293        guard let scene = SyntheticScene(width: w, height: h),294              let buffer = scene.render(time: CACurrentMediaTime() - start, controls: controls(biasOverride: biasOverride)),295              let image = PixelBuffers.cgImage(from: buffer) else { return nil }296        let data = NSMutableData()297        guard let destination = CGImageDestinationCreateWithData(data, UTType.heic.identifier as CFString, 1, nil) else { return nil }298        let lens = Self.allLenses.first { $0.id == lensID } ?? Self.allLenses[1]299        let formatter = DateFormatter()300        formatter.locale = Locale(identifier: "en_US_POSIX"); formatter.dateFormat = "yyyy:MM:dd HH:mm:ss"301        let properties: [CFString: Any] = [302            kCGImageDestinationLossyCompressionQuality: 0.9,303            kCGImagePropertyTIFFDictionary: [kCGImagePropertyTIFFMake: "ORIX", kCGImagePropertyTIFFModel: "Simulator virtual camera", kCGImagePropertyTIFFSoftware: "ORIX Camera (synthetic scene)"],304            kCGImagePropertyExifDictionary: [305                kCGImagePropertyExifDateTimeOriginal: formatter.string(from: Date()),306                kCGImagePropertyExifLensModel: "Virtual \(lens.kind) \(lens.label)",307                kCGImagePropertyExifISOSpeedRatings: [Int(state.iso)], kCGImagePropertyExifExposureTime: state.exposureDuration,308                kCGImagePropertyExifFNumber: lens.aperture, kCGImagePropertyExifFocalLenIn35mmFilm: Int(lens.focalLength35mm),309                kCGImagePropertyExifExposureBiasValue: biasOverride ?? state.exposureBias,310            ] as [CFString: Any],311        ]312        CGImageDestinationAddImage(destination, image, properties as CFDictionary)313        return CGImageDestinationFinalize(destination) ? data as Data : nil314    }315316    func capturePhoto(_ request: PhotoRequest) async throws -> CapturedPhoto {317        if request.format.isRAW {318            throw CameraError.unsupported(String(localized: "RAW needs a real sensor; the simulator has none."))319        }320        return try await withCheckedThrowingContinuation { continuation in321            queue.async {322                let w = request.maxWidth ?? 4032, h = request.maxHeight ?? 3024323                guard let data = self.stillData(width: w, height: h) else { continuation.resume(throwing: CameraError.captureFailed("render")); return }324                var photo = CapturedPhoto(processed: data, processedExtension: "heic")325                photo.width = self.portrait ? min(w, h) : max(w, h); photo.height = self.portrait ? max(w, h) : min(w, h)326                continuation.resume(returning: photo)327            }328        }329    }330331    func captureBracket(biases: [Double]) async throws -> [Data] {332        try await withCheckedThrowingContinuation { continuation in333            queue.async {334                let frames = biases.prefix(3).compactMap { self.stillData(biasOverride: $0, width: 2016, height: 1512) }335                if frames.count >= 2 { continuation.resume(returning: frames) } else { continuation.resume(throwing: CameraError.captureFailed("bracket")) }336            }337        }338    }339}340#endif341
Files main
Menu

Theme