SPB Git

Repository Public License

main.swift 10.6 KB 219 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Camera9// File             : Packages/ORIXCameraKit/Sources/orix-bench/main.swift10// Description      : Benchmark of the imaging engines on the host machine.11//                    Prints median wall-clock times as Markdown. usage: swift12//                    run -c release orix-bench (numbers describe the Mac that13//                    ran it, not an iPhone)14// Module           : orix-bench15// 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 CoreGraphics94import CoreImage95import CoreMedia96import CoreVideo97import Foundation98import ORIXImaging99100@MainActor func median(_ runs: Int, _ body: () -> Void) -> Double {101    var times: [Double] = []102    for _ in 0..<runs {103        let start = DispatchTime.now().uptimeNanoseconds104        body()105        times.append(Double(DispatchTime.now().uptimeNanoseconds - start) / 1e6)106    }107    return times.sorted()[times.count / 2]108}109110func memoryMB() -> Double {111    var info = mach_task_basic_info()112    var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size) / 4113    let result = withUnsafeMutablePointer(to: &info) { $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count) } }114    return result == KERN_SUCCESS ? Double(info.resident_size) / 1_048_576 : 0115}116117nonisolated(unsafe) var rows: [(String, String, String)] = []118119// `orix-bench fusion <megapixels> [baseline]`: one bracket fusion alone, so /usr/bin/time -l reports its peak memory.120if CommandLine.arguments.count >= 3, CommandLine.arguments[1] == "fusion", let mp = Double(CommandLine.arguments[2]) {121    let h = Int((mp * 1_000_000 * 3 / 4).squareRoot()), w = h * 4 / 3122    let scene = SyntheticScene(width: w, height: h)!123    let images = [0.25, 1.0, 4.0].map { gain -> CGImage in124        var controls = SyntheticScene.Controls(); controls.exposureGain = gain125        return PixelBuffers.cgImage(from: scene.render(time: 1, controls: controls)!)!126    }127    if CommandLine.arguments.count == 3 { _ = try? ExposureFusion.fuse(images) }128    print("\(w)x\(h) done")129    exit(0)130}131@MainActor func report(_ name: String, _ input: String, _ ms: Double) {132    rows.append((name, input, String(format: "%.2f ms", ms)))133    FileHandle.standardError.write(Data("\(name) [\(input)]: \(String(format: "%.2f", ms)) ms\n".utf8))134}135136let sizes: [(String, Int, Int)] = [("1080p", 1920, 1080), ("4K", 3840, 2160)]137let renderer = MonitorRenderer()138for (label, w, h) in sizes {139    let scene = SyntheticScene(width: w, height: h)!140    let frame = scene.render(time: 1)!141    report("Histogram (RGB + luma, every pixel)", label, median(15) { _ = HistogramProcessor.compute(frame) })142    report("Focus analysis (480 px luma plane)", label, median(15) { _ = FocusAnalyzer.analyze(frame, maxDimension: 480) })143    if let renderer {144        var settings = MonitorSettings()145        settings.peakingEnabled = true; settings.zebra = ZebraSettings(highlightsEnabled: true, highlightThreshold: 90); settings.lutIntensity = 1146        renderer.setLUT(.tide)147        report("Monitor pass, peaking + zebra + LUT (GPU, incl. readback)", label, median(15) { _ = renderer.renderOffscreen(pixelBuffer: frame, settings: settings, width: w, height: h) })148    }149    let accumulator = FrameAccumulator(width: w, height: h, mode: .mean)150    report("Accumulate one frame (long exposure)", label, median(15) { accumulator.add(frame) })151    report("Accumulation preview (float → 8-bit)", label, median(5) { _ = accumulator.result().pixelBuffer() })152    let denoiser = StackDenoiser(reference: frame)!153    report("Night stack: merge one frame", label, median(5) { denoiser.add(frame) })154    report("Night stack: register one frame (Vision)", label, median(5) { _ = ImageAligner.shift(moving: frame, reference: frame) })155}156157// Bracket fusion at still sizes.158for (label, w, h) in [("3 MP ×3", 2016, 1512), ("12 MP ×3", 4032, 3024)] {159    let scene = SyntheticScene(width: w, height: h)!160    var images: [CGImage] = []161    for gain in [0.25, 1.0, 4.0] {162        var controls = SyntheticScene.Controls(); controls.exposureGain = gain163        images.append(PixelBuffers.cgImage(from: scene.render(time: 1, controls: controls)!)!)164    }165    let before = memoryMB()166    var peak = before167    report("Bracket fusion (decode + Mertens pyramid)", label, median(1) {168        _ = try? ExposureFusion.fuse(images)169        peak = max(peak, memoryMB())170    })171    rows.append(("Bracket fusion: resident memory after", label, String(format: "%.0f MB (was %.0f MB)", peak, before)))172}173174// Editing and export at 12 MP.175do {176    let scene = SyntheticScene(width: 4032, height: 3024)!177    let image = PixelBuffers.cgImage(from: scene.render(time: 1)!)!178    let source = CIImage(cgImage: image)179    var recipe = EditRecipe()180    recipe.exposure = 0.3; recipe.contrast = 0.2; recipe.shadows = 0.4; recipe.lookID = ColorLUT.tide.id; recipe.sharpness = 0.4; recipe.vignette = 0.3; recipe.straighten = 2181    report("Edit recipe render, preview 1600 px", "12 MP source", median(5) { _ = EditPipeline.render(recipe: recipe, source: source, maxDimension: 1600) })182    report("Edit recipe render, full size", "12 MP source", median(3) { _ = EditPipeline.render(recipe: recipe, source: source) })183    let directory = FileManager.default.temporaryDirectory.appendingPathComponent("orix-bench-\(UUID().uuidString)")184    for format in ExportImageFormat.allCases {185        var options = ImageExportOptions(); options.format = format186        report("Export \(format.rawValue.uppercased())", "12 MP", median(3) { _ = try? ImageExporter.export(image, options: options, to: directory) })187    }188    try? FileManager.default.removeItem(at: directory)189}190191// Movie writer throughput.192for codec in VideoCodec.allCases {193    let url = FileManager.default.temporaryDirectory.appendingPathComponent("orix-bench-\(UUID().uuidString).mov")194    var configuration = VideoRecorderConfiguration(url: url, width: 1920, height: 1080, codec: codec, frameRate: 30)195    configuration.audio = false196    guard let recorder = try? VideoRecorder(configuration: configuration) else { continue }197    let scene = SyntheticScene(width: 1920, height: 1080)!198    let frames = (0..<8).map { scene.render(time: Double($0) / 30)! }199    let start = DispatchTime.now().uptimeNanoseconds200    for i in 0..<120 {201        while !recorder.isReadyForVideo { usleep(500) }202        recorder.appendVideo(frames[i % 8], time: CMTime(value: CMTimeValue(i), timescale: 30))203    }204    let semaphore = DispatchSemaphore(value: 0)205    nonisolated(unsafe) var size: Int64 = 0206    Task.detached { size = (try? await recorder.finish())?.fileSize ?? 0; semaphore.signal() }207    semaphore.wait()208    let seconds = Double(DispatchTime.now().uptimeNanoseconds - start) / 1e9209    rows.append(("Encode 120 frames \(codec.title)", "1080p", String(format: "%.0f fps, %.1f MB", 120 / seconds, Double(size) / 1_048_576)))210    try? FileManager.default.removeItem(at: url)211}212213var model = [CChar](repeating: 0, count: 128)214var length = model.count215sysctlbyname("machdep.cpu.brand_string", &model, &length, nil, 0)216print("Host: \(String(cString: model)), \(ProcessInfo.processInfo.physicalMemory / 1_073_741_824) GB, \(ProcessInfo.processInfo.operatingSystemVersionString)\n")217print("| Operation | Input | Median |\n|---|---|---|")218for row in rows { print("| \(row.0) | \(row.1) | \(row.2) |") }219
Files main
Menu

Theme