SPB Git

Repository Public License

MediaSupport.swift 11.7 KB 275 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Camera9// File             : App/Sources/Features/Library/MediaSupport.swift10// Description      : Off-main helpers shared by the library, viewer, editor and11//                    export: a Sendable snapshot of an item, image loading (RAW12//                    development included), recipe rendering, the thumbnail13//                    cache and formatting.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 SwiftUI97import UIKit9899/// What background work needs to know about an item (MediaItem itself is a main-actor model object).100nonisolated struct ItemSnapshot: Sendable, Equatable, Identifiable {101    var id: UUID102    var kind: MediaKind103    var url: URL104    var companionURL: URL?105    var thumbnailURL: URL106    var fileName: String107    var recipe: EditRecipe?108    var title: String109    var captureSummary: String110    var createdAt: Date111    var pixelWidth: Int112    var pixelHeight: Int113    var duration: Double114    var byteSize: Int64115    var isSynthetic: Bool116117    var isVideo: Bool { kind.isVideo }118    var isRAW: Bool { kind.isRAW }119    var baseName: String { (fileName as NSString).deletingPathExtension }120}121122extension MediaItem {123    func snapshot(storage: CaptureStorage) -> ItemSnapshot {124        ItemSnapshot(id: id, kind: kind, url: storage.url(for: fileName), companionURL: companionFileName.map(storage.url(for:)),125                     thumbnailURL: storage.thumbnailURL(for: fileName), fileName: fileName, recipe: recipe, title: title,126                     captureSummary: captureSummary, createdAt: createdAt, pixelWidth: pixelWidth, pixelHeight: pixelHeight,127                     duration: duration, byteSize: byteSize, isSynthetic: isSynthetic)128    }129}130131nonisolated enum MediaRenderer {132    /// The upright source image of an item, before any edit. RAW files are developed with `raw` (or the defaults).133    static func source(url: URL, isRAW: Bool, raw: RAWSettings? = nil, draft: Bool = false, scale: Double = 1) -> CIImage? {134        if isRAW { return try? RAWDeveloper.develop(url: url, settings: raw ?? RAWSettings(), draft: draft, scale: scale) }135        return EditPipeline.load(url: url)136    }137138    /// A downsized, unedited bitmap to edit against (fast previews). For RAW the development settings are baked in,139    /// so it is rendered again when they change.140    static func previewBase(url: URL, isRAW: Bool, raw: RAWSettings?, maxDimension: CGFloat) -> CGImage? {141        var scale = 1.0142        if isRAW, let info = RAWDeveloper.info(url: url), info.nativeWidth > 0 {143            scale = min(1, Double(maxDimension) * 1.2 / Double(max(info.nativeWidth, info.nativeHeight)))144        }145        guard let image = source(url: url, isRAW: isRAW, raw: raw, draft: isRAW, scale: scale) else { return nil }146        return EditPipeline.render(image, maxDimension: maxDimension)147    }148149    /// The item as it should be shown: source, RAW development and recipe applied.150    static func rendered(_ item: ItemSnapshot, maxDimension: CGFloat?) -> CGImage? {151        guard !item.isVideo else { return nil }152        var scale = 1.0153        if item.isRAW, let maxDimension, let info = RAWDeveloper.info(url: item.url), info.nativeWidth > 0 {154            scale = min(1, Double(maxDimension) * 1.5 / Double(max(info.nativeWidth, info.nativeHeight)))155        }156        guard let image = source(url: item.url, isRAW: item.isRAW, raw: item.recipe?.raw, scale: scale) else { return nil }157        return EditPipeline.render(recipe: item.recipe ?? EditRecipe(), source: image, maxDimension: maxDimension)158    }159160    /// A grid thumbnail: the stored thumbnail with the recipe's look, tone and geometry applied.161    static func thumbnail(_ item: ItemSnapshot) -> CGImage? {162        guard let data = try? Data(contentsOf: item.thumbnailURL), let stored = UIImage(data: data)?.cgImage else {163            return item.isVideo ? nil : rendered(item, maxDimension: 480)164        }165        guard let recipe = item.recipe, !item.isVideo else { return stored }166        var light = recipe167        light.noiseReduction = 0; light.sharpness = 0        // invisible at this size, not worth the time168        return EditPipeline.render(recipe: light, source: CIImage(cgImage: stored)) ?? stored169    }170}171172/// In-memory cache of grid thumbnails, keyed by file and recipe so an edit refreshes its tile.173final class ThumbnailCache {174    static let shared = ThumbnailCache()175    private let cache = NSCache<NSString, UIImage>()176    init() { cache.countLimit = 600 }177178    nonisolated static func key(_ item: ItemSnapshot) -> String {179        "\(item.fileName)#\(item.recipe.map { String($0.hashValueStable) } ?? "-")"180    }181182    func cached(_ item: ItemSnapshot) -> UIImage? { cache.object(forKey: Self.key(item) as NSString) }183184    func image(for item: ItemSnapshot) async -> UIImage? {185        if let hit = cached(item) { return hit }186        let cg = await Task.detached(priority: .utility) { MediaRenderer.thumbnail(item) }.value187        guard let cg else { return nil }188        let image = UIImage(cgImage: cg)189        cache.setObject(image, forKey: Self.key(item) as NSString)190        return image191    }192193    func removeAll() { cache.removeAllObjects() }194}195196extension EditRecipe {197    /// A hash that is stable for the life of the process and changes with any parameter.198    nonisolated var hashValueStable: Int {199        let encoder = JSONEncoder()200        encoder.outputFormatting = .sortedKeys          // without it the key order, and so the hash, can change between calls201        guard let data = try? encoder.encode(self) else { return 0 }202        var hasher = Hasher(); hasher.combine(data)203        return hasher.finalize()204    }205}206207nonisolated enum MediaFormat {208    static func bytes(_ count: Int64) -> String { count.formatted(.byteCount(style: .file)) }209210    static func megapixels(width: Int, height: Int) -> String {211        (Double(width * height) / 1_000_000).formatted(.number.precision(.fractionLength(1))) + " MP"212    }213214    static func dimensions(width: Int, height: Int) -> String { "\(width) × \(height)" }215216    static func kindTitle(_ kind: MediaKind) -> String {217        switch kind {218        case .photo: String(localized: "Photo")219        case .raw: String(localized: "RAW photo")220        case .proRAW: String(localized: "Apple ProRAW photo")221        case .video: String(localized: "Video")222        case .timeLapse: String(localized: "Time-lapse")223        case .slowMotion: String(localized: "Slow motion")224        case .longExposure: String(localized: "Long exposure")225        case .lightTrails: String(localized: "Light trails")226        case .hdrFusion: String(localized: "Bracket fusion")227        case .noiseStack: String(localized: "Night stack")228        }229    }230231    /// Short badge shown on a tile; nil for a plain photo.232    static func badge(_ kind: MediaKind) -> String? {233        switch kind {234        case .photo, .video: nil235        case .raw: "RAW"236        case .proRAW: "ProRAW"237        case .timeLapse: String(localized: "LAPSE")238        case .slowMotion: String(localized: "SLO-MO")239        case .longExposure: String(localized: "LONG")240        case .lightTrails: String(localized: "TRAILS")241        case .hdrFusion: String(localized: "FUSION")242        case .noiseStack: String(localized: "STACK")243        }244    }245}246247/// The system share sheet.248struct ShareSheet: UIViewControllerRepresentable {249    let items: [URL]250    func makeUIViewController(context: Context) -> UIActivityViewController { UIActivityViewController(activityItems: items, applicationActivities: nil) }251    func updateUIViewController(_ controller: UIActivityViewController, context: Context) {}252}253254struct SharePayload: Identifiable {255    let id = UUID()256    let urls: [URL]257}258259/// The camera screen forces a dark appearance, and sheets presented from it inherit that. The library and settings260/// follow the system appearance instead.261struct SystemAppearance: ViewModifier {262    @State private var scheme: ColorScheme = UIScreen.main.traitCollection.userInterfaceStyle == .dark ? .dark : .light263    func body(content: Content) -> some View {264        content265            .preferredColorScheme(scheme)266            .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in267                scheme = UIScreen.main.traitCollection.userInterfaceStyle == .dark ? .dark : .light268            }269    }270}271272extension View {273    func systemAppearance() -> some View { modifier(SystemAppearance()) }274}275
Files main
Menu

Theme