Repository Public License
1// ORIX Convert — Packages/EngineImage/Tests/EngineImageTests/FeatureTests.swift2// Description: Behaviour of the image engine's operations: lossless round-trips, geometry, colour management,3// bit depth, HDR, metadata, animation, icons, watermark, background removal, encoder settings.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import ConvertCore6import CoreGraphics7import CoreImage8import Foundation9import ImageIO10import Testing11@testable import EngineImage1213@Suite("Lossless round-trips")14struct LosslessTests {15 @Test("PNG → TIFF → PNG gives back the same pixels (8-bit with alpha)")16 func pngTiffPng() async throws {17 let original = Synth.image(120, 80, alpha: true)18 let source = try await makeFile("rt.png") { try Synth.encode("public.png", [original]) }19 let tiff = try await convert(source, from: .png, to: .tiff)20 let back = try await convert(tiff.url, from: .tiff, to: .png)21 #expect(tiff.failedChecks.isEmpty && back.failedChecks.isEmpty)22 #expect(try PixelCompare.compare(original, try back.image()).identical)23 #expect(back.checks.contains { $0.name == "pixels" && $0.passed && $0.detail.contains("SHA-256") })24 }2526 @Test("16-bit PNG keeps 16 bits through PNG and TIFF")27 func sixteenBit() async throws {28 let original = Synth.image(64, 48, bits: 16, alpha: true)29 let source = try await makeFile("deep.png") { try Synth.encode("public.png", [original]) }30 for destination in [FormatID.png, .tiff, .psd] {31 let run = try await convert(source, from: .png, to: destination, ["png.effort": .int(2)])32 let image = try run.image()33 #expect(image.bitsPerComponent == 16)34 if destination != .psd { #expect(try PixelCompare.compare(original, image).identical) }35 }36 }3738 @Test("A Display P3 PNG stays Display P3 and pixel-exact")39 func p3Preserved() async throws {40 let original = Synth.image(64, 48, space: Synth.p3)41 let source = try await makeFile("p3.png") { try Synth.encode("public.png", [original]) }42 let run = try await convert(source, from: .png, to: .png)43 let image = try run.image()44 #expect(image.colorSpace?.name as String? == CGColorSpace.displayP3 as String)45 #expect(try PixelCompare.compare(original, image).identical)46 #expect(!run.codes.contains("gamut-reduced"))47 let jpeg = try await convert(source, from: .png, to: .jpeg)48 #expect(try jpeg.image().colorSpace?.name as String? == CGColorSpace.displayP3 as String)49 #expect(jpeg.output.facts["metadata.icc"]?.contains("P3") == true)50 let webp = try await convert(source, from: .png, to: .webp, ["lossless": .bool(true)])51 #expect(webp.output.facts["webp.chunks"]?.contains("ICCP") == true)52 #expect(try Synth.decode(webp.url).colorSpace?.name as String? == CGColorSpace.displayP3 as String) // ImageIO reads the embedded profile53 #expect(try PixelCompare.compare(original, try Synth.decode(webp.url)).identical)54 }5556 @Test("Lossless WebP and lossless JPEG 2000 are bit-exact; lossy WebP reports a PSNR")57 func losslessModes() async throws {58 let original = Synth.image(100, 60, alpha: true)59 let source = try await makeFile("w.png") { try Synth.encode("public.png", [original]) }60 let webp = try await convert(source, from: .png, to: .webp, ["lossless": .bool(true)])61 #expect(webp.output.facts["verify.pixels"] == "identical" && webp.output.facts["pixels.sha256"] != nil)62 #expect(try PixelCompare.compare(original, try webp.image()).identical)63 #expect(webp.output.facts["verify.decoder"]?.contains("libwebp") == true)64 let lossy = try await convert(source, from: .png, to: .webp, ["quality": .int(60)])65 #expect(lossy.output.facts["psnr.db"] != nil && lossy.output.facts["pixels.sha256"] == nil)66 let opaque = Synth.image(100, 60)67 let opaqueSource = try await makeFile("j.png") { try Synth.encode("public.png", [opaque]) }68 let jp2 = try await convert(opaqueSource, from: .png, to: .jp2, ["lossless": .bool(true)])69 #expect(jp2.output.facts["verify.pixels"] == "identical")70 #expect(try PixelCompare.compare(opaque, try jp2.image()).identical)71 }7273 @Test("Grayscale PNG stays single-channel and exact; gray JPEG is written as grayscale")74 func gray() async throws {75 var bytes = Data(count: 64 * 48)76 for i in 0..<bytes.count { bytes[i] = UInt8((i * 7) % 256) }77 let grayImage = CGImage(width: 64, height: 48, bitsPerComponent: 8, bitsPerPixel: 8, bytesPerRow: 64, space: CGColorSpace(name: CGColorSpace.genericGrayGamma2_2)!,78 bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue), provider: CGDataProvider(data: bytes as CFData)!, decode: nil, shouldInterpolate: false, intent: .defaultIntent)!79 let source = try await makeFile("gray.png") { try Synth.encode("public.png", [grayImage]) }80 let png = try await convert(source, from: .png, to: .png)81 #expect(try png.image().colorSpace?.model == .monochrome)82 #expect(try PixelCompare.compare(grayImage, try png.image()).identical)83 let jpeg = try await convert(source, from: .png, to: .jpeg)84 #expect(jpeg.output.facts["jpeg.subsampling"] == "grayscale")85 let bmp = try await convert(source, from: .png, to: .bmp)86 #expect(bmp.failedChecks.isEmpty)87 }88}8990@Suite("Unusual sources")91struct UnusualSourceTests {92 @Test("A CMYK JPEG is converted to RGB with ColorSync and says so")93 func cmyk() async throws {94 var bytes = Data(count: 64 * 48 * 4)95 for i in 0..<(64 * 48) { bytes[4 * i] = 255; bytes[4 * i + 1] = 0; bytes[4 * i + 2] = 0; bytes[4 * i + 3] = 0 } // 100 % cyan96 let cmyk = CGImage(width: 64, height: 48, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: 256, space: CGColorSpace(name: CGColorSpace.genericCMYK)!,97 bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue), provider: CGDataProvider(data: bytes as CFData)!, decode: nil, shouldInterpolate: false, intent: .defaultIntent)!98 let source = try await makeFile("cmyk.jpg") { try Synth.encode("public.jpeg", [cmyk], properties: [kCGImageDestinationLossyCompressionQuality: 0.95]) }99 let inspection = try await engine.inspect(source, format: .jpeg)100 #expect(inspection.fields.contains { $0.group == "Color" && $0.key == "Model" && $0.value == "CMYK" })101 for destination in [FormatID.png, .webp, .bmp, .jpeg] {102 let run = try await convert(source, from: .jpeg, to: destination)103 #expect(run.failedChecks.isEmpty, "\(destination) \(run.failedChecks)")104 let image = try run.image()105 #expect(image.colorSpace?.model == .rgb)106 let p = try Synth.pixel(image, 30, 20)107 #expect(p[0] < 90 && p[1] > 120 && p[2] > 180, "cyan expected, got \(p)")108 #expect(run.codes.contains("profile-converted"))109 }110 }111112 @Test("An indexed-colour PNG keeps its exact colours")113 func indexed() async throws {114 let palette: [UInt8] = [255, 0, 0, 0, 255, 0, 0, 0, 255, 250, 240, 10]115 let space = CGColorSpace(indexedBaseSpace: Synth.sRGB, last: 3, colorTable: palette)!116 var indices = Data(count: 40 * 30)117 for i in 0..<indices.count { indices[i] = UInt8((i % 40) / 10) }118 let image = CGImage(width: 40, height: 30, bitsPerComponent: 8, bitsPerPixel: 8, bytesPerRow: 40, space: space, bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue),119 provider: CGDataProvider(data: indices as CFData)!, decode: nil, shouldInterpolate: false, intent: .defaultIntent)!120 let source = try await makeFile("indexed.png") { try Synth.encode("public.png", [image]) }121 for destination in [FormatID.png, .tiff, .bmp, .ppm, .gif] {122 let run = try await convert(source, from: .png, to: destination, ["rotate.angle": .double(destination == .tiff ? 180 : 0)])123 #expect(run.failedChecks.isEmpty)124 let output = try run.image()125 let columns = destination == .tiff ? [35, 25, 15, 5] : [5, 15, 25, 35]126 #expect(try columns.map { Array(try Synth.pixel(output, $0, 10).prefix(3)) } == [[255, 0, 0], [0, 255, 0], [0, 0, 255], [250, 240, 10]], "\(destination)")127 }128 }129130 @Test("Camera RAW paths run through the same decoder as DNG and announce Apple's rendering")131 func rawRendering() async throws {132 let dng = try await Fixtures.url(for: .dng)133 let run = try await convert(dng, from: .raw, to: .jpeg)134 #expect(run.codes.contains("raw-default-rendering") && run.failedChecks.isEmpty)135 #expect(try run.image().width == 256)136 // The synthetic scene is reddish on the left and bluish on the right: the rendering must keep that.137 let left = try Synth.pixel(try run.image(), 20, 96), right = try Synth.pixel(try run.image(), 235, 96)138 #expect(left[0] > left[2] && right[2] > right[0], "left \(left) right \(right)")139 #expect(engine.paths.filter { $0.source == .raw }.allSatisfy { $0.status == .experimental && $0.limitations.contains { $0.contains("No manufacturer RAW file") } })140 }141}142143@Suite("Geometry")144struct GeometryTests {145 static func source(_ w: Int = 400, _ h: Int = 300) async throws -> (URL, CGImage) {146 let image = Synth.image(w, h)147 return (try await makeFile("geo.png") { try Synth.encode("public.png", [image]) }, image)148 }149150 @Test("Resize modes give the documented sizes", arguments: [151 (["resize.mode": OptionValue.string("fit"), "resize.width": .int(200), "resize.height": .int(200)], 200, 150),152 (["resize.mode": .string("fit"), "resize.width": .int(100)], 100, 75),153 (["resize.mode": .string("fill"), "resize.width": .int(100), "resize.height": .int(100)], 100, 100),154 (["resize.mode": .string("exact"), "resize.width": .int(50), "resize.height": .int(80)], 50, 80),155 (["resize.mode": .string("percent"), "resize.percent": .double(50)], 200, 150),156 (["resize.mode": .string("long-edge"), "resize.long-edge": .int(80)], 80, 60),157 (["resize.mode": .string("long-edge"), "resize.long-edge": .int(800)], 400, 300),158 (["resize.mode": .string("long-edge"), "resize.long-edge": .int(800), "resize.upscale": .bool(true)], 800, 600),159 ])160 func resizeModes(options: [String: OptionValue], width: Int, height: Int) async throws {161 let (source, original) = try await Self.source()162 let run = try await convert(source, from: .png, to: .png, options)163 let image = try run.image()164 #expect(image.width == width && image.height == height)165 #expect(run.failedChecks.isEmpty)166 #expect(run.codes.contains("upscaled") == (width > 400))167 if width == 400 { #expect(try PixelCompare.compare(original, image).identical) } // no resampling when nothing changes168 }169170 @Test("Lanczos resampling keeps flat colours and works in linear light")171 func resampleQuality() async throws {172 let flat = Synth.solid(200, 100, 0.2, 0.6, 0.9)173 let flatSource = try await makeFile("flat.png") { try Synth.encode("public.png", [flat]) }174 let run = try await convert(flatSource, from: .png, to: .png, ["resize.mode": .string("percent"), "resize.percent": .double(37)])175 let expected = try Synth.pixel(flat, 5, 5)176 for (x, y) in [(0, 0), (36, 18), (73, 36)] { #expect(near(try Synth.pixel(try run.image(), x, y), expected, 1)) }177178 // 1-pixel black/white checkerboard: its light average is 50 % linear, i.e. about 188 in sRGB, not 128.179 let checker = Synth.image(256, 256) { x, y in let v = Double((x + y) % 2); return (v, v, v, 1) }180 let checkerSource = try await makeFile("checker.png") { try Synth.encode("public.png", [checker]) }181 let small = try await convert(checkerSource, from: .png, to: .png, ["resize.mode": .string("percent"), "resize.percent": .double(25)])182 let centre = try Synth.pixel(try small.image(), 32, 32)183 #expect((180...196).contains(centre[0]), "centre value \(centre[0])")184 }185186 @Test("Crop rectangle and centred aspect crop move pixels exactly")187 func crop() async throws {188 let (source, original) = try await Self.source()189 let rect = try await convert(source, from: .png, to: .png, ["crop.mode": .string("rect"), "crop.x": .int(10), "crop.y": .int(20), "crop.width": .int(50), "crop.height": .int(40)])190 let cropped = try rect.image()191 #expect(cropped.width == 50 && cropped.height == 40)192 #expect(try PixelCompare.compare(try #require(original.cropping(to: CGRect(x: 10, y: 20, width: 50, height: 40))), cropped).identical)193 let aspect = try await convert(source, from: .png, to: .png, ["crop.mode": .string("aspect"), "crop.aspect": .string("1:1")])194 let square = try aspect.image()195 #expect(square.width == 300 && square.height == 300)196 #expect(try Synth.pixel(square, 0, 0) == (try Synth.pixel(original, 50, 0)))197 await #expect(throws: ConversionError.self) {198 _ = try await convert(source, from: .png, to: .png, ["crop.mode": .string("rect"), "crop.x": .int(900), "crop.width": .int(10), "crop.height": .int(10)])199 }200 }201202 @Test("Quarter turns and flips are pure pixel permutations")203 func rotateFlip() async throws {204 let (source, original) = try await Self.source(40, 30)205 let w = 40, h = 30206 let r90 = try await convert(source, from: .png, to: .png, ["rotate.angle": .double(90)]).image()207 #expect(r90.width == h && r90.height == w)208 for (x, y) in [(0, 0), (29, 0), (7, 33), (29, 39)] { #expect(try Synth.pixel(r90, x, y) == (try Synth.pixel(original, y, h - 1 - x))) }209 let r180 = try await convert(source, from: .png, to: .png, ["rotate.angle": .double(180)]).image()210 #expect(try Synth.pixel(r180, 3, 4) == (try Synth.pixel(original, w - 4, h - 5)))211 let r270 = try await convert(source, from: .png, to: .png, ["rotate.angle": .double(-90)]).image()212 #expect(r270.width == h && r270.height == w)213 #expect(try Synth.pixel(r270, 5, 9) == (try Synth.pixel(original, w - 1 - 9, 5)))214 let flipH = try await convert(source, from: .png, to: .png, ["flip.horizontal": .bool(true)]).image()215 #expect(try Synth.pixel(flipH, 2, 11) == (try Synth.pixel(original, w - 3, 11)))216 let flipV = try await convert(source, from: .png, to: .png, ["flip.vertical": .bool(true)]).image()217 #expect(try Synth.pixel(flipV, 2, 11) == (try Synth.pixel(original, 2, h - 12)))218 // Four quarter turns come back to the start, exactly.219 var url = source220 for _ in 0..<4 { url = try await convert(url, from: .png, to: .png, ["rotate.angle": .double(90)]).url }221 #expect(try PixelCompare.compare(original, try Synth.decode(url)).identical)222 }223224 @Test("Free rotation enlarges the canvas and leaves transparent corners")225 func freeRotation() async throws {226 let flat = Synth.solid(200, 100, 0.9, 0.3, 0.1)227 let source = try await makeFile("rot.png") { try Synth.encode("public.png", [flat]) }228 let run = try await convert(source, from: .png, to: .png, ["rotate.angle": .double(30)])229 let image = try run.image()230 #expect(image.width == 224 && image.height == 187) // |200·cos30| + |100·sin30|, |200·sin30| + |100·cos30|231 #expect(try Synth.pixel(image, 1, 1)[3] == 0)232 #expect(near(try Synth.pixel(image, 112, 93), try Synth.pixel(flat, 5, 5), 1))233 #expect(run.failedChecks.isEmpty)234 let jpeg = try await convert(source, from: .png, to: .jpeg, ["rotate.angle": .double(30), "background.color": .string("#000000")])235 #expect(jpeg.codes.contains("alpha-flattened"))236 }237238 @Test("EXIF orientation is applied to the pixels and reset, or kept on request")239 func orientation() async throws {240 // Stored 60×40: left half red, right half blue, tagged "rotate 90° clockwise to view" (orientation 6).241 let stored = Synth.image(60, 40) { x, _ in x < 30 ? (1, 0, 0, 1) : (0, 0, 1, 1) }242 let source = try await makeFile("o6.jpg") { try Synth.encode("public.jpeg", [stored], properties: [kCGImagePropertyOrientation: 6, kCGImageDestinationLossyCompressionQuality: 0.95]) }243 let inspection = try await engine.inspect(source, format: .jpeg)244 #expect(inspection.fields.contains { $0.group == "General" && $0.key == "Orientation" && $0.value == "6" })245 let run = try await convert(source, from: .jpeg, to: .png)246 let upright = try run.image()247 #expect(upright.width == 40 && upright.height == 60)248 #expect(near(try Synth.pixel(upright, 20, 5), [254, 0, 0, 255], 8)) // the stored left edge is now the top249 #expect(near(try Synth.pixel(upright, 20, 55), [0, 0, 254, 255], 8))250 #expect((Synth.properties(run.url)["Orientation"] as? Int ?? 1) == 1)251 #expect(run.failedChecks.isEmpty)252 let kept = try await convert(source, from: .jpeg, to: .jpeg, ["orientation.normalize": .bool(false)])253 #expect(try kept.image().width == 60)254 #expect(Synth.properties(kept.url)["Orientation"] as? Int == 6)255 #expect(kept.failedChecks.isEmpty)256 // BMP cannot carry an orientation tag: the pixels are turned whatever the option says.257 let bmp = try await convert(source, from: .jpeg, to: .bmp, ["orientation.normalize": .bool(false)])258 #expect(try bmp.image().width == 40)259 #expect(bmp.failedChecks.isEmpty)260 }261}262263@Suite("Colour, depth and HDR")264struct ColourTests {265 static func solidFile(_ r: Double, _ g: Double, _ b: Double, space: CGColorSpace = Synth.sRGB, bits: Int = 8, a: Double = 1) async throws -> URL {266 let image = Synth.solid(32, 32, r, g, b, a: a, bits: bits, space: space)267 return try await makeFile("solid.png") { try Synth.encode("public.png", [image]) }268 }269270 @Test("ColorSync conversions give the known values")271 func knownValues() async throws {272 let red = try await Self.solidFile(1, 0, 0)273 let p3 = try await convert(red, from: .png, to: .png, ["color.profile": .string("display-p3")])274 #expect(near(try Synth.pixel(try p3.image(), 4, 4), [234, 51, 35, 255], 2))275 #expect(try p3.image().colorSpace?.name as String? == CGColorSpace.displayP3 as String)276 #expect(!p3.codes.contains("gamut-reduced"))277278 let green = try await Self.solidFile(0, 1, 0)279 let adobe = try await convert(green, from: .png, to: .tiff, ["color.profile": .string("adobe-rgb")])280 #expect(near(try Synth.pixel(try adobe.image(), 4, 4), [144, 255, 60, 255], 2))281282 let gray = try await convert(red, from: .png, to: .png, ["color.profile": .string("gray")])283 let grayImage = try gray.image()284 #expect(grayImage.colorSpace?.model == .monochrome)285 #expect(abs(try Synth.pixel(grayImage, 4, 4)[0] - 127) <= 3) // Y = 0.2126 → gamma 2.2 → 0.495286287 let mid = try await Self.solidFile(0.5, 0.5, 0.5)288 let same = try await convert(mid, from: .png, to: .jpeg, ["color.profile": .string("srgb"), "quality": .int(95)])289 #expect(near(try Synth.pixel(try same.image(), 4, 4), [128, 128, 128, 255], 2))290 }291292 @Test("Wide gamut → sRGB warns and clips to the sRGB boundary")293 func gamutWarning() async throws {294 let p3Red = try await Self.solidFile(1, 0, 0, space: Synth.p3)295 let explicit = try await convert(p3Red, from: .png, to: .png, ["color.profile": .string("srgb")])296 #expect(explicit.codes.contains("gamut-reduced"))297 #expect(explicit.warnings.first { $0.code == "gamut-reduced" }?.severity == .dataLoss)298 #expect(near(try Synth.pixel(try explicit.image(), 4, 4), [255, 0, 0, 255], 1))299 // BMP cannot embed a profile: the conversion to sRGB happens by itself, and is announced.300 let bmp = try await convert(p3Red, from: .png, to: .bmp)301 #expect(bmp.codes.contains("gamut-reduced"))302 #expect(near(try Synth.pixel(try bmp.image(), 4, 4), [255, 0, 0, 255], 1))303 // An in-gamut P3 colour keeps its appearance: P3 (234, 51, 35) is sRGB red.304 let inGamut = try await Self.solidFile(234.0 / 255, 51.0 / 255, 35.0 / 255, space: Synth.p3)305 let back = try await convert(inGamut, from: .png, to: .png, ["color.profile": .string("srgb")])306 #expect(near(try Synth.pixel(try back.image(), 4, 4), [255, 0, 0, 255], 3))307 await #expect(throws: ConversionError.self) { _ = try await convert(p3Red, from: .png, to: .bmp, ["color.profile": .string("display-p3")]) }308 }309310 @Test("Bit depth: reduction warns, promotion and 10-bit HEIC work, impossible depths are refused")311 func depth() async throws {312 let deep = Synth.image(64, 48, bits: 16)313 let source = try await makeFile("deep16.png") { try Synth.encode("public.png", [deep]) }314 let jpeg = try await convert(source, from: .png, to: .jpeg)315 #expect(jpeg.codes.contains("bit-depth-reduced"))316 #expect(try jpeg.image().bitsPerComponent == 8)317 let tiff = try await convert(source, from: .png, to: .tiff)318 #expect(!tiff.codes.contains("bit-depth-reduced") && tiff.output.facts["bits"] == "16")319 let heic = try await convert(source, from: .png, to: .heic)320 #expect(try heic.image().bitsPerComponent > 8)321 let forced = try await convert(source, from: .png, to: .tiff, ["color.depth": .string("8")])322 #expect(try forced.image().bitsPerComponent == 8 && forced.codes.contains("bit-depth-reduced"))323324 let shallow = try await ColourTests.solidFile(0.5, 0.25, 1)325 let promoted = try await convert(shallow, from: .png, to: .tiff, ["color.depth": .string("16")])326 let image = try promoted.image()327 #expect(image.bitsPerComponent == 16)328 #expect(near(try Synth.pixel(image, 3, 3), [128, 64, 255, 255], 0))329 let float = try await convert(shallow, from: .png, to: .tiff, ["color.depth": .string("float")])330 #expect(try float.image().bitmapInfo.contains(.floatComponents))331 #expect(abs(try Synth.floatPixel(try float.image(), 3, 3)[0] - 128.0 / 255) < 0.001)332 await #expect(throws: ConversionError.self) { _ = try await convert(shallow, from: .png, to: .jpeg, ["color.depth": .string("16")]) }333 }334335 @Test("HDR → SDR is tone-mapped with a warning, never clipped; HDR → float formats keeps the values")336 func hdr() async throws {337 let exr = try await Fixtures.url(for: .exr) // red ramps from 0 to 4× SDR white along x338 let png = try await convert(exr, from: .exr, to: .png)339 let warning = try #require(png.warnings.first { $0.code == "hdr-tone-mapped" })340 #expect(warning.severity == .dataLoss && warning.message.contains("4.00"))341 let sdr = try png.image()342 let reds = try [24, 48, 72, 95].map { try Synth.pixel(sdr, $0, 0)[0] } // 1×, 2×, 3×, 4× SDR white343 #expect(reds == reds.sorted() && Set(reds).count >= 3, "tone-mapped highlights must stay distinct: \(reds)")344 let inspection = try await engine.inspect(exr, format: .exr)345 #expect(inspection.fields.contains { $0.group == "Color" && $0.key == "HDR" })346 #expect(engine.preflight(ConversionRequest(source: exr, sourceFormat: .exr, destinationFormat: .jpeg), inspection: inspection).contains { $0.code == "hdr-tone-mapped" })347348 for destination in [FormatID.tiff, .exr, .hdr] {349 let run = try await convert(exr, from: .exr, to: destination)350 #expect(!run.codes.contains("hdr-tone-mapped"))351 let peak = try Synth.floatPixel(try run.image(), 95, 0)[0]352 #expect(abs(peak - 4) < 0.05, "\(destination): peak \(peak)")353 #expect(abs(try Synth.floatPixel(try run.image(), 48, 0)[0] - 4 * 48.0 / 95) < 0.03)354 }355 let radiance = try await Fixtures.url(for: .hdr)356 let jpeg = try await convert(radiance, from: .hdr, to: .jpeg)357 #expect(jpeg.codes.contains("hdr-tone-mapped"))358 // An SDR picture written to EXR is stored as linear values: sRGB 128 is 0.2158 linear.359 let mid = try await Self.solidFile(128.0 / 255, 128.0 / 255, 128.0 / 255)360 let linear = try await convert(mid, from: .png, to: .exr)361 #expect(abs(try Synth.floatPixel(try linear.image(), 3, 3)[0] - 0.2158) < 0.003)362 }363364 @Test("A 10-bit PQ HEIC is detected as HDR and tone-mapped for JPEG")365 func pqHEIC() async throws {366 let made: Data? = await offPool {367 guard let pq = CGColorSpace(name: CGColorSpace.itur_2100_PQ) else { return nil }368 let hdr = Synth.image(256, 128, bits: 32, space: Synth.linear) { x, _ in let v = 6 * Double(x) / 255; return (v, v, v, 1) }369 return try? CIContext().heif10Representation(of: CIImage(cgImage: hdr), colorSpace: pq, options: [:])370 }371 guard let made else { print("NOTE: this system could not write a PQ HEIC fixture; PQ test skipped"); return }372 let source = try Fixtures.write(made, name: "pq.heic")373 let inspection = try await engine.inspect(source, format: .heic)374 let run = try await convert(source, from: .heic, to: .jpeg)375 #expect(run.codes.contains("hdr-tone-mapped"), "inspection: \(inspection.fields.filter { $0.group == "Color" })")376 #expect(run.failedChecks.isEmpty)377 let image = try run.image()378 let values = try [40, 120, 250].map { try Synth.pixel(image, $0, 60)[0] }379 #expect(values == values.sorted() && Set(values).count == 3, "\(values)")380 let float = try await convert(source, from: .heic, to: .exr)381 #expect(!float.codes.contains("hdr-tone-mapped"))382 #expect(try Synth.floatPixel(try float.image(), 250, 60)[0] > 1.5) // highlights above SDR white survive383 }384385 @Test("A gain-map HEIC keeps its SDR rendition for SDR targets, with a warning")386 func gainMap() async throws {387 let made: Data? = await offPool {388 let sdr = CIImage(cgImage: Synth.image(256, 128, space: Synth.p3))389 let hdr = CIImage(cgImage: Synth.image(256, 128, bits: 32, space: Synth.linear) { x, y in let v = 3 * Double(x) / 255; return (v, v * 0.8, Double(y) / 127, 1) })390 return try? CIContext().heifRepresentation(of: sdr, format: .RGBA8, colorSpace: Synth.p3, options: [.hdrImage: hdr])391 }392 guard let made, let source = try? Fixtures.write(made, name: "gain.heic"), (try? ImageSourceHandle.open(source).info.hasGainMap) == true else {393 print("NOTE: this system could not write a gain-map HEIC fixture; gain-map test skipped"); return394 }395 let inspection = try await engine.inspect(source, format: .heic)396 #expect(inspection.fields.contains { $0.key == "HDR" && $0.value.contains("gain map") })397 let jpeg = try await convert(source, from: .heic, to: .jpeg)398 #expect(jpeg.codes.contains("hdr-gain-map-dropped"))399 let exr = try await convert(source, from: .heic, to: .exr)400 #expect(!exr.codes.contains("hdr-gain-map-dropped"))401 print("NOTE: gain-map HEIC fixture written and converted; EXR peak red = \(try Synth.floatPixel(try exr.image(), 250, 10)[0])")402 }403}404405@Suite("Alpha, animation, pages and icons")406struct StructureTests {407 @Test("Alpha into an opaque format is flattened over the chosen colour, with a data-loss warning")408 func flatten() async throws {409 // Left third fully transparent, middle third 50 % white, right third opaque blue.410 let image = Synth.image(90, 30, alpha: true) { x, _ in x < 30 ? (0, 1, 0, 0) : (x < 60 ? (1, 1, 1, 128.0 / 255) : (0, 0, 1, 1)) }411 let source = try await makeFile("alpha.png") { try Synth.encode("public.png", [image]) }412 let ppm = try await convert(source, from: .png, to: .ppm, ["background.color": .string("#FF0000")])413 let warning = try #require(ppm.warnings.first { $0.code == "alpha-flattened" })414 #expect(warning.severity == .dataLoss && warning.message.contains("FF0000"))415 let flat = try ppm.image()416 #expect(try Synth.pixel(flat, 10, 10) == [255, 0, 0, 255])417 #expect(near(try Synth.pixel(flat, 45, 10), [255, 128, 128, 255], 1))418 #expect(try Synth.pixel(flat, 80, 10) == [0, 0, 255, 255])419 let jpeg = try await convert(source, from: .png, to: .jpeg) // default background: white420 #expect(jpeg.codes.contains("alpha-flattened"))421 #expect(near(try Synth.pixel(try jpeg.image(), 10, 10), [255, 255, 255, 255], 6))422 #expect(jpeg.output.facts["alpha"] == "no")423 // A fully opaque alpha channel is not a loss: no warning.424 let opaque = Synth.image(40, 30, alpha: true) { _, _ in (0.3, 0.6, 0.9, 1) }425 let opaqueSource = try await makeFile("opaque.png") { try Synth.encode("public.png", [opaque]) }426 let quiet = try await convert(opaqueSource, from: .png, to: .jpeg)427 #expect(!quiet.codes.contains("alpha-flattened"))428 // Preflight says it before converting.429 let inspection = try await engine.inspect(source, format: .png)430 #expect(engine.preflight(ConversionRequest(source: source, sourceFormat: .png, destinationFormat: .jpeg), inspection: inspection).contains { $0.code == "alpha-flattened" })431 }432433 @Test("GIF → APNG → WebP → GIF keeps frames, delays and loop count")434 func animationChain() async throws {435 let gif = try await Fixtures.url(for: .gif)436 let apng = try await convert(gif, from: .gif, to: .apng)437 let webp = try await convert(apng.url, from: .apng, to: .webp)438 let back = try await convert(webp.url, from: .webp, to: .gif)439 for run in [apng, webp, back] {440 #expect(run.failedChecks.isEmpty, "\(run.failedChecks)")441 #expect(run.output.facts["frames"] == "4" && run.output.facts["animation.loop"] == "3")442 #expect(run.checks.contains { $0.name == "animation timing" && $0.passed } && run.checks.contains { $0.name == "loop count" && $0.passed })443 }444 // Independent readers: ImageIO for APNG and GIF, libwebp for WebP.445 let apngInfo = try ImageSourceHandle.open(apng.url).info446 #expect(apngInfo.imageCount == 4 && apngInfo.loopCount == 3)447 #expect(zip(apngInfo.delays, Fixtures.animationDelays).allSatisfy { abs($0 - $1) < 0.011 })448 let decoded = try WebPCodec.decode(try Data(contentsOf: webp.url), maxPixels: 1 << 28)449 #expect(decoded.frames.count == 4 && decoded.info.loopCount == 3 && decoded.timestamps == [100, 300, 450, 750])450 let gifInfo = try ImageSourceHandle.open(back.url).info451 #expect(gifInfo.imageCount == 4 && gifInfo.loopCount == 3)452 #expect(zip(gifInfo.delays, Fixtures.animationDelays).allSatisfy { abs($0 - $1) < 0.011 })453 // GIF frames are stored exactly by APNG (lossless path).454 #expect(try PixelCompare.compare(try Synth.decode(gif, index: 2), try Synth.decode(apng.url, index: 2)).identical)455 let relooped = try await convert(gif, from: .gif, to: .webp, ["animation.loop": .int(7), "lossless": .bool(true)])456 #expect(try WebPCodec.info(try Data(contentsOf: relooped.url)).loopCount == 7)457 #expect(relooped.output.facts["verify.pixels"] != "different")458 }459460 @Test("Animated → still keeps the first frame and warns")461 func firstFrame() async throws {462 let apng = try await Fixtures.url(for: .apng)463 let run = try await convert(apng, from: .apng, to: .png)464 let warning = try #require(run.warnings.first { $0.code == "animation-first-frame" })465 #expect(warning.severity == .dataLoss && warning.message.contains("4 frames"))466 #expect(Synth.frameCount(run.url) == 1)467 #expect(try PixelCompare.compare(try Synth.decode(apng, index: 0), try run.image()).identical)468 let inspection = try await engine.inspect(apng, format: .apng)469 #expect(inspection.isAnimated == true && inspection.frameCount == 4)470 #expect(abs((inspection.durationSeconds ?? 0) - 0.75) < 0.02)471 #expect(engine.preflight(ConversionRequest(source: apng, sourceFormat: .apng, destinationFormat: .jpeg), inspection: inspection).contains { $0.code == "animation-first-frame" })472 }473474 @Test("Multi-page TIFF: all pages to TIFF, one page elsewhere")475 func tiffPages() async throws {476 let pages = (0..<3).map { Synth.image(80, 60, seed: $0) }477 let source = try await makeFile("pages.tiff") { try Synth.encode("public.tiff", pages) }478 let inspection = try await engine.inspect(source, format: .tiff)479 #expect(inspection.pageCount == 3)480 let all = try await convert(source, from: .tiff, to: .tiff, ["tiff.compression": .string("deflate")])481 #expect(Synth.frameCount(all.url) == 3 && all.failedChecks.isEmpty && !all.codes.contains("pages-first-page"))482 for index in 0..<3 { #expect(try PixelCompare.compare(pages[index], try all.image(index)).identical) }483 let first = try await convert(source, from: .tiff, to: .png)484 #expect(first.codes.contains("pages-first-page") && first.failedChecks.isEmpty)485 #expect(try PixelCompare.compare(pages[0], try first.image()).identical)486 let second = try await convert(source, from: .tiff, to: .png, ["page": .int(2)])487 #expect(try PixelCompare.compare(pages[1], try second.image()).identical)488 await #expect(throws: ConversionError.self) { _ = try await convert(source, from: .tiff, to: .png, ["page": .int(9)]) }489 #expect(engine.preflight(ConversionRequest(source: source, sourceFormat: .tiff, destinationFormat: .png), inspection: inspection).contains { $0.code == "pages-first-page" })490 }491492 @Test("Multi-size ICO and ICNS are generated from one image; the largest representation is read back")493 func icons() async throws {494 let wide = Synth.image(300, 200)495 let source = try await makeFile("icon-source.png") { try Synth.encode("public.png", [wide]) }496 let ico = try await convert(source, from: .png, to: .ico)497 #expect(ico.output.facts["icon.sizes"] == "16,24,32,48,64,128,256" && ico.failedChecks.isEmpty)498 #expect(Synth.frameCount(ico.url) == 7)499 #expect(ico.codes.contains("icon-resampled"))500 let handle = try ImageSourceHandle.open(ico.url)501 #expect(handle.info.kind == .representations && handle.info.width == 256 && handle.info.height == 256)502 let largest = try handle.image(at: handle.info.selectedIndex, maxPixels: 1 << 24, checkCancellation: {})503 #expect(try Synth.pixel(largest, 128, 2)[3] == 0) // 3:2 image centred in a square: transparent bands504 #expect(try Synth.pixel(largest, 128, 128)[3] == 255)505506 let big = Synth.image(1024, 1024, alpha: true)507 let bigSource = try await makeFile("icon-1024.png") { try Synth.encode("public.png", [big]) }508 let icns = try await convert(bigSource, from: .png, to: .icns)509 #expect(icns.output.facts["icon.sizes"] == "16,32,64,128,256,512,1024" && icns.failedChecks.isEmpty, "\(icns.failedChecks)")510 #expect(try ImageSourceHandle.open(icns.url).info.width == 1024)511512 let chosen = try await convert(source, from: .png, to: .ico, ["icon.sizes": .string("16,32")])513 #expect(Synth.frameCount(chosen.url) == 2)514 await #expect(throws: ConversionError.self) { _ = try await convert(source, from: .png, to: .ico, ["icon.sizes": .string("17")]) }515516 let fromIcon = try await convert(ico.url, from: .ico, to: .png)517 #expect(try fromIcon.image().width == 256 && fromIcon.codes.contains("icon-largest-representation"))518 // A small source is never silently enlarged to the big sizes.519 let small = try await convert(try await Fixtures.url(for: .png), from: .png, to: .ico)520 #expect(small.output.facts["icon.sizes"] == "16,24,32,48,64")521 }522}523524@Suite("Metadata")525struct MetadataTests {526 @Test("Keep, remove location only, remove all — checked by re-reading the result", arguments: [FormatID.jpeg, .png, .tiff, .heic, .heif, .avif, .webp])527 func policies(destination: FormatID) async throws {528 let source = try await Fixtures.url(for: .jpeg)529 func dictionaries(_ url: URL) throws -> (exif: [String: Any], gps: [String: Any], tiff: [String: Any], iptc: [String: Any]) {530 let p = Synth.properties(url)531 return ((p["{Exif}"] as? [String: Any]) ?? [:], (p["{GPS}"] as? [String: Any]) ?? [:], (p["{TIFF}"] as? [String: Any]) ?? [:], (p["{IPTC}"] as? [String: Any]) ?? [:])532 }533 let kept = try await convert(source, from: .jpeg, to: destination)534 #expect(!kept.codes.contains("metadata-dropped"), "\(kept.warnings)")535 #expect(kept.output.facts["metadata.exif"] != "none" && kept.output.facts["metadata.gps"] != "none")536 let k = try dictionaries(kept.url)537 #expect(k.exif["LensModel"] as? String == "Synthetic 50mm")538 #expect(abs((k.gps["Latitude"] as? Double ?? 0) - 45.4287) < 0.001)539 #expect(k.tiff["Make"] as? String == "ORIX")540541 let noLocation = try await convert(source, from: .jpeg, to: destination, ["metadata": .string("strip-location")])542 let n = try dictionaries(noLocation.url)543 #expect(n.gps.isEmpty && n.iptc["City"] == nil)544 #expect(n.exif["LensModel"] as? String == "Synthetic 50mm")545 #expect(noLocation.output.facts["metadata.location"] == "removed (verified)")546547 let stripped = try await convert(source, from: .jpeg, to: destination, ["metadata": .string("strip")])548 let s = try dictionaries(stripped.url)549 #expect(s.gps.isEmpty && s.iptc.isEmpty && s.exif["LensModel"] == nil && s.exif["UserComment"] == nil && s.tiff["Make"] == nil)550 #expect(stripped.output.facts["metadata.stripped"] == "verified")551 }552553 @Test("Metadata is read from every source format that declares it, including WebP, AVIF and DNG")554 func sources() async throws {555 let jpeg = try await Fixtures.url(for: .jpeg)556 for intermediate in [FormatID.webp, .avif, .heic, .png, .tiff] {557 let first = try await convert(jpeg, from: .jpeg, to: intermediate)558 let back = try await convert(first.url, from: intermediate, to: .jpeg)559 let p = Synth.properties(back.url)560 #expect((p["{Exif}"] as? [String: Any])?["LensModel"] as? String == "Synthetic 50mm", "via \(intermediate)")561 #expect(abs(((p["{GPS}"] as? [String: Any])?["Longitude"] as? Double ?? 0) - 75.7135) < 0.001, "via \(intermediate)")562 #expect(!back.codes.contains("metadata-dropped"), "via \(intermediate)")563 }564 let dng = try await convert(try await Fixtures.url(for: .dng), from: .dng, to: .jpeg)565 #expect((Synth.properties(dng.url)["{TIFF}"] as? [String: Any])?["Model"] as? String == "Synthetic DNG")566 }567568 @Test("Formats that carry no metadata say so")569 func dropped() async throws {570 let source = try await Fixtures.url(for: .jpeg)571 for destination in [FormatID.bmp, .ppm, .gif, .tga] {572 let run = try await convert(source, from: .jpeg, to: destination)573 #expect(run.warnings.contains { $0.code == "metadata-dropped" && $0.severity == .dataLoss }, "\(destination)")574 }575 let inspection = try await engine.inspect(source, format: .jpeg)576 #expect(engine.preflight(ConversionRequest(source: source, sourceFormat: .jpeg, destinationFormat: .bmp), inspection: inspection).contains { $0.code == "metadata-dropped" })577 let quiet = try await convert(source, from: .jpeg, to: .bmp, ["metadata": .string("strip")])578 #expect(!quiet.codes.contains("metadata-dropped"))579 }580581 @Test("Inspection flattens EXIF, GPS, TIFF, IPTC, XMP and colour facts")582 func inspect() async throws {583 let source = try await Fixtures.url(for: .jpeg)584 let inspection = try await engine.inspect(source, format: .jpeg)585 #expect(inspection.pixelWidth == 96 && inspection.pixelHeight == 64 && inspection.hasAlpha == false && inspection.bitDepth == 8)586 #expect(inspection.hasMetadata == true && inspection.isAnimated == false)587 let groups = Set(inspection.fields.map(\.group))588 for group in ["General", "Color", "EXIF", "GPS", "TIFF", "IPTC", "XMP"] { #expect(groups.contains(group), "missing group \(group)") }589 #expect(inspection.fields.contains { $0.group == "EXIF" && $0.key == "LensModel" && $0.value == "Synthetic 50mm" })590 #expect(inspection.fields.contains { $0.group == "GPS" && $0.key == "LatitudeRef" && $0.value == "N" })591 #expect(inspection.fields.contains { $0.group == "TIFF" && $0.key == "Make" && $0.value == "ORIX" })592 #expect(inspection.fields.contains { $0.group == "Color" && $0.key == "ICC profile" })593 #expect(Set(inspection.fields.map(\.id)).count == inspection.fields.count)594 let ico = try await engine.inspect(try await Fixtures.url(for: .ico), format: .ico)595 #expect(ico.pixelWidth == 48 && ico.fields.contains { $0.key == "Icon representations" && $0.value.contains("16×16") })596 let pgm = try await engine.inspect(try await Fixtures.url(for: .pgm), format: .pgm)597 #expect(pgm.bitDepth == 16 && pgm.pixelWidth == 96 && pgm.colorSpace == "Gray")598 let dng = try await engine.inspect(try await Fixtures.url(for: .dng), format: .dng)599 #expect(dng.pixelWidth == 256 && !dng.notes.isEmpty)600 #expect(engine.inspectableFormats.contains(.jxl))601 }602}603604@Suite("Encoders")605struct EncoderTests {606 @Test("Target file size is reached by measuring real encodes", arguments: [FormatID.jpeg, .webp, .heic])607 func targetSize(destination: FormatID) async throws {608 let source = try await makeFile("noisy.png") { try Synth.encode("public.png", [Synth.noisy(800, 600)]) }609 let free = try await convert(source, from: .png, to: destination, ["quality": .int(95)])610 let freeSize = try #require(free.output.facts["bytes"].flatMap(Int.init))611 let target = freeSize / 3612 let run = try await convert(source, from: .png, to: destination, ["target.size-kb": .double(Double(target) / 1000)])613 let size = try #require((try FileManager.default.attributesOfItem(atPath: run.url.path)[.size]) as? Int)614 #expect(size <= target && size > target / 2, "size \(size) for target \(target)")615 #expect(run.output.facts["target.reached"] == "yes" && run.output.facts["quality"] != nil && run.output.facts["psnr.db"] != nil)616 let impossible = try await convert(source, from: .png, to: destination, ["target.size-kb": .double(0.3)])617 #expect(impossible.codes.contains("target-size-not-reached") && impossible.output.facts["target.reached"] == "no")618 let ignored = try await convert(source, from: .png, to: .png, ["target.size-kb": .double(10)])619 #expect(ignored.output.facts["target.reached"] == nil)620 }621622 @Test("PNG optimisation effort shrinks the file and never changes a pixel")623 func pngEffort() async throws {624 // 16-bit container holding 8-bit values, opaque alpha channel: both reductions apply.625 let image = Synth.image(400, 300, bits: 16, alpha: true) { x, y in626 let r = Double((x * 255 / 399)) / 255, g = Double((y * 255 / 299)) / 255, b = Double((x / 8 + y / 8) % 2)627 return (r, g, b, 1)628 }629 let source = try await makeFile("fat.png") { try Synth.encode("public.png", [image]) }630 var sizes: [Int] = []631 for effort in 0...2 {632 let run = try await convert(source, from: .png, to: .png, ["png.effort": .int(effort)])633 #expect(run.failedChecks.isEmpty && run.output.facts["verify.pixels"] == "identical")634 #expect(try PixelCompare.compare(image, try run.image()).identical)635 sizes.append(try #require(run.output.facts["bytes"].flatMap(Int.init)))636 if effort >= 1 { #expect(run.output.facts["png.reductions"]?.contains("alpha") == true && run.output.facts["png.reductions"]?.contains("8-bit") == true) }637 if effort == 0 { #expect(try run.image().bitsPerComponent == 16) }638 }639 #expect(sizes[1] < sizes[0] && sizes[2] <= sizes[1], "\(sizes)")640 let optimized = try await convert(source, from: .png, to: .png, operation: ImageEngine.optimizeOperation)641 #expect(optimized.output.facts["bytes"].flatMap(Int.init) == sizes[2])642 print("NOTE: PNG effort sizes 0/1/2 = \(sizes) bytes (source \((try? Data(contentsOf: source).count) ?? 0))")643 }644645 @Test("JPEG: progressive scan, measured chroma subsampling, quality changes size and PSNR")646 func jpeg() async throws {647 let source = try await makeFile("photo.png") { try Synth.encode("public.png", [Synth.noisy(320, 240)]) }648 func hasMarker(_ url: URL, _ marker: UInt8) throws -> Bool {649 let bytes = [UInt8](try Data(contentsOf: url))650 return zip(bytes, bytes.dropFirst()).contains { $0 == 0xFF && $1 == marker }651 }652 let baseline = try await convert(source, from: .png, to: .jpeg)653 let progressive = try await convert(source, from: .png, to: .jpeg, ["jpeg.progressive": .bool(true)])654 #expect(try hasMarker(progressive.url, 0xC2) && !(try hasMarker(baseline.url, 0xC2)))655 #expect(["4:4:4", "4:2:2", "4:2:0"].contains(baseline.output.facts["jpeg.subsampling"] ?? ""))656 let low = try await convert(source, from: .png, to: .jpeg, ["quality": .int(30)])657 let high = try await convert(source, from: .png, to: .jpeg, ["quality": .int(95)])658 let lowSize = try #require(low.output.facts["bytes"].flatMap(Int.init)), highSize = try #require(high.output.facts["bytes"].flatMap(Int.init))659 let lowPSNR = try #require(low.output.facts["psnr.db"].flatMap(Double.init)), highPSNR = try #require(high.output.facts["psnr.db"].flatMap(Double.init))660 #expect(lowSize < highSize && lowPSNR < highPSNR)661 await #expect(throws: ConversionError.self) { _ = try await convert(source, from: .png, to: .jpeg, ["quality": .int(0)]) }662 }663664 @Test("TIFF compressions and plain Netpbm output decode to the same pixels")665 func containers() async throws {666 let image = Synth.image(96, 64)667 let source = try await makeFile("c.png") { try Synth.encode("public.png", [image]) }668 for compression in ["none", "lzw", "packbits", "deflate"] {669 let run = try await convert(source, from: .png, to: .tiff, ["tiff.compression": .string(compression)])670 #expect(try PixelCompare.compare(image, try run.image()).identical, "\(compression)")671 }672 let plain = try await convert(source, from: .png, to: .ppm, ["pnm.plain": .bool(true)])673 #expect(try Data(contentsOf: plain.url).prefix(2) == Data("P3".utf8))674 #expect(try PixelCompare.compare(image, try plain.image()).identical)675 let bitmap = try await convert(source, from: .png, to: .pbm)676 #expect(bitmap.codes.contains("bilevel-threshold") && bitmap.failedChecks.isEmpty)677 #expect(try Data(contentsOf: bitmap.url).prefix(2) == Data("P4".utf8))678 }679680 @Test("Text and image watermarks land where asked and leave the rest alone")681 func watermark() async throws {682 let base = Synth.solid(400, 300, 0.5, 0.5, 0.5)683 let source = try await makeFile("base.png") { try Synth.encode("public.png", [base]) }684 let text = try await convert(source, from: .png, to: .png, ["watermark.text": .string("ORIX"), "watermark.color": .string("#FF0000"),685 "watermark.opacity": .double(100), "watermark.scale": .double(40)])686 let image = try text.image()687 #expect(image.width == 400 && image.height == 300)688 var redPixels = 0689 for y in stride(from: 200, to: 295, by: 2) { for x in stride(from: 220, to: 395, by: 2) { let p = try Synth.pixel(image, x, y); if p[0] > 200 && p[1] < 60 { redPixels += 1 } } }690 #expect(redPixels > 50, "red watermark pixels found: \(redPixels)")691 for (x, y) in [(5, 5), (100, 50), (390, 10), (20, 290)] { #expect(near(try Synth.pixel(image, x, y), [128, 128, 128, 255], 1)) }692693 let logo = try await makeFile("logo.png") { try Synth.encode("public.png", [Synth.solid(40, 20, 0, 1, 0)]) }694 let stamped = try await convert(source, from: .png, to: .png, ["watermark.image": .string(logo.path), "watermark.position": .string("top-left"),695 "watermark.margin": .double(0), "watermark.opacity": .double(100), "watermark.scale": .double(25)])696 let stampedImage = try stamped.image()697 #expect(near(try Synth.pixel(stampedImage, 50, 25), [0, 255, 0, 255], 2)) // 100×50 logo at the top-left698 #expect(near(try Synth.pixel(stampedImage, 300, 250), [128, 128, 128, 255], 1))699 let half = try await convert(source, from: .png, to: .png, ["watermark.image": .string(logo.path), "watermark.position": .string("center"), "watermark.opacity": .double(50)])700 let blended = try Synth.pixel(try half.image(), 200, 150)701 #expect(blended[1] > 150 && blended[0] < 128 && blended[0] > 40, "\(blended)")702 await #expect(throws: ConversionError.self) { _ = try await convert(source, from: .png, to: .png, ["watermark.image": .string("/nonexistent/logo.png")]) }703 }704705 @Test("Background removal uses the system subject model and outputs alpha, or says why not")706 func backgroundRemoval() async throws {707 // A saturated disc with a shaded edge on a plain backdrop: the kind of subject the model lifts.708 let image = Synth.image(512, 512) { x, y in709 let dx = Double(x - 256), dy = Double(y - 256), d = (dx * dx + dy * dy).squareRoot()710 if d < 150 { let shade = 1 - 0.5 * d / 150; return (0.9 * shade, 0.2 * shade, 0.1 * shade, 1) }711 return (0.75, 0.8, 0.85, 1)712 }713 let source = try await makeFile("subject.png") { try Synth.encode("public.png", [image]) }714 do {715 let run = try await convert(source, from: .png, to: .png, ["background.remove": .bool(true)])716 #expect(run.failedChecks.isEmpty)717 if run.codes.contains("background-removed") {718 let output = try run.image()719 #expect(run.output.facts["alpha"] == "yes")720 #expect(try Synth.pixel(output, 256, 256)[3] > 200 && (try Synth.pixel(output, 5, 5)[3]) < 50)721 print("NOTE: Vision subject lifting available: disc kept, backdrop removed")722 } else {723 #expect(run.codes.contains("background-no-subject"))724 print("NOTE: Vision subject lifting ran but found no subject in the synthetic image")725 }726 } catch ConversionError.engineUnavailable(let reason) {727 print("NOTE: Vision subject lifting unavailable on this system: \(reason)")728 }729 // The option needs a destination with alpha... or flattens what it removed, with a warning.730 if let flat = try? await convert(source, from: .png, to: .jpeg, ["background.remove": .bool(true)]), flat.codes.contains("background-removed") {731 #expect(flat.codes.contains("alpha-flattened"))732 }733 }734}735