open-merou

Open Mérou, a free iOS app for the Oceanic+ underwater iPhone housing
git clone https://git.schurger.org/open-merou.git
Log | Files | Refs | README | LICENSE

CameraEngine.swift (22597B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 // Shooting: queries this iPhone and uses what it can do (lenses, full resolution, ProRAW, video
      3 // formats, stabilization). All the AVFoundation work happens on a serial queue; the state comes
      4 // back through `onState` on the main queue.
      5 @preconcurrency import AVFoundation
      6 import Photos
      7 import UIKit
      8 
      9 struct CameraState: Equatable, Sendable {
     10     var authorized = true
     11     var running = false
     12     var capabilities = CameraCapabilities()
     13     var zoomIndex = 0
     14     var recordingSince: Date?
     15     var shots = 0
     16     var message: String?
     17     /// Changes at each message, even a repeated one, so that the screen shows it again.
     18     var messageCount = 0
     19     /// Color gains applied to the sensor (nil: the iPhone's white balance).
     20     var gains: ColorGains?
     21     var gainsSaturated = false
     22     /// Diagnostics: raw "gray world" gains measured by the iPhone, and the sensor's ceiling.
     23     var grayWorld: ColorGains?
     24     var maxGain: Double?
     25     /// Last calibration done on request, to be saved in the settings.
     26     var calibration: ColorGains?
     27     /// Denied permissions, to be fixed before closing the housing.
     28     var denied: [String] = []
     29     /// Focus and exposure locked (long press on the shutter).
     30     var focusLocked = false
     31 }
     32 
     33 final class CameraEngine: NSObject, @unchecked Sendable {
     34     let session = AVCaptureSession()
     35     let previewLayer: AVCaptureVideoPreviewLayer
     36     var onState: (@MainActor @Sendable (CameraState) -> Void)?
     37 
     38     private let queue = DispatchQueue(label: "org.schurger.openmerou.camera")
     39     private var device: AVCaptureDevice?
     40     private var photoOutput = AVCapturePhotoOutput()
     41     private var movieOutput = AVCaptureMovieFileOutput()
     42     private var audioInput: AVCaptureDeviceInput?
     43     private var zoomFactors: [CGFloat] = [1]
     44     private var settings = CameraSettings()
     45     private var state = CameraState()
     46     private var photoDelegates: [Int64: PhotoDelegate] = [:]
     47     private var colorTimer: DispatchSourceTimer?
     48 
     49     override init() {
     50         previewLayer = AVCaptureVideoPreviewLayer(session: session)
     51         previewLayer.videoGravity = .resizeAspect
     52         super.init()
     53     }
     54 
     55     private func publish() {
     56         let snapshot = state, sink = onState
     57         DispatchQueue.main.async { MainActor.assumeIsolated { sink?(snapshot) } }
     58     }
     59 
     60     private func say(_ text: String) {
     61         state.message = text
     62         state.messageCount += 1
     63         publish()
     64     }
     65 
     66     // MARK: Startup
     67 
     68     func start(_ settings: CameraSettings) {
     69         // "-noPermissionPrompts": screenshots in the simulator, which has no camera; nothing is asked.
     70         if ProcessInfo.processInfo.arguments.contains("-noPermissionPrompts") { return }
     71         // All the permissions at once at launch: once the housing is closed, the screen is out of reach.
     72         AVCaptureDevice.requestAccess(for: .video) { [self] granted in
     73           AVCaptureDevice.requestAccess(for: .audio) { [self] audio in
     74            PHPhotoLibrary.requestAuthorization(for: .addOnly) { [self] photos in
     75             queue.async { [self] in
     76                 self.settings = settings
     77                 if !audio { state.denied.append(String(localized: "microphone (videos without sound)")) }
     78                 if photos != .authorized && photos != .limited { state.denied.append(String(localized: "photo library (nothing will be saved)")) }
     79                 guard granted else { state.authorized = false; publish(); return }
     80                 configure()
     81                 session.startRunning()
     82                 state.running = session.isRunning
     83                 publish()
     84             }
     85            }
     86           }
     87         }
     88     }
     89 
     90     private func configure() {
     91         // The most complete virtual device: it switches lenses by itself according to the zoom.
     92         let types: [AVCaptureDevice.DeviceType] = [.builtInTripleCamera, .builtInDualWideCamera, .builtInDualCamera, .builtInWideAngleCamera]
     93         guard let device = AVCaptureDevice.DiscoverySession(deviceTypes: types, mediaType: .video, position: .back).devices.first,
     94               let input = try? AVCaptureDeviceInput(device: device) else {
     95             say(String(localized: "No camera"))
     96             return
     97         }
     98         self.device = device
     99         // The app sets its audio session itself ("play and record" on the loudspeaker, `AlertPlayer.prepare`)
    100         // so that the alarms are heard whatever the ring/silent switch says, while videos keep their sound.
    101         session.automaticallyConfiguresApplicationAudioSession = false
    102         session.beginConfiguration()
    103         if session.canAddInput(input) { session.addInput(input) }
    104         if session.canAddOutput(photoOutput) { session.addOutput(photoOutput) }
    105         if session.canAddOutput(movieOutput) { session.addOutput(movieOutput) }
    106         session.commitConfiguration()
    107 
    108         // Zoom stops: each lens, plus the ×2 crop of the wide and telephoto lenses.
    109         let switchOvers = device.virtualDeviceSwitchOverVideoZoomFactors.map { CGFloat(truncating: $0) }
    110         let hasUltraWide = device.deviceType == .builtInTripleCamera || device.deviceType == .builtInDualWideCamera
    111         let wide = hasUltraWide ? (switchOvers.first ?? 1) : 1
    112         let natives = [1] + switchOvers
    113         var stops = natives + natives.filter { $0 >= wide }.map { $0 * 2 }
    114         stops = stops.filter { $0 <= device.maxAvailableVideoZoomFactor }.sorted()
    115         zoomFactors = stops.reduce(into: [CGFloat]()) { kept, stop in
    116             if let last = kept.last, abs(stop - last) <= 0.05 { return }
    117             kept.append(stop)
    118         }
    119         state.capabilities.zoomLabels = zoomFactors.map {
    120             let shown = Double($0 / wide)
    121             return (shown == shown.rounded() ? String(format: "%.0f", shown) : String(format: "%.1f", shown)) + "×"
    122         }
    123         state.zoomIndex = zoomFactors.firstIndex { abs($0 - wide) < 0.05 } ?? 0
    124 
    125         state.capabilities.qualities = VideoQuality.all.filter { format(for: $0, on: device) != nil }
    126         state.capabilities.minBias = Double(device.minExposureTargetBias)
    127         state.capabilities.maxBias = Double(device.maxExposureTargetBias)
    128 
    129         applyMode()
    130     }
    131 
    132     private func format(for quality: VideoQuality, on device: AVCaptureDevice) -> AVCaptureDevice.Format? {
    133         device.formats.last { format in
    134             let dims = CMVideoFormatDescriptionGetDimensions(format.formatDescription)
    135             let pixel = CMFormatDescriptionGetMediaSubType(format.formatDescription)
    136             return dims.width == quality.width && dims.height == quality.height
    137                 && (pixel == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange || pixel == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange)
    138                 && format.videoSupportedFrameRateRanges.contains { $0.maxFrameRate >= Double(quality.fps) }
    139         }
    140     }
    141 
    142     // MARK: Settings
    143 
    144     func apply(_ settings: CameraSettings) {
    145         queue.async { [self] in
    146             let colorChanged = settings.colorMode != self.settings.colorMode
    147             let modeChanged = settings.mode != self.settings.mode || settings.videoQuality != self.settings.videoQuality
    148                 || settings.photoFormat != self.settings.photoFormat
    149             self.settings = settings
    150             guard device != nil, !movieOutput.isRecording else { return }
    151             if modeChanged { applyMode() } else { applyLight() }
    152             if colorChanged && !modeChanged { applyColor() }
    153             publish()
    154         }
    155     }
    156 
    157     private func applyMode() {
    158         guard let device else { return }
    159         session.beginConfiguration()
    160         switch settings.mode {
    161         case .photo:
    162             session.sessionPreset = .photo
    163         case .video:
    164             let quality = state.capabilities.qualities.contains(settings.videoQuality)
    165                 ? settings.videoQuality : (state.capabilities.qualities.last ?? settings.videoQuality)
    166             if let format = format(for: quality, on: device), (try? device.lockForConfiguration()) != nil {
    167                 session.sessionPreset = .inputPriority
    168                 device.activeFormat = format
    169                 let duration = CMTime(value: 1, timescale: CMTimeScale(quality.fps))
    170                 device.activeVideoMinFrameDuration = duration
    171                 device.activeVideoMaxFrameDuration = duration
    172                 device.unlockForConfiguration()
    173             }
    174             addMicrophone()
    175         }
    176         session.commitConfiguration()
    177 
    178         // Full sensor resolution (48 MP when the iPhone offers it) and ProRAW.
    179         if let largest = device.activeFormat.supportedMaxPhotoDimensions.max(by: { $0.width * $0.height < $1.width * $1.height }) {
    180             photoOutput.maxPhotoDimensions = largest
    181         }
    182         photoOutput.maxPhotoQualityPrioritization = .quality
    183         state.capabilities.proRAW = photoOutput.isAppleProRAWSupported
    184         photoOutput.isAppleProRAWEnabled = photoOutput.isAppleProRAWSupported && settings.photoFormat == .rawHeif
    185 
    186         let modes: [(Stabilization, AVCaptureVideoStabilizationMode)] = [(.off, .off), (.standard, .standard), (.cinematic, .cinematic), (.extended, .cinematicExtended)]
    187         state.capabilities.stabilizations = modes.filter { $0.1 == .off || device.activeFormat.isVideoStabilizationModeSupported($0.1) }.map(\.0)
    188         applyLight()
    189         applyColor()
    190     }
    191 
    192     private func rotate(_ connection: AVCaptureConnection?) {
    193         let angle = settings.orientation.videoAngle
    194         if let connection, connection.isVideoRotationAngleSupported(angle) { connection.videoRotationAngle = angle }
    195     }
    196 
    197     /// Settings that do not require reconfiguring the session.
    198     private func applyLight() {
    199         guard let device else { return }
    200         let layer = previewLayer, angle = settings.orientation.videoAngle
    201         DispatchQueue.main.async {
    202             if let connection = layer.connection, connection.isVideoRotationAngleSupported(angle) { connection.videoRotationAngle = angle }
    203         }
    204         if (try? device.lockForConfiguration()) != nil {
    205             let bias = Float(settings.exposureBias)
    206             device.setExposureTargetBias(min(max(bias, device.minExposureTargetBias), device.maxExposureTargetBias))
    207             device.videoZoomFactor = zoomFactors[state.zoomIndex]
    208             device.unlockForConfiguration()
    209         }
    210         if let connection = movieOutput.connection(with: .video), connection.isVideoStabilizationSupported {
    211             let wanted: AVCaptureVideoStabilizationMode = switch settings.stabilization {
    212             case .off: .off
    213             case .standard: .standard
    214             case .cinematic: .cinematic
    215             case .extended: .cinematicExtended
    216             }
    217             connection.preferredVideoStabilizationMode = device.activeFormat.isVideoStabilizationModeSupported(wanted) ? wanted : .standard
    218         }
    219     }
    220 
    221     // MARK: Colors
    222 
    223     /// "Gray world" gains measured by the iPhone on the scene, fitted to what the sensor accepts.
    224     private func measuredGains() -> (gains: ColorGains, saturated: Bool)? {
    225         guard let device, device.isLockingWhiteBalanceWithCustomDeviceGainsSupported else { return nil }
    226         let g = device.grayWorldDeviceWhiteBalanceGains
    227         guard g.redGain > 0, g.greenGain > 0, g.blueGain > 0 else { return nil }
    228         let raw = ColorGains(red: Double(g.redGain), green: Double(g.greenGain), blue: Double(g.blueGain))
    229         let max = Double(device.maxWhiteBalanceGain)
    230         state.grayWorld = raw
    231         state.maxGain = max
    232         var fit = raw.fitted(max: max)
    233         // Hysteresis: the indicator turns on above the ceiling and only turns off 10% below it.
    234         if state.gainsSaturated && raw.relativeRed > max * 0.9 { fit.saturated = true }
    235         return fit
    236     }
    237 
    238     private func lock(_ gains: ColorGains, saturated: Bool) {
    239         guard let device, device.isLockingWhiteBalanceWithCustomDeviceGainsSupported else { return }
    240         let fitted = gains.fitted(max: Double(device.maxWhiteBalanceGain)).gains  // never out of bounds
    241         guard (try? device.lockForConfiguration()) != nil else { return }
    242         device.setWhiteBalanceModeLocked(with: .init(redGain: Float(fitted.red), greenGain: Float(fitted.green), blueGain: Float(fitted.blue)))
    243         device.unlockForConfiguration()
    244         state.gains = fitted
    245         state.gainsSaturated = saturated
    246     }
    247 
    248     private func applyColor() {
    249         guard let device else { return }
    250         colorTimer?.cancel()
    251         colorTimer = nil
    252         guard settings.colorMode != .system, device.isLockingWhiteBalanceWithCustomDeviceGainsSupported else {
    253             if settings.colorMode != .system { state.message = String(localized: "Colors: manual setting unavailable on this device") }
    254             if device.isWhiteBalanceModeSupported(.continuousAutoWhiteBalance), (try? device.lockForConfiguration()) != nil {
    255                 device.whiteBalanceMode = .continuousAutoWhiteBalance
    256                 device.unlockForConfiguration()
    257             }
    258             state.gains = nil
    259             state.gainsSaturated = false
    260             return
    261         }
    262         switch settings.colorMode {
    263         case .calibrated:
    264             if let saved = settings.calibration { lock(saved, saturated: false) } else { calibrateNow() }
    265         default:
    266             // Automatic tracking: two measurements per second, smoothed to keep the colors from hunting.
    267             let timer = DispatchSource.makeTimerSource(queue: queue)
    268             timer.schedule(deadline: .now() + 0.5, repeating: 0.5)
    269             timer.setEventHandler { [weak self] in
    270                 guard let self, let measured = self.measuredGains() else { return }
    271                 let next = self.state.gains?.moved(toward: measured.gains, by: 0.25) ?? measured.gains
    272                 let before = self.state
    273                 self.lock(next, saturated: measured.saturated)
    274                 if self.state != before { self.publish() }
    275             }
    276             timer.resume()
    277             colorTimer = timer
    278         }
    279     }
    280 
    281     private func calibrateNow() {
    282         guard let measured = measuredGains() else { say(String(localized: "Calibration failed")); return }
    283         lock(measured.gains, saturated: measured.saturated)
    284         state.calibration = measured.gains
    285         say(measured.saturated ? String(localized: "Colors calibrated (red at maximum)") : String(localized: "Colors calibrated"))
    286     }
    287 
    288     /// Calibration on request: aim at a light surface (sand, slate) and press.
    289     func calibrate() {
    290         queue.async { [self] in
    291             colorTimer?.cancel()
    292             colorTimer = nil
    293             settings.colorMode = .calibrated
    294             calibrateNow()
    295         }
    296     }
    297 
    298     private func addMicrophone() {
    299         guard audioInput == nil, AVCaptureDevice.authorizationStatus(for: .audio) != .denied,
    300               let mic = AVCaptureDevice.default(for: .audio), let input = try? AVCaptureDeviceInput(device: mic),
    301               session.canAddInput(input) else { return }
    302         session.addInput(input)
    303         audioInput = input
    304     }
    305 
    306     // MARK: Commands
    307 
    308     func cycleLens(_ step: Int) {
    309         queue.async { [self] in
    310             guard device != nil, zoomFactors.count > 1 else { return }
    311             state.zoomIndex = (state.zoomIndex + step + zoomFactors.count) % zoomFactors.count
    312             applyLight()
    313             publish()
    314         }
    315     }
    316 
    317     /// Underwater, autofocus hunts on particles: focus and exposure can be locked.
    318     func toggleFocusLock() {
    319         queue.async { [self] in
    320             guard let device, (try? device.lockForConfiguration()) != nil else { return }
    321             let lock = !state.focusLocked
    322             if lock {
    323                 if device.isFocusModeSupported(.locked) { device.focusMode = .locked }
    324                 if device.isExposureModeSupported(.locked) { device.exposureMode = .locked }
    325             } else {
    326                 if device.isFocusModeSupported(.continuousAutoFocus) { device.focusMode = .continuousAutoFocus }
    327                 if device.isExposureModeSupported(.continuousAutoExposure) { device.exposureMode = .continuousAutoExposure }
    328             }
    329             device.unlockForConfiguration()
    330             state.focusLocked = lock
    331             say(lock ? String(localized: "Focus and exposure locked") : String(localized: "Focus and exposure automatic"))
    332         }
    333     }
    334 
    335     /// `comment`: basic dive information to write in the metadata of the photo (Exif UserComment), or nil.
    336     func capturePhoto(comment: String? = nil) {
    337         queue.async { [self] in
    338             guard device != nil, session.isRunning else { return }
    339             let heif: [String: Any] = [AVVideoCodecKey: AVVideoCodecType.hevc]
    340             let raw = photoOutput.isAppleProRAWEnabled
    341                 ? photoOutput.availableRawPhotoPixelFormatTypes.first { AVCapturePhotoOutput.isAppleProRAWPixelFormat($0) } : nil
    342             let photoSettings = raw.map { AVCapturePhotoSettings(rawPixelFormatType: $0, processedFormat: heif) }
    343                 ?? AVCapturePhotoSettings(format: heif)
    344             photoSettings.maxPhotoDimensions = photoOutput.maxPhotoDimensions
    345             photoSettings.photoQualityPrioritization = .balanced  // bursts come before the heaviest processing
    346             rotate(photoOutput.connection(with: .video))
    347             let delegate = PhotoDelegate(comment: comment) { [weak self] id, result in
    348                 self?.queue.async {
    349                     self?.photoDelegates[id] = nil
    350                     switch result {
    351                     case .success: self?.state.shots += 1; self?.publish()
    352                     case .failure(let error): self?.say(String(localized: "Photo: \(error.localizedDescription)"))
    353                     }
    354                 }
    355             }
    356             photoDelegates[photoSettings.uniqueID] = delegate
    357             photoOutput.capturePhoto(with: photoSettings, delegate: delegate)
    358         }
    359     }
    360 
    361     /// `comment`: basic dive information at the start of the recording, written as the QuickTime comment of
    362     /// the movie, or nil.
    363     func toggleRecording(comment: String? = nil) {
    364         queue.async { [self] in
    365             guard device != nil, session.isRunning else { return }
    366             if movieOutput.isRecording {
    367                 movieOutput.stopRecording()
    368                 return
    369             }
    370             rotate(movieOutput.connection(with: .video))
    371             if let connection = movieOutput.connection(with: .video), movieOutput.availableVideoCodecTypes.contains(.hevc) {
    372                 movieOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecType.hevc], for: connection)
    373             }
    374             movieOutput.metadata = comment.map { [Self.movieComment($0)] }
    375             let url = Roll.newBase().appendingPathExtension("mov")
    376             movieOutput.startRecording(to: url, recordingDelegate: self)
    377             state.recordingSince = Date()
    378             publish()
    379         }
    380     }
    381 
    382     /// Top-level QuickTime metadata item `com.apple.quicktime.comment`.
    383     static func movieComment(_ text: String) -> AVMetadataItem {
    384         let item = AVMutableMetadataItem()
    385         item.identifier = .quickTimeMetadataComment
    386         item.dataType = kCMMetadataBaseDataType_UTF8 as String
    387         item.value = text as NSString
    388         return item
    389     }
    390 
    391     func stopForBackground() {
    392         queue.async { [self] in
    393             if movieOutput.isRecording { movieOutput.stopRecording() }
    394         }
    395     }
    396 }
    397 
    398 extension CameraEngine: AVCaptureFileOutputRecordingDelegate {
    399     func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo url: URL, from connections: [AVCaptureConnection], error: Error?) {
    400         // An interrupted recording (disk full, phone call) often leaves a valid file: keep it.
    401         let usable = (error as NSError?)?.userInfo[AVErrorRecordingSuccessfullyFinishedKey] as? Bool ?? (error == nil)
    402         queue.async { [self] in
    403             state.recordingSince = nil
    404             publish()
    405         }
    406         queue.async { [self] in
    407             if usable {
    408                 state.shots += 1
    409                 publish()
    410             } else {
    411                 try? FileManager.default.removeItem(at: url)
    412                 say(String(localized: "Video: \(error?.localizedDescription ?? String(localized: "failed"))"))
    413             }
    414         }
    415     }
    416 }
    417 
    418 private final class PhotoDelegate: NSObject, AVCapturePhotoCaptureDelegate, AVCapturePhotoFileDataRepresentationCustomizer, @unchecked Sendable {
    419     private let done: @Sendable (Int64, Result<Void, Error>) -> Void
    420     private let comment: String?
    421     private var processed: Data?
    422     private var raw: Data?
    423 
    424     init(comment: String?, done: @escaping @Sendable (Int64, Result<Void, Error>) -> Void) {
    425         self.comment = comment
    426         self.done = done
    427     }
    428 
    429     func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
    430         guard error == nil else { return }
    431         // With a comment, the file is written through the customizer below; should that fail, the plain
    432         // representation is used: a shot is never lost for its metadata.
    433         let customized = comment == nil ? nil : photo.fileDataRepresentation(with: self)
    434         guard let data = customized ?? photo.fileDataRepresentation() else { return }
    435         if photo.isRawPhoto { raw = data } else { processed = data }
    436     }
    437 
    438     /// Everything the camera wrote, plus the dive information as the Exif UserComment. (ImageIO has no key
    439     /// for the Exif 2.31 WaterDepth, Temperature and Pressure tags, so they cannot be written this way.)
    440     func replacementMetadata(for photo: AVCapturePhoto) -> [String: Any]? {
    441         var metadata = photo.metadata
    442         guard let comment else { return metadata }
    443         var exif = metadata[kCGImagePropertyExifDictionary as String] as? [String: Any] ?? [:]
    444         exif[kCGImagePropertyExifUserComment as String] = comment
    445         metadata[kCGImagePropertyExifDictionary as String] = exif
    446         return metadata
    447     }
    448 
    449     func photoOutput(_ output: AVCapturePhotoOutput, didFinishCaptureFor resolved: AVCaptureResolvedPhotoSettings, error: Error?) {
    450         let id = resolved.uniqueID
    451         guard error == nil, let processed else {
    452             done(id, .failure(error ?? CocoaError(.fileWriteUnknown)))
    453             return
    454         }
    455         let base = Roll.newBase()
    456         do {
    457             try processed.write(to: base.appendingPathExtension("heic"), options: .atomic)
    458             if let raw { try raw.write(to: base.appendingPathExtension("dng"), options: .atomic) }
    459             done(id, .success(()))
    460         } catch {
    461             done(id, .failure(error))
    462         }
    463     }
    464 }
    465