SPB Git

Repository Public License

EditPipeline.swift 11.6 KB 220 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/Editing/EditPipeline.swift10// Description      : Renders an EditRecipe with Core Image. The original file11//                    is never modified: the pipeline reads it, applies the12//                    recipe and produces a new image for display or export.13// Module           : ORIXImaging14// Repository       : https://git.spboucher.ai/orix-camera15// Project Website  : https://www.orixlab.dev16// Created          : 2026-11-2117// Last Modified    : 2026-11-2118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : Proprietary, all rights reserved (see license file)84// License File     : LICENSE85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import CoreGraphics93import CoreImage94import Foundation95import ImageIO9697public enum EditPipeline {98    /// One shared context (Metal-backed where available, linear sRGB working space, half-float intermediates).99    public static let context: CIContext = CIContext(options: [.cacheIntermediates: false, .name: "orix.edit"])100    static let sRGB = CGColorSpace(name: CGColorSpace.sRGB)!101102    /// Loads an image file with its EXIF orientation applied. RAW files are developed by `RAWDeveloper` instead.103    public static func load(url: URL) -> CIImage? {104        CIImage(contentsOf: url, options: [.applyOrientationProperty: true])105    }106107    /// Scale factor that keeps the largest rectangle of the original aspect ratio inside an image rotated by `degrees`.108    public static func inscribedScale(width: Double, height: Double, degrees: Double) -> Double {109        let t = abs(degrees) * .pi / 180110        guard t > 0 else { return 1 }111        return min(width / (width * cos(t) + height * sin(t)), height / (width * sin(t) + height * cos(t)))112    }113114    /// Tonal and colour part of the recipe (no geometry, no vignette).115    public static func applyTone(_ recipe: EditRecipe, to input: CIImage) -> CIImage {116        var image = input117        if recipe.noiseReduction > 0 {118            image = image.applyingFilter("CINoiseReduction", parameters: ["inputNoiseLevel": recipe.noiseReduction * 0.06, "inputSharpness": 0.4])119        }120        if recipe.exposure != 0 {121            image = image.applyingFilter("CIExposureAdjust", parameters: [kCIInputEVKey: recipe.exposure])122        }123        if recipe.temperature != 0 || recipe.tint != 0 {124            // Moving the assumed neutral toward blue makes the rendering warmer.125            let neutral = CIVector(x: 6500 + recipe.temperature * 2500, y: recipe.tint * 60)126            image = image.applyingFilter("CITemperatureAndTint", parameters: ["inputNeutral": neutral, "inputTargetNeutral": CIVector(x: 6500, y: 0)])127        }128        if recipe.hasToneCurve {129            let table = ToneCurve.table(ys: recipe.combinedCurve, count: 256)130            var rgb = [Float](); rgb.reserveCapacity(256 * 3)131            for v in table { rgb.append(v); rgb.append(v); rgb.append(v) }132            let data = rgb.withUnsafeBufferPointer { Data(buffer: $0) }133            image = image.applyingFilter("CIColorCurves", parameters: ["inputCurvesData": data, "inputCurvesDomain": CIVector(x: 0, y: 1), "inputColorSpace": sRGB])134        }135        if recipe.contrast != 0 || recipe.saturation != 0 {136            image = image.applyingFilter("CIColorControls", parameters: [kCIInputContrastKey: 1 + recipe.contrast * 0.5, kCIInputSaturationKey: 1 + recipe.saturation, kCIInputBrightnessKey: 0])137        }138        if recipe.vibrance != 0 {139            image = image.applyingFilter("CIVibrance", parameters: ["inputAmount": recipe.vibrance])140        }141        if let id = recipe.lookID, let lut = ColorLUT.builtIn(id: id), recipe.lookIntensity > 0, lut.id != ColorLUT.identity.id {142            let graded = image.applyingFilter("CIColorCubeWithColorSpace", parameters: [143                "inputCubeDimension": lut.size, "inputCubeData": lut.rgbaFloatData(), "inputColorSpace": sRGB,144            ])145            if recipe.lookIntensity >= 1 { image = graded } else {146                image = graded.applyingFilter("CIDissolveTransition", parameters: [kCIInputTargetImageKey: image, kCIInputTimeKey: 1 - recipe.lookIntensity])147            }148        }149        if recipe.monochrome {150            image = image.applyingFilter("CIColorControls", parameters: [kCIInputSaturationKey: 0])151        }152        if recipe.sharpness > 0 {153            image = image.applyingFilter("CISharpenLuminance", parameters: [kCIInputSharpnessKey: recipe.sharpness * 1.2, kCIInputRadiusKey: 1.6])154        }155        return image.cropped(to: input.extent)156    }157158    /// Geometry: flip, quarter turns, straighten (with inscribed crop), crop. Output extent starts at the origin.159    public static func applyGeometry(_ recipe: EditRecipe, to input: CIImage) -> CIImage {160        var image = input.transformed(by: CGAffineTransform(translationX: -input.extent.minX, y: -input.extent.minY))161        if recipe.flippedHorizontally {162            image = image.transformed(by: CGAffineTransform(scaleX: -1, y: 1).translatedBy(x: -image.extent.width, y: 0))163        }164        let turns = ((recipe.quarterTurns % 4) + 4) % 4165        if turns != 0 {166            // Clockwise on screen = negative angle in Core Image's bottom-left coordinate system.167            image = image.transformed(by: CGAffineTransform(rotationAngle: -CGFloat(turns) * .pi / 2))168            image = image.transformed(by: CGAffineTransform(translationX: -image.extent.minX, y: -image.extent.minY))169        }170        if recipe.straighten != 0 {171            let w = image.extent.width, h = image.extent.height172            let centre = CGAffineTransform(translationX: -w / 2, y: -h / 2)173            let rotated = image.transformed(by: centre.concatenating(CGAffineTransform(rotationAngle: -CGFloat(recipe.straighten) * .pi / 180)))174            let s = CGFloat(inscribedScale(width: w, height: h, degrees: recipe.straighten))175            let rect = CGRect(x: -w * s / 2, y: -h * s / 2, width: w * s, height: h * s).integral176            image = rotated.cropped(to: rect).transformed(by: CGAffineTransform(translationX: -rect.minX, y: -rect.minY))177        }178        if let crop = recipe.crop {179            let w = image.extent.width, h = image.extent.height180            let c = crop.standardized.intersection(CGRect(x: 0, y: 0, width: 1, height: 1))181            if !c.isEmpty, c.width > 0.01, c.height > 0.01 {182                let rect = CGRect(x: c.minX * w, y: (1 - c.maxY) * h, width: c.width * w, height: c.height * h).integral183                image = image.cropped(to: rect).transformed(by: CGAffineTransform(translationX: -rect.minX, y: -rect.minY))184            }185        }186        return image187    }188189    public static func apply(_ recipe: EditRecipe, to input: CIImage) -> CIImage {190        var image = applyGeometry(recipe, to: applyTone(recipe, to: input))191        if recipe.vignette > 0 {192            let extent = image.extent193            image = image.applyingFilter("CIVignette", parameters: [kCIInputIntensityKey: recipe.vignette * 1.6, kCIInputRadiusKey: 1.8]).cropped(to: extent)194        }195        return image196    }197198    /// Renders to a CGImage. `maxDimension` downsizes for previews; `deep` renders 16 bits per channel.199    public static func render(_ image: CIImage, maxDimension: CGFloat? = nil, deep: Bool = false, colorSpace: CGColorSpace? = nil) -> CGImage? {200        var output = image201        if let maxDimension, max(image.extent.width, image.extent.height) > maxDimension {202            let scale = maxDimension / max(image.extent.width, image.extent.height)203            output = image.applyingFilter("CILanczosScaleTransform", parameters: [kCIInputScaleKey: scale, kCIInputAspectRatioKey: 1])204        }205        let extent = output.extent.integral206        guard extent.width >= 1, extent.height >= 1, !extent.isInfinite else { return nil }207        return context.createCGImage(output, from: extent, format: deep ? .RGBA16 : .RGBA8, colorSpace: colorSpace ?? sRGB)208    }209210    public static func render(recipe: EditRecipe, source: CIImage, maxDimension: CGFloat? = nil, deep: Bool = false, colorSpace: CGColorSpace? = nil) -> CGImage? {211        // Downsize before filtering when a preview is requested: same look, a fraction of the work.212        var input = source213        if let maxDimension, max(source.extent.width, source.extent.height) > maxDimension * 1.5 {214            let scale = maxDimension * 1.5 / max(source.extent.width, source.extent.height)215            input = source.applyingFilter("CILanczosScaleTransform", parameters: [kCIInputScaleKey: scale, kCIInputAspectRatioKey: 1])216        }217        return render(apply(recipe, to: input), maxDimension: maxDimension, deep: deep, colorSpace: colorSpace)218    }219}220
Files main
Menu

Theme