swapchain.cpp revision 178b69664a5f56470c143b5930162f285adc83fa
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#include <algorithm> 18#include <memory> 19 20#include <gui/BufferQueue.h> 21#include <log/log.h> 22#include <sync/sync.h> 23 24#include "loader.h" 25 26using namespace vulkan; 27 28// TODO(jessehall): Currently we don't have a good error code for when a native 29// window operation fails. Just returning INITIALIZATION_FAILED for now. Later 30// versions (post SDK 0.9) of the API/extension have a better error code. 31// When updating to that version, audit all error returns. 32 33namespace { 34 35// ---------------------------------------------------------------------------- 36// These functions/classes form an adaptor that allows objects to be refcounted 37// by both android::sp<> and std::shared_ptr<> simultaneously, and delegates 38// allocation of the shared_ptr<> control structure to VkAllocationCallbacks. 39// The 40// platform holds a reference to the ANativeWindow using its embedded reference 41// count, and the ANativeWindow implementation holds references to the 42// ANativeWindowBuffers using their embedded reference counts, so the 43// shared_ptr *must* cooperate with these and hold at least one reference to 44// the object using the embedded reference count. 45 46template <typename T> 47struct NativeBaseDeleter { 48 void operator()(T* obj) { obj->common.decRef(&obj->common); } 49}; 50 51template <typename Host> 52struct AllocScope {}; 53 54template <> 55struct AllocScope<VkInstance> { 56 static const VkSystemAllocationScope kScope = 57 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE; 58}; 59 60template <> 61struct AllocScope<VkDevice> { 62 static const VkSystemAllocationScope kScope = 63 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE; 64}; 65 66template <typename T> 67class VulkanAllocator { 68 public: 69 typedef T value_type; 70 71 VulkanAllocator(const VkAllocationCallbacks& allocator, 72 VkSystemAllocationScope scope) 73 : allocator_(allocator), scope_(scope) {} 74 75 template <typename U> 76 explicit VulkanAllocator(const VulkanAllocator<U>& other) 77 : allocator_(other.allocator_), scope_(other.scope_) {} 78 79 T* allocate(size_t n) const { 80 T* p = static_cast<T*>(allocator_.pfnAllocation( 81 allocator_.pUserData, n * sizeof(T), alignof(T), scope_)); 82 if (!p) 83 throw std::bad_alloc(); 84 return p; 85 } 86 void deallocate(T* p, size_t) const noexcept { 87 return allocator_.pfnFree(allocator_.pUserData, p); 88 } 89 90 private: 91 template <typename U> 92 friend class VulkanAllocator; 93 const VkAllocationCallbacks& allocator_; 94 const VkSystemAllocationScope scope_; 95}; 96 97template <typename T, typename Host> 98std::shared_ptr<T> InitSharedPtr(Host host, T* obj) { 99 try { 100 obj->common.incRef(&obj->common); 101 return std::shared_ptr<T>( 102 obj, NativeBaseDeleter<T>(), 103 VulkanAllocator<T>(*GetAllocator(host), AllocScope<Host>::kScope)); 104 } catch (std::bad_alloc&) { 105 obj->common.decRef(&obj->common); 106 return nullptr; 107 } 108} 109 110const VkSurfaceTransformFlagsKHR kSupportedTransforms = 111 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR | 112 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR | 113 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR | 114 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR | 115 // TODO(jessehall): See TODO in TranslateNativeToVulkanTransform. 116 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR | 117 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR | 118 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR | 119 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR | 120 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR; 121 122VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) { 123 // Native and Vulkan transforms are isomorphic, but are represented 124 // differently. Vulkan transforms are built up of an optional horizontal 125 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native 126 // transforms are built up from a horizontal flip, vertical flip, and 127 // 90-degree rotation, all optional but always in that order. 128 129 // TODO(jessehall): For now, only support pure rotations, not 130 // flip or flip-and-rotate, until I have more time to test them and build 131 // sample code. As far as I know we never actually use anything besides 132 // pure rotations anyway. 133 134 switch (native) { 135 case 0: // 0x0 136 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; 137 // case NATIVE_WINDOW_TRANSFORM_FLIP_H: // 0x1 138 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR; 139 // case NATIVE_WINDOW_TRANSFORM_FLIP_V: // 0x2 140 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR; 141 case NATIVE_WINDOW_TRANSFORM_ROT_180: // FLIP_H | FLIP_V 142 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR; 143 case NATIVE_WINDOW_TRANSFORM_ROT_90: // 0x4 144 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR; 145 // case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90: 146 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR; 147 // case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90: 148 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR; 149 case NATIVE_WINDOW_TRANSFORM_ROT_270: // FLIP_H | FLIP_V | ROT_90 150 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR; 151 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY: 152 default: 153 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; 154 } 155} 156 157int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) { 158 switch (transform) { 159 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR: 160 return NATIVE_WINDOW_TRANSFORM_ROT_270; 161 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR: 162 return NATIVE_WINDOW_TRANSFORM_ROT_180; 163 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR: 164 return NATIVE_WINDOW_TRANSFORM_ROT_90; 165 // TODO(jessehall): See TODO in TranslateNativeToVulkanTransform. 166 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR: 167 // return NATIVE_WINDOW_TRANSFORM_FLIP_H; 168 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR: 169 // return NATIVE_WINDOW_TRANSFORM_FLIP_H | 170 // NATIVE_WINDOW_TRANSFORM_ROT_90; 171 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR: 172 // return NATIVE_WINDOW_TRANSFORM_FLIP_V; 173 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR: 174 // return NATIVE_WINDOW_TRANSFORM_FLIP_V | 175 // NATIVE_WINDOW_TRANSFORM_ROT_90; 176 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR: 177 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR: 178 default: 179 return 0; 180 } 181} 182 183// ---------------------------------------------------------------------------- 184 185struct Surface { 186 std::shared_ptr<ANativeWindow> window; 187}; 188 189VkSurfaceKHR HandleFromSurface(Surface* surface) { 190 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface)); 191} 192 193Surface* SurfaceFromHandle(VkSurfaceKHR handle) { 194 return reinterpret_cast<Surface*>(handle); 195} 196 197struct Swapchain { 198 Swapchain(Surface& surface_, uint32_t num_images_) 199 : surface(surface_), num_images(num_images_) {} 200 201 Surface& surface; 202 uint32_t num_images; 203 204 struct Image { 205 Image() : image(VK_NULL_HANDLE), dequeue_fence(-1), dequeued(false) {} 206 VkImage image; 207 std::shared_ptr<ANativeWindowBuffer> buffer; 208 // The fence is only valid when the buffer is dequeued, and should be 209 // -1 any other time. When valid, we own the fd, and must ensure it is 210 // closed: either by closing it explicitly when queueing the buffer, 211 // or by passing ownership e.g. to ANativeWindow::cancelBuffer(). 212 int dequeue_fence; 213 bool dequeued; 214 } images[android::BufferQueue::NUM_BUFFER_SLOTS]; 215}; 216 217VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) { 218 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain)); 219} 220 221Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) { 222 return reinterpret_cast<Swapchain*>(handle); 223} 224 225} // anonymous namespace 226 227namespace vulkan { 228 229VKAPI_ATTR 230VkResult CreateAndroidSurfaceKHR_Bottom( 231 VkInstance instance, 232 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo, 233 const VkAllocationCallbacks* allocator, 234 VkSurfaceKHR* out_surface) { 235 if (!allocator) 236 allocator = GetAllocator(instance); 237 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface), 238 alignof(Surface), 239 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); 240 if (!mem) 241 return VK_ERROR_OUT_OF_HOST_MEMORY; 242 Surface* surface = new (mem) Surface; 243 244 surface->window = InitSharedPtr(instance, pCreateInfo->window); 245 if (!surface->window) { 246 ALOGE("surface creation failed: out of memory"); 247 surface->~Surface(); 248 allocator->pfnFree(allocator->pUserData, surface); 249 return VK_ERROR_OUT_OF_HOST_MEMORY; 250 } 251 252 // TODO(jessehall): Create and use NATIVE_WINDOW_API_VULKAN. 253 int err = 254 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL); 255 if (err != 0) { 256 // TODO(jessehall): Improve error reporting. Can we enumerate possible 257 // errors and translate them to valid Vulkan result codes? 258 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err), 259 err); 260 surface->~Surface(); 261 allocator->pfnFree(allocator->pUserData, surface); 262 return VK_ERROR_INITIALIZATION_FAILED; 263 } 264 265 *out_surface = HandleFromSurface(surface); 266 return VK_SUCCESS; 267} 268 269VKAPI_ATTR 270void DestroySurfaceKHR_Bottom(VkInstance instance, 271 VkSurfaceKHR surface_handle, 272 const VkAllocationCallbacks* allocator) { 273 Surface* surface = SurfaceFromHandle(surface_handle); 274 if (!surface) 275 return; 276 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL); 277 surface->~Surface(); 278 if (!allocator) 279 allocator = GetAllocator(instance); 280 allocator->pfnFree(allocator->pUserData, surface); 281} 282 283VKAPI_ATTR 284VkResult GetPhysicalDeviceSurfaceSupportKHR_Bottom(VkPhysicalDevice /*pdev*/, 285 uint32_t /*queue_family*/, 286 VkSurfaceKHR /*surface*/, 287 VkBool32* supported) { 288 *supported = VK_TRUE; 289 return VK_SUCCESS; 290} 291 292VKAPI_ATTR 293VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR_Bottom( 294 VkPhysicalDevice /*pdev*/, 295 VkSurfaceKHR surface, 296 VkSurfaceCapabilitiesKHR* capabilities) { 297 int err; 298 ANativeWindow* window = SurfaceFromHandle(surface)->window.get(); 299 300 int width, height; 301 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width); 302 if (err != 0) { 303 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)", 304 strerror(-err), err); 305 return VK_ERROR_INITIALIZATION_FAILED; 306 } 307 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height); 308 if (err != 0) { 309 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)", 310 strerror(-err), err); 311 return VK_ERROR_INITIALIZATION_FAILED; 312 } 313 314 int transform_hint; 315 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint); 316 if (err != 0) { 317 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)", 318 strerror(-err), err); 319 return VK_ERROR_INITIALIZATION_FAILED; 320 } 321 322 // TODO(jessehall): Figure out what the min/max values should be. 323 capabilities->minImageCount = 2; 324 capabilities->maxImageCount = 3; 325 326 capabilities->currentExtent = 327 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)}; 328 329 // TODO(jessehall): Figure out what the max extent should be. Maximum 330 // texture dimension maybe? 331 capabilities->minImageExtent = VkExtent2D{1, 1}; 332 capabilities->maxImageExtent = VkExtent2D{4096, 4096}; 333 334 capabilities->maxImageArrayLayers = 1; 335 336 capabilities->supportedTransforms = kSupportedTransforms; 337 capabilities->currentTransform = 338 TranslateNativeToVulkanTransform(transform_hint); 339 340 // On Android, window composition is a WindowManager property, not something 341 // associated with the bufferqueue. It can't be changed from here. 342 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR; 343 344 // TODO(jessehall): I think these are right, but haven't thought hard about 345 // it. Do we need to query the driver for support of any of these? 346 // Currently not included: 347 // - VK_IMAGE_USAGE_GENERAL: maybe? does this imply cpu mappable? 348 // - VK_IMAGE_USAGE_DEPTH_STENCIL_BIT: definitely not 349 // - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT: definitely not 350 capabilities->supportedUsageFlags = 351 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | 352 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | 353 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | 354 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; 355 356 return VK_SUCCESS; 357} 358 359VKAPI_ATTR 360VkResult GetPhysicalDeviceSurfaceFormatsKHR_Bottom( 361 VkPhysicalDevice /*pdev*/, 362 VkSurfaceKHR /*surface*/, 363 uint32_t* count, 364 VkSurfaceFormatKHR* formats) { 365 // TODO(jessehall): Fill out the set of supported formats. Longer term, add 366 // a new gralloc method to query whether a (format, usage) pair is 367 // supported, and check that for each gralloc format that corresponds to a 368 // Vulkan format. Shorter term, just add a few more formats to the ones 369 // hardcoded below. 370 371 const VkSurfaceFormatKHR kFormats[] = { 372 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLORSPACE_SRGB_NONLINEAR_KHR}, 373 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLORSPACE_SRGB_NONLINEAR_KHR}, 374 {VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLORSPACE_SRGB_NONLINEAR_KHR}, 375 }; 376 const uint32_t kNumFormats = sizeof(kFormats) / sizeof(kFormats[0]); 377 378 VkResult result = VK_SUCCESS; 379 if (formats) { 380 if (*count < kNumFormats) 381 result = VK_INCOMPLETE; 382 std::copy(kFormats, kFormats + std::min(*count, kNumFormats), formats); 383 } 384 *count = kNumFormats; 385 return result; 386} 387 388VKAPI_ATTR 389VkResult GetPhysicalDeviceSurfacePresentModesKHR_Bottom( 390 VkPhysicalDevice /*pdev*/, 391 VkSurfaceKHR /*surface*/, 392 uint32_t* count, 393 VkPresentModeKHR* modes) { 394 const VkPresentModeKHR kModes[] = { 395 VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR, 396 }; 397 const uint32_t kNumModes = sizeof(kModes) / sizeof(kModes[0]); 398 399 VkResult result = VK_SUCCESS; 400 if (modes) { 401 if (*count < kNumModes) 402 result = VK_INCOMPLETE; 403 std::copy(kModes, kModes + std::min(*count, kNumModes), modes); 404 } 405 *count = kNumModes; 406 return result; 407} 408 409VKAPI_ATTR 410VkResult CreateSwapchainKHR_Bottom(VkDevice device, 411 const VkSwapchainCreateInfoKHR* create_info, 412 const VkAllocationCallbacks* allocator, 413 VkSwapchainKHR* swapchain_handle) { 414 int err; 415 VkResult result = VK_SUCCESS; 416 417 if (!allocator) 418 allocator = GetAllocator(device); 419 420 ALOGV_IF(create_info->imageArrayLayers != 1, 421 "Swapchain imageArrayLayers (%u) != 1 not supported", 422 create_info->imageArrayLayers); 423 424 ALOGE_IF(create_info->imageColorSpace != VK_COLORSPACE_SRGB_NONLINEAR_KHR, 425 "color spaces other than SRGB_NONLINEAR not yet implemented"); 426 ALOGE_IF(create_info->oldSwapchain, 427 "swapchain re-creation not yet implemented"); 428 ALOGE_IF((create_info->preTransform & ~kSupportedTransforms) != 0, 429 "swapchain preTransform %d not supported", 430 create_info->preTransform); 431 ALOGW_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR || 432 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR), 433 "swapchain present mode %d not supported", 434 create_info->presentMode); 435 436 // -- Configure the native window -- 437 438 Surface& surface = *SurfaceFromHandle(create_info->surface); 439 const DriverDispatchTable& dispatch = GetDriverDispatch(device); 440 441 int native_format = HAL_PIXEL_FORMAT_RGBA_8888; 442 switch (create_info->imageFormat) { 443 case VK_FORMAT_R8G8B8A8_UNORM: 444 case VK_FORMAT_R8G8B8A8_SRGB: 445 native_format = HAL_PIXEL_FORMAT_RGBA_8888; 446 break; 447 case VK_FORMAT_R5G6B5_UNORM_PACK16: 448 native_format = HAL_PIXEL_FORMAT_RGB_565; 449 break; 450 default: 451 ALOGE("unsupported swapchain format %d", create_info->imageFormat); 452 break; 453 } 454 err = native_window_set_buffers_format(surface.window.get(), native_format); 455 if (err != 0) { 456 // TODO(jessehall): Improve error reporting. Can we enumerate possible 457 // errors and translate them to valid Vulkan result codes? 458 ALOGE("native_window_set_buffers_format(%d) failed: %s (%d)", 459 native_format, strerror(-err), err); 460 return VK_ERROR_INITIALIZATION_FAILED; 461 } 462 err = native_window_set_buffers_data_space(surface.window.get(), 463 HAL_DATASPACE_SRGB_LINEAR); 464 if (err != 0) { 465 // TODO(jessehall): Improve error reporting. Can we enumerate possible 466 // errors and translate them to valid Vulkan result codes? 467 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)", 468 HAL_DATASPACE_SRGB_LINEAR, strerror(-err), err); 469 return VK_ERROR_INITIALIZATION_FAILED; 470 } 471 472 err = native_window_set_buffers_dimensions( 473 surface.window.get(), static_cast<int>(create_info->imageExtent.width), 474 static_cast<int>(create_info->imageExtent.height)); 475 if (err != 0) { 476 // TODO(jessehall): Improve error reporting. Can we enumerate possible 477 // errors and translate them to valid Vulkan result codes? 478 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)", 479 create_info->imageExtent.width, create_info->imageExtent.height, 480 strerror(-err), err); 481 return VK_ERROR_INITIALIZATION_FAILED; 482 } 483 484 // VkSwapchainCreateInfo::preTransform indicates the transformation the app 485 // applied during rendering. native_window_set_transform() expects the 486 // inverse: the transform the app is requesting that the compositor perform 487 // during composition. With native windows, pre-transform works by rendering 488 // with the same transform the compositor is applying (as in Vulkan), but 489 // then requesting the inverse transform, so that when the compositor does 490 // it's job the two transforms cancel each other out and the compositor ends 491 // up applying an identity transform to the app's buffer. 492 err = native_window_set_buffers_transform( 493 surface.window.get(), 494 InvertTransformToNative(create_info->preTransform)); 495 if (err != 0) { 496 // TODO(jessehall): Improve error reporting. Can we enumerate possible 497 // errors and translate them to valid Vulkan result codes? 498 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)", 499 InvertTransformToNative(create_info->preTransform), 500 strerror(-err), err); 501 return VK_ERROR_INITIALIZATION_FAILED; 502 } 503 504 err = native_window_set_scaling_mode( 505 surface.window.get(), NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW); 506 if (err != 0) { 507 // TODO(jessehall): Improve error reporting. Can we enumerate possible 508 // errors and translate them to valid Vulkan result codes? 509 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)", 510 strerror(-err), err); 511 return VK_ERROR_INITIALIZATION_FAILED; 512 } 513 514 uint32_t min_undequeued_buffers; 515 err = surface.window->query( 516 surface.window.get(), NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, 517 reinterpret_cast<int*>(&min_undequeued_buffers)); 518 if (err != 0) { 519 // TODO(jessehall): Improve error reporting. Can we enumerate possible 520 // errors and translate them to valid Vulkan result codes? 521 ALOGE("window->query failed: %s (%d)", strerror(-err), err); 522 return VK_ERROR_INITIALIZATION_FAILED; 523 } 524 // The MIN_UNDEQUEUED_BUFFERS query doesn't know whether we'll be using 525 // async mode or not, and assumes not. But in async mode, the BufferQueue 526 // requires an extra undequeued buffer. 527 // See BufferQueueCore::getMinUndequeuedBufferCountLocked(). 528 if (create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR) 529 min_undequeued_buffers += 1; 530 531 uint32_t num_images = 532 (create_info->minImageCount - 1) + min_undequeued_buffers; 533 err = native_window_set_buffer_count(surface.window.get(), num_images); 534 if (err != 0) { 535 // TODO(jessehall): Improve error reporting. Can we enumerate possible 536 // errors and translate them to valid Vulkan result codes? 537 ALOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err), 538 err); 539 return VK_ERROR_INITIALIZATION_FAILED; 540 } 541 542 int gralloc_usage = 0; 543 // TODO(jessehall): Remove conditional once all drivers have been updated 544 if (dispatch.GetSwapchainGrallocUsageANDROID) { 545 result = dispatch.GetSwapchainGrallocUsageANDROID( 546 device, create_info->imageFormat, create_info->imageUsage, 547 &gralloc_usage); 548 if (result != VK_SUCCESS) { 549 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result); 550 return VK_ERROR_INITIALIZATION_FAILED; 551 } 552 } else { 553 gralloc_usage = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE; 554 } 555 err = native_window_set_usage(surface.window.get(), gralloc_usage); 556 if (err != 0) { 557 // TODO(jessehall): Improve error reporting. Can we enumerate possible 558 // errors and translate them to valid Vulkan result codes? 559 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err); 560 return VK_ERROR_INITIALIZATION_FAILED; 561 } 562 563 err = surface.window->setSwapInterval( 564 surface.window.get(), 565 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1); 566 if (err != 0) { 567 // TODO(jessehall): Improve error reporting. Can we enumerate possible 568 // errors and translate them to valid Vulkan result codes? 569 ALOGE("native_window->setSwapInterval failed: %s (%d)", strerror(-err), 570 err); 571 return VK_ERROR_INITIALIZATION_FAILED; 572 } 573 574 // -- Allocate our Swapchain object -- 575 // After this point, we must deallocate the swapchain on error. 576 577 void* mem = allocator->pfnAllocation(allocator->pUserData, 578 sizeof(Swapchain), alignof(Swapchain), 579 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); 580 if (!mem) 581 return VK_ERROR_OUT_OF_HOST_MEMORY; 582 Swapchain* swapchain = new (mem) Swapchain(surface, num_images); 583 584 // -- Dequeue all buffers and create a VkImage for each -- 585 // Any failures during or after this must cancel the dequeued buffers. 586 587 VkNativeBufferANDROID image_native_buffer = { 588#pragma clang diagnostic push 589#pragma clang diagnostic ignored "-Wold-style-cast" 590 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID, 591#pragma clang diagnostic pop 592 .pNext = nullptr, 593 }; 594 VkImageCreateInfo image_create = { 595 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, 596 .pNext = &image_native_buffer, 597 .imageType = VK_IMAGE_TYPE_2D, 598 .format = create_info->imageFormat, 599 .extent = {0, 0, 1}, 600 .mipLevels = 1, 601 .arrayLayers = 1, 602 .samples = VK_SAMPLE_COUNT_1_BIT, 603 .tiling = VK_IMAGE_TILING_OPTIMAL, 604 .usage = create_info->imageUsage, 605 .flags = 0, 606 .sharingMode = create_info->imageSharingMode, 607 .queueFamilyIndexCount = create_info->queueFamilyIndexCount, 608 .pQueueFamilyIndices = create_info->pQueueFamilyIndices, 609 }; 610 611 for (uint32_t i = 0; i < num_images; i++) { 612 Swapchain::Image& img = swapchain->images[i]; 613 614 ANativeWindowBuffer* buffer; 615 err = surface.window->dequeueBuffer(surface.window.get(), &buffer, 616 &img.dequeue_fence); 617 if (err != 0) { 618 // TODO(jessehall): Improve error reporting. Can we enumerate 619 // possible errors and translate them to valid Vulkan result codes? 620 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err); 621 result = VK_ERROR_INITIALIZATION_FAILED; 622 break; 623 } 624 img.buffer = InitSharedPtr(device, buffer); 625 if (!img.buffer) { 626 ALOGE("swapchain creation failed: out of memory"); 627 surface.window->cancelBuffer(surface.window.get(), buffer, 628 img.dequeue_fence); 629 result = VK_ERROR_OUT_OF_HOST_MEMORY; 630 break; 631 } 632 img.dequeued = true; 633 634 image_create.extent = 635 VkExtent3D{static_cast<uint32_t>(img.buffer->width), 636 static_cast<uint32_t>(img.buffer->height), 637 1}; 638 image_native_buffer.handle = img.buffer->handle; 639 image_native_buffer.stride = img.buffer->stride; 640 image_native_buffer.format = img.buffer->format; 641 image_native_buffer.usage = img.buffer->usage; 642 643 result = 644 dispatch.CreateImage(device, &image_create, nullptr, &img.image); 645 if (result != VK_SUCCESS) { 646 ALOGD("vkCreateImage w/ native buffer failed: %u", result); 647 break; 648 } 649 } 650 651 // -- Cancel all buffers, returning them to the queue -- 652 // If an error occurred before, also destroy the VkImage and release the 653 // buffer reference. Otherwise, we retain a strong reference to the buffer. 654 // 655 // TODO(jessehall): The error path here is the same as DestroySwapchain, 656 // but not the non-error path. Should refactor/unify. 657 for (uint32_t i = 0; i < num_images; i++) { 658 Swapchain::Image& img = swapchain->images[i]; 659 if (img.dequeued) { 660 surface.window->cancelBuffer(surface.window.get(), img.buffer.get(), 661 img.dequeue_fence); 662 img.dequeue_fence = -1; 663 img.dequeued = false; 664 } 665 if (result != VK_SUCCESS) { 666 if (img.image) 667 dispatch.DestroyImage(device, img.image, nullptr); 668 } 669 } 670 671 if (result != VK_SUCCESS) { 672 swapchain->~Swapchain(); 673 allocator->pfnFree(allocator->pUserData, swapchain); 674 return result; 675 } 676 677 *swapchain_handle = HandleFromSwapchain(swapchain); 678 return VK_SUCCESS; 679} 680 681VKAPI_ATTR 682void DestroySwapchainKHR_Bottom(VkDevice device, 683 VkSwapchainKHR swapchain_handle, 684 const VkAllocationCallbacks* allocator) { 685 const DriverDispatchTable& dispatch = GetDriverDispatch(device); 686 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle); 687 const std::shared_ptr<ANativeWindow>& window = swapchain->surface.window; 688 689 for (uint32_t i = 0; i < swapchain->num_images; i++) { 690 Swapchain::Image& img = swapchain->images[i]; 691 if (img.dequeued) { 692 window->cancelBuffer(window.get(), img.buffer.get(), 693 img.dequeue_fence); 694 img.dequeue_fence = -1; 695 img.dequeued = false; 696 } 697 if (img.image) { 698 dispatch.DestroyImage(device, img.image, nullptr); 699 } 700 } 701 702 if (!allocator) 703 allocator = GetAllocator(device); 704 swapchain->~Swapchain(); 705 allocator->pfnFree(allocator->pUserData, swapchain); 706} 707 708VKAPI_ATTR 709VkResult GetSwapchainImagesKHR_Bottom(VkDevice, 710 VkSwapchainKHR swapchain_handle, 711 uint32_t* count, 712 VkImage* images) { 713 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle); 714 VkResult result = VK_SUCCESS; 715 if (images) { 716 uint32_t n = swapchain.num_images; 717 if (*count < swapchain.num_images) { 718 n = *count; 719 result = VK_INCOMPLETE; 720 } 721 for (uint32_t i = 0; i < n; i++) 722 images[i] = swapchain.images[i].image; 723 } 724 *count = swapchain.num_images; 725 return result; 726} 727 728VKAPI_ATTR 729VkResult AcquireNextImageKHR_Bottom(VkDevice device, 730 VkSwapchainKHR swapchain_handle, 731 uint64_t timeout, 732 VkSemaphore semaphore, 733 VkFence vk_fence, 734 uint32_t* image_index) { 735 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle); 736 ANativeWindow* window = swapchain.surface.window.get(); 737 VkResult result; 738 int err; 739 740 ALOGW_IF( 741 timeout != UINT64_MAX, 742 "vkAcquireNextImageKHR: non-infinite timeouts not yet implemented"); 743 744 ANativeWindowBuffer* buffer; 745 int fence_fd; 746 err = window->dequeueBuffer(window, &buffer, &fence_fd); 747 if (err != 0) { 748 // TODO(jessehall): Improve error reporting. Can we enumerate possible 749 // errors and translate them to valid Vulkan result codes? 750 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err); 751 return VK_ERROR_INITIALIZATION_FAILED; 752 } 753 754 uint32_t idx; 755 for (idx = 0; idx < swapchain.num_images; idx++) { 756 if (swapchain.images[idx].buffer.get() == buffer) { 757 swapchain.images[idx].dequeued = true; 758 swapchain.images[idx].dequeue_fence = fence_fd; 759 break; 760 } 761 } 762 if (idx == swapchain.num_images) { 763 ALOGE("dequeueBuffer returned unrecognized buffer"); 764 window->cancelBuffer(window, buffer, fence_fd); 765 return VK_ERROR_OUT_OF_DATE_KHR; 766 } 767 768 int fence_clone = -1; 769 if (fence_fd != -1) { 770 fence_clone = dup(fence_fd); 771 if (fence_clone == -1) { 772 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)", 773 strerror(errno), errno); 774 sync_wait(fence_fd, -1 /* forever */); 775 } 776 } 777 778 result = GetDriverDispatch(device).AcquireImageANDROID( 779 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence); 780 if (result != VK_SUCCESS) { 781 // NOTE: we're relying on AcquireImageANDROID to close fence_clone, 782 // even if the call fails. We could close it ourselves on failure, but 783 // that would create a race condition if the driver closes it on a 784 // failure path: some other thread might create an fd with the same 785 // number between the time the driver closes it and the time we close 786 // it. We must assume one of: the driver *always* closes it even on 787 // failure, or *never* closes it on failure. 788 window->cancelBuffer(window, buffer, fence_fd); 789 swapchain.images[idx].dequeued = false; 790 swapchain.images[idx].dequeue_fence = -1; 791 return result; 792 } 793 794 *image_index = idx; 795 return VK_SUCCESS; 796} 797 798VKAPI_ATTR 799VkResult QueuePresentKHR_Bottom(VkQueue queue, 800 const VkPresentInfoKHR* present_info) { 801 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, 802 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d", 803 present_info->sType); 804 ALOGV_IF(present_info->pNext, "VkPresentInfo::pNext != NULL"); 805 806 const DriverDispatchTable& dispatch = GetDriverDispatch(queue); 807 VkResult final_result = VK_SUCCESS; 808 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) { 809 Swapchain& swapchain = 810 *SwapchainFromHandle(present_info->pSwapchains[sc]); 811 ANativeWindow* window = swapchain.surface.window.get(); 812 uint32_t image_idx = present_info->pImageIndices[sc]; 813 Swapchain::Image& img = swapchain.images[image_idx]; 814 VkResult result; 815 int err; 816 817 int fence = -1; 818 result = dispatch.QueueSignalReleaseImageANDROID( 819 queue, present_info->waitSemaphoreCount, 820 present_info->pWaitSemaphores, img.image, &fence); 821 if (result != VK_SUCCESS) { 822 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result); 823 if (present_info->pResults) 824 present_info->pResults[sc] = result; 825 if (final_result == VK_SUCCESS) 826 final_result = result; 827 // TODO(jessehall): What happens to the buffer here? Does the app 828 // still own it or not, i.e. should we cancel the buffer? Hard to 829 // do correctly without synchronizing, though I guess we could wait 830 // for the queue to idle. 831 continue; 832 } 833 834 err = window->queueBuffer(window, img.buffer.get(), fence); 835 if (err != 0) { 836 // TODO(jessehall): What now? We should probably cancel the buffer, 837 // I guess? 838 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err); 839 if (present_info->pResults) 840 present_info->pResults[sc] = result; 841 if (final_result == VK_SUCCESS) 842 final_result = VK_ERROR_INITIALIZATION_FAILED; 843 continue; 844 } 845 846 if (img.dequeue_fence != -1) { 847 close(img.dequeue_fence); 848 img.dequeue_fence = -1; 849 } 850 img.dequeued = false; 851 852 if (present_info->pResults) 853 present_info->pResults[sc] = VK_SUCCESS; 854 } 855 856 return final_result; 857} 858 859} // namespace vulkan 860