SPB Git

Repository Public License

main.swift 9.5 KB 147 lines swift

1// ORIX Convert — Packages/EngineImage/Sources/EngineImageBench/main.swift2// Description: Throughput benchmark of the image engine on generated 12-megapixel pictures. One scenario per3//              process so that the peak resident size belongs to that scenario alone.4//              Usage: EngineImageBench prepare <dir> [count]   |   EngineImageBench run <dir> <from> <to> [concurrency] [verify|noverify] [key=value …]5//                     EngineImageBench paths   (prints the declared path table as Markdown)6// Author: Simon-Pierre Boucher — contact@spboucher.ai7import ConvertCore8import CoreGraphics9import EngineImage10import Foundation11import ImageIO1213func fail(_ message: String) -> Never {14    FileHandle.standardError.write(Data((message + "\n").utf8))15    exit(2)16}1718/// A photograph-like synthetic picture: large smooth structures, a few hard edges, fine low-amplitude texture.19func picture(width: Int, height: Int, seed: Int) -> CGImage? {20    var data = Data(count: width * height * 4)21    data.withUnsafeMutableBytes { raw in22        let p = raw.bindMemory(to: UInt8.self)23        var state = UInt32(truncatingIfNeeded: 2_654_435_761 &* (seed + 1))24        let phase = Double(seed) * 0.725        for y in 0..<height {26            let fy = Double(y) / Double(height)27            for x in 0..<width {28                let fx = Double(x) / Double(width)29                state = state &* 1_664_525 &+ 1_013_904_22330                let grain = (Double(state >> 24) / 255 - 0.5) * 0.0431                var r = 0.5 + 0.35 * sin(6 * fx + phase) * cos(4 * fy) + grain32                var g = 0.45 + 0.3 * sin(5 * fy + 2 * fx + phase) + grain33                var b = 0.55 + 0.3 * cos(7 * fx - 3 * fy + phase) + grain34                if (x / 400 + y / 400 + seed) % 7 == 0 { r *= 0.6; g *= 0.7; b *= 0.9 }35                let i = (y * width + x) * 436                p[i] = UInt8(max(0, min(255, r * 255))); p[i + 1] = UInt8(max(0, min(255, g * 255))); p[i + 2] = UInt8(max(0, min(255, b * 255))); p[i + 3] = 25537            }38        }39    }40    guard let provider = CGDataProvider(data: data as CFData), let space = CGColorSpace(name: CGColorSpace.sRGB) else { return nil }41    return CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4, space: space,42                   bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue), provider: provider, decode: nil, shouldInterpolate: true, intent: .defaultIntent)43}4445func peakResidentBytes() -> Int {46    var usage = rusage()47    getrusage(RUSAGE_SELF, &usage)48    return Int(usage.ru_maxrss)49}5051func directorySize(_ url: URL, ext: String) -> Int {52    let files = (try? FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: [.fileSizeKey])) ?? []53    return files.filter { $0.pathExtension == ext }.reduce(0) { $0 + ((try? $1.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) }54}5556let arguments = CommandLine.arguments57guard arguments.count >= 3 || (arguments.count == 2 && arguments[1] == "paths") else { fail("usage: EngineImageBench prepare <dir> [count] | run <dir> <from> <to> [concurrency] [verify|noverify] [key=value …]") }58let root = URL(fileURLWithPath: arguments.count > 2 ? arguments[2] : NSTemporaryDirectory(), isDirectory: true)59let engine = ImageEngine()6061switch arguments[1] {62case "prepare":63    let count = arguments.count > 3 ? Int(arguments[3]) ?? 200 : 20064    let sources = root.appendingPathComponent("png", isDirectory: true)65    try FileManager.default.createDirectory(at: sources, withIntermediateDirectories: true)66    let started = Date()67    DispatchQueue.concurrentPerform(iterations: count) { index in68        let url = sources.appendingPathComponent(String(format: "picture-%03d.png", index))69        guard !FileManager.default.fileExists(atPath: url.path), let image = picture(width: 4000, height: 3000, seed: index),70              let destination = CGImageDestinationCreateWithURL(url as CFURL, "public.png" as CFString, 1, nil) else { return }71        CGImageDestinationAddImage(destination, image, nil)72        if !CGImageDestinationFinalize(destination) { FileHandle.standardError.write(Data("could not write \(url.lastPathComponent)\n".utf8)) }73    }74    print(String(format: "prepared %d PNG files of 4000×3000 in %.1f s, %.1f MB in total", count, Date().timeIntervalSince(started), Double(directorySize(sources, ext: "png")) / 1e6))7576case "run":77    guard arguments.count >= 5 else { fail("run needs <dir> <from> <to>") }78    let from = FormatID(arguments[3]), to = FormatID(arguments[4])79    let concurrency = arguments.count > 5 ? max(1, Int(arguments[5]) ?? ProcessInfo.processInfo.activeProcessorCount) : ProcessInfo.processInfo.activeProcessorCount80    let verify = !(arguments.count > 6 && arguments[6] == "noverify")81    var options: [String: OptionValue] = ["verify.measure": .bool(verify)]82    for pair in arguments.dropFirst(7) {83        let parts = pair.split(separator: "=", maxSplits: 1).map(String.init)84        guard parts.count == 2 else { continue }85        if let i = Int(parts[1]) { options[parts[0]] = .int(i) } else if parts[1] == "true" || parts[1] == "false" { options[parts[0]] = .bool(parts[1] == "true") } else { options[parts[0]] = .string(parts[1]) }86    }87    let sourceExtension = FormatCatalog.format(from)?.preferredExtension ?? from.rawValue88    let sourceDirectory = root.appendingPathComponent(from.rawValue, isDirectory: true)89    let files = ((try? FileManager.default.contentsOfDirectory(at: sourceDirectory, includingPropertiesForKeys: nil)) ?? [])90        .filter { $0.pathExtension == sourceExtension }.sorted { $0.lastPathComponent < $1.lastPathComponent }91    guard !files.isEmpty else { fail("no .\(sourceExtension) files in \(sourceDirectory.path); run prepare (and png → \(from.rawValue)) first") }92    let outputDirectory = root.appendingPathComponent(to.rawValue + (options.count > 1 || !verify ? "-run" : ""), isDirectory: true)93    try? FileManager.default.removeItem(at: outputDirectory)94    try FileManager.default.createDirectory(at: outputDirectory, withIntermediateDirectories: true)95    let jobOptions = ConversionOptions(options)9697    let started = Date()98    let results: [(bytes: Int, psnr: Double?, warnings: Int)] = try await withThrowingTaskGroup(of: (Int, Double?, Int).self) { group in99        var iterator = files.makeIterator()100        var collected: [(Int, Double?, Int)] = []101        func add(_ url: URL) {102            group.addTask {103                final class Count: @unchecked Sendable { let lock = NSLock(); var n = 0 }104                let count = Count()105                let request = ConversionRequest(source: url, sourceFormat: from, destinationFormat: to, options: jobOptions)106                let context = ConversionContext(workDirectory: outputDirectory, warn: { _ in count.lock.lock(); count.n += 1; count.lock.unlock() })107                let output = try await engine.convert(request, context: context)108                return (Int(output.facts["bytes"] ?? "") ?? 0, output.facts["psnr.db"].flatMap(Double.init), count.n)109            }110        }111        for _ in 0..<concurrency { if let url = iterator.next() { add(url) } }112        while let item = try await group.next() {113            collected.append(item)114            if let url = iterator.next() { add(url) }115        }116        return collected.map { (bytes: $0.0, psnr: $0.1, warnings: $0.2) }117    }118    let elapsed = Date().timeIntervalSince(started)119    let inputBytes = directorySize(sourceDirectory, ext: sourceExtension)120    let outputBytes = results.reduce(0) { $0 + $1.bytes }121    let psnrs = results.compactMap(\.psnr)122    let psnr = psnrs.isEmpty ? "n/a" : String(format: "%.2f dB mean, %.2f dB min", psnrs.reduce(0, +) / Double(psnrs.count), psnrs.min() ?? 0)123    print(String(format: "%@ → %@  files=%d  concurrency=%d  verify=%@  options=%@", from.rawValue, to.rawValue, files.count, concurrency, verify ? "on" : "off",124                 options.filter { $0.key != "verify.measure" }.map { "\($0.key)=\($0.value)" }.sorted().joined(separator: ",")))125    print(String(format: "  wall %.2f s   %.1f images/s   %.0f MP/s   peak RSS %.0f MB   input %.1f MB   output %.1f MB   PSNR %@   warnings %d",126                 elapsed, Double(files.count) / elapsed, Double(files.count) * 12 / elapsed, Double(peakResidentBytes()) / 1e6, Double(inputBytes) / 1e6,127                 Double(outputBytes) / 1e6, psnr, results.reduce(0) { $0 + $1.warnings }))128    if to == .heic || to == .jpeg, !options.keys.contains(where: { $0 != "verify.measure" }), verify {129        // Keep the results as sources for the next scenario (png → heic prepares heic → jpeg).130        let keep = root.appendingPathComponent(to.rawValue, isDirectory: true)131        if keep != outputDirectory { try? FileManager.default.removeItem(at: keep); try? FileManager.default.moveItem(at: outputDirectory, to: keep) }132    }133134case "paths":135    // Markdown table of every declared path, for docs/compatibility/engines/image.md.136    print("| Source | Destination | Operation | Status | Fidelity | Preserves | Limitations | Test |")137    print("|---|---|---|---|---|---|---|---|")138    for path in engine.paths {139        let preserves = path.preserves.map(\.rawValue).sorted().joined(separator: ", ")140        let test = path.operation == nil ? "MatrixTests.everyPath" : "MatrixTests.operations"141        print("| \(path.source) | \(path.destination) | \(path.operation ?? "—") | \(path.status.rawValue) | \(path.fidelity.rawValue) | \(preserves.isEmpty ? "—" : preserves) | \(path.limitations.joined(separator: " ")) | \(test) |")142    }143144default:145    fail("unknown command \(arguments[1])")146}147
Files main
Menu

Theme