SPB Git

Repository Public License

Support.swift 20.2 KB 376 lines swift

1// ORIX Convert — Packages/EngineImage/Tests/EngineImageTests/Support.swift2// Description: Test support: images and fixture files generated in code for every readable format (ImageIO for the3//              formats it writes, hand-written bytes for Netpbm, Radiance and DNG, libwebp for WebP), and a helper4//              that runs convert + validate like the core does.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import ConvertCore7import CoreGraphics8import Foundation9import ImageIO10@testable import EngineImage1112enum TestError: Error { case fixture(String) }1314// MARK: - Synthetic images1516enum Synth {17    static let sRGB = CGColorSpace(name: CGColorSpace.sRGB)!18    static let p3 = CGColorSpace(name: CGColorSpace.displayP3)!19    static let linear = CGColorSpace(name: CGColorSpace.extendedLinearSRGB)!2021    /// Smooth gradients plus a hard-edged block, optional alpha ramp. `value(x, y)` returns R, G, B, A in 0…1.22    static func image(_ w: Int, _ h: Int, bits: Int = 8, alpha: Bool = false, space: CGColorSpace = sRGB, seed: Int = 0,23                      value: ((Int, Int) -> (Double, Double, Double, Double))? = nil) -> CGImage {24        let depth: PixelDepth = bits == 32 ? .float : (bits == 16 ? .sixteen : .eight)25        var data = Data(count: w * h * 4 * bits / 8)26        data.withUnsafeMutableBytes { raw in27            for y in 0..<h {28                for x in 0..<w {29                    var v: (Double, Double, Double, Double)30                    if let value { v = value(x, y) } else {31                        let fx = Double(x) / Double(max(1, w - 1)), fy = Double(y) / Double(max(1, h - 1))32                        v = (fx, fy, 0.5 + 0.5 * sin(Double(x + 2 * y + seed * 11) / 9), alpha ? max(0, 1 - fx * 1.25) : 1)33                        if x >= w / 4, x < w / 2, y >= h / 4, y < h / 2 { v = (Double(seed % 3 == 0 ? 1 : 0), Double(seed % 3 == 1 ? 1 : 0), Double(seed % 3 == 2 ? 1 : 0), alpha ? 1 : 1) }34                    }35                    let c = [v.0, v.1, v.2, alpha ? v.3 : 1]36                    let i = (y * w + x) * 437                    for k in 0..<4 {38                        switch depth {39                        case .eight: raw.storeBytes(of: UInt8((max(0, min(1, c[k])) * 255).rounded()), toByteOffset: i + k, as: UInt8.self)40                        case .sixteen: raw.storeBytes(of: UInt16((max(0, min(1, c[k])) * 65535).rounded()), toByteOffset: (i + k) * 2, as: UInt16.self)41                        case .float: raw.storeBytes(of: Float(c[k]), toByteOffset: (i + k) * 4, as: Float.self)42                        }43                    }44                }45            }46        }47        return try! PixelData(width: w, height: h, depth: depth, hasAlpha: alpha, colorSpace: space, bytes: data).makeCGImage()48    }4950    /// Pseudo-random noise over a gradient: hard to compress, used for size-driven tests.51    static func noisy(_ w: Int, _ h: Int) -> CGImage {52        var state: UInt32 = 1234553        return image(w, h) { x, y in54            state = state &* 1664525 &+ 101390422355            let n = Double(state >> 24) / 25556            return (0.5 * Double(x) / Double(w) + 0.5 * n, 0.5 * Double(y) / Double(h) + 0.25 * n, n, 1)57        }58    }5960    static func solid(_ w: Int, _ h: Int, _ r: Double, _ g: Double, _ b: Double, a: Double = 1, bits: Int = 8, space: CGColorSpace = sRGB) -> CGImage {61        image(w, h, bits: bits, alpha: a < 1, space: space) { _, _ in (r, g, b, a) }62    }6364    static var metadata: [CFString: Any] { [65        kCGImagePropertyExifDictionary: [kCGImagePropertyExifUserComment: "ORIX fixture", kCGImagePropertyExifLensModel: "Synthetic 50mm",66                                         kCGImagePropertyExifDateTimeOriginal: "2026:11:21 10:00:00", kCGImagePropertyExifISOSpeedRatings: [200]],67        kCGImagePropertyGPSDictionary: [kCGImagePropertyGPSLatitude: 45.4287, kCGImagePropertyGPSLatitudeRef: "N",68                                        kCGImagePropertyGPSLongitude: 75.7135, kCGImagePropertyGPSLongitudeRef: "W"],69        kCGImagePropertyTIFFDictionary: [kCGImagePropertyTIFFMake: "ORIX", kCGImagePropertyTIFFModel: "Test Camera", kCGImagePropertyTIFFArtist: "Fixture Author"],70        kCGImagePropertyIPTCDictionary: [kCGImagePropertyIPTCCity: "Gatineau", kCGImagePropertyIPTCKeywords: ["orix", "fixture"]],71    ] }7273    static func encode(_ uti: String, _ images: [CGImage], properties: [CFString: Any] = [:], file: [CFString: Any]? = nil,74                       perFrame: ((Int) -> [CFString: Any])? = nil) throws -> Data {75        let out = NSMutableData()76        guard let destination = CGImageDestinationCreateWithData(out, uti as CFString, images.count, nil) else { throw TestError.fixture("no destination for \(uti)") }77        if let file { CGImageDestinationSetProperties(destination, file as CFDictionary) }78        for (index, image) in images.enumerated() {79            var p = properties80            if let extra = perFrame?(index) { for (k, v) in extra { p[k] = v } }81            CGImageDestinationAddImage(destination, image, p as CFDictionary)82        }83        guard CGImageDestinationFinalize(destination) else { throw TestError.fixture("ImageIO could not write \(uti)") }84        return out as Data85    }8687    static func decode(_ data: Data, index: Int = 0) throws -> CGImage {88        guard let source = CGImageSourceCreateWithData(data as CFData, nil),89              let image = CGImageSourceCreateImageAtIndex(source, index, [kCGImageSourceShouldAllowFloat: true] as CFDictionary) else { throw TestError.fixture("cannot decode") }90        return image91    }9293    static func decode(_ url: URL, index: Int = 0) throws -> CGImage { try decode(try Data(contentsOf: url), index: index) }9495    static func frameCount(_ url: URL) -> Int { CGImageSourceCreateWithURL(url as CFURL, nil).map { CGImageSourceGetCount($0) } ?? 0 }9697    static func properties(_ url: URL, index: Int = 0) -> [String: Any] {98        guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { return [:] }99        return (CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [String: Any]) ?? [:]100    }101102    /// 8-bit R, G, B, A of one pixel (top-left origin), raw sample values.103    static func pixel(_ image: CGImage, _ x: Int, _ y: Int) throws -> [Int] {104        let p = try PixelData(cgImage: image, depth: .eight)105        let o = (y * p.width + x) * 4106        return (0..<4).map { Int(p.bytes[o + $0]) }107    }108109    static func floatPixel(_ image: CGImage, _ x: Int, _ y: Int) throws -> [Float] {110        let p = try PixelData(cgImage: image, depth: .float)111        return p.bytes.withUnsafeBytes { raw in112            let f = raw.bindMemory(to: Float.self)113            let o = (y * p.width + x) * 4114            return (0..<4).map { f[o + $0] }115        }116    }117118    // MARK: Hand-written formats119120    static func ppm(_ w: Int, _ h: Int) -> Data {121        var d = Data("P6\n# fixture\n\(w) \(h)\n255\n".utf8)122        for y in 0..<h { for x in 0..<w { d.append(contentsOf: [UInt8(x * 255 / max(1, w - 1)), UInt8(y * 255 / max(1, h - 1)), UInt8((x + y) % 256)]) } }123        return d124    }125126    static func pgm16(_ w: Int, _ h: Int) -> Data {127        var d = Data("P5 \(w) \(h) 65535\n".utf8)128        for y in 0..<h { for x in 0..<w { let v = (x * 65535 / max(1, w - 1) + y * 257) % 65536; d.append(UInt8(v >> 8)); d.append(UInt8(v & 255)) } }129        return d130    }131132    static func pbm(_ w: Int, _ h: Int) -> Data {133        var d = Data("P4\n\(w) \(h)\n".utf8)134        let rowBytes = (w + 7) / 8135        for y in 0..<h {136            var row = [UInt8](repeating: 0, count: rowBytes)137            for x in 0..<w where (x / 4 + y / 4) % 2 == 0 { row[x / 8] |= UInt8(0x80 >> (x % 8)) }138            d.append(contentsOf: row)139        }140        return d141    }142143    /// Flat (uncompressed) Radiance RGBE with a horizontal ramp from 0 to `peak`.144    static func radiance(_ w: Int, _ h: Int, peak: Float = 4) -> Data {145        var d = Data("#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y \(h) +X \(w)\n".utf8)146        for _ in 0..<h {147            for x in 0..<w {148                let v = peak * Float(x) / Float(max(1, w - 1))149                let c: [Float] = [v, v * 0.5, v * 0.25]150                let top = c.max() ?? 0151                if top < 1e-6 { d.append(contentsOf: [0, 0, 0, 0]); continue }152                var e: Int32 = 0153                let m = frexpf(top, &e)154                let scale = m * 256 / top155                d.append(contentsOf: [UInt8(min(255, c[0] * scale)), UInt8(min(255, c[1] * scale)), UInt8(min(255, c[2] * scale)), UInt8(Int(e) + 128)])156            }157        }158        return d159    }160161    /// Minimal little-endian TIFF writer, enough for a linear-raw DNG.162    private struct TIFF {163        var entries: [(tag: UInt16, type: UInt16, count: UInt32, payload: Data)] = []164        private static func bytes<T: FixedWidthInteger>(_ values: [T]) -> Data {165            var d = Data()166            for v in values { withUnsafeBytes(of: v.littleEndian) { d.append(contentsOf: $0) } }167            return d168        }169        mutating func shorts(_ tag: UInt16, _ v: [UInt16]) { entries.append((tag, 3, UInt32(v.count), TIFF.bytes(v))) }170        mutating func longs(_ tag: UInt16, _ v: [UInt32]) { entries.append((tag, 4, UInt32(v.count), TIFF.bytes(v))) }171        mutating func raw(_ tag: UInt16, _ v: [UInt8]) { entries.append((tag, 1, UInt32(v.count), Data(v))) }172        mutating func ascii(_ tag: UInt16, _ s: String) { let b = Array(s.utf8) + [0]; entries.append((tag, 2, UInt32(b.count), Data(b))) }173        mutating func srationals(_ tag: UInt16, _ v: [Int32]) { entries.append((tag, 10, UInt32(v.count / 2), TIFF.bytes(v))) }174        mutating func rationals(_ tag: UInt16, _ v: [UInt32]) { entries.append((tag, 5, UInt32(v.count / 2), TIFF.bytes(v))) }175        func build(pixels: Data) -> Data {176            var all = entries177            all.append((273, 4, 1, TIFF.bytes([UInt32(8)])))178            all.sort { $0.tag < $1.tag }179            let ifdOffset = 8 + pixels.count + pixels.count % 2180            var out = Data([0x49, 0x49, 42, 0]) + TIFF.bytes([UInt32(ifdOffset)]) + pixels181            if pixels.count % 2 == 1 { out.append(0) }182            let extraBase = ifdOffset + 2 + all.count * 12 + 4183            var ifd = TIFF.bytes([UInt16(all.count)]), extra = Data()184            for e in all {185                ifd += TIFF.bytes([e.tag]) + TIFF.bytes([e.type]) + TIFF.bytes([e.count])186                if e.payload.count <= 4 { ifd += e.payload + Data(count: 4 - e.payload.count) }187                else { ifd += TIFF.bytes([UInt32(extraBase + extra.count)]); extra += e.payload; if extra.count % 2 == 1 { extra.append(0) } }188            }189            return out + ifd + Data(count: 4) + extra190        }191    }192193    /// A valid DNG 1.4 with demosaiced linear data (PhotometricInterpretation = LinearRaw), 16 bits per sample.194    static func linearDNG(_ w: Int, _ h: Int) -> Data {195        var pixels = Data(count: w * h * 6)196        pixels.withUnsafeMutableBytes { raw in197            for y in 0..<h {198                for x in 0..<w {199                    let t = Double(x) / Double(w - 1), u = Double(y) / Double(h - 1)200                    let v = [0.8 * (1 - t) + 0.1, 0.5 * u + 0.2, 0.8 * t + 0.1]201                    for c in 0..<3 { raw.storeBytes(of: UInt16(v[c] * 60000).littleEndian, toByteOffset: ((y * w + x) * 3 + c) * 2, as: UInt16.self) }202                }203            }204        }205        var t = TIFF()206        t.longs(254, [0]); t.longs(256, [UInt32(w)]); t.longs(257, [UInt32(h)])207        t.shorts(258, [16, 16, 16]); t.shorts(259, [1]); t.shorts(262, [34892])208        t.ascii(271, "ORIX"); t.ascii(272, "Synthetic DNG"); t.shorts(274, [1])209        t.shorts(277, [3]); t.longs(278, [UInt32(h)]); t.longs(279, [UInt32(w * h * 6)]); t.shorts(284, [1])210        t.raw(50706, [1, 4, 0, 0]); t.raw(50707, [1, 1, 0, 0]); t.ascii(50708, "ORIX Synthetic DNG")211        t.shorts(50714, [0, 0, 0]); t.shorts(50717, [65535, 65535, 65535])212        t.srationals(50721, [8000, 10000, -2000, 10000, -500, 10000, -3000, 10000, 11000, 10000, 2000, 10000, -500, 10000, 1500, 10000, 6000, 10000])213        t.rationals(50728, [5, 10, 1, 1, 6, 10])214        t.shorts(50778, [21])215        return t.build(pixels: pixels)216    }217}218219// MARK: - Fixture files220221enum Fixtures {222    static let directory: URL = {223        let url = FileManager.default.temporaryDirectory.appendingPathComponent("orix-engine-image-tests-\(ProcessInfo.processInfo.processIdentifier)", isDirectory: true)224        try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)225        return url226    }()227228    static let animationDelays = [0.10, 0.20, 0.15, 0.30]229230    static func animationFrames(_ w: Int = 48, _ h: Int = 32, alpha: Bool = true) -> [CGImage] {231        (0..<4).map { Synth.image(w, h, alpha: alpha, seed: $0 + 1) }232    }233234    /// Bytes of the primary fixture of a source format.235    static func data(for format: FormatID) throws -> Data {236        switch format {237        case .png: return try Synth.encode("public.png", [Synth.image(96, 64, alpha: true)], properties: Synth.metadata)238        case .apng:239            return try Synth.encode("public.png", animationFrames(), file: [kCGImagePropertyPNGDictionary: [kCGImagePropertyAPNGLoopCount: 3]]) {240                [kCGImagePropertyPNGDictionary: [kCGImagePropertyAPNGDelayTime: animationDelays[$0]]]241            }242        case .gif:243            return try Synth.encode("com.compuserve.gif", animationFrames(alpha: false), file: [kCGImagePropertyGIFDictionary: [kCGImagePropertyGIFLoopCount: 3]]) {244                [kCGImagePropertyGIFDictionary: [kCGImagePropertyGIFDelayTime: animationDelays[$0]]]245            }246        case .jpeg:247            var p = Synth.metadata; p[kCGImageDestinationLossyCompressionQuality] = 0.9248            return try Synth.encode("public.jpeg", [Synth.image(96, 64)], properties: p)249        case .heic, .heif: return try Synth.encode("public.heic", [Synth.image(96, 64, alpha: true)], properties: Synth.metadata)250        case .avif: return try Synth.encode("public.avif", [Synth.image(96, 64, alpha: true)], properties: [kCGImageDestinationLossyCompressionQuality: 0.8])251        case .webp:252            let frames = try animationFrames().map { try PixelData(cgImage: $0) }253            return try WebPCodec.encodeAnimation(frames, delays: animationDelays, loopCount: 3, settings: WebPCodec.Settings(quality: 90)) { _ in }254        case .tiff: return try Synth.encode("public.tiff", [Synth.image(96, 64, bits: 16, alpha: true)], properties: Synth.metadata)255        case .bmp: return try Synth.encode("com.microsoft.bmp", [Synth.image(96, 64)])256        case .ico: return try Synth.encode("com.microsoft.ico", [16, 32, 48].map { Synth.image($0, $0, alpha: true, seed: $0) })257        case .icns: return try Synth.encode("com.apple.icns", [16, 32, 128].map { Synth.image($0, $0, alpha: true, seed: $0) })258        case .psd: return try Synth.encode("com.adobe.photoshop-image", [Synth.image(96, 64, bits: 16, alpha: true)])259        case .exr:260            let hdr = Synth.image(96, 64, bits: 32, alpha: true, space: Synth.linear) { x, y in (4 * Double(x) / 95, 2 * Double(y) / 63, 0.25, x < 8 ? 0.5 : 1) }261            return try Synth.encode("com.ilm.openexr-image", [hdr])262        case .hdr: return Synth.radiance(96, 64)263        case .tga: return try Synth.encode("com.truevision.tga-image", [Synth.image(96, 64, alpha: true)])264        case .ppm: return Synth.ppm(96, 64)265        case .pgm: return Synth.pgm16(96, 64)266        case .pbm: return Synth.pbm(96, 64)267        case .jp2: return try Synth.encode("public.jpeg-2000", [Synth.image(96, 64, alpha: true)], properties: [kCGImageDestinationLossyCompressionQuality: 0.9])268        case .dng, .raw: return Synth.linearDNG(256, 192)   // Apple's RAW decoder rejects the same file at 128×96269        default: throw TestError.fixture("no fixture for \(format)")270        }271    }272273    /// Every fixture, generated once on a plain thread: system encoders (AVIF) wait for their own worker threads and274    /// must never block Swift's cooperative pool.275    private static let generated = Task.detached { () -> [FormatID: Result<URL, Error>] in276        await offPool {277            var map: [FormatID: Result<URL, Error>] = [:]278            for spec in ImageFormats.all where ImageFormats.isReadable(spec) && spec.id != .jxl {279                let format = spec.id280                let ext = format == .raw ? "dng" : (FormatCatalog.format(format)?.preferredExtension ?? format.rawValue)281                let url = Fixtures.directory.appendingPathComponent("fixture-\(format.rawValue).\(ext)")282                map[format] = Result { try Fixtures.data(for: format).write(to: url); return url }283            }284            return map285        }286    }287288    static func url(for format: FormatID) async throws -> URL {289        guard let result = await generated.value[format] else { throw TestError.fixture("no fixture for \(format)") }290        return try result.get()291    }292293    static func write(_ data: Data, name: String) throws -> URL {294        let url = directory.appendingPathComponent(UUID().uuidString.prefix(8) + "-" + name)295        try data.write(to: url)296        return url297    }298}299300// MARK: - Running the engine301302final class WarningBox: @unchecked Sendable {303    private let lock = NSLock()304    private var items: [ConversionWarning] = []305    func add(_ w: ConversionWarning) { lock.lock(); items.append(w); lock.unlock() }306    var all: [ConversionWarning] { lock.lock(); defer { lock.unlock() }; return items }307    var codes: Set<String> { Set(all.map(\.code)) }308}309310struct Run {311    let output: ConversionOutput312    let url: URL313    let warnings: [ConversionWarning]314    let checks: [ValidationCheck]315    let inspection: FileInspection316    var codes: Set<String> { Set(warnings.map(\.code)) }317    var failedChecks: [ValidationCheck] { checks.filter { !$0.passed } }318    func image(_ index: Int = 0) throws -> CGImage {319        if url.pathExtension == "webp" { return try WebPCodec.decode(try Data(contentsOf: url), maxPixels: 1 << 30).frames[index] }320        if ["ppm", "pgm", "pbm"].contains(url.pathExtension) { return try PNMCodec.decode(try Data(contentsOf: url), maxPixels: 1 << 30, checkCancellation: {}) }321        return try Synth.decode(url, index: index)322    }323}324325let engine = ImageEngine()326327func workDirectory() throws -> URL {328    let url = Fixtures.directory.appendingPathComponent("work-" + UUID().uuidString, isDirectory: true)329    try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)330    return url331}332333/// Inspect → convert → validate, as the core does it.334func convert(_ source: URL, from: FormatID, to: FormatID, operation: String? = nil, _ options: [String: OptionValue] = [:]) async throws -> Run {335    let request = ConversionRequest(source: source, sourceFormat: from, destinationFormat: to, operation: operation, options: ConversionOptions(options))336    let inspection = try await engine.inspect(source, format: from)337    let box = WarningBox()338    let work = try workDirectory()339    let context = ConversionContext(workDirectory: work, warn: { box.add($0) })340    let output = try await engine.convert(request, context: context)341    let checks = try await engine.validate(output, request: request, source: inspection)342    guard let url = output.files.first else { throw TestError.fixture("no output") }343    return Run(output: output, url: url, warnings: box.all, checks: checks, inspection: inspection)344}345346/// Runs blocking work on a plain thread and suspends (does not block) the caller.347func offPool<T: Sendable>(_ body: @escaping @Sendable () -> T) async -> T {348    await withCheckedContinuation { continuation in349        let thread = Thread { continuation.resume(returning: body()) }350        thread.stackSize = 8 << 20351        thread.start()352    }353}354355func offPoolThrowing<T: Sendable>(_ body: @escaping @Sendable () throws -> T) async throws -> T {356    try await offPool { Result { try body() } }.get()357}358359/// Builds a file from bytes produced off the cooperative pool (ImageIO encoders may block on worker threads).360func makeFile(_ name: String, _ body: @escaping @Sendable () throws -> Data) async throws -> URL {361    try await offPoolThrowing { try Fixtures.write(try body(), name: name) }362}363364func crc32Checksum(_ bytes: [UInt8]) -> UInt32 {365    var crc: UInt32 = 0xFFFF_FFFF366    for byte in bytes {367        crc ^= UInt32(byte)368        for _ in 0..<8 { crc = (crc >> 1) ^ (crc & 1 == 1 ? 0xEDB8_8320 : 0) }369    }370    return ~crc371}372373func near(_ a: [Int], _ b: [Int], _ tolerance: Int) -> Bool {374    zip(a, b).allSatisfy { abs($0 - $1) <= tolerance }375}376
Files main
Menu

Theme