6#include <CoreVideo/CVPixelBuffer.h>
7#include <IOSurface/IOSurfaceRef.h>
8#include <webgpu/webgpu_cpp.h>
12#include <unordered_map>
18 wgpu::SharedTextureMemory memory;
19 wgpu::Texture texture;
20 wgpu::TextureView view;
28IOSurfaceRef makeSurface(
u32 width,
u32 height,
u32 pixelFormat,
u32 bytesPerPixel) {
29 const void* keys[] = {kIOSurfaceWidth, kIOSurfaceHeight, kIOSurfacePixelFormat, kIOSurfaceBytesPerElement};
30 const i64 values[] = {width, height, pixelFormat, bytesPerPixel};
31 CFNumberRef numbers[4];
32 const void* entries[4];
33 for (
unsigned i = 0; i < 4; ++i) {
34 numbers[i] = CFNumberCreate(
nullptr, kCFNumberSInt64Type, &values[i]);
35 entries[i] = numbers[i];
37 CFDictionaryRef properties = CFDictionaryCreate(
nullptr, keys, entries, 4,
38 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
39 IOSurfaceRef surface = IOSurfaceCreate(properties);
40 CFRelease(properties);
41 for (
auto number : numbers) CFRelease(number);
45bool importImage(Endpoint& endpoint, WGPUDevice device, IOSurfaceRef surface,
const WGPUTextureDescriptor& desc) {
46 WGPUSharedTextureMemoryIOSurfaceDescriptor io = WGPU_SHARED_TEXTURE_MEMORY_IO_SURFACE_DESCRIPTOR_INIT;
47 io.ioSurface = surface;
48 io.allowStorageBinding = (desc.usage & WGPUTextureUsage_StorageBinding) != 0;
49 WGPUSharedTextureMemoryDescriptor shared{};
50 shared.nextInChain = &io.chain;
51 endpoint.memory = wgpu::SharedTextureMemory::Acquire(wgpuDeviceImportSharedTextureMemory(device, &shared));
52 WGPUSharedTextureMemoryProperties properties{};
53 if (!endpoint.memory || wgpuSharedTextureMemoryGetProperties(endpoint.memory.Get(), &properties) != WGPUStatus_Success ||
54 properties.format != desc.format || (properties.usage & desc.usage) != desc.usage)
return false;
55 endpoint.texture = wgpu::Texture::Acquire(wgpuSharedTextureMemoryCreateTexture(endpoint.memory.Get(), &desc));
56 if (!endpoint.texture)
return false;
57 endpoint.view = wgpu::TextureView::Acquire(wgpuTextureCreateView(endpoint.texture.Get(),
nullptr));
58 return !!endpoint.view;
61void touch(WGPUDevice device, WGPUQueue queue, WGPUTexture image, WGPUBuffer scratch) {
62 auto encoder = wgpu::CommandEncoder::Acquire(wgpuDeviceCreateCommandEncoder(device,
nullptr));
63 WGPUTexelCopyTextureInfo src{};
65 WGPUTexelCopyBufferInfo dst{};
67 dst.layout.bytesPerRow = 256;
68 dst.layout.rowsPerImage = 1;
69 const WGPUExtent3D pixel{1, 1, 1};
70 wgpuCommandEncoderCopyTextureToBuffer(encoder.Get(), &src, &dst, &pixel);
71 auto commands = wgpu::CommandBuffer::Acquire(wgpuCommandEncoderFinish(encoder.Get(),
nullptr));
72 WGPUCommandBuffer raw = commands.Get();
73 wgpuQueueSubmit(queue, 1, &raw);
77 u32 id, offset, words, width;
79 WGPUBuffer graphics, compute;
82 void copy(WGPUCommandEncoder encoder,
bool graphicsSide,
bool toImage)
const {
83 WGPUTexelCopyBufferInfo buffer{};
84 buffer.buffer = graphicsSide ? graphics : compute;
85 buffer.layout.offset = offset;
86 buffer.layout.bytesPerRow = (width * 4 + 255u) & ~255u;
87 WGPUTexelCopyTextureInfo texture{};
88 texture.texture = (graphicsSide ? image->graphics : image->compute).texture.Get();
89 auto rows = [&](
u32 w,
u32 h) {
90 const WGPUExtent3D extent{w, h, 1};
91 buffer.layout.rowsPerImage = h;
92 if (toImage) wgpuCommandEncoderCopyBufferToTexture(encoder, &buffer, &texture, &extent);
93 else wgpuCommandEncoderCopyTextureToBuffer(encoder, &texture, &buffer, &extent);
95 const u32 full = words / width;
97 if (
const u32 tail = words % width) {
98 texture.origin.y = full;
99 buffer.layout.offset +=
static_cast<u64>(full) * width * 4;
105void copyBuffers(
const std::vector<BufferRange>& ranges, WGPUDevice device, WGPUQueue queue,
106 bool graphicsSide,
bool toImage,
bool outputs) {
107 if (ranges.empty() || (outputs && std::none_of(ranges.begin(), ranges.end(), [](
auto& r) { return r.writable; })))
return;
108 auto encoder = wgpu::CommandEncoder::Acquire(wgpuDeviceCreateCommandEncoder(device,
nullptr));
109 for (
const auto& range : ranges)
if (!outputs || range.writable) range.copy(encoder.Get(), graphicsSide, toImage);
110 auto commands = wgpu::CommandBuffer::Acquire(wgpuCommandEncoderFinish(encoder.Get(),
nullptr));
111 WGPUCommandBuffer raw = commands.Get();
112 wgpuQueueSubmit(queue, 1, &raw);
115enum class Transfer { Success, Restored,
Lost };
117Transfer transfer(Endpoint& from, Endpoint& to, WGPUDevice device) {
118 WGPUSharedTextureMemoryEndAccessState end{};
119 if (wgpuSharedTextureMemoryEndAccess(from.memory.Get(), from.texture.Get(), &end) != WGPUStatus_Success)
120 return Transfer::Lost;
122 std::vector<wgpu::SharedFence> imported;
123 std::vector<WGPUSharedFence> handles;
124 for (
size_t i = 0; i < end.fenceCount; ++i) {
125 WGPUSharedFenceMTLSharedEventExportInfo
event = WGPU_SHARED_FENCE_MTL_SHARED_EVENT_EXPORT_INFO_INIT;
126 WGPUSharedFenceExportInfo info{};
127 info.nextInChain = &
event.chain;
128 wgpuSharedFenceExportInfo(end.fences[i], &info);
129 if (!event.sharedEvent)
break;
130 WGPUSharedFenceMTLSharedEventDescriptor metal = WGPU_SHARED_FENCE_MTL_SHARED_EVENT_DESCRIPTOR_INIT;
131 metal.sharedEvent =
event.sharedEvent;
132 WGPUSharedFenceDescriptor fd{};
133 fd.nextInChain = &metal.chain;
134 auto fence = wgpu::SharedFence::Acquire(wgpuDeviceImportSharedFence(device, &fd));
136 handles.push_back(fence.Get());
137 imported.push_back(std::move(fence));
140 WGPUSharedTextureMemoryBeginAccessDescriptor begin{};
141 begin.initialized = end.initialized;
142 begin.fenceCount = end.fenceCount;
143 begin.signaledValueCount = end.signaledValueCount;
144 begin.signaledValues = end.signaledValues;
145 begin.fences = handles.data();
146 Transfer result = Transfer::Success;
147 if (handles.size() != end.fenceCount ||
148 wgpuSharedTextureMemoryBeginAccess(to.memory.Get(), to.texture.Get(), &begin) != WGPUStatus_Success) {
149 begin.fences = end.fences;
150 result = wgpuSharedTextureMemoryBeginAccess(from.memory.Get(), from.texture.Get(), &begin) == WGPUStatus_Success
151 ? Transfer::Restored : Transfer::Lost;
153 wgpuSharedTextureMemoryEndAccessStateFreeMembers(end);
166 std::unordered_map<WGPUTexture, SharedImage>
images;
174MetalComputeQueue::MetalComputeQueue(std::unique_ptr<State> state) : state_(
std::move(state)) {}
179 constexpr std::array features{WGPUFeatureName_SharedTextureMemoryIOSurface, WGPUFeatureName_SharedFenceMTLSharedEvent};
180 for (
auto feature : features)
if (!wgpuDeviceHasFeature(graphics.device_, feature))
return {};
181 WGPUDeviceDescriptor desc{};
182 desc.label = {
"Estella async compute", WGPU_STRLEN};
183 desc.requiredFeatures = features.data();
184 desc.requiredFeatureCount = features.size();
185 std::promise<WGPUDevice> request;
186 auto result = request.get_future();
187 WGPURequestDeviceCallbackInfo cb{};
188 cb.mode = WGPUCallbackMode_AllowSpontaneous;
189 cb.userdata1 = &request;
190 cb.callback = [](WGPURequestDeviceStatus status, WGPUDevice device, WGPUStringView,
void* result,
void*) {
191 static_cast<std::promise<WGPUDevice>*
>(result)->set_value(status == WGPURequestDeviceStatus_Success ? device :
nullptr);
193 wgpuAdapterRequestDevice(graphics.adapter_, &desc, cb);
194 WGPUDevice raw = result.get();
196 auto state = std::make_unique<State>(graphics, wgpu::Device::Acquire(raw));
197 WGPUBufferDescriptor bd{};
199 bd.usage = WGPUBufferUsage_CopyDst;
200 state->waitBuffer = wgpu::Buffer::Acquire(wgpuDeviceCreateBuffer(graphics.device_, &bd));
201 if (!state->waitBuffer)
return {};
202 state->workerScratch = wgpu::Buffer::Acquire(wgpuDeviceCreateBuffer(raw, &bd));
203 if (!state->workerScratch)
return {};
204 return std::unique_ptr<MetalComputeQueue>(
new MetalComputeQueue(std::move(state)));
209WGPUTexture MetalComputeQueue::makeTexture(
const WGPUTextureDescriptor& desc) {
210 if (!
available() || desc.dimension != WGPUTextureDimension_2D || desc.size.depthOrArrayLayers != 1 ||
211 desc.mipLevelCount != 1 || desc.sampleCount != 1)
return nullptr;
213 switch (desc.format) {
214 case WGPUTextureFormat_RGBA8Unorm: format = kCVPixelFormatType_32RGBA; bytes = 4;
break;
215 case WGPUTextureFormat_RGBA16Float: format = kCVPixelFormatType_64RGBAHalf; bytes = 8;
break;
216 default:
return nullptr;
218 IOSurfaceRef surface = makeSurface(desc.size.width, desc.size.height, format, bytes);
219 if (!surface)
return nullptr;
221 bool ok = importImage(image.graphics, state_->graphics.device_, surface, desc) &&
222 importImage(image.compute, state_->device.Get(), surface, desc);
224 WGPUSharedTextureMemoryBeginAccessDescriptor begin{};
225 if (!ok || wgpuSharedTextureMemoryBeginAccess(image.graphics.memory.Get(), image.graphics.texture.Get(), &begin)
226 != WGPUStatus_Success)
return nullptr;
227 WGPUTexture texture = image.graphics.texture.Get();
228 state_->images.emplace(texture, std::move(image));
229 wgpuTextureAddRef(texture);
233bool MetalComputeQueue::shareTexture(
u32 id) {
235 auto& rec = s.graphics.textures_.at(
id);
236 if (s.images.contains(rec.texture))
return true;
237 const auto* record = s.graphics.resourceRecords().textures.find(
id);
238 if (!record || (!record->desc.asyncShareable && !rec.storage) || rec.samples != 1 ||
239 rec.mipLevels != 1 || rec.layers != 1 || rec.volume)
return false;
240 WGPUTextureDescriptor td{};
241 td.dimension = WGPUTextureDimension_2D;
242 td.format = rec.format;
243 td.size = {rec.width, rec.height, 1};
244 td.sampleCount = td.mipLevelCount = 1;
245 td.usage = wgpuTextureGetUsage(rec.texture);
246 auto texture = wgpu::Texture::Acquire(makeTexture(td));
247 if (!texture)
return false;
250 auto encoder = wgpu::CommandEncoder::Acquire(wgpuDeviceCreateCommandEncoder(s.graphics.device_,
nullptr));
251 WGPUTexelCopyTextureInfo src{}, dst{};
252 src.texture = rec.texture;
253 dst.texture = texture.Get();
254 wgpuCommandEncoderCopyTextureToTexture(encoder.Get(), &src, &dst, &td.size);
255 auto command = wgpu::CommandBuffer::Acquire(wgpuCommandEncoderFinish(encoder.Get(),
nullptr));
256 WGPUCommandBuffer raw = command.Get();
257 wgpuQueueSubmit(s.graphics.queue_, 1, &raw);
258 auto replacement = rec;
259 replacement.texture = texture.MoveToCHandle();
260 replacement.view = replacement.sampleView = s.images.at(replacement.texture).graphics.view.Get();
261 wgpuTextureViewAddRef(replacement.view);
262 s.graphics.releaseTexture(rec);
267WGPUTexture MetalComputeQueue::bufferSurface(
u32 slot,
u32 width,
u32 height) {
269 if (s.bufferSurfaces.size() <= slot) s.bufferSurfaces.resize(slot + 1);
270 auto& texture = s.bufferSurfaces[slot];
271 if (texture && wgpuTextureGetWidth(texture.Get()) == width && wgpuTextureGetHeight(texture.Get()) == height)
272 return texture.Get();
273 if (texture) s.images.erase(texture.Get());
274 WGPUTextureDescriptor td{};
275 td.dimension = WGPUTextureDimension_2D;
276 td.size = {width, height, 1};
277 td.sampleCount = td.mipLevelCount = 1;
278 td.format = WGPUTextureFormat_RGBA8Unorm;
279 td.usage = WGPUTextureUsage_CopySrc | WGPUTextureUsage_CopyDst;
280 texture = wgpu::Texture::Acquire(makeTexture(td));
281 return texture.Get();
286 auto& worker = s.worker;
287 if (!
available() || s.graphics.inPass() || s.graphics.armed_pass_tag_ || (s.graphics.span_open_ && !s.graphics.parallel_span_) ||
288 count > WebGPUDevice::kMaxComputeBindings || std::max({x, y, z}) > WebGPUDevice::kMaxWorkgroupsPerDimension)
290 if (!worker.computes_.contains(program)) {
291 const auto* p = s.graphics.resourceRecords().computes.find(program);
292 if (!p || !worker.backendCreateCompute(program, {GfxShaderLanguage::WGSL, p->source.c_str(), p->entry.c_str()},
nullptr))
295 std::vector<std::pair<u32, SharedImage*>> textures;
296 std::vector<BufferRange> ranges;
298 for (
u32 i = 0; i < count; ++i) {
299 const auto& b = bindings[i];
300 if (b.kind == Kind::Texture || b.kind == Kind::StorageTexture) {
301 const u32 id =
static_cast<u32>(b.texture);
302 const auto original = s.graphics.textures_.find(
id);
303 if (original == s.graphics.textures_.end() || (b.kind == Kind::StorageTexture && !original->second.storage))
return false;
304 if (!shareTexture(
id))
return false;
305 auto image = s.images.find(original->second.texture);
306 if (std::none_of(textures.begin(), textures.end(), [
id](
auto& t) { return t.first == id; }))
307 textures.emplace_back(
id, &image->second);
308 }
else if (b.kind == Kind::StorageRead || b.kind == Kind::Storage) {
309 const u32 id =
static_cast<u32>(b.buffer);
310 auto it = s.graphics.buffers_.find(
id);
312 const u64 allocation = wgpuBufferGetSize(it->second.buffer);
313 if (b.offset >= allocation || b.offset % 4)
return false;
314 const u64 bytes = b.size ? b.size : allocation - b.offset;
315 if (!bytes || bytes % 4 || bytes > allocation - b.offset)
return false;
316 const u32 words =
static_cast<u32>(bytes / 4);
317 const u32 width = std::min(8192u, words);
318 const u32 height = (words + width - 1) / width;
319 if (height > 8192)
return false;
320 const auto surface = bufferSurface(
static_cast<u32>(ranges.size()), width, height);
321 if (!surface)
return false;
322 if (!worker.buffers_.contains(
id) &&
323 !worker.backendCreateBuffer(
id, {GfxBufferUsage::Storage, it->second.size},
nullptr))
return false;
324 ranges.push_back({id, b.offset, words, width, b.kind == Kind::Storage, it->second.buffer,
325 worker.buffers_.at(
id).buffer, &s.images.at(surface)});
326 }
else if (b.kind == Kind::Uniform) {
327 const u32 id =
static_cast<u32>(b.buffer);
328 const auto* record = s.graphics.resourceRecords().buffers.find(
id);
330 record->bytes.empty())
return false;
331 auto mirror = worker.buffers_.find(
id);
332 if (mirror != worker.buffers_.end() && mirror->second.size != record->desc.size) worker.backendDeleteBuffer(
id);
333 if (worker.buffers_.contains(
id)) worker.backendUpdateBuffer(
id, 0, record->bytes.data(), record->desc.size);
334 else if (!worker.backendCreateBuffer(
id, record->desc, record->bytes.data()))
return false;
335 }
else if (b.kind != Kind::Sampler && !(b.kind == Kind::DepthTexture && b.texture ==
TextureHandle::Invalid)) {
339 if (ranges.empty() && textures.empty())
return false;
340 copyBuffers(ranges, s.graphics.device_, s.graphics.queue_,
true,
true,
false);
341 std::vector<SharedImage*> images;
342 for (
auto [
id, image] : textures) images.push_back(image);
343 for (
auto& range : ranges) images.push_back(range.image);
344 for (
auto* image : images) {
345 const Transfer result = transfer(image->graphics, image->compute, s.device.Get());
346 if (result != Transfer::Success) {
349 if (result == Transfer::Lost)
353 s.pending.push_back(image);
355 copyBuffers(ranges, s.device.Get(), worker.queue_,
false,
false,
false);
356 for (
auto [
id, image] : textures) {
357 auto rec = s.graphics.textures_.at(
id);
358 rec.texture = image->compute.texture.Get();
359 rec.view = rec.sampleView = image->compute.view.Get();
360 worker.textures_.emplace(
id, rec);
362 const bool submitted = worker.backendDispatchCompute(program, bindings, count, x, y, z);
363 for (
auto [
id, image] : textures) worker.textures_.erase(
id);
364 if (submitted && !ranges.empty()) {
365 copyBuffers(ranges, s.device.Get(), worker.queue_,
false,
true,
true);
367 touch(s.device.Get(), worker.queue_, images.front()->compute.texture.Get(), s.workerScratch.Get());
368 s.pendingCopies = std::move(ranges);
370 if (!submitted)
wait();
376 if (s.pending.empty())
return;
378 for (SharedImage* image : s.pending) {
379 if (transfer(image->compute, image->graphics, s.graphics.device_) != Transfer::Success) ok =
false;
381 auto* image = s.pending.front();
390 touch(s.graphics.device_, s.graphics.queue_, image->graphics.texture.Get(), s.waitBuffer.Get());
391 copyBuffers(s.pendingCopies, s.graphics.device_, s.graphics.queue_,
true,
false,
true);
392 s.pendingCopies.clear();
396 auto it = state_->images.find(texture);
397 if (it == state_->images.end())
return;
398 if (std::find(state_->pending.begin(), state_->pending.end(), &it->second) != state_->pending.end())
399 state_->graphics.manualComputeBarrier();
400 state_->images.erase(it);
403 if (std::any_of(state_->pendingCopies.begin(), state_->pendingCopies.end(), [
id](
auto& range) { return range.id == id; }))
404 state_->graphics.manualComputeBarrier();
405 state_->worker.backendDeleteBuffer(
id);
410 if (metal_compute_attempted_)
return metal_compute_ && metal_compute_->available();
411 return device_ && adapter_ && instance_ && queue_ && wgpuDeviceHasFeature(device_, WGPUFeatureName_SharedTextureMemoryIOSurface) &&
412 wgpuDeviceHasFeature(device_, WGPUFeatureName_SharedFenceMTLSharedEvent);
416 if (enabled && !metal_compute_attempted_ && supportsAsyncCompute()) {
417 metal_compute_attempted_ =
true;
425 return metal_compute_ && metal_compute_->dispatch(
id, bindings, count, x, y, z);
430 if (inPass()) endRenderPass();
431 if (metal_compute_) metal_compute_->wait();
WebGPU (Dawn / emdawnwebgpu) backend for GfxDevice (REARCH_WGSL Phase 2).
virtual void backendSetAsyncComputeEnabled(bool)
virtual bool supportsAsyncCompute() const
Hardware with an independent queue. Individual bindings can still require the graphics queue.
virtual void backendWaitAsyncCompute()
virtual bool backendDispatchAsyncCompute(AsyncComputePriority, u32, const GfxComputeBinding *, u32, u32, u32, u32)
std::uint64_t u64
Unsigned 64-bit integer.
@ Storage
Read and written by compute shaders (var<storage, read_write>), and readable back....
@ Lost
Every handle issued before is dead; submission has stopped.
std::uint32_t u32
Unsigned 32-bit integer.
std::int64_t i64
Signed 64-bit integer.
@ Retained
The device keeps the last bytes it was given and uploads them again.
One resource a compute dispatch binds, at @group(0) @binding(binding).