-
Notifications
You must be signed in to change notification settings - Fork 6
/
TestUtilities.swift
227 lines (190 loc) · 6.51 KB
/
TestUtilities.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import Accelerate
import CoreGraphics
import Metal
import MetalKit
import MetalPerformanceShaders
import MPSX
extension MTLCommandQueue {
@discardableResult
func sync<T>(_ body: (MPSCommandBuffer) throws -> T) rethrows -> T {
let commandBuffer = MPSCommandBuffer(from: self)
let result = try autoreleasepool {
try body(commandBuffer)
}
commandBuffer.commit()
commandBuffer.waitUntilCompleted()
return result
}
}
extension CGImage {
func jpeg(compressionQuality: Float = 1.0) -> Data? {
guard
let mutableData = CFDataCreateMutable(kCFAllocatorDefault, 0),
let destination = CGImageDestinationCreateWithData(mutableData, "public.jpeg" as CFString, 1, nil)
else { return nil }
let properties: [CFString: Any] = [
kCGImageDestinationLossyCompressionQuality: compressionQuality as CFNumber,
]
CGImageDestinationAddImage(destination, self, properties as CFDictionary)
guard CGImageDestinationFinalize(destination) else {
return nil
}
return mutableData as Data
}
}
extension MTLTexture {
func cgImage(colorSpace: CGColorSpace? = nil) -> CGImage? {
switch pixelFormat {
case .r8Unorm:
let rowBytes = width
let length = rowBytes * height
let bytes = UnsafeMutableRawPointer.allocate(
byteCount: length,
alignment: MemoryLayout<UInt8>.alignment
)
defer { bytes.deallocate() }
getBytes(
bytes,
bytesPerRow: rowBytes,
from: MTLRegionMake2D(0, 0, width, height),
mipmapLevel: 0
)
guard
let data = CFDataCreate(
nil,
bytes.assumingMemoryBound(to: UInt8.self),
length
),
let dataProvider = CGDataProvider(data: data),
let cgImage = CGImage(
width: width,
height: height,
bitsPerComponent: 8,
bitsPerPixel: 8,
bytesPerRow: rowBytes,
space: colorSpace ?? CGColorSpaceCreateDeviceGray(),
bitmapInfo: .init(rawValue: CGImageAlphaInfo.none.rawValue),
provider: dataProvider,
decode: nil,
shouldInterpolate: true,
intent: .defaultIntent
)
else { return nil }
return cgImage
case .rgba8Unorm,
.rgba8Unorm_srgb:
let rowBytes = width * 4
let length = rowBytes * height
let bytes = UnsafeMutableRawPointer.allocate(
byteCount: length,
alignment: MemoryLayout<UInt8>.alignment
)
defer { bytes.deallocate() }
getBytes(
bytes,
bytesPerRow: rowBytes,
from: MTLRegionMake2D(0, 0, width, height),
mipmapLevel: 0
)
guard
let data = CFDataCreate(
nil,
bytes.assumingMemoryBound(to: UInt8.self),
length
),
let dataProvider = CGDataProvider(data: data),
let cgImage = CGImage(
width: width,
height: height,
bitsPerComponent: 8,
bitsPerPixel: 32,
bytesPerRow: rowBytes,
space: colorSpace ?? CGColorSpace(name: CGColorSpace.displayP3)!,
bitmapInfo: .init(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
provider: dataProvider,
decode: nil,
shouldInterpolate: false,
intent: .defaultIntent
)
else { return nil }
return cgImage
default: return nil
}
}
}
final class GPU {
// MARK: Lifecycle
init(commandQueue: MTLCommandQueue) {
self.commandQueue = commandQueue
textureLoader = .init(device: commandQueue.device)
}
// MARK: Internal
static let `default` = GPU(commandQueue: MTLCreateSystemDefaultDevice()!.makeCommandQueue()!)
let commandQueue: MTLCommandQueue
let textureLoader: MTKTextureLoader
var device: MTLDevice {
commandQueue.device
}
}
func compare(texture: MTLTexture, with reference: MTLTexture, treshold: Float = 1e-3) -> Bool {
let graph = MPSCompiledGraph(
device: GPU.default.device,
options: .init(runtimeTypeInference: true)
) { graph in
let x = graph.imagePlaceholder(
dataType: .float32,
height: reference.height,
width: reference.width,
channels: -1,
name: "X"
)
let y = graph.imagePlaceholder(
dataType: .float32,
height: reference.height,
width: reference.width,
channels: -1,
name: "Y"
)
let z = (x.mean(axes: [3]) - y.mean(axes: [3])).pow(2).mean(axes: [1, 2])
return ["Z": z]
}
let result = GPU.default.commandQueue.sync {
graph([
"X": .texture(texture),
"Y": .texture(reference),
], in: $0).synchronizedNDArray(in: $0)
}.floats
return result[0] < treshold
}
let testResourcesPath = "TestResources"
func data(bundlePath: String) throws -> Data {
try Data(contentsOf: Bundle.module.url(forResource: bundlePath, withExtension: nil)!)
}
func texture(bundlePath: String) async throws -> MTLTexture {
try await GPU.default.textureLoader.newTexture(
URL: .init(
fileURLWithPath: Bundle.module.path(forResource: bundlePath, ofType: nil)!
),
options: [.SRGB: false]
)
}
func data(arg: Int) throws -> Data {
try Data(contentsOf: URL(fileURLWithPath: CommandLine.arguments[arg]))
}
func inputTexture(arg: Int) async throws -> MTLTexture {
try await GPU.default.textureLoader.newTexture(
URL: .init(
fileURLWithPath: CommandLine.arguments[arg]
),
options: [.SRGB: false]
)
}
func save(texture: MTLTexture, arg: Int) throws {
let image = texture.cgImage()
try image?.jpeg(compressionQuality: 0.85)?.write(
to: .init(
fileURLWithPath: CommandLine.arguments[arg]
),
options: .atomic
)
}