Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Camera9// File : Packages/ORIXCameraKit/Sources/ORIXImaging/Monitoring/Histogram.swift10// Description : Real-time histogram engine. Counts every pixel of the11// frame with vImage: red, green, blue and Rec. 709 luma, 25612// bins each, on the gamma-encoded 8-bit preview signal.13// Clipping figures derive from the same counts.14// Module : ORIXImaging15// 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 Accelerate94import CoreVideo95import Foundation9697public struct HistogramData: Sendable, Equatable {98 public static let binCount = 25699 public var red: [UInt32]100 public var green: [UInt32]101 public var blue: [UInt32]102 public var luma: [UInt32]103 public var pixelCount: Int104105 public init(red: [UInt32], green: [UInt32], blue: [UInt32], luma: [UInt32], pixelCount: Int) {106 self.red = red; self.green = green; self.blue = blue; self.luma = luma; self.pixelCount = pixelCount107 }108109 public static let empty = HistogramData(red: .init(repeating: 0, count: 256), green: .init(repeating: 0, count: 256),110 blue: .init(repeating: 0, count: 256), luma: .init(repeating: 0, count: 256), pixelCount: 0)111112 public enum Channel: String, Sendable, CaseIterable { case red, green, blue, luma }113114 public func bins(_ channel: Channel) -> [UInt32] {115 switch channel {116 case .red: red117 case .green: green118 case .blue: blue119 case .luma: luma120 }121 }122123 /// Fraction (0…1) of pixels whose value in `channel` is at or above `level`.124 public func fraction(atOrAbove level: Int, in channel: Channel = .luma) -> Double {125 guard pixelCount > 0 else { return 0 }126 let b = bins(channel)127 let sum = b[max(0, min(255, level))...].reduce(UInt64(0)) { $0 + UInt64($1) }128 return Double(sum) / Double(pixelCount)129 }130131 /// Fraction (0…1) of pixels whose value in `channel` is at or below `level`.132 public func fraction(atOrBelow level: Int, in channel: Channel = .luma) -> Double {133 guard pixelCount > 0 else { return 0 }134 let b = bins(channel)135 let sum = b[...max(0, min(255, level))].reduce(UInt64(0)) { $0 + UInt64($1) }136 return Double(sum) / Double(pixelCount)137 }138139 /// Pixels with at least one channel at the top of the scale are reported per channel; this is the largest of the three.140 public var highlightClipping: Double {141 max(fraction(atOrAbove: 254, in: .red), fraction(atOrAbove: 254, in: .green), fraction(atOrAbove: 254, in: .blue))142 }143144 public var shadowClipping: Double {145 max(fraction(atOrBelow: 1, in: .red), fraction(atOrBelow: 1, in: .green), fraction(atOrBelow: 1, in: .blue))146 }147148 public func mean(_ channel: Channel = .luma) -> Double {149 guard pixelCount > 0 else { return 0 }150 var total: UInt64 = 0151 for (value, count) in bins(channel).enumerated() { total += UInt64(value) * UInt64(count) }152 return Double(total) / Double(pixelCount)153 }154155 /// The level below which `p` (0…1) of the pixels fall.156 public func percentile(_ p: Double, in channel: Channel = .luma) -> Int {157 guard pixelCount > 0 else { return 0 }158 let target = UInt64((Double(pixelCount) * min(max(p, 0), 1)).rounded(.up))159 var running: UInt64 = 0160 for (value, count) in bins(channel).enumerated() {161 running += UInt64(count)162 if running >= target { return value }163 }164 return 255165 }166167 /// Largest bin of the channel, ignoring the two end bins so a clipped spike does not flatten the drawing.168 public func peak(_ channel: Channel) -> UInt32 {169 bins(channel)[1..<255].max() ?? 0170 }171}172173public enum HistogramProcessor {174 /// Exact histogram of a 32BGRA frame. Returns nil for other pixel formats.175 public static func compute(_ pixelBuffer: CVPixelBuffer) -> HistogramData? {176 guard PixelBuffers.isBGRA(pixelBuffer) else { return nil }177 let result: HistogramData?? = PixelBuffers.withLocked(pixelBuffer) { base, rowBytes, width, height -> HistogramData? in178 var source = vImage_Buffer(data: base, height: vImagePixelCount(height), width: vImagePixelCount(width), rowBytes: rowBytes)179 var b = [vImagePixelCount](repeating: 0, count: 256), g = b, r = b, a = b180 let error = b.withUnsafeMutableBufferPointer { bp in181 g.withUnsafeMutableBufferPointer { gp in182 r.withUnsafeMutableBufferPointer { rp in183 a.withUnsafeMutableBufferPointer { ap -> vImage_Error in184 var channels: [UnsafeMutablePointer<vImagePixelCount>?] = [bp.baseAddress, gp.baseAddress, rp.baseAddress, ap.baseAddress]185 return vImageHistogramCalculation_ARGB8888(&source, &channels, vImage_Flags(kvImageNoFlags))186 }187 }188 }189 }190 guard error == kvImageNoError else { return nil }191 // Luma: one matrix multiply into a planar scratch buffer, then a planar histogram.192 var lumaBuffer = vImage_Buffer()193 guard vImageBuffer_Init(&lumaBuffer, vImagePixelCount(height), vImagePixelCount(width), 8, vImage_Flags(kvImageNoFlags)) == kvImageNoError else { return nil }194 defer { free(lumaBuffer.data) }195 guard vImageMatrixMultiply_ARGB8888ToPlanar8(&source, &lumaBuffer, LumaPlane.matrix, 256, nil, 0, vImage_Flags(kvImageNoFlags)) == kvImageNoError else { return nil }196 var l = [vImagePixelCount](repeating: 0, count: 256)197 guard vImageHistogramCalculation_Planar8(&lumaBuffer, &l, vImage_Flags(kvImageNoFlags)) == kvImageNoError else { return nil }198 return HistogramData(red: r.map(UInt32.init), green: g.map(UInt32.init), blue: b.map(UInt32.init), luma: l.map(UInt32.init), pixelCount: width * height)199 }200 return result ?? nil201 }202}203204/// Temporal smoothing of the drawn histogram (the numbers reported for clipping are never smoothed).205public struct HistogramSmoother: Sendable {206 public var factor: Float207 private var state: [[Float]] = []208 public init(factor: Float = 0.45) { self.factor = factor }209210 /// Returns four normalized curves (red, green, blue, luma), each 256 values in 0…1.211 public mutating func push(_ data: HistogramData) -> [[Float]] {212 let peak = Float(max(1, max(data.peak(.red), data.peak(.green), data.peak(.blue), data.peak(.luma))))213 let fresh = HistogramData.Channel.allCases.map { channel in data.bins(channel).map { min(1, Float($0) / peak) } }214 if state.isEmpty { state = fresh } else {215 for c in 0..<4 { for i in 0..<256 { state[c][i] += (fresh[c][i] - state[c][i]) * factor } }216 }217 return state218 }219}220