blob: 2f4c82e77653b6b95ec5de08983b16feca4bff9e [file] [log] [blame]
Jesse Hallb1352bc2015-09-04 16:12:33 -07001/*
2 * Copyright 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jesse Halld7b994a2015-09-07 14:17:37 -070017// #define LOG_NDEBUG 0
18
19#include <algorithm>
20#include <memory>
21
22#include <gui/BufferQueue.h>
Jesse Hallb1352bc2015-09-04 16:12:33 -070023#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070024#include <sync/sync.h>
25
26#include "loader.h"
27
28using namespace vulkan;
29
Jesse Hall5ae3abb2015-10-08 14:00:22 -070030// TODO(jessehall): Currently we don't have a good error code for when a native
31// window operation fails. Just returning INITIALIZATION_FAILED for now. Later
32// versions (post SDK 0.9) of the API/extension have a better error code.
33// When updating to that version, audit all error returns.
34
Jesse Halld7b994a2015-09-07 14:17:37 -070035namespace {
36
37// ----------------------------------------------------------------------------
38// These functions/classes form an adaptor that allows objects to be refcounted
39// by both android::sp<> and std::shared_ptr<> simultaneously, and delegates
40// allocation of the shared_ptr<> control structure to VkAllocCallbacks. The
41// platform holds a reference to the ANativeWindow using its embedded reference
42// count, and the ANativeWindow implementation holds references to the
43// ANativeWindowBuffers using their embedded reference counts, so the
44// shared_ptr *must* cooperate with these and hold at least one reference to
45// the object using the embedded reference count.
46
47template <typename T>
48struct NativeBaseDeleter {
49 void operator()(T* obj) { obj->common.decRef(&obj->common); }
50};
51
52template <typename T>
53class VulkanAllocator {
54 public:
55 typedef T value_type;
56
57 explicit VulkanAllocator(VkDevice device) : device_(device) {}
58
59 template <typename U>
60 explicit VulkanAllocator(const VulkanAllocator<U>& other)
61 : device_(other.device_) {}
62
63 T* allocate(size_t n) const {
64 return static_cast<T*>(AllocDeviceMem(
65 device_, n * sizeof(T), alignof(T), VK_SYSTEM_ALLOC_TYPE_INTERNAL));
66 }
67 void deallocate(T* p, size_t) const { return FreeDeviceMem(device_, p); }
68
69 private:
70 template <typename U>
71 friend class VulkanAllocator;
72 VkDevice device_;
73};
74
75template <typename T>
76std::shared_ptr<T> InitSharedPtr(VkDevice device, T* obj) {
77 obj->common.incRef(&obj->common);
78 return std::shared_ptr<T>(obj, NativeBaseDeleter<T>(),
79 VulkanAllocator<T>(device));
80}
81
82// ----------------------------------------------------------------------------
83
84struct Swapchain {
85 Swapchain(std::shared_ptr<ANativeWindow> window_, uint32_t num_images_)
86 : window(window_), num_images(num_images_) {}
87
88 std::shared_ptr<ANativeWindow> window;
89 uint32_t num_images;
90
91 struct Image {
92 Image() : image(VK_NULL_HANDLE), dequeue_fence(-1), dequeued(false) {}
93 VkImage image;
94 std::shared_ptr<ANativeWindowBuffer> buffer;
95 // The fence is only valid when the buffer is dequeued, and should be
96 // -1 any other time. When valid, we own the fd, and must ensure it is
97 // closed: either by closing it explicitly when queueing the buffer,
98 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
99 int dequeue_fence;
100 bool dequeued;
101 } images[android::BufferQueue::NUM_BUFFER_SLOTS];
102};
103
104VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
105 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
106}
107
108Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
109 return reinterpret_cast<Swapchain*>(handle.handle);
110}
111
112} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700113
114namespace vulkan {
115
116VkResult GetPhysicalDeviceSurfaceSupportKHR(
117 VkPhysicalDevice /*pdev*/,
118 uint32_t /*queue_family*/,
119 const VkSurfaceDescriptionKHR* surface_desc,
120 VkBool32* supported) {
121// TODO(jessehall): Fix the header, preferrably upstream, so values added to
122// existing enums don't trigger warnings like this.
123#pragma clang diagnostic push
124#pragma clang diagnostic ignored "-Wold-style-cast"
125#pragma clang diagnostic ignored "-Wsign-conversion"
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700126 ALOGE_IF(
127 surface_desc->sType != VK_STRUCTURE_TYPE_SURFACE_DESCRIPTION_WINDOW_KHR,
128 "vkGetPhysicalDeviceSurfaceSupportKHR: pSurfaceDescription->sType=%#x "
129 "not supported",
130 surface_desc->sType);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700131#pragma clang diagnostic pop
132
133 const VkSurfaceDescriptionWindowKHR* window_desc =
134 reinterpret_cast<const VkSurfaceDescriptionWindowKHR*>(surface_desc);
135
136 // TODO(jessehall): Also check whether the physical device exports the
137 // VK_EXT_ANDROID_native_buffer extension. For now, assume it does.
138 *supported = (window_desc->platform == VK_PLATFORM_ANDROID_KHR &&
139 !window_desc->pPlatformHandle &&
140 static_cast<ANativeWindow*>(window_desc->pPlatformWindow)
141 ->common.magic == ANDROID_NATIVE_WINDOW_MAGIC);
142
143 return VK_SUCCESS;
144}
145
Jesse Halld7b994a2015-09-07 14:17:37 -0700146VkResult GetSurfacePropertiesKHR(VkDevice /*device*/,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700147 const VkSurfaceDescriptionKHR* surface_desc,
148 VkSurfacePropertiesKHR* properties) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700149 const VkSurfaceDescriptionWindowKHR* window_desc =
150 reinterpret_cast<const VkSurfaceDescriptionWindowKHR*>(surface_desc);
151 ANativeWindow* window =
152 static_cast<ANativeWindow*>(window_desc->pPlatformWindow);
153
154 int err;
155
156 // TODO(jessehall): Currently the window must be connected for several
157 // queries -- including default dimensions -- to work, since Surface caches
158 // the queried values at connect() and queueBuffer(), and query() returns
159 // those cached values.
160 //
161 // The proposed refactoring to create a VkSurface object (bug 14596) will
162 // give us a place to connect once per window. If that doesn't end up
163 // happening, we'll probably need to maintain an internal list of windows
164 // that have swapchains created for them, search that list here, and
165 // only temporarily connect if the window doesn't have a swapchain.
166
167 bool disconnect = true;
168 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
169 if (err == -EINVAL) {
170 // This is returned if the window is already connected, among other
171 // things. We'll just assume we're already connected and charge ahead.
172 // See TODO above, this is not cool.
173 ALOGW(
174 "vkGetSurfacePropertiesKHR: native_window_api_connect returned "
175 "-EINVAL, assuming already connected");
176 err = 0;
177 disconnect = false;
178 } else if (err != 0) {
179 // TODO(jessehall): Improve error reporting. Can we enumerate possible
180 // errors and translate them to valid Vulkan result codes?
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700181 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700182 }
183
184 int width, height;
185 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
186 if (err != 0) {
187 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
188 strerror(-err), err);
189 if (disconnect)
190 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700191 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700192 }
193 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
194 if (err != 0) {
195 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
196 strerror(-err), err);
197 if (disconnect)
198 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700199 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700200 }
201
202 if (disconnect)
203 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
204
205 properties->currentExtent = VkExtent2D{width, height};
206
207 // TODO(jessehall): Figure out what the min/max values should be.
208 properties->minImageCount = 2;
209 properties->maxImageCount = 3;
210
211 // TODO(jessehall): Figure out what the max extent should be. Maximum
212 // texture dimension maybe?
213 properties->minImageExtent = VkExtent2D{1, 1};
214 properties->maxImageExtent = VkExtent2D{4096, 4096};
215
216 // TODO(jessehall): We can support all transforms, fix this once
217 // implemented.
218 properties->supportedTransforms = VK_SURFACE_TRANSFORM_NONE_BIT_KHR;
219
220 // TODO(jessehall): Implement based on NATIVE_WINDOW_TRANSFORM_HINT.
221 properties->currentTransform = VK_SURFACE_TRANSFORM_NONE_KHR;
222
223 properties->maxImageArraySize = 1;
224
225 // TODO(jessehall): I think these are right, but haven't thought hard about
226 // it. Do we need to query the driver for support of any of these?
227 // Currently not included:
228 // - VK_IMAGE_USAGE_GENERAL: maybe? does this imply cpu mappable?
229 // - VK_IMAGE_USAGE_DEPTH_STENCIL_BIT: definitely not
230 // - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT: definitely not
231 properties->supportedUsageFlags =
232 VK_IMAGE_USAGE_TRANSFER_SOURCE_BIT |
233 VK_IMAGE_USAGE_TRANSFER_DESTINATION_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
234 VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
235 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
236
Jesse Hallb1352bc2015-09-04 16:12:33 -0700237 return VK_SUCCESS;
238}
239
Jesse Halld7b994a2015-09-07 14:17:37 -0700240VkResult GetSurfaceFormatsKHR(VkDevice /*device*/,
241 const VkSurfaceDescriptionKHR* /*surface_desc*/,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700242 uint32_t* count,
243 VkSurfaceFormatKHR* formats) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700244 // TODO(jessehall): Fill out the set of supported formats. Open question
245 // whether we should query the driver for support -- how does it know what
246 // the consumer can support? Should we support formats that don't
247 // correspond to gralloc formats?
248
249 const VkSurfaceFormatKHR kFormats[] = {
250 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLORSPACE_SRGB_NONLINEAR_KHR},
251 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLORSPACE_SRGB_NONLINEAR_KHR},
252 };
253 const uint32_t kNumFormats = sizeof(kFormats) / sizeof(kFormats[0]);
254
255 VkResult result = VK_SUCCESS;
256 if (formats) {
257 if (*count < kNumFormats)
258 result = VK_INCOMPLETE;
259 std::copy(kFormats, kFormats + std::min(*count, kNumFormats), formats);
260 }
261 *count = kNumFormats;
262 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700263}
264
Jesse Halld7b994a2015-09-07 14:17:37 -0700265VkResult GetSurfacePresentModesKHR(
266 VkDevice /*device*/,
267 const VkSurfaceDescriptionKHR* /*surface_desc*/,
268 uint32_t* count,
269 VkPresentModeKHR* modes) {
270 const VkPresentModeKHR kModes[] = {
271 VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
272 };
273 const uint32_t kNumModes = sizeof(kModes) / sizeof(kModes[0]);
274
275 VkResult result = VK_SUCCESS;
276 if (modes) {
277 if (*count < kNumModes)
278 result = VK_INCOMPLETE;
279 std::copy(kModes, kModes + std::min(*count, kNumModes), modes);
280 }
281 *count = kNumModes;
282 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700283}
284
285VkResult CreateSwapchainKHR(VkDevice device,
286 const VkSwapchainCreateInfoKHR* create_info,
Jesse Halld7b994a2015-09-07 14:17:37 -0700287 VkSwapchainKHR* swapchain_handle) {
288 int err;
289 VkResult result = VK_SUCCESS;
290
291 ALOGV_IF(create_info->imageArraySize != 1,
292 "Swapchain imageArraySize (%u) != 1 not supported",
293 create_info->imageArraySize);
294
295 ALOGE_IF(create_info->imageFormat != VK_FORMAT_R8G8B8A8_UNORM,
296 "swapchain formats other than R8G8B8A8_UNORM not yet implemented");
297 ALOGE_IF(create_info->imageColorSpace != VK_COLORSPACE_SRGB_NONLINEAR_KHR,
298 "color spaces other than SRGB_NONLINEAR not yet implemented");
299 ALOGE_IF(create_info->oldSwapchain,
300 "swapchain re-creation not yet implemented");
301 ALOGE_IF(create_info->preTransform != VK_SURFACE_TRANSFORM_NONE_KHR,
302 "swapchain preTransform not yet implemented");
303 ALOGE_IF(create_info->presentMode != VK_PRESENT_MODE_FIFO_KHR,
304 "present modes other than FIFO are not yet implemented");
305
306 // -- Configure the native window --
307 // Failure paths from here on need to disconnect the window.
308
309 std::shared_ptr<ANativeWindow> window = InitSharedPtr(
310 device, static_cast<ANativeWindow*>(
311 reinterpret_cast<const VkSurfaceDescriptionWindowKHR*>(
312 create_info->pSurfaceDescription)
313 ->pPlatformWindow));
314
315 // TODO(jessehall): Create and use NATIVE_WINDOW_API_VULKAN.
316 err = native_window_api_connect(window.get(), NATIVE_WINDOW_API_EGL);
317 if (err != 0) {
318 // TODO(jessehall): Improve error reporting. Can we enumerate possible
319 // errors and translate them to valid Vulkan result codes?
320 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
321 err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700322 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700323 }
324
325 err = native_window_set_buffers_dimensions(window.get(),
326 create_info->imageExtent.width,
327 create_info->imageExtent.height);
328 if (err != 0) {
329 // TODO(jessehall): Improve error reporting. Can we enumerate possible
330 // errors and translate them to valid Vulkan result codes?
331 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
332 create_info->imageExtent.width, create_info->imageExtent.height,
333 strerror(-err), err);
334 native_window_api_disconnect(window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700335 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700336 }
337
Jesse Hallf64ca122015-11-03 16:11:10 -0800338 err = native_window_set_scaling_mode(
339 window.get(), NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
340 if (err != 0) {
341 // TODO(jessehall): Improve error reporting. Can we enumerate possible
342 // errors and translate them to valid Vulkan result codes?
343 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
344 strerror(-err), err);
345 native_window_api_disconnect(window.get(), NATIVE_WINDOW_API_EGL);
346 return VK_ERROR_INITIALIZATION_FAILED;
347 }
348
Jesse Halld7b994a2015-09-07 14:17:37 -0700349 uint32_t min_undequeued_buffers;
350 err = window->query(window.get(), NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
351 reinterpret_cast<int*>(&min_undequeued_buffers));
352 if (err != 0) {
353 // TODO(jessehall): Improve error reporting. Can we enumerate possible
354 // errors and translate them to valid Vulkan result codes?
355 ALOGE("window->query failed: %s (%d)", strerror(-err), err);
356 native_window_api_disconnect(window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700357 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700358 }
359 uint32_t num_images =
360 (create_info->minImageCount - 1) + min_undequeued_buffers;
361 err = native_window_set_buffer_count(window.get(), num_images);
362 if (err != 0) {
363 // TODO(jessehall): Improve error reporting. Can we enumerate possible
364 // errors and translate them to valid Vulkan result codes?
365 ALOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err),
366 err);
367 native_window_api_disconnect(window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700368 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700369 }
370
371 // TODO(jessehall): Do we need to call modify native_window_set_usage()
372 // based on create_info->imageUsageFlags?
373
374 // -- Allocate our Swapchain object --
375 // After this point, we must deallocate the swapchain on error.
376
377 void* mem = AllocDeviceMem(device, sizeof(Swapchain), alignof(Swapchain),
378 VK_SYSTEM_ALLOC_TYPE_API_OBJECT);
379 if (!mem) {
380 native_window_api_disconnect(window.get(), NATIVE_WINDOW_API_EGL);
381 return VK_ERROR_OUT_OF_HOST_MEMORY;
382 }
383 Swapchain* swapchain = new (mem) Swapchain(window, num_images);
384
385 // -- Dequeue all buffers and create a VkImage for each --
386 // Any failures during or after this must cancel the dequeued buffers.
387
388 VkNativeBufferANDROID image_native_buffer = {
389// TODO(jessehall): Figure out how to make extension headers not horrible.
390#pragma clang diagnostic push
391#pragma clang diagnostic ignored "-Wold-style-cast"
392 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
393#pragma clang diagnostic pop
394 .pNext = nullptr,
395 };
396 VkImageCreateInfo image_create = {
397 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
398 .pNext = &image_native_buffer,
399 .imageType = VK_IMAGE_TYPE_2D,
400 .format = VK_FORMAT_R8G8B8A8_UNORM, // TODO(jessehall)
401 .extent = {0, 0, 1},
402 .mipLevels = 1,
403 .arraySize = 1,
404 .samples = 1,
405 .tiling = VK_IMAGE_TILING_OPTIMAL,
406 .usage = create_info->imageUsageFlags,
407 .flags = 0,
408 .sharingMode = create_info->sharingMode,
409 .queueFamilyCount = create_info->queueFamilyCount,
410 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
411 };
412
413 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device);
414 for (uint32_t i = 0; i < num_images; i++) {
415 Swapchain::Image& img = swapchain->images[i];
416
417 ANativeWindowBuffer* buffer;
418 err = window->dequeueBuffer(window.get(), &buffer, &img.dequeue_fence);
419 if (err != 0) {
420 // TODO(jessehall): Improve error reporting. Can we enumerate
421 // possible errors and translate them to valid Vulkan result codes?
422 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700423 result = VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700424 break;
425 }
426 img.buffer = InitSharedPtr(device, buffer);
427 img.dequeued = true;
428
429 image_create.extent =
430 VkExtent3D{img.buffer->width, img.buffer->height, 1};
431 image_native_buffer.handle = img.buffer->handle;
432 image_native_buffer.stride = img.buffer->stride;
433 image_native_buffer.format = img.buffer->format;
434 image_native_buffer.usage = img.buffer->usage;
435
436 result = driver_vtbl.CreateImage(device, &image_create, &img.image);
437 if (result != VK_SUCCESS) {
438 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
439 break;
440 }
441 }
442
443 // -- Cancel all buffers, returning them to the queue --
444 // If an error occurred before, also destroy the VkImage and release the
445 // buffer reference. Otherwise, we retain a strong reference to the buffer.
446 //
447 // TODO(jessehall): The error path here is the same as DestroySwapchain,
448 // but not the non-error path. Should refactor/unify.
449 for (uint32_t i = 0; i < num_images; i++) {
450 Swapchain::Image& img = swapchain->images[i];
451 if (img.dequeued) {
452 window->cancelBuffer(window.get(), img.buffer.get(),
453 img.dequeue_fence);
454 img.dequeue_fence = -1;
455 img.dequeued = false;
456 }
457 if (result != VK_SUCCESS) {
458 if (img.image)
459 driver_vtbl.DestroyImage(device, img.image);
460 }
461 }
462
463 if (result != VK_SUCCESS) {
464 native_window_api_disconnect(window.get(), NATIVE_WINDOW_API_EGL);
465 swapchain->~Swapchain();
466 FreeDeviceMem(device, swapchain);
467 return result;
468 }
469
470 *swapchain_handle = HandleFromSwapchain(swapchain);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700471 return VK_SUCCESS;
472}
473
Jesse Halld7b994a2015-09-07 14:17:37 -0700474VkResult DestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain_handle) {
475 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device);
476 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
477 const std::shared_ptr<ANativeWindow>& window = swapchain->window;
478
479 for (uint32_t i = 0; i < swapchain->num_images; i++) {
480 Swapchain::Image& img = swapchain->images[i];
481 if (img.dequeued) {
482 window->cancelBuffer(window.get(), img.buffer.get(),
483 img.dequeue_fence);
484 img.dequeue_fence = -1;
485 img.dequeued = false;
486 }
487 if (img.image) {
488 driver_vtbl.DestroyImage(device, img.image);
489 }
490 }
491
492 native_window_api_disconnect(window.get(), NATIVE_WINDOW_API_EGL);
493 swapchain->~Swapchain();
494 FreeDeviceMem(device, swapchain);
495
Jesse Hallb1352bc2015-09-04 16:12:33 -0700496 return VK_SUCCESS;
497}
498
Jesse Halld7b994a2015-09-07 14:17:37 -0700499VkResult GetSwapchainImagesKHR(VkDevice,
500 VkSwapchainKHR swapchain_handle,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700501 uint32_t* count,
Jesse Halld7b994a2015-09-07 14:17:37 -0700502 VkImage* images) {
503 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
504 VkResult result = VK_SUCCESS;
505 if (images) {
506 uint32_t n = swapchain.num_images;
507 if (*count < swapchain.num_images) {
508 n = *count;
509 result = VK_INCOMPLETE;
510 }
511 for (uint32_t i = 0; i < n; i++)
512 images[i] = swapchain.images[i].image;
513 }
514 *count = swapchain.num_images;
515 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700516}
517
518VkResult AcquireNextImageKHR(VkDevice device,
Jesse Halld7b994a2015-09-07 14:17:37 -0700519 VkSwapchainKHR swapchain_handle,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700520 uint64_t timeout,
521 VkSemaphore semaphore,
522 uint32_t* image_index) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700523 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
524 VkResult result;
525 int err;
526
527 ALOGW_IF(
528 timeout != UINT64_MAX,
529 "vkAcquireNextImageKHR: non-infinite timeouts not yet implemented");
530
531 ANativeWindowBuffer* buffer;
532 int fence;
533 err = swapchain.window->dequeueBuffer(swapchain.window.get(), &buffer,
534 &fence);
535 if (err != 0) {
536 // TODO(jessehall): Improve error reporting. Can we enumerate possible
537 // errors and translate them to valid Vulkan result codes?
538 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700539 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700540 }
541
542 uint32_t idx;
543 for (idx = 0; idx < swapchain.num_images; idx++) {
544 if (swapchain.images[idx].buffer.get() == buffer) {
545 swapchain.images[idx].dequeued = true;
546 swapchain.images[idx].dequeue_fence = fence;
547 break;
548 }
549 }
550 if (idx == swapchain.num_images) {
551 ALOGE("dequeueBuffer returned unrecognized buffer");
552 swapchain.window->cancelBuffer(swapchain.window.get(), buffer, fence);
553#pragma clang diagnostic push
554#pragma clang diagnostic ignored "-Wold-style-cast"
555 return VK_ERROR_OUT_OF_DATE_KHR;
556#pragma clang diagnostic pop
557 }
558
559 int fence_clone = -1;
560 if (fence != -1) {
561 fence_clone = dup(fence);
562 if (fence_clone == -1) {
563 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
564 strerror(errno), errno);
565 sync_wait(fence, -1 /* forever */);
566 }
567 }
568
569 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device);
570 result =
571 driver_vtbl.ImportNativeFenceANDROID(device, semaphore, fence_clone);
572 if (result != VK_SUCCESS) {
573 // NOTE: we're relying on ImportNativeFenceANDROID to close
574 // fence_clone, even if the call fails. We could close it ourselves on
575 // failure, but that would create a race condition if the driver closes
576 // it on a failure path. We must assume one of: the driver *always*
577 // closes it even on failure, or *never* closes it on failure.
578 swapchain.window->cancelBuffer(swapchain.window.get(), buffer, fence);
579 swapchain.images[idx].dequeued = false;
580 swapchain.images[idx].dequeue_fence = -1;
581 return result;
582 }
583
584 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700585 return VK_SUCCESS;
586}
587
588VkResult QueuePresentKHR(VkQueue queue, VkPresentInfoKHR* present_info) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700589#pragma clang diagnostic push
590#pragma clang diagnostic ignored "-Wold-style-cast"
591#pragma clang diagnostic ignored "-Wsign-conversion"
592 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
593 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
594 present_info->sType);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700595#pragma clang diagnostic pop
Jesse Halld7b994a2015-09-07 14:17:37 -0700596 ALOGV_IF(present_info->pNext, "VkPresentInfo::pNext != NULL");
597
598 const DeviceVtbl& driver_vtbl = GetDriverVtbl(queue);
599 VkResult final_result = VK_SUCCESS;
600 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
601 Swapchain& swapchain =
602 *SwapchainFromHandle(present_info->swapchains[sc]);
603 uint32_t image_idx = present_info->imageIndices[sc];
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700604 Swapchain::Image& img = swapchain.images[image_idx];
Jesse Halld7b994a2015-09-07 14:17:37 -0700605 VkResult result;
606 int err;
607
Jesse Halld7b994a2015-09-07 14:17:37 -0700608 int fence = -1;
609 result = driver_vtbl.QueueSignalNativeFenceANDROID(queue, &fence);
610 if (result != VK_SUCCESS) {
611 ALOGE("vkQueueSignalNativeFenceANDROID failed: %d", result);
612 if (final_result == VK_SUCCESS)
613 final_result = result;
614 // TODO(jessehall): What happens to the buffer here? Does the app
615 // still own it or not, i.e. should we cancel the buffer? Hard to
616 // do correctly without synchronizing, though I guess we could wait
617 // for the queue to idle.
618 continue;
619 }
620
621 err = swapchain.window->queueBuffer(swapchain.window.get(),
622 img.buffer.get(), fence);
623 if (err != 0) {
624 // TODO(jessehall): What now? We should probably cancel the buffer,
625 // I guess?
626 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
627 if (final_result == VK_SUCCESS)
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700628 final_result = VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700629 continue;
630 }
631
632 if (img.dequeue_fence != -1) {
633 close(img.dequeue_fence);
634 img.dequeue_fence = -1;
635 }
636 img.dequeued = false;
637 }
638
639 return final_result;
640}
Jesse Hallb1352bc2015-09-04 16:12:33 -0700641
642} // namespace vulkan