SPB Git

Repository Public License

PixelBuffers.swift 12.1 KB 249 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/Support/PixelBuffers.swift10// Description      : Creation, locking and conversion helpers for 32BGRA pixel11//                    buffers, the single frame format of the pipeline.12// Module           : ORIXImaging13// Repository       : https://git.spboucher.ai/orix-camera14// Project Website  : https://www.orixlab.dev15// Created          : 2026-11-2116// Last Modified    : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : Proprietary, all rights reserved (see license file)83// License File     : LICENSE84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Accelerate92import CoreGraphics93import CoreVideo94import Foundation9596/// A pixel buffer that crosses isolation domains. The pipeline treats frames as immutable once delivered.97public struct Frame: @unchecked Sendable {98    public let pixelBuffer: CVPixelBuffer99    /// Presentation time in seconds (capture clock).100    public let time: Double101    public init(pixelBuffer: CVPixelBuffer, time: Double) {102        self.pixelBuffer = pixelBuffer103        self.time = time104    }105    public var width: Int { CVPixelBufferGetWidth(pixelBuffer) }106    public var height: Int { CVPixelBufferGetHeight(pixelBuffer) }107}108109public enum PixelBuffers {110    /// A Metal-compatible, IOSurface-backed 32BGRA buffer.111    public static func makeBGRA(width: Int, height: Int) -> CVPixelBuffer? {112        let attributes: [CFString: Any] = [113            kCVPixelBufferMetalCompatibilityKey: true,114            kCVPixelBufferIOSurfacePropertiesKey: [:] as CFDictionary,115            kCVPixelBufferCGImageCompatibilityKey: true,116            kCVPixelBufferCGBitmapContextCompatibilityKey: true,117        ]118        var buffer: CVPixelBuffer?119        CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_32BGRA, attributes as CFDictionary, &buffer)120        return buffer121    }122123    public static func isBGRA(_ buffer: CVPixelBuffer) -> Bool {124        CVPixelBufferGetPixelFormatType(buffer) == kCVPixelFormatType_32BGRA125    }126127    /// Runs `body` with the buffer locked. `body` receives base address, bytes per row, width and height.128    @discardableResult129    public static func withLocked<T>(_ buffer: CVPixelBuffer, readOnly: Bool = true, _ body: (UnsafeMutableRawPointer, Int, Int, Int) throws -> T) rethrows -> T? {130        let flags: CVPixelBufferLockFlags = readOnly ? .readOnly : []131        guard CVPixelBufferLockBaseAddress(buffer, flags) == kCVReturnSuccess else { return nil }132        defer { CVPixelBufferUnlockBaseAddress(buffer, flags) }133        guard let base = CVPixelBufferGetBaseAddress(buffer) else { return nil }134        return try body(base, CVPixelBufferGetBytesPerRow(buffer), CVPixelBufferGetWidth(buffer), CVPixelBufferGetHeight(buffer))135    }136137    /// Fills a BGRA buffer by calling `pixel(x, y)` → (r, g, b) in 0…255. Used by tests and by the synthetic scene.138    public static func fill(_ buffer: CVPixelBuffer, _ pixel: (Int, Int) -> (UInt8, UInt8, UInt8)) {139        withLocked(buffer, readOnly: false) { base, rowBytes, width, height in140            for y in 0..<height {141                let row = base.advanced(by: y * rowBytes).assumingMemoryBound(to: UInt8.self)142                for x in 0..<width {143                    let (r, g, b) = pixel(x, y)144                    row[x * 4] = b; row[x * 4 + 1] = g; row[x * 4 + 2] = r; row[x * 4 + 3] = 255145                }146            }147        }148    }149150    /// Reads one pixel as (r, g, b).151    public static func pixel(_ buffer: CVPixelBuffer, x: Int, y: Int) -> (UInt8, UInt8, UInt8)? {152        withLocked(buffer) { base, rowBytes, _, _ in153            let p = base.advanced(by: y * rowBytes + x * 4).assumingMemoryBound(to: UInt8.self)154            return (p[2], p[1], p[0])155        }156    }157158    /// An sRGB CGImage that copies the buffer contents.159    public static func cgImage(from buffer: CVPixelBuffer) -> CGImage? {160        guard isBGRA(buffer) else { return nil }161        return withLocked(buffer) { base, rowBytes, width, height -> CGImage? in162            let data = Data(bytes: base, count: rowBytes * height)163            guard let provider = CGDataProvider(data: data as CFData) else { return nil }164            let info = CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)165            return CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: rowBytes,166                           space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: info, provider: provider,167                           decode: nil, shouldInterpolate: true, intent: .defaultIntent)168        } ?? nil169    }170171    /// Draws a CGImage into a new BGRA buffer (optionally resized).172    public static func make(from image: CGImage, width: Int? = nil, height: Int? = nil) -> CVPixelBuffer? {173        let w = width ?? image.width, h = height ?? image.height174        guard let buffer = makeBGRA(width: w, height: h) else { return nil }175        let ok: Bool? = withLocked(buffer, readOnly: false) { base, rowBytes, _, _ in176            let info = CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue177            guard let context = CGContext(data: base, width: w, height: h, bitsPerComponent: 8, bytesPerRow: rowBytes,178                                          space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: info) else { return false }179            context.interpolationQuality = .high180            context.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))181            return true182        }183        return ok == true ? buffer : nil184    }185186    /// A deep copy (frames from the capture pool must not be retained for long).187    public static func copy(_ buffer: CVPixelBuffer) -> CVPixelBuffer? {188        guard isBGRA(buffer), let out = makeBGRA(width: CVPixelBufferGetWidth(buffer), height: CVPixelBufferGetHeight(buffer)) else { return nil }189        withLocked(buffer) { src, srcRow, _, height in190            withLocked(out, readOnly: false) { dst, dstRow, _, _ in191                let count = min(srcRow, dstRow)192                for y in 0..<height { memcpy(dst.advanced(by: y * dstRow), src.advanced(by: y * srcRow), count) }193            }194        }195        return out196    }197}198199/// An 8-bit luma plane (Rec. 709 weights applied to the gamma-encoded BGRA signal), optionally downscaled.200public struct LumaPlane: Sendable {201    public let width: Int202    public let height: Int203    public var pixels: [UInt8]204205    public init(width: Int, height: Int, pixels: [UInt8]) {206        self.width = width; self.height = height; self.pixels = pixels207    }208209    /// Rec. 709 luma weights scaled to a divisor of 256, in BGRA memory order.210    static let matrix: [Int16] = [18, 183, 55, 0]211212    public init?(pixelBuffer: CVPixelBuffer, maxDimension: Int? = nil) {213        guard PixelBuffers.isBGRA(pixelBuffer) else { return nil }214        let result: LumaPlane?? = PixelBuffers.withLocked(pixelBuffer) { base, rowBytes, width, height -> LumaPlane? in215            var source = vImage_Buffer(data: base, height: vImagePixelCount(height), width: vImagePixelCount(width), rowBytes: rowBytes)216            var full = [UInt8](repeating: 0, count: width * height)217            let error = full.withUnsafeMutableBytes { raw -> vImage_Error in218                var dest = vImage_Buffer(data: raw.baseAddress, height: vImagePixelCount(height), width: vImagePixelCount(width), rowBytes: width)219                return vImageMatrixMultiply_ARGB8888ToPlanar8(&source, &dest, LumaPlane.matrix, 256, nil, 0, vImage_Flags(kvImageNoFlags))220            }221            guard error == kvImageNoError else { return nil }222            guard let maxDimension, max(width, height) > maxDimension else { return LumaPlane(width: width, height: height, pixels: full) }223            let scale = Double(maxDimension) / Double(max(width, height))224            let w = max(1, Int(Double(width) * scale)), h = max(1, Int(Double(height) * scale))225            var small = [UInt8](repeating: 0, count: w * h)226            let scaleError = full.withUnsafeMutableBytes { src -> vImage_Error in227                small.withUnsafeMutableBytes { dst -> vImage_Error in228                    var s = vImage_Buffer(data: src.baseAddress, height: vImagePixelCount(height), width: vImagePixelCount(width), rowBytes: width)229                    var d = vImage_Buffer(data: dst.baseAddress, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: w)230                    return vImageScale_Planar8(&s, &d, nil, vImage_Flags(kvImageNoFlags))231                }232            }233            guard scaleError == kvImageNoError else { return nil }234            return LumaPlane(width: w, height: h, pixels: small)235        }236        guard let plane = result ?? nil else { return nil }237        self = plane238    }239240    public var mean: Double {241        guard !pixels.isEmpty else { return 0 }242        var floats = [Float](repeating: 0, count: pixels.count)243        vDSP_vfltu8(pixels, 1, &floats, 1, vDSP_Length(pixels.count))244        var m: Float = 0245        vDSP_meanv(floats, 1, &m, vDSP_Length(floats.count))246        return Double(m)247    }248}249
Files main
Menu

Theme