SPB Git

Repository Public License

MonitorRenderer.swift 20.6 KB 402 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/Monitoring/MonitorRenderer.swift10// Description      : Metal monitor: draws a camera frame with rotation,11//                    mirroring, aspect fit/fill and focus magnification, and12//                    composites the monitoring aids in one fragment pass: focus13//                    peaking (Sobel on luma), zebras, clipping warning, false14//                    colour, monochrome and a display LUT. None of this touches15//                    the recorded pixels.16// Module           : ORIXImaging17// 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 CoreGraphics96import CoreVideo97import Foundation98import Metal99100public enum PeakingColor: String, Sendable, CaseIterable, Codable {101    case red, yellow, green, cyan, magenta, white102    public var rgb: SIMD3<Float> {103        switch self {104        case .red: SIMD3(1.0, 0.16, 0.2)105        case .yellow: SIMD3(1.0, 0.9, 0.1)106        case .green: SIMD3(0.2, 1.0, 0.35)107        case .cyan: SIMD3(0.1, 0.9, 1.0)108        case .magenta: SIMD3(1.0, 0.25, 0.95)109        case .white: SIMD3(1, 1, 1)110        }111    }112}113114public struct MonitorSettings: Sendable, Equatable {115    /// Clockwise rotation applied to the frame for display (0, 90, 180, 270).116    public var rotationDegrees: Double = 0117    public var mirrored = false118    /// Aspect fill (true) or aspect fit (false).119    public var fill = false120    public var peakingEnabled = false121    public var peakingSensitivity: Double = 0.5122    public var peakingColor: PeakingColor = .red123    public var zebra = ZebraSettings(highlightsEnabled: false)124    public var clippingWarning = false125    public var falseColor = false126    public var monochrome = false127    /// 0 disables the LUT set with `setLUT`.128    public var lutIntensity: Double = 0129    /// Focus magnification (1 = none) around `zoomCenter` (normalized, in displayed-image space).130    public var zoom: Double = 1131    public var zoomCenter = CGPoint(x: 0.5, y: 0.5)132    public init() {}133}134135/// False-colour bands (percent of full scale on the encoded luma). Documented in the README.136public enum FalseColorScale {137    public struct Band: Sendable { public let range: ClosedRange<Double>; public let name: String; public let rgb: SIMD3<Float> }138    public static let bands: [Band] = [139        Band(range: 0...2, name: "Crushed", rgb: SIMD3(0.45, 0.1, 0.75)),140        Band(range: 2...8, name: "Deep shadow", rgb: SIMD3(0.1, 0.25, 0.9)),141        Band(range: 40...48, name: "Middle grey", rgb: SIMD3(0.15, 0.75, 0.25)),142        Band(range: 52...58, name: "One stop over", rgb: SIMD3(1.0, 0.55, 0.7)),143        Band(range: 90...97, name: "Near clip", rgb: SIMD3(1.0, 0.9, 0.1)),144        Band(range: 97...100, name: "Clipped", rgb: SIMD3(1.0, 0.1, 0.1)),145    ]146}147148public final class MonitorRenderer: @unchecked Sendable {149    public let device: MTLDevice150    private let queue: MTLCommandQueue151    private let pipeline: MTLRenderPipelineState152    private let sampler: MTLSamplerState153    private var textureCache: CVMetalTextureCache?154    private let lock = NSLock()155    private var lutTexture: MTLTexture?156    private var lutSize: Float = 0157    private let neutralLUT: MTLTexture158159    struct Uniforms {160        var quad: SIMD4<Float>      // scale x, scale y, zoom, unused161        var uvMatrix: SIMD4<Float>  // m00, m01, m10, m11162        var texel: SIMD4<Float>     // 1/w, 1/h, time, pixel scale163        var peaking: SIMD4<Float>   // enabled, threshold, 0, 0164        var peakColor: SIMD4<Float>165        var zebra: SIMD4<Float>     // hi enabled, hi level, lo enabled, lo level166        var flags: SIMD4<Float>     // mono, false colour, clipping, lut mix167        var misc: SIMD4<Float>      // zebra opacity, lut size, zoom centre x, zoom centre y168    }169170    public init?(device: MTLDevice? = MTLCreateSystemDefaultDevice(), pixelFormat: MTLPixelFormat = .bgra8Unorm) {171        guard let device, let queue = device.makeCommandQueue() else { return nil }172        self.device = device173        self.queue = queue174        do {175            let library = try device.makeLibrary(source: MonitorRenderer.shaderSource, options: nil)176            let descriptor = MTLRenderPipelineDescriptor()177            descriptor.vertexFunction = library.makeFunction(name: "orix_vertex")178            descriptor.fragmentFunction = library.makeFunction(name: "orix_fragment")179            descriptor.colorAttachments[0].pixelFormat = pixelFormat180            pipeline = try device.makeRenderPipelineState(descriptor: descriptor)181        } catch {182            return nil183        }184        let samplerDescriptor = MTLSamplerDescriptor()185        samplerDescriptor.minFilter = .linear186        samplerDescriptor.magFilter = .linear187        samplerDescriptor.sAddressMode = .clampToEdge188        samplerDescriptor.tAddressMode = .clampToEdge189        samplerDescriptor.rAddressMode = .clampToEdge190        guard let sampler = device.makeSamplerState(descriptor: samplerDescriptor),191              let neutral = MonitorRenderer.makeLUTTexture(.identity, device: device) else { return nil }192        self.sampler = sampler193        self.neutralLUT = neutral194        CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, device, nil, &textureCache)195    }196197    private static func makeLUTTexture(_ lut: ColorLUT, device: MTLDevice) -> MTLTexture? {198        let descriptor = MTLTextureDescriptor()199        descriptor.textureType = .type3D200        descriptor.pixelFormat = .rgba32Float201        descriptor.width = lut.size; descriptor.height = lut.size; descriptor.depth = lut.size202        descriptor.usage = .shaderRead203        guard let texture = device.makeTexture(descriptor: descriptor) else { return nil }204        let data = lut.rgbaFloatData()205        data.withUnsafeBytes { raw in206            texture.replace(region: MTLRegionMake3D(0, 0, 0, lut.size, lut.size, lut.size), mipmapLevel: 0, slice: 0,207                            withBytes: raw.baseAddress!, bytesPerRow: lut.size * 16, bytesPerImage: lut.size * lut.size * 16)208        }209        return texture210    }211212    /// Sets (or clears) the display LUT.213    public func setLUT(_ lut: ColorLUT?) {214        let texture = lut.flatMap { MonitorRenderer.makeLUTTexture($0, device: device) }215        lock.lock(); lutTexture = texture; lutSize = Float(lut?.size ?? 0); lock.unlock()216    }217218    /// Quad scale for an image of `imageSize` (already rotated) inside `drawableSize`.219    public static func quadScale(imageSize: CGSize, drawableSize: CGSize, fill: Bool) -> (Float, Float) {220        guard imageSize.width > 0, imageSize.height > 0, drawableSize.width > 0, drawableSize.height > 0 else { return (1, 1) }221        let ratio = Float((imageSize.width / imageSize.height) / (drawableSize.width / drawableSize.height))222        if fill { return ratio > 1 ? (ratio, 1) : (1, 1 / ratio) }223        return ratio > 1 ? (1, 1 / ratio) : (ratio, 1)224    }225226    /// The rectangle (in drawable points, origin top-left) the image occupies. Overlays in SwiftUI use the same geometry.227    public static func imageRect(imageSize: CGSize, in bounds: CGSize, fill: Bool) -> CGRect {228        let (sx, sy) = quadScale(imageSize: imageSize, drawableSize: bounds, fill: fill)229        let w = bounds.width * CGFloat(sx), h = bounds.height * CGFloat(sy)230        return CGRect(x: (bounds.width - w) / 2, y: (bounds.height - h) / 2, width: w, height: h)231    }232233    private func makeTexture(_ pixelBuffer: CVPixelBuffer) -> MTLTexture? {234        guard let textureCache, PixelBuffers.isBGRA(pixelBuffer) else { return nil }235        var cvTexture: CVMetalTexture?236        CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache, pixelBuffer, nil, .bgra8Unorm,237                                                  CVPixelBufferGetWidth(pixelBuffer), CVPixelBufferGetHeight(pixelBuffer), 0, &cvTexture)238        return cvTexture.flatMap(CVMetalTextureGetTexture)239    }240241    private func uniforms(for settings: MonitorSettings, source: MTLTexture, drawableSize: CGSize, time: Double, pixelScale: Float) -> Uniforms {242        let quarter = ((Int((settings.rotationDegrees / 90).rounded()) % 4) + 4) % 4243        let rotated = quarter % 2 == 1244        let imageSize = rotated ? CGSize(width: source.height, height: source.width) : CGSize(width: source.width, height: source.height)245        let (sx, sy) = MonitorRenderer.quadScale(imageSize: imageSize, drawableSize: drawableSize, fill: settings.fill)246        let theta = Float(quarter) * .pi / 2247        let c = cos(theta), s = sin(theta)248        let flip: Float = settings.mirrored ? -1 : 1249        // Source uv (centred) = R(θ) · (±u, v): see docs/architecture/camera-engine.md, "Display geometry".250        let matrix = SIMD4<Float>(c * flip, s, -s * flip, c)251        let threshold = FocusAnalyzer.threshold(sensitivity: settings.peakingSensitivity)252        lock.lock(); let hasLUT = lutTexture != nil; let size = lutSize; lock.unlock()253        return Uniforms(254            quad: SIMD4(sx, sy, Float(max(settings.zoom, 1)), 0),255            uvMatrix: matrix,256            texel: SIMD4(1 / Float(source.width), 1 / Float(source.height), Float(time), pixelScale),257            peaking: SIMD4(settings.peakingEnabled ? 1 : 0, threshold, 0, 0),258            peakColor: SIMD4(settings.peakingColor.rgb, 1),259            zebra: SIMD4(settings.zebra.highlightsEnabled ? 1 : 0, Float(Zebra.level(percent: settings.zebra.highlightThreshold)) / 255,260                         settings.zebra.shadowsEnabled ? 1 : 0, Float(Zebra.level(percent: settings.zebra.shadowThreshold)) / 255),261            flags: SIMD4(settings.monochrome ? 1 : 0, settings.falseColor ? 1 : 0, settings.clippingWarning ? 1 : 0,262                         hasLUT ? Float(min(max(settings.lutIntensity, 0), 1)) : 0),263            misc: SIMD4(Float(settings.zebra.opacity), max(size, 2), Float(settings.zoomCenter.x), Float(settings.zoomCenter.y))264        )265    }266267    /// Encodes one draw into `descriptor`. Returns the command buffer (uncommitted) so the caller can present a drawable.268    public func encode(pixelBuffer: CVPixelBuffer, settings: MonitorSettings, time: Double, descriptor: MTLRenderPassDescriptor,269                       drawableSize: CGSize, pixelScale: Float = 1) -> MTLCommandBuffer? {270        guard let source = makeTexture(pixelBuffer), let commandBuffer = queue.makeCommandBuffer(),271              let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: descriptor) else { return nil }272        var u = uniforms(for: settings, source: source, drawableSize: drawableSize, time: time, pixelScale: pixelScale)273        lock.lock(); let lut = lutTexture ?? neutralLUT; lock.unlock()274        encoder.setRenderPipelineState(pipeline)275        encoder.setVertexBytes(&u, length: MemoryLayout<Uniforms>.stride, index: 0)276        encoder.setFragmentBytes(&u, length: MemoryLayout<Uniforms>.stride, index: 0)277        encoder.setFragmentTexture(source, index: 0)278        encoder.setFragmentTexture(lut, index: 1)279        encoder.setFragmentSamplerState(sampler, index: 0)280        encoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)281        encoder.endEncoding()282        return commandBuffer283    }284285    /// Renders to an offscreen texture and returns BGRA bytes (row-major, `width × height × 4`). Used by tests and stills.286    public func renderOffscreen(pixelBuffer: CVPixelBuffer, settings: MonitorSettings, width: Int, height: Int, time: Double = 0) -> [UInt8]? {287        let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm, width: width, height: height, mipmapped: false)288        descriptor.usage = [.renderTarget, .shaderRead]289        descriptor.storageMode = .shared290        guard let target = device.makeTexture(descriptor: descriptor) else { return nil }291        let pass = MTLRenderPassDescriptor()292        pass.colorAttachments[0].texture = target293        pass.colorAttachments[0].loadAction = .clear294        pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)295        pass.colorAttachments[0].storeAction = .store296        guard let commandBuffer = encode(pixelBuffer: pixelBuffer, settings: settings, time: time, descriptor: pass,297                                         drawableSize: CGSize(width: width, height: height)) else { return nil }298        commandBuffer.commit()299        commandBuffer.waitUntilCompleted()300        var bytes = [UInt8](repeating: 0, count: width * height * 4)301        target.getBytes(&bytes, bytesPerRow: width * 4, from: MTLRegionMake2D(0, 0, width, height), mipmapLevel: 0)302        return bytes303    }304305    /// Offscreen render as a CGImage (sRGB).306    public func renderImage(pixelBuffer: CVPixelBuffer, settings: MonitorSettings, width: Int, height: Int, time: Double = 0) -> CGImage? {307        guard let bytes = renderOffscreen(pixelBuffer: pixelBuffer, settings: settings, width: width, height: height, time: time),308              let provider = CGDataProvider(data: Data(bytes) as CFData) else { return nil }309        let info = CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)310        return CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,311                       space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: info, provider: provider, decode: nil,312                       shouldInterpolate: true, intent: .defaultIntent)313    }314315    static let shaderSource = """316    #include <metal_stdlib>317    using namespace metal;318319    struct Uniforms {320        float4 quad; float4 uvMatrix; float4 texel; float4 peaking; float4 peakColor; float4 zebra; float4 flags; float4 misc;321    };322    struct VOut { float4 position [[position]]; float2 uv; };323324    vertex VOut orix_vertex(uint vid [[vertex_id]], constant Uniforms &u [[buffer(0)]]) {325        float2 corners[4] = { float2(-1, -1), float2(1, -1), float2(-1, 1), float2(1, 1) };326        float2 p = corners[vid];327        VOut out;328        out.position = float4(p * u.quad.xy, 0, 1);329        // Screen uv, origin top-left, centred.330        float2 c = float2(p.x, -p.y) * 0.5;331        // Focus magnification around the chosen centre (in displayed-image space).332        float2 centre = u.misc.zw - 0.5;333        c = centre * (1.0 - 1.0 / u.quad.z) + c / u.quad.z;334        out.uv = float2(u.uvMatrix.x * c.x + u.uvMatrix.y * c.y, u.uvMatrix.z * c.x + u.uvMatrix.w * c.y) + 0.5;335        return out;336    }337338    static inline float luma709(float3 c) { return dot(c, float3(0.2126, 0.7152, 0.0722)); }339340    fragment float4 orix_fragment(VOut in [[stage_in]], constant Uniforms &u [[buffer(0)]],341                                  texture2d<float> source [[texture(0)]], texture3d<float> lut [[texture(1)]],342                                  sampler s [[sampler(0)]]) {343        float3 raw = source.sample(s, in.uv).rgb;344        float y = luma709(raw);345        float3 color = raw;346347        if (u.flags.w > 0.0) {348            float n = u.misc.y;349            float3 graded = lut.sample(s, raw * ((n - 1.0) / n) + 0.5 / n).rgb;350            color = mix(color, graded, u.flags.w);351        }352        if (u.flags.x > 0.5) { color = float3(luma709(color)); }353354        if (u.flags.y > 0.5) {355            float p = y * 100.0;356            float3 grey = float3(y);357            if (p <= 2.0) color = float3(0.45, 0.1, 0.75);358            else if (p <= 8.0) color = float3(0.1, 0.25, 0.9);359            else if (p >= 40.0 && p <= 48.0) color = float3(0.15, 0.75, 0.25);360            else if (p >= 52.0 && p <= 58.0) color = float3(1.0, 0.55, 0.7);361            else if (p >= 97.0) color = float3(1.0, 0.1, 0.1);362            else if (p >= 90.0) color = float3(1.0, 0.9, 0.1);363            else color = grey;364        }365366        if (u.flags.z > 0.5) {367            float hi = max(raw.r, max(raw.g, raw.b));368            float lo = min(raw.r, min(raw.g, raw.b));369            if (hi >= 0.995) color = float3(1.0, 0.12, 0.12);370            else if (lo <= 0.005 && hi <= 0.02) color = float3(0.15, 0.3, 1.0);371        }372373        float2 pix = in.position.xy / max(u.texel.w, 1.0);374        if (u.zebra.x > 0.5 && y >= u.zebra.y) {375            float stripe = step(0.5, fract((pix.x + pix.y) / 12.0 + u.texel.z * 0.8));376            color = mix(color, float3(stripe), u.misc.x);377        }378        if (u.zebra.z > 0.5 && y <= u.zebra.w) {379            float stripe = step(0.5, fract((pix.x - pix.y) / 12.0 + u.texel.z * 0.8));380            color = mix(color, mix(float3(0.05, 0.1, 0.5), float3(0.3, 0.55, 1.0), stripe), u.misc.x);381        }382383        if (u.peaking.x > 0.5) {384            float2 d = u.texel.xy;385            float tl = luma709(source.sample(s, in.uv + float2(-d.x, -d.y)).rgb);386            float tc = luma709(source.sample(s, in.uv + float2(0.0, -d.y)).rgb);387            float tr = luma709(source.sample(s, in.uv + float2(d.x, -d.y)).rgb);388            float ml = luma709(source.sample(s, in.uv + float2(-d.x, 0.0)).rgb);389            float mr = luma709(source.sample(s, in.uv + float2(d.x, 0.0)).rgb);390            float bl = luma709(source.sample(s, in.uv + float2(-d.x, d.y)).rgb);391            float bc = luma709(source.sample(s, in.uv + float2(0.0, d.y)).rgb);392            float br = luma709(source.sample(s, in.uv + float2(d.x, d.y)).rgb);393            float gx = (tr + 2.0 * mr + br) - (tl + 2.0 * ml + bl);394            float gy = (bl + 2.0 * bc + br) - (tl + 2.0 * tc + tr);395            float magnitude = (fabs(gx) + fabs(gy)) / 4.0;396            if (magnitude > u.peaking.y) color = u.peakColor.rgb;397        }398        return float4(color, 1.0);399    }400    """401}402
Files main
Menu

Theme