SPB Git

Repository Public License

Export.swift 12.9 KB 270 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Camera9// File             : Packages/ORIXCameraKit/Sources/ORIXImaging/Media/Export.swift10// Description      : Export engine. Images: JPEG, HEIC, PNG, TIFF with size,11//                    quality, colour space and metadata policy, or a12//                    byte-identical copy of the original (RAW/DNG included).13//                    Videos: passthrough (original) or re-encode. A re-encoded14//                    file is never described as original quality.15// Module           : ORIXImaging16// Repository       : https://git.spboucher.ai/orix-camera17// Project Website  : https://www.orixlab.dev18// Created          : 2026-11-2119// Last Modified    : 2026-11-2120//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : Proprietary, all rights reserved (see license file)86// License File     : LICENSE87// Maintainer       : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import AVFoundation95import CoreGraphics96import Foundation97import ImageIO98import UniformTypeIdentifiers99100public enum ExportImageFormat: String, Sendable, CaseIterable, Codable {101    case jpeg, heic, png, tiff102    public var type: UTType {103        switch self {104        case .jpeg: .jpeg105        case .heic: .heic106        case .png: .png107        case .tiff: .tiff108        }109    }110    public var fileExtension: String { self == .jpeg ? "jpg" : rawValue }111    public var isLossy: Bool { self == .jpeg || self == .heic }112    /// Whether the encoder keeps 16 bits per channel.113    public var supportsDeepColor: Bool { self == .png || self == .tiff }114}115116public enum ExportColorSpace: String, Sendable, CaseIterable, Codable {117    case sRGB, displayP3118    public var cgColorSpace: CGColorSpace {119        CGColorSpace(name: self == .sRGB ? CGColorSpace.sRGB : CGColorSpace.displayP3)!120    }121}122123public enum MetadataPolicy: String, Sendable, CaseIterable, Codable {124    case keepAll, removeLocation, removeAll125}126127public struct ImageExportOptions: Sendable, Equatable, Codable {128    public var format: ExportImageFormat = .jpeg129    /// 0…1, lossy formats only.130    public var quality: Double = 0.9131    /// Longest side in pixels. Nil keeps the rendered size.132    public var maxDimension: Int?133    public var colorSpace: ExportColorSpace = .sRGB134    public var metadata: MetadataPolicy = .keepAll135    /// File name without extension.136    public var fileName: String = "ORIX"137    public init() {}138}139140public enum ExportError: Error, Equatable {141    case cannotCreateDestination, encodeFailed, cannotRead, sessionFailed(String), unsupportedPreset142}143144public enum ImageExporter {145    /// Removes characters that are unsafe in file names.146    public static func sanitized(_ name: String) -> String {147        let cleaned = name.components(separatedBy: CharacterSet(charactersIn: "/\\:?%*|\"<>\n\r\t")).joined(separator: "-").trimmingCharacters(in: .whitespaces)148        return cleaned.isEmpty ? "ORIX" : String(cleaned.prefix(120))149    }150151    /// A URL in `directory` that does not collide with an existing file.152    public static func uniqueURL(directory: URL, name: String, ext: String) -> URL {153        var candidate = directory.appendingPathComponent("\(name).\(ext)")154        var index = 2155        while FileManager.default.fileExists(atPath: candidate.path) {156            candidate = directory.appendingPathComponent("\(name)-\(index).\(ext)"); index += 1157        }158        return candidate159    }160161    /// Metadata to embed for a policy. Orientation is reset because rendered pixels are already upright.162    public static func filteredProperties(_ properties: [CFString: Any]?, policy: MetadataPolicy, width: Int, height: Int) -> [CFString: Any] {163        guard policy != .removeAll, var p = properties else { return [:] }164        if policy == .removeLocation { p[kCGImagePropertyGPSDictionary] = nil }165        p[kCGImagePropertyOrientation] = 1166        p[kCGImagePropertyPixelWidth] = width167        p[kCGImagePropertyPixelHeight] = height168        if var tiff = p[kCGImagePropertyTIFFDictionary] as? [CFString: Any] { tiff[kCGImagePropertyTIFFOrientation] = 1; p[kCGImagePropertyTIFFDictionary] = tiff }169        if var exif = p[kCGImagePropertyExifDictionary] as? [CFString: Any] {170            exif[kCGImagePropertyExifPixelXDimension] = width; exif[kCGImagePropertyExifPixelYDimension] = height171            p[kCGImagePropertyExifDictionary] = exif172        }173        // Format-specific containers of the source do not belong in a different output format.174        for key in [kCGImagePropertyDNGDictionary, kCGImagePropertyMakerAppleDictionary, kCGImagePropertyRawDictionary, kCGImagePropertyJFIFDictionary, kCGImagePropertyPNGDictionary, kCGImagePropertyHEICSDictionary, kCGImagePropertyProfileName, kCGImagePropertyColorModel, kCGImagePropertyDepth] {175            p[key] = nil176        }177        return p178    }179180    /// Redraws `image` at the target size, colour space and bit depth.181    static func prepared(_ image: CGImage, options: ImageExportOptions) -> CGImage? {182        var w = image.width, h = image.height183        if let limit = options.maxDimension, max(w, h) > limit, limit > 0 {184            let scale = Double(limit) / Double(max(w, h))185            w = max(1, Int((Double(w) * scale).rounded())); h = max(1, Int((Double(h) * scale).rounded()))186        }187        let deep = image.bitsPerComponent > 8 && options.format.supportsDeepColor188        let info = deep ? CGImageAlphaInfo.noneSkipLast.rawValue | CGBitmapInfo.byteOrder16Little.rawValue : CGImageAlphaInfo.noneSkipLast.rawValue189        guard let context = CGContext(data: nil, width: w, height: h, bitsPerComponent: deep ? 16 : 8, bytesPerRow: 0,190                                      space: options.colorSpace.cgColorSpace, bitmapInfo: info) else { return nil }191        context.interpolationQuality = .high192        context.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))193        return context.makeImage()194    }195196    /// Encodes `image` into `directory` and returns the file URL.197    @discardableResult198    public static func export(_ image: CGImage, sourceProperties: [CFString: Any]? = nil, options: ImageExportOptions, to directory: URL) throws -> URL {199        guard let output = prepared(image, options: options) else { throw ExportError.encodeFailed }200        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)201        let url = uniqueURL(directory: directory, name: sanitized(options.fileName), ext: options.format.fileExtension)202        guard let destination = CGImageDestinationCreateWithURL(url as CFURL, options.format.type.identifier as CFString, 1, nil) else { throw ExportError.cannotCreateDestination }203        var properties = filteredProperties(sourceProperties, policy: options.metadata, width: output.width, height: output.height)204        if options.format.isLossy { properties[kCGImageDestinationLossyCompressionQuality] = min(max(options.quality, 0.01), 1) }205        if options.format == .tiff { properties[kCGImagePropertyTIFFDictionary] = ((properties[kCGImagePropertyTIFFDictionary] as? [CFString: Any]) ?? [:]).merging([kCGImagePropertyTIFFCompression: 5]) { a, _ in a } }206        CGImageDestinationAddImage(destination, output, properties as CFDictionary)207        guard CGImageDestinationFinalize(destination) else {208            try? FileManager.default.removeItem(at: url)209            throw ExportError.encodeFailed210        }211        return url212    }213214    /// Byte-identical copy of the original file (the only export that may be called "original").215    @discardableResult216    public static func exportOriginal(_ source: URL, fileName: String? = nil, to directory: URL) throws -> URL {217        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)218        let name = sanitized(fileName ?? source.deletingPathExtension().lastPathComponent)219        let url = uniqueURL(directory: directory, name: name, ext: source.pathExtension)220        try FileManager.default.copyItem(at: source, to: url)221        return url222    }223}224225public enum VideoExportPreset: String, Sendable, CaseIterable, Codable {226    /// No re-encoding: the original streams in a new container.227    case original228    case hevc4K, hevc1080, h264_1080, h264_720229230    public var isReencoded: Bool { self != .original }231    var avPreset: String {232        switch self {233        case .original: AVAssetExportPresetPassthrough234        case .hevc4K: AVAssetExportPresetHEVC3840x2160235        case .hevc1080: AVAssetExportPresetHEVC1920x1080236        case .h264_1080: AVAssetExportPreset1920x1080237        case .h264_720: AVAssetExportPreset1280x720238        }239    }240}241242public enum VideoExporter {243    @discardableResult244    public static func export(_ source: URL, preset: VideoExportPreset, removeLocation: Bool, fileName: String? = nil, to directory: URL) async throws -> URL {245        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)246        let name = ImageExporter.sanitized(fileName ?? source.deletingPathExtension().lastPathComponent)247        if preset == .original && !removeLocation {248            return try ImageExporter.exportOriginal(source, fileName: name, to: directory)249        }250        let asset = AVURLAsset(url: source)251        guard let session = AVAssetExportSession(asset: asset, presetName: preset.avPreset) else { throw ExportError.unsupportedPreset }252        let url = ImageExporter.uniqueURL(directory: directory, name: name, ext: "mov")253        if removeLocation {254            let all = (try? await asset.load(.metadata)) ?? []255            session.metadata = all.filter { item in256                let id = item.identifier?.rawValue ?? ""257                return !id.localizedCaseInsensitiveContains("location") && !id.contains("©xyz")258            }259            session.metadataItemFilter = AVMetadataItemFilter.forSharing()260        }261        do {262            try await session.export(to: url, as: .mov)263        } catch {264            try? FileManager.default.removeItem(at: url)265            throw ExportError.sessionFailed(error.localizedDescription)266        }267        return url268    }269}270
Files main
Menu

Theme