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/Library/MediaExport.swift10// Description : Export jobs for library items: rendered image exports11// (recipe applied), byte-identical originals, video12// passthrough or re-encode, metadata reports, and adding13// exported files to Photos.14// Module : Features15// 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 CoreImage94import Foundation95import ORIXImaging96import Photos9798nonisolated enum ExportSize: Int, Sendable, CaseIterable, Identifiable {99 case original = 0, uhd = 3840, large = 2048, hd = 1080100 var id: Int { rawValue }101 var maxDimension: Int? { self == .original ? nil : rawValue }102}103104nonisolated struct ExportSettings: Sendable, Equatable {105 /// Nil = the original file, copied byte for byte.106 var imageFormat: ExportImageFormat? = .jpeg107 var quality = 0.9108 var size: ExportSize = .original109 var colorSpace: ExportColorSpace = .sRGB110 var metadata: MetadataPolicy = .removeLocation111 var videoPreset: VideoExportPreset = .original112 /// Used when exactly one item is exported; otherwise each file keeps its own name.113 var fileName = ""114}115116nonisolated enum MediaExport {117 /// Exports the items into `directory`. `progress` receives the number of finished items.118 static func run(_ items: [ItemSnapshot], settings: ExportSettings, directory: URL, progress: @Sendable (Int) -> Void = { _ in }) async throws -> [URL] {119 var urls: [URL] = []120 for (index, item) in items.enumerated() {121 try Task.checkCancellation()122 let name = items.count == 1 && !settings.fileName.trimmingCharacters(in: .whitespaces).isEmpty ? settings.fileName : item.baseName123 if item.isVideo {124 urls.append(try await VideoExporter.export(item.url, preset: settings.videoPreset, removeLocation: settings.metadata != .keepAll, fileName: name, to: directory))125 } else if let format = settings.imageFormat {126 urls.append(try image(item, format: format, settings: settings, name: name, directory: directory))127 } else {128 urls.append(try ImageExporter.exportOriginal(item.url, fileName: name, to: directory))129 }130 progress(index + 1)131 }132 return urls133 }134135 static func image(_ item: ItemSnapshot, format: ExportImageFormat, settings: ExportSettings, name: String, directory: URL) throws -> URL {136 guard let source = MediaRenderer.source(url: item.url, isRAW: item.isRAW, raw: item.recipe?.raw) else { throw ExportError.cannotRead }137 // RAW and 16-bit sources keep their depth in formats that can hold it.138 let sourceDepth = MetadataInspector.readImage(url: item.url)?.bitDepth ?? 8139 let deep = format.supportsDeepColor && (item.isRAW || sourceDepth > 8)140 guard let rendered = EditPipeline.render(recipe: item.recipe ?? EditRecipe(), source: source, deep: deep, colorSpace: settings.colorSpace.cgColorSpace) else { throw ExportError.encodeFailed }141 var options = ImageExportOptions()142 options.format = format; options.quality = settings.quality; options.maxDimension = settings.size.maxDimension143 options.colorSpace = settings.colorSpace; options.metadata = settings.metadata; options.fileName = name144 return try ImageExporter.export(rendered, sourceProperties: MetadataInspector.properties(url: item.url), options: options, to: directory)145 }146147 /// Writes the metadata report of an item (JSON) and returns its URL.148 static func metadataReport(_ metadata: MediaMetadata, name: String, directory: URL) throws -> URL {149 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)150 let url = ImageExporter.uniqueURL(directory: directory, name: ImageExporter.sanitized(name + "-metadata"), ext: "json")151 try MetadataInspector.jsonReport(metadata).write(to: url, options: .atomic)152 return url153 }154155 /// Adds exported files to the Photos library (add-only access). Returns false when access is refused.156 static func addToPhotos(_ urls: [URL]) async throws -> Bool {157 let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly)158 guard status == .authorized || status == .limited else { return false }159 try await PHPhotoLibrary.shared().performChanges {160 for url in urls {161 let request = PHAssetCreationRequest.forAsset()162 let options = PHAssetResourceCreationOptions()163 options.shouldMoveFile = false164 let isVideo = ["mov", "mp4", "m4v"].contains(url.pathExtension.lowercased())165 request.addResource(with: isVideo ? .video : .photo, fileURL: url, options: options)166 }167 }168 return true169 }170}171172/// One row of the metadata inspector.173nonisolated struct MetadataRow: Sendable, Equatable, Identifiable {174 var label: String175 var value: String176 var id: String { label }177}178179nonisolated struct MetadataSection: Sendable, Equatable, Identifiable {180 var title: String181 var rows: [MetadataRow]182 var id: String { title }183}184185nonisolated enum MetadataRows {186 /// Sections for the inspector. A field appears only when the file (or the library) really has it.187 static func sections(item: ItemSnapshot, metadata: MediaMetadata?, companion: MediaMetadata? = nil) -> [MetadataSection] {188 var sections: [MetadataSection] = []189 func add(_ title: String, _ rows: [(String, String?)]) {190 let present = rows.compactMap { label, value in value.flatMap { $0.isEmpty ? nil : MetadataRow(label: label, value: $0) } }191 if !present.isEmpty { sections.append(MetadataSection(title: title, rows: present)) }192 }193 func number(_ value: Double?, _ digits: Int = 1) -> String? { value.map { $0.formatted(.number.precision(.fractionLength(0...digits))) } }194195 add(String(localized: "Capture"), [196 (String(localized: "Kind"), MediaFormat.kindTitle(item.kind)),197 (String(localized: "Title"), item.title),198 (String(localized: "Captured"), item.createdAt.formatted(date: .abbreviated, time: .standard)),199 (String(localized: "Capture settings"), item.captureSummary),200 (String(localized: "Edits"), item.recipe == nil ? nil : String(localized: "Non-destructive edits stored beside the original")),201 (String(localized: "Source"), item.isSynthetic ? String(localized: "Synthetic test scene (simulator)") : nil),202 ])203 if let m = metadata {204 add(String(localized: "File"), [205 (String(localized: "File name"), m.fileName),206 (String(localized: "Format"), m.typeIdentifier),207 (String(localized: "File size"), m.fileSize.map(MediaFormat.bytes)),208 (String(localized: "Dimensions"), m.pixelWidth.flatMap { w in m.pixelHeight.map { MediaFormat.dimensions(width: w, height: $0) } }),209 (String(localized: "Resolution"), m.megapixels.flatMap { $0 >= 0.1 && m.duration == nil ? $0.formatted(.number.precision(.fractionLength(1))) + " MP" : nil }),210 (String(localized: "Bit depth"), m.bitDepth.map { String(localized: "\($0) bits per channel") }),211 (String(localized: "Colour profile"), m.colorProfile),212 (String(localized: "RAW"), m.isRAW ? String(localized: "Yes (DNG)") : nil),213 (String(localized: "Companion file"), companion?.fileName),214 (String(localized: "Companion size"), companion?.fileSize.map(MediaFormat.bytes)),215 ])216 add(String(localized: "Camera"), [217 (String(localized: "Make"), m.cameraMake),218 (String(localized: "Model"), m.cameraModel),219 (String(localized: "Lens"), m.lensModel),220 (String(localized: "Software"), m.software),221 (String(localized: "Date in file"), m.captureDate),222 ])223 add(String(localized: "Exposure"), [224 (String(localized: "ISO"), m.iso.map { ExposureMath.isoLabel($0) }),225 (String(localized: "Exposure time"), m.exposureTime.map { ExposureMath.shutterLabel($0) + " s" }),226 (String(localized: "Aperture"), m.aperture.flatMap { number($0, 2) }.map { "f/\($0)" }),227 (String(localized: "Focal length"), m.focalLength.flatMap { number($0, 2) }.map { "\($0) mm" }),228 (String(localized: "Focal length (35 mm)"), m.focalLength35mm.flatMap { number($0, 0) }.map { "\($0) mm" }),229 (String(localized: "Exposure bias"), m.exposureBias.map { $0.formatted(.number.precision(.fractionLength(1)).sign(strategy: .always())) + " EV" }),230 (String(localized: "Flash"), m.flashFired.map { $0 ? String(localized: "Fired") : String(localized: "Did not fire") }),231 (String(localized: "White balance"), m.whiteBalanceManual.map { $0 ? String(localized: "Manual") : String(localized: "Auto") }),232 ])233 add(String(localized: "Video"), [234 (String(localized: "Duration"), m.duration.map { ExposureMath.timecode($0) }),235 (String(localized: "Frame rate"), m.frameRate.flatMap { number($0, 2) }.map { "\($0) fps" }),236 (String(localized: "Codec"), m.videoCodec),237 (String(localized: "Data rate"), m.bitRate.map { ($0 / 1_000_000).formatted(.number.precision(.fractionLength(1))) + " Mbit/s" }),238 (String(localized: "Sound"), m.hasAudio.map { $0 ? String(localized: "Yes") : String(localized: "No") }),239 ])240 if m.hasLocation {241 add(String(localized: "Location"), [242 (String(localized: "Latitude"), m.latitude.map { $0.formatted(.number.precision(.fractionLength(5))) }),243 (String(localized: "Longitude"), m.longitude.map { $0.formatted(.number.precision(.fractionLength(5))) }),244 (String(localized: "Altitude"), m.altitude.map { Measurement(value: $0, unit: UnitLength.meters).formatted(.measurement(width: .abbreviated, usage: .asProvided)) }),245 ])246 }247 }248 return sections249 }250}251