swapchain.cpp revision 3fbc856120217247c72fb5ed88500000f3881c45
1/* 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 17// #define LOG_NDEBUG 0 18 19#include <algorithm> 20#include <memory> 21 22#include <gui/BufferQueue.h> 23#include <log/log.h> 24#include <sync/sync.h> 25 26#include "loader.h" 27 28using namespace vulkan; 29 30// 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 35namespace { 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 VkAllocationCallbacks. 41// The 42// platform holds a reference to the ANativeWindow using its embedded reference 43// count, and the ANativeWindow implementation holds references to the 44// ANativeWindowBuffers using their embedded reference counts, so the 45// shared_ptr *must* cooperate with these and hold at least one reference to 46// the object using the embedded reference count. 47 48template <typename T> 49struct NativeBaseDeleter { 50 void operator()(T* obj) { obj->common.decRef(&obj->common); } 51}; 52 53template <typename Host> 54struct AllocScope {}; 55 56template <> 57struct AllocScope<VkInstance> { 58 static const VkSystemAllocationScope kScope = 59 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE; 60}; 61 62template <> 63struct AllocScope<VkDevice> { 64 static const VkSystemAllocationScope kScope = 65 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE; 66}; 67 68template <typename T, typename Host> 69class VulkanAllocator { 70 public: 71 typedef T value_type; 72 73 explicit VulkanAllocator(Host host) : host_(host) {} 74 75 template <typename U> 76 explicit VulkanAllocator(const VulkanAllocator<U, Host>& other) 77 : host_(other.host_) {} 78 79 T* allocate(size_t n) const { 80 return static_cast<T*>(AllocMem(host_, n * sizeof(T), alignof(T), 81 AllocScope<Host>::kScope)); 82 } 83 void deallocate(T* p, size_t) const { return FreeMem(host_, p); } 84 85 private: 86 template <typename U, typename H> 87 friend class VulkanAllocator; 88 Host host_; 89}; 90 91template <typename T, typename Host> 92std::shared_ptr<T> InitSharedPtr(Host host, T* obj) { 93 obj->common.incRef(&obj->common); 94 return std::shared_ptr<T>(obj, NativeBaseDeleter<T>(), 95 VulkanAllocator<T, Host>(host)); 96} 97 98// ---------------------------------------------------------------------------- 99 100struct Surface { 101 std::shared_ptr<ANativeWindow> window; 102}; 103 104VkSurfaceKHR HandleFromSurface(Surface* surface) { 105 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface)); 106} 107 108Surface* SurfaceFromHandle(VkSurfaceKHR handle) { 109 return reinterpret_cast<Surface*>(handle); 110} 111 112struct Swapchain { 113 Swapchain(Surface& surface_, uint32_t num_images_) 114 : surface(surface_), num_images(num_images_) {} 115 116 Surface& surface; 117 uint32_t num_images; 118 119 struct Image { 120 Image() : image(VK_NULL_HANDLE), dequeue_fence(-1), dequeued(false) {} 121 VkImage image; 122 std::shared_ptr<ANativeWindowBuffer> buffer; 123 // The fence is only valid when the buffer is dequeued, and should be 124 // -1 any other time. When valid, we own the fd, and must ensure it is 125 // closed: either by closing it explicitly when queueing the buffer, 126 // or by passing ownership e.g. to ANativeWindow::cancelBuffer(). 127 int dequeue_fence; 128 bool dequeued; 129 } images[android::BufferQueue::NUM_BUFFER_SLOTS]; 130}; 131 132VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) { 133 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain)); 134} 135 136Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) { 137 return reinterpret_cast<Swapchain*>(handle); 138} 139 140} // anonymous namespace 141 142namespace vulkan { 143 144VkResult CreateAndroidSurfaceKHR(VkInstance instance, 145 ANativeWindow* window, 146 VkSurfaceKHR* out_surface) { 147 void* mem = AllocMem(instance, sizeof(Surface), alignof(Surface), 148 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); 149 if (!mem) 150 return VK_ERROR_OUT_OF_HOST_MEMORY; 151 Surface* surface = new (mem) Surface; 152 153 surface->window = InitSharedPtr(instance, window); 154 155 // TODO(jessehall): Create and use NATIVE_WINDOW_API_VULKAN. 156 int err = 157 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL); 158 if (err != 0) { 159 // TODO(jessehall): Improve error reporting. Can we enumerate possible 160 // errors and translate them to valid Vulkan result codes? 161 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err), 162 err); 163 surface->~Surface(); 164 FreeMem(instance, surface); 165 return VK_ERROR_INITIALIZATION_FAILED; 166 } 167 168 *out_surface = HandleFromSurface(surface); 169 return VK_SUCCESS; 170} 171 172void DestroySurfaceKHR(VkInstance instance, VkSurfaceKHR surface_handle) { 173 Surface* surface = SurfaceFromHandle(surface_handle); 174 if (!surface) 175 return; 176 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL); 177 surface->~Surface(); 178 FreeMem(instance, surface); 179} 180 181VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/, 182 uint32_t /*queue_family*/, 183 VkSurfaceKHR /*surface*/, 184 VkBool32* pSupported) { 185 *pSupported = VK_TRUE; 186 return VK_SUCCESS; 187} 188 189VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR( 190 VkPhysicalDevice /*pdev*/, 191 VkSurfaceKHR surface, 192 VkSurfaceCapabilitiesKHR* capabilities) { 193 int err; 194 ANativeWindow* window = SurfaceFromHandle(surface)->window.get(); 195 196 int width, height; 197 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width); 198 if (err != 0) { 199 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)", 200 strerror(-err), err); 201 return VK_ERROR_INITIALIZATION_FAILED; 202 } 203 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height); 204 if (err != 0) { 205 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)", 206 strerror(-err), err); 207 return VK_ERROR_INITIALIZATION_FAILED; 208 } 209 210 capabilities->currentExtent = VkExtent2D{width, height}; 211 212 // TODO(jessehall): Figure out what the min/max values should be. 213 capabilities->minImageCount = 2; 214 capabilities->maxImageCount = 3; 215 216 // TODO(jessehall): Figure out what the max extent should be. Maximum 217 // texture dimension maybe? 218 capabilities->minImageExtent = VkExtent2D{1, 1}; 219 capabilities->maxImageExtent = VkExtent2D{4096, 4096}; 220 221 // TODO(jessehall): We can support all transforms, fix this once 222 // implemented. 223 capabilities->supportedTransforms = VK_SURFACE_TRANSFORM_NONE_BIT_KHR; 224 225 // TODO(jessehall): Implement based on NATIVE_WINDOW_TRANSFORM_HINT. 226 capabilities->currentTransform = VK_SURFACE_TRANSFORM_NONE_KHR; 227 228 capabilities->maxImageArraySize = 1; 229 230 // TODO(jessehall): I think these are right, but haven't thought hard about 231 // it. Do we need to query the driver for support of any of these? 232 // Currently not included: 233 // - VK_IMAGE_USAGE_GENERAL: maybe? does this imply cpu mappable? 234 // - VK_IMAGE_USAGE_DEPTH_STENCIL_BIT: definitely not 235 // - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT: definitely not 236 capabilities->supportedUsageFlags = 237 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | 238 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | 239 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | 240 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; 241 242 return VK_SUCCESS; 243} 244 245VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice /*pdev*/, 246 VkSurfaceKHR /*surface*/, 247 uint32_t* count, 248 VkSurfaceFormatKHR* formats) { 249 // TODO(jessehall): Fill out the set of supported formats. Longer term, add 250 // a new gralloc method to query whether a (format, usage) pair is 251 // supported, and check that for each gralloc format that corresponds to a 252 // Vulkan format. Shorter term, just add a few more formats to the ones 253 // hardcoded below. 254 255 const VkSurfaceFormatKHR kFormats[] = { 256 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLORSPACE_SRGB_NONLINEAR_KHR}, 257 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLORSPACE_SRGB_NONLINEAR_KHR}, 258 }; 259 const uint32_t kNumFormats = sizeof(kFormats) / sizeof(kFormats[0]); 260 261 VkResult result = VK_SUCCESS; 262 if (formats) { 263 if (*count < kNumFormats) 264 result = VK_INCOMPLETE; 265 std::copy(kFormats, kFormats + std::min(*count, kNumFormats), formats); 266 } 267 *count = kNumFormats; 268 return result; 269} 270 271VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice /*pdev*/, 272 VkSurfaceKHR /*surface*/, 273 uint32_t* count, 274 VkPresentModeKHR* modes) { 275 const VkPresentModeKHR kModes[] = { 276 VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR, 277 }; 278 const uint32_t kNumModes = sizeof(kModes) / sizeof(kModes[0]); 279 280 VkResult result = VK_SUCCESS; 281 if (modes) { 282 if (*count < kNumModes) 283 result = VK_INCOMPLETE; 284 std::copy(kModes, kModes + std::min(*count, kNumModes), modes); 285 } 286 *count = kNumModes; 287 return result; 288} 289 290VkResult CreateSwapchainKHR(VkDevice device, 291 const VkSwapchainCreateInfoKHR* create_info, 292 VkSwapchainKHR* swapchain_handle) { 293 int err; 294 VkResult result = VK_SUCCESS; 295 296 ALOGV_IF(create_info->imageArraySize != 1, 297 "Swapchain imageArraySize (%u) != 1 not supported", 298 create_info->imageArraySize); 299 300 ALOGE_IF(create_info->imageFormat != VK_FORMAT_R8G8B8A8_UNORM, 301 "swapchain formats other than R8G8B8A8_UNORM not yet implemented"); 302 ALOGE_IF(create_info->imageColorSpace != VK_COLORSPACE_SRGB_NONLINEAR_KHR, 303 "color spaces other than SRGB_NONLINEAR not yet implemented"); 304 ALOGE_IF(create_info->oldSwapchain, 305 "swapchain re-creation not yet implemented"); 306 ALOGE_IF(create_info->preTransform != VK_SURFACE_TRANSFORM_NONE_KHR, 307 "swapchain preTransform not yet implemented"); 308 ALOGE_IF(create_info->presentMode != VK_PRESENT_MODE_FIFO_KHR, 309 "present modes other than FIFO are not yet implemented"); 310 311 // -- Configure the native window -- 312 313 Surface& surface = *SurfaceFromHandle(create_info->surface); 314 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device); 315 316 err = native_window_set_buffers_dimensions(surface.window.get(), 317 create_info->imageExtent.width, 318 create_info->imageExtent.height); 319 if (err != 0) { 320 // TODO(jessehall): Improve error reporting. Can we enumerate possible 321 // errors and translate them to valid Vulkan result codes? 322 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)", 323 create_info->imageExtent.width, create_info->imageExtent.height, 324 strerror(-err), err); 325 return VK_ERROR_INITIALIZATION_FAILED; 326 } 327 328 err = native_window_set_scaling_mode( 329 surface.window.get(), NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW); 330 if (err != 0) { 331 // TODO(jessehall): Improve error reporting. Can we enumerate possible 332 // errors and translate them to valid Vulkan result codes? 333 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)", 334 strerror(-err), err); 335 return VK_ERROR_INITIALIZATION_FAILED; 336 } 337 338 uint32_t min_undequeued_buffers; 339 err = surface.window->query( 340 surface.window.get(), NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, 341 reinterpret_cast<int*>(&min_undequeued_buffers)); 342 if (err != 0) { 343 // TODO(jessehall): Improve error reporting. Can we enumerate possible 344 // errors and translate them to valid Vulkan result codes? 345 ALOGE("window->query failed: %s (%d)", strerror(-err), err); 346 return VK_ERROR_INITIALIZATION_FAILED; 347 } 348 uint32_t num_images = 349 (create_info->minImageCount - 1) + min_undequeued_buffers; 350 err = native_window_set_buffer_count(surface.window.get(), num_images); 351 if (err != 0) { 352 // TODO(jessehall): Improve error reporting. Can we enumerate possible 353 // errors and translate them to valid Vulkan result codes? 354 ALOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err), 355 err); 356 return VK_ERROR_INITIALIZATION_FAILED; 357 } 358 359 int gralloc_usage = 0; 360 // TODO(jessehall): Remove conditional once all drivers have been updated 361 if (driver_vtbl.GetSwapchainGrallocUsageANDROID) { 362 result = driver_vtbl.GetSwapchainGrallocUsageANDROID( 363 device, create_info->imageFormat, create_info->imageUsageFlags, 364 &gralloc_usage); 365 if (result != VK_SUCCESS) { 366 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result); 367 return VK_ERROR_INITIALIZATION_FAILED; 368 } 369 } else { 370 gralloc_usage = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE; 371 } 372 err = native_window_set_usage(surface.window.get(), gralloc_usage); 373 if (err != 0) { 374 // TODO(jessehall): Improve error reporting. Can we enumerate possible 375 // errors and translate them to valid Vulkan result codes? 376 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err); 377 return VK_ERROR_INITIALIZATION_FAILED; 378 } 379 380 // -- Allocate our Swapchain object -- 381 // After this point, we must deallocate the swapchain on error. 382 383 void* mem = AllocMem(device, sizeof(Swapchain), alignof(Swapchain), 384 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); 385 if (!mem) 386 return VK_ERROR_OUT_OF_HOST_MEMORY; 387 Swapchain* swapchain = new (mem) Swapchain(surface, num_images); 388 389 // -- Dequeue all buffers and create a VkImage for each -- 390 // Any failures during or after this must cancel the dequeued buffers. 391 392 VkNativeBufferANDROID image_native_buffer = { 393// TODO(jessehall): Figure out how to make extension headers not horrible. 394#pragma clang diagnostic push 395#pragma clang diagnostic ignored "-Wold-style-cast" 396 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID, 397#pragma clang diagnostic pop 398 .pNext = nullptr, 399 }; 400 VkImageCreateInfo image_create = { 401 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, 402 .pNext = &image_native_buffer, 403 .imageType = VK_IMAGE_TYPE_2D, 404 .format = VK_FORMAT_R8G8B8A8_UNORM, // TODO(jessehall) 405 .extent = {0, 0, 1}, 406 .mipLevels = 1, 407 .arrayLayers = 1, 408 .samples = 1, 409 .tiling = VK_IMAGE_TILING_OPTIMAL, 410 .usage = create_info->imageUsageFlags, 411 .flags = 0, 412 .sharingMode = create_info->sharingMode, 413 .queueFamilyIndexCount = create_info->queueFamilyIndexCount, 414 .pQueueFamilyIndices = create_info->pQueueFamilyIndices, 415 }; 416 417 for (uint32_t i = 0; i < num_images; i++) { 418 Swapchain::Image& img = swapchain->images[i]; 419 420 ANativeWindowBuffer* buffer; 421 err = surface.window->dequeueBuffer(surface.window.get(), &buffer, 422 &img.dequeue_fence); 423 if (err != 0) { 424 // TODO(jessehall): Improve error reporting. Can we enumerate 425 // possible errors and translate them to valid Vulkan result codes? 426 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err); 427 result = VK_ERROR_INITIALIZATION_FAILED; 428 break; 429 } 430 img.buffer = InitSharedPtr(device, buffer); 431 img.dequeued = true; 432 433 image_create.extent = 434 VkExtent3D{img.buffer->width, img.buffer->height, 1}; 435 image_native_buffer.handle = img.buffer->handle; 436 image_native_buffer.stride = img.buffer->stride; 437 image_native_buffer.format = img.buffer->format; 438 image_native_buffer.usage = img.buffer->usage; 439 440 result = 441 driver_vtbl.CreateImage(device, &image_create, nullptr, &img.image); 442 if (result != VK_SUCCESS) { 443 ALOGD("vkCreateImage w/ native buffer failed: %u", result); 444 break; 445 } 446 } 447 448 // -- Cancel all buffers, returning them to the queue -- 449 // If an error occurred before, also destroy the VkImage and release the 450 // buffer reference. Otherwise, we retain a strong reference to the buffer. 451 // 452 // TODO(jessehall): The error path here is the same as DestroySwapchain, 453 // but not the non-error path. Should refactor/unify. 454 for (uint32_t i = 0; i < num_images; i++) { 455 Swapchain::Image& img = swapchain->images[i]; 456 if (img.dequeued) { 457 surface.window->cancelBuffer(surface.window.get(), img.buffer.get(), 458 img.dequeue_fence); 459 img.dequeue_fence = -1; 460 img.dequeued = false; 461 } 462 if (result != VK_SUCCESS) { 463 if (img.image) 464 driver_vtbl.DestroyImage(device, img.image, nullptr); 465 } 466 } 467 468 if (result != VK_SUCCESS) { 469 swapchain->~Swapchain(); 470 FreeMem(device, swapchain); 471 return result; 472 } 473 474 *swapchain_handle = HandleFromSwapchain(swapchain); 475 return VK_SUCCESS; 476} 477 478VkResult DestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain_handle) { 479 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device); 480 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle); 481 const std::shared_ptr<ANativeWindow>& window = swapchain->surface.window; 482 483 for (uint32_t i = 0; i < swapchain->num_images; i++) { 484 Swapchain::Image& img = swapchain->images[i]; 485 if (img.dequeued) { 486 window->cancelBuffer(window.get(), img.buffer.get(), 487 img.dequeue_fence); 488 img.dequeue_fence = -1; 489 img.dequeued = false; 490 } 491 if (img.image) { 492 driver_vtbl.DestroyImage(device, img.image, nullptr); 493 } 494 } 495 496 swapchain->~Swapchain(); 497 FreeMem(device, swapchain); 498 499 return VK_SUCCESS; 500} 501 502VkResult GetSwapchainImagesKHR(VkDevice, 503 VkSwapchainKHR swapchain_handle, 504 uint32_t* count, 505 VkImage* images) { 506 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle); 507 VkResult result = VK_SUCCESS; 508 if (images) { 509 uint32_t n = swapchain.num_images; 510 if (*count < swapchain.num_images) { 511 n = *count; 512 result = VK_INCOMPLETE; 513 } 514 for (uint32_t i = 0; i < n; i++) 515 images[i] = swapchain.images[i].image; 516 } 517 *count = swapchain.num_images; 518 return result; 519} 520 521VkResult AcquireNextImageKHR(VkDevice device, 522 VkSwapchainKHR swapchain_handle, 523 uint64_t timeout, 524 VkSemaphore semaphore, 525 uint32_t* image_index) { 526 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle); 527 ANativeWindow* window = swapchain.surface.window.get(); 528 VkResult result; 529 int err; 530 531 ALOGW_IF( 532 timeout != UINT64_MAX, 533 "vkAcquireNextImageKHR: non-infinite timeouts not yet implemented"); 534 535 ANativeWindowBuffer* buffer; 536 int fence; 537 err = window->dequeueBuffer(window, &buffer, &fence); 538 if (err != 0) { 539 // TODO(jessehall): Improve error reporting. Can we enumerate possible 540 // errors and translate them to valid Vulkan result codes? 541 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err); 542 return VK_ERROR_INITIALIZATION_FAILED; 543 } 544 545 uint32_t idx; 546 for (idx = 0; idx < swapchain.num_images; idx++) { 547 if (swapchain.images[idx].buffer.get() == buffer) { 548 swapchain.images[idx].dequeued = true; 549 swapchain.images[idx].dequeue_fence = fence; 550 break; 551 } 552 } 553 if (idx == swapchain.num_images) { 554 ALOGE("dequeueBuffer returned unrecognized buffer"); 555 window->cancelBuffer(window, buffer, fence); 556#pragma clang diagnostic push 557#pragma clang diagnostic ignored "-Wold-style-cast" 558 return VK_ERROR_OUT_OF_DATE_KHR; 559#pragma clang diagnostic pop 560 } 561 562 int fence_clone = -1; 563 if (fence != -1) { 564 fence_clone = dup(fence); 565 if (fence_clone == -1) { 566 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)", 567 strerror(errno), errno); 568 sync_wait(fence, -1 /* forever */); 569 } 570 } 571 572 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device); 573 if (driver_vtbl.AcquireImageANDROID) { 574 result = driver_vtbl.AcquireImageANDROID( 575 device, swapchain.images[idx].image, fence_clone, semaphore); 576 } else { 577 ALOG_ASSERT(driver_vtbl.ImportNativeFenceANDROID, 578 "Have neither vkAcquireImageANDROID nor " 579 "vkImportNativeFenceANDROID"); 580 result = driver_vtbl.ImportNativeFenceANDROID(device, semaphore, 581 fence_clone); 582 } 583 if (result != VK_SUCCESS) { 584 // NOTE: we're relying on AcquireImageANDROID to close fence_clone, 585 // even if the call fails. We could close it ourselves on failure, but 586 // that would create a race condition if the driver closes it on a 587 // failure path: some other thread might create an fd with the same 588 // number between the time the driver closes it and the time we close 589 // it. We must assume one of: the driver *always* closes it even on 590 // failure, or *never* closes it on failure. 591 window->cancelBuffer(window, buffer, fence); 592 swapchain.images[idx].dequeued = false; 593 swapchain.images[idx].dequeue_fence = -1; 594 return result; 595 } 596 597 *image_index = idx; 598 return VK_SUCCESS; 599} 600 601VkResult QueuePresentKHR(VkQueue queue, VkPresentInfoKHR* present_info) { 602#pragma clang diagnostic push 603#pragma clang diagnostic ignored "-Wold-style-cast" 604#pragma clang diagnostic ignored "-Wsign-conversion" 605 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, 606 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d", 607 present_info->sType); 608#pragma clang diagnostic pop 609 ALOGV_IF(present_info->pNext, "VkPresentInfo::pNext != NULL"); 610 611 const DeviceVtbl& driver_vtbl = GetDriverVtbl(queue); 612 VkResult final_result = VK_SUCCESS; 613 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) { 614 Swapchain& swapchain = 615 *SwapchainFromHandle(present_info->pSwapchains[sc]); 616 ANativeWindow* window = swapchain.surface.window.get(); 617 uint32_t image_idx = present_info->imageIndices[sc]; 618 Swapchain::Image& img = swapchain.images[image_idx]; 619 VkResult result; 620 int err; 621 622 int fence = -1; 623 if (driver_vtbl.QueueSignalReleaseImageANDROID) { 624 result = driver_vtbl.QueueSignalReleaseImageANDROID( 625 queue, img.image, &fence); 626 } else { 627 ALOG_ASSERT(driver_vtbl.QueueSignalNativeFenceANDROID, 628 "Have neither vkQueueSignalReleaseImageANDROID nor " 629 "vkQueueSignalNativeFenceANDROID"); 630 result = driver_vtbl.QueueSignalNativeFenceANDROID(queue, &fence); 631 } 632 if (result != VK_SUCCESS) { 633 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result); 634 if (final_result == VK_SUCCESS) 635 final_result = result; 636 // TODO(jessehall): What happens to the buffer here? Does the app 637 // still own it or not, i.e. should we cancel the buffer? Hard to 638 // do correctly without synchronizing, though I guess we could wait 639 // for the queue to idle. 640 continue; 641 } 642 643 err = window->queueBuffer(window, img.buffer.get(), fence); 644 if (err != 0) { 645 // TODO(jessehall): What now? We should probably cancel the buffer, 646 // I guess? 647 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err); 648 if (final_result == VK_SUCCESS) 649 final_result = VK_ERROR_INITIALIZATION_FAILED; 650 continue; 651 } 652 653 if (img.dequeue_fence != -1) { 654 close(img.dequeue_fence); 655 img.dequeue_fence = -1; 656 } 657 img.dequeued = false; 658 } 659 660 return final_result; 661} 662 663} // namespace vulkan 664