Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Camera9// File : App/Sources/Features/Camera/CameraModel+Capture.swift10// Description : Capture flows: photo (timer, burst, RAW), movie recording,11// time-lapse, long exposure, light trails, night stack,12// bracket fusion and the intervalometer; and the single path13// that stores a capture and indexes it. A capture either14// ends in the library or ends with an error shown to the15// user.16// Module : Features17// Repository : https://git.spboucher.ai/orix-camera18// Project Website : https://www.orixlab.dev19// Created : 2026-11-2120// Last Modified : 2026-11-2121//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author : Simon-Pierre Boucher27// Position : Professor of Finance28// Institution : Université du Québec en Outaouais (UQO)29// Department : Département des sciences administratives30// Organization : SP Boucher31//32// Website : https://spboucher.ai33// Git : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General : info@spboucher.ai40// Professional : contact@spboucher.ai41// Direct : simon@spboucher.ai42// Research : research@spboucher.ai43// Development : dev@spboucher.ai44// Support : support@spboucher.ai45// Security/Admin : admin@spboucher.ai46// Notifications : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification : Public73// Distribution : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License : Proprietary, all rights reserved (see license file)87// License File : LICENSE88// Maintainer : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import AVFoundation96import CoreImage97import Foundation98import ImageIO99import ORIXDesign100import ORIXImaging101import Photos102import UIKit103104extension CameraModel {105 // MARK: Shutter106107 /// The shutter button. What it does depends on the mode.108 func shutter() {109 guard phase == .running else { return }110 if isRecording { Task { await stopRecording() }; return }111 if accumulating { finishAccumulation(); return }112 if intervalRemaining != nil || countdown != nil { cancelSequence(); return }113 guard !isBusy else { return }114 switch settings.mode {115 case .auto, .photo, .analysis:116 startPhotoSequence()117 case .video:118 Task { await startRecording() }119 case .creative:120 switch settings.creativeTool {121 case .longExposure: startAccumulation(mode: .mean)122 case .lightTrails: startAccumulation(mode: .lighten)123 case .noiseStack: startNoiseStack()124 case .hdrFusion: startBracketFusion()125 case .timeLapse: Task { await startRecording(timeLapse: true) }126 case .intervalometer: startIntervalometer()127 }128 }129 }130131 func cancelSequence() {132 captureTask?.cancel(); captureTask = nil133 countdown = nil; intervalRemaining = nil134 }135136 func cancelMultiFrameCapture() {137 accumulationTimer?.cancel(); accumulationTimer = nil138 _ = pipeline.stopAccumulation()139 _ = pipeline.takeNoiseStack()140 monitor.overrideFrame = nil141 accumulating = false; accumulationFrames = 0142 cancelSequence()143 processingMessage = nil144 }145146 // MARK: Photo147148 private func photoRequest(speed: Bool = false) -> PhotoRequest {149 var request = PhotoRequest(format: settings.mode == .auto ? .heic : settings.photoFormat, flash: settings.flash, prioritizeSpeed: speed)150 if !settings.highResolutionPhotos { request.maxWidth = 4032; request.maxHeight = 3024 }151 return request152 }153154 private func startPhotoSequence() {155 let seconds = settings.timerSeconds156 captureTask = Task {157 if seconds > 0 {158 for remaining in stride(from: seconds, to: 0, by: -1) {159 countdown = remaining160 haptic()161 try? await Task.sleep(for: .seconds(1))162 if Task.isCancelled { countdown = nil; return }163 }164 countdown = nil165 }166 await takePhoto()167 }168 }169170 @discardableResult171 func takePhoto(speed: Bool = false, quiet: Bool = false) async -> Bool {172 guard !isCapturing else { return false }173 isCapturing = true174 defer { isCapturing = false }175 shutterFlash += 1176 if settings.haptics { ORIXHaptics.press() }177 do {178 let request = photoRequest(speed: speed)179 let photo = try await backend.capturePhoto(request)180 try store(photo: photo, format: request.format)181 return true182 } catch {183 show((error as? LocalizedError)?.errorDescription ?? error.localizedDescription, .failure)184 return false185 }186 }187188 /// Burst: repeated speed-prioritized captures while the shutter is held (as fast as the photo output completes them).189 func startBurst() {190 guard phase == .running, !isBusy, !isRecording, settings.mode == .photo || settings.mode == .auto, !settings.photoFormat.isRAW || settings.mode == .auto else { return }191 burstCount = 0192 captureTask = Task {193 while !Task.isCancelled && burstCount < 30 {194 if await takePhoto(speed: true, quiet: true) { burstCount += 1 } else { break }195 }196 }197 }198199 func endBurst() {200 guard burstCount > 0 || captureTask != nil else { return }201 captureTask?.cancel(); captureTask = nil202 if burstCount > 1 { show(String(localized: "\(burstCount) photos saved"), .success) }203 burstCount = 0204 }205206 /// The non-destructive recipe a capture starts with: look, aspect crop and front-camera mirroring. The file itself207 /// always holds the full, unmodified sensor image.208 private func initialRecipe(width: Int, height: Int) -> EditRecipe? {209 var recipe = EditRecipe()210 if settings.mode != .auto, let look = settings.captureLookID, ColorLUT.builtIn(id: look) != nil { recipe.lookID = look }211 if settings.mode != .auto, settings.aspect != .native, width > 0, height > 0 {212 recipe.crop = settings.aspect.rect(frameAspect: Double(width) / Double(height), portrait: height > width)213 }214 if settings.mirrorFrontPhotos, capabilities?.lens.position == .front { recipe.flippedHorizontally = true }215 return recipe.isIdentity ? nil : recipe216 }217218 private func store(photo: CapturedPhoto, format: PhotoFormat) throws {219 let base = CaptureStorage.baseName()220 var primary: String?221 var companion: String?222 if let raw = photo.raw { primary = try library.storage.write(raw, base: base, ext: "dng") }223 if let processed = photo.processed {224 let name = try library.storage.write(processed, base: base, ext: photo.processedExtension)225 if primary == nil { primary = name } else { companion = name }226 }227 guard let primary else { throw CameraError.captureFailed("no data") }228 let kind: MediaKind = photo.raw == nil ? .photo : (photo.isProRAW ? .proRAW : .raw)229 // Dimensions as displayed (orientation applied).230 var width = photo.width, height = photo.height231 if let meta = MetadataInspector.readImage(url: library.storage.url(for: companion ?? primary)), let w = meta.pixelWidth, let h = meta.pixelHeight {232 let turned = [5, 6, 7, 8].contains(meta.orientation ?? 1)233 width = turned ? h : w; height = turned ? w : h234 }235 let item = MediaItem(kind: kind, fileName: primary, companionFileName: companion, pixelWidth: width, pixelHeight: height,236 captureSummary: captureSummary(extra: format.title), isSynthetic: isSynthetic)237 item.recipe = initialRecipe(width: width, height: height)238 finishIndexing(item, thumbnailSource: companion ?? primary)239 }240241 /// Thumbnail, visual hash, index row, optional copy to Photos.242 func finishIndexing(_ item: MediaItem, thumbnailSource: String) {243 if let url = library.storage.makeImageThumbnail(for: thumbnailSource), thumbnailSource != item.fileName {244 try? FileManager.default.copyItem(at: url, to: library.storage.thumbnailURL(for: item.fileName))245 }246 if let image = UIImage(contentsOfFile: library.storage.thumbnailURL(for: item.fileName).path)?.cgImage,247 let hash = DuplicateDetector.differenceHash(image) {248 item.visualHash = Int64(bitPattern: hash)249 }250 library.add(item)251 refreshLastThumbnail()252 refreshStorage()253 if settings.saveToPhotos { Task { await copyToPhotos(item) } }254 }255256 // MARK: Movies257258 func startRecording(timeLapse: Bool = false) async {259 guard !isRecording, let caps = capabilities else { return }260 // The movie has the size of the frames actually delivered, read from the stream itself.261 guard let frame = pipeline.latestFrame else { return }262 let width = frame.width, height = frame.height263 let codec = caps.videoCodecs.contains(settings.videoCodec) ? settings.videoCodec : .h264264 let rate = live.activeFrameRate > 0 ? live.activeFrameRate : 30265 refreshStorage()266 let perSecond = ExposureMath.bytesPerSecond(codec: codec, width: width, height: height, frameRate: rate, audio: settings.recordAudio)267 guard Double(freeBytes) > perSecond * 10 + Double(CaptureStorage.reserveBytes) else {268 show(String(localized: "Not enough free space to record."), .failure)269 return270 }271 var configuration = VideoRecorderConfiguration(url: library.storage.incomingURL(ext: "mov"), width: width, height: height, codec: codec, frameRate: rate)272 configuration.transform = CaptureGeometry.movieTransform(rotationDegrees: captureRotation)273 configuration.audio = !timeLapse && settings.recordAudio && backend.microphoneAccess() == .granted274 let slowMotion = !timeLapse && rate > 60 && settings.slowMotionPlayback275 if timeLapse || slowMotion { configuration.timeLapsePlaybackRate = 30 }276 recordingKind = timeLapse ? .timeLapse : (slowMotion ? .slowMotion : .video)277 var extra = "\(VideoFormatOption(width: max(width, height), height: min(width, height), frameRate: rate).resolutionLabel) \(Int(rate)) \(codec.title)"278 if timeLapse { extra = "time-lapse \(settings.timeLapseInterval)s" }279 if slowMotion { extra += " slow motion" }280 recordingSummary = captureSummary(extra: extra)281 do {282 let recorder = try VideoRecorder(configuration: configuration)283 recordingDuration = 0; recordingDropped = 0284 pipeline.startRecording(recorder, timeLapseInterval: timeLapse ? settings.timeLapseInterval : nil)285 isRecording = true286 UIApplication.shared.isIdleTimerDisabled = true287 if settings.haptics { ORIXHaptics.press() }288 } catch {289 show(String(localized: "Recording could not start: \(error.localizedDescription)"), .failure)290 }291 }292293 func stopRecording(reason: String? = nil) async {294 guard isRecording, let recorder = pipeline.stopRecording() else { return }295 isRecording = false296 UIApplication.shared.isIdleTimerDisabled = false297 processingMessage = String(localized: "Saving video…")298 defer { processingMessage = nil }299 do {300 let result = try await recorder.finish()301 let name = try library.storage.adopt(result.url)302 let displayed = CaptureGeometry.displayedSize(width: recorder.configuration.width, height: recorder.configuration.height, rotationDegrees: captureRotation)303 let item = MediaItem(kind: recordingKind, fileName: name, pixelWidth: Int(displayed.width), pixelHeight: Int(displayed.height),304 duration: result.duration, captureSummary: recordingSummary, isSynthetic: isSynthetic)305 if let thumbnail = await CameraModel.videoThumbnail(url: library.storage.url(for: name)) { library.storage.writeThumbnail(thumbnail, for: name) }306 finishIndexing(item, thumbnailSource: name)307 if settings.haptics { ORIXHaptics.success() }308 if result.droppedFrames > 0 {309 show(String(localized: "Video saved. \(result.droppedFrames) frames were dropped while recording."), .warning)310 } else if let reason {311 show(String(localized: "Recording stopped and saved. \(reason)"), .warning)312 }313 } catch {314 show(String(localized: "The video could not be saved: \(error.localizedDescription)"), .failure)315 }316 }317318 static func videoThumbnail(url: URL) async -> CGImage? {319 let generator = AVAssetImageGenerator(asset: AVURLAsset(url: url))320 generator.appliesPreferredTrackTransform = true321 generator.maximumSize = CGSize(width: 480, height: 480)322 return try? await generator.image(at: .zero).image323 }324325 /// Movies an interrupted session left behind are finished files up to their last fragment: adopt them.326 func recoverInterruptedRecordings() async {327 for url in library.storage.interruptedRecordings() {328 guard let meta = await MetadataInspector.readVideo(url: url), (meta.duration ?? 0) > 0, let name = try? library.storage.adopt(url) else { continue }329 let item = MediaItem(kind: .video, fileName: name, pixelWidth: meta.pixelWidth ?? 0, pixelHeight: meta.pixelHeight ?? 0, duration: meta.duration ?? 0, captureSummary: "recovered")330 if let thumbnail = await CameraModel.videoThumbnail(url: library.storage.url(for: name)) { library.storage.writeThumbnail(thumbnail, for: name) }331 finishIndexing(item, thumbnailSource: name)332 }333 }334335 // MARK: Long exposure and light trails336337 private func startAccumulation(mode: FrameAccumulator.Mode) {338 let rate = max(live.activeFrameRate, 1)339 accumulationTarget = Int((settings.longExposureSeconds * rate).rounded())340 accumulationFrames = 0341 pipeline.startAccumulation(mode: mode, limit: accumulationTarget)342 accumulating = true343 UIApplication.shared.isIdleTimerDisabled = true344 if settings.haptics { ORIXHaptics.press() }345 // Show the result as it builds: the monitor displays the running stack twice per second.346 accumulationTimer = Task { [weak self] in347 while !Task.isCancelled {348 try? await Task.sleep(for: .milliseconds(450))349 guard let self, self.accumulating, !Task.isCancelled else { return }350 self.updateAccumulationPreview()351 }352 }353 }354355 private func updateAccumulationPreview() {356 // Reads the running result without stopping the accumulation.357 guard let preview = pipeline.accumulationPreview() else { return }358 monitor.overrideFrame = Frame(pixelBuffer: preview, time: CACurrentMediaTime())359 }360361 func accumulationTick(_ count: Int) {362 guard accumulating else { return }363 accumulationFrames = abs(count)364 if count < 0 { finishAccumulation() }365 }366367 func finishAccumulation() {368 guard accumulating, let accumulator = pipeline.stopAccumulation() else { return }369 accumulating = false370 accumulationTimer?.cancel(); accumulationTimer = nil371 UIApplication.shared.isIdleTimerDisabled = false372 let kind: MediaKind = accumulator.mode == .mean ? .longExposure : .lightTrails373 let frames = accumulator.frameCount374 let seconds = Double(frames) / max(live.activeFrameRate, 1)375 guard frames >= 2 else { monitor.overrideFrame = nil; show(String(localized: "Too few frames were captured."), .warning); return }376 let summary = captureSummary(extra: "\(frames) frames · \(String(format: "%.1f", seconds)) s")377 saveComputed(kind: kind, summary: summary, message: String(localized: "Saving…")) { accumulator.result() }378 }379380 // MARK: Night stack381382 private func startNoiseStack() {383 processingMessage = String(localized: "Hold still…")384 if settings.haptics { ORIXHaptics.press() }385 let count = settings.noiseStackFrames386 pipeline.startNoiseStack(count: count) { [weak self] in387 Task { @MainActor in self?.finishNoiseStack() }388 }389 // Safety net: if frames stop arriving, give up instead of waiting for ever.390 captureTask = Task { [weak self] in391 try? await Task.sleep(for: .seconds(8))392 if !Task.isCancelled { self?.finishNoiseStack() }393 }394 }395396 private func finishNoiseStack() {397 captureTask?.cancel(); captureTask = nil398 guard let (denoiser, skipped) = pipeline.takeNoiseStack() else { processingMessage = nil; return }399 guard denoiser.frameCount >= 2 else {400 processingMessage = nil401 show(String(localized: "The frames could not be aligned. Hold the camera steady or use a tripod."), .failure)402 return403 }404 var extra = "\(denoiser.frameCount) frames merged"405 if skipped > 0 { extra += " · \(skipped) skipped" }406 saveComputed(kind: .noiseStack, summary: captureSummary(extra: extra), message: String(localized: "Merging…")) { denoiser.result() }407 }408409 // MARK: Bracket fusion410411 private func startBracketFusion() {412 guard let caps = capabilities, caps.maxBracketCount >= 2 else {413 show(capabilities?.localizedExplanation(for: .bracketing) ?? "", .warning); return414 }415 let stops = settings.bracketStops416 let biases = caps.maxBracketCount >= 3 ? [-stops, 0, stops] : [-stops, stops]417 processingMessage = String(localized: "Capturing bracket…")418 shutterFlash += 1419 if settings.haptics { ORIXHaptics.press() }420 let summary = captureSummary(extra: "bracket ±\(stops) EV fused")421 let physicalMemory = ProcessInfo.processInfo.physicalMemory422 captureTask = Task {423 do {424 let frames = try await backend.captureBracket(biases: biases)425 processingMessage = String(localized: "Fusing exposures…")426 let fused: (image: FloatImage, orientation: Int, used: Int) = try await Task.detached(priority: .userInitiated) {427 try CameraModel.fuse(frames, physicalMemory: physicalMemory)428 }.value429 let used = fused.used430 saveComputed(kind: .hdrFusion, summary: summary + " · \(used) exposures", orientation: fused.orientation, message: String(localized: "Saving…")) { fused.image }431 } catch {432 processingMessage = nil433 show((error as? LocalizedError)?.errorDescription ?? error.localizedDescription, .failure)434 }435 }436 }437438 /// Largest fusion size for a device. Measured peak memory of a three-exposure fusion (orix-bench fusion): 542 MB at439 /// 6 MP, 720 MB at 8 MP, 929 MB at 12 MP. The tiers keep that peak well under what iOS grants a foreground app.440 nonisolated static func fusionPixelBudget(physicalMemory: UInt64) -> Int {441 switch physicalMemory {442 case ..<5_000_000_000: 4_000_000443 case ..<7_000_000_000: 6_000_000444 case ..<11_000_000_000: 8_000_000445 default: 12_500_000446 }447 }448449 /// Decodes, aligns and fuses a bracket. Exposures that cannot be registered are left out; at least two must remain.450 nonisolated static func fuse(_ frames: [Data], physicalMemory: UInt64) throws -> (image: FloatImage, orientation: Int, used: Int) {451 let pixelBudget = fusionPixelBudget(physicalMemory: physicalMemory)452 var images: [CGImage] = []453 var orientation = 1454 for (index, data) in frames.enumerated() {455 guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { continue }456 let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]457 if index == 0 { orientation = properties?[kCGImagePropertyOrientation] as? Int ?? 1 }458 let w = properties?[kCGImagePropertyPixelWidth] as? Int ?? 0, h = properties?[kCGImagePropertyPixelHeight] as? Int ?? 0459 var image: CGImage?460 if w * h > pixelBudget, w > 0 {461 let scale = (Double(pixelBudget) / Double(w * h)).squareRoot()462 let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: false,463 kCGImageSourceThumbnailMaxPixelSize: Int(Double(max(w, h)) * scale)]464 image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary)465 } else {466 image = CGImageSourceCreateImageAtIndex(source, 0, nil)467 }468 if let image { images.append(image) }469 }470 guard images.count >= 2 else { throw CameraError.captureFailed("bracket decode") }471 // Align everything to the middle exposure (the best exposed one, the most reliable to register against).472 let reference = images[images.count / 2]473 var aligned: [CGImage] = [], shifts: [(dx: Int, dy: Int)] = []474 for image in images {475 if image === reference { aligned.append(image); shifts.append((0, 0)); continue }476 guard image.width == reference.width, image.height == reference.height, let shift = ImageAligner.shift(moving: image, reference: reference) else { continue }477 aligned.append(image); shifts.append(shift)478 }479 guard aligned.count >= 2 else {480 throw CameraError.captureFailed(String(localized: "the exposures could not be aligned. Use a tripod."))481 }482 return (try ExposureFusion.fuse(aligned, shifts: shifts), orientation, aligned.count)483 }484485 // MARK: Intervalometer486487 private func startIntervalometer() {488 let count = settings.intervalCount, interval = settings.intervalSeconds489 intervalRemaining = count490 UIApplication.shared.isIdleTimerDisabled = true491 captureTask = Task {492 var taken = 0493 while !Task.isCancelled, taken < count {494 let began = ContinuousClock.now495 if await takePhoto(quiet: true) { taken += 1 }496 intervalRemaining = count - taken497 if taken >= count { break }498 let elapsed = ContinuousClock.now - began499 try? await Task.sleep(for: .seconds(interval) - elapsed)500 }501 intervalRemaining = nil502 UIApplication.shared.isIdleTimerDisabled = false503 if taken > 0 { show(String(localized: "\(taken) photos saved"), .success) }504 }505 }506507 // MARK: Saving computed images508509 /// Renders a multi-frame result upright, encodes it (HEIC, or 16-bit TIFF when the setting asks) and indexes it.510 func saveComputed(kind: MediaKind, summary: String, orientation: Int? = nil, message: String, produce: @escaping @Sendable () -> FloatImage) {511 processingMessage = message512 let tag = orientation ?? CaptureGeometry.exifOrientation(rotationDegrees: captureRotation)513 let deep = settings.deepComputationalFiles514 let storage = library.storage515 let synthetic = isSynthetic516 let mirrored = settings.mirrorFrontPhotos && capabilities?.lens.position == .front517 Task {518 let outcome: Result<(String, Int, Int), Error> = await Task.detached(priority: .userInitiated) {519 do {520 let result = produce()521 guard let cg = result.cgImage16() else { throw CameraError.captureFailed("render") }522 let upright = CIImage(cgImage: cg).oriented(CGImagePropertyOrientation(rawValue: UInt32(tag)) ?? .up)523 guard let rendered = EditPipeline.render(upright, deep: true) else { throw CameraError.captureFailed("render") }524 var options = ImageExportOptions()525 options.format = deep ? .tiff : .heic526 options.quality = 0.95527 options.fileName = UUID().uuidString528 let formatter = DateFormatter()529 formatter.locale = Locale(identifier: "en_US_POSIX"); formatter.dateFormat = "yyyy:MM:dd HH:mm:ss"530 let properties: [CFString: Any] = [531 kCGImagePropertyTIFFDictionary: [kCGImagePropertyTIFFSoftware: synthetic ? "ORIX Camera (synthetic scene)" : "ORIX Camera", kCGImagePropertyTIFFMake: synthetic ? "ORIX" : "Apple"],532 kCGImagePropertyExifDictionary: [kCGImagePropertyExifDateTimeOriginal: formatter.string(from: Date()), kCGImagePropertyExifUserComment: summary] as [CFString: Any],533 ]534 let temp = try ImageExporter.export(rendered, sourceProperties: properties, options: options, to: storage.incomingDirectory)535 let name = try storage.adopt(temp)536 return .success((name, rendered.width, rendered.height))537 } catch {538 return .failure(error)539 }540 }.value541 monitor.overrideFrame = nil542 processingMessage = nil543 switch outcome {544 case .success(let (name, width, height)):545 let item = MediaItem(kind: kind, fileName: name, pixelWidth: width, pixelHeight: height, captureSummary: summary, isSynthetic: synthetic)546 if mirrored { var recipe = EditRecipe(); recipe.flippedHorizontally = true; item.recipe = recipe }547 finishIndexing(item, thumbnailSource: name)548 if settings.haptics { ORIXHaptics.success() }549 case .failure(let error):550 show(String(localized: "The image could not be saved: \((error as? LocalizedError)?.errorDescription ?? error.localizedDescription)"), .failure)551 }552 }553 }554555 // MARK: Photos library (add-only)556557 func copyToPhotos(_ item: MediaItem) async {558 let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly)559 guard status == .authorized || status == .limited else {560 show(String(localized: "ORIX Camera is not allowed to add to Photos. The capture is safe in the ORIX library."), .warning)561 return562 }563 let primary = library.storage.url(for: item.fileName)564 let companion = item.companionFileName.map { library.storage.url(for: $0) }565 let isVideo = item.kind.isVideo566 do {567 try await PHPhotoLibrary.shared().performChanges {568 let request = PHAssetCreationRequest.forAsset()569 let options = PHAssetResourceCreationOptions()570 options.shouldMoveFile = false571 if isVideo {572 request.addResource(with: .video, fileURL: primary, options: options)573 } else if let companion {574 // RAW + processed: the processed image is the main resource, the DNG the alternate.575 request.addResource(with: .photo, fileURL: companion, options: options)576 request.addResource(with: .alternatePhoto, fileURL: primary, options: options)577 } else {578 request.addResource(with: .photo, fileURL: primary, options: options)579 }580 }581 } catch {582 show(String(localized: "Could not add to Photos: \(error.localizedDescription)"), .warning)583 }584 }585}586