blob: 5b35506b5450481084e6d45d9ea1fa6e61eecf3e [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
Jesse Hall3fbc8562015-11-29 22:10:52 -080040// allocation of the shared_ptr<> control structure to VkAllocationCallbacks.
41// The
Jesse Halld7b994a2015-09-07 14:17:37 -070042// 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
Jesse Hall03b6fe12015-11-24 12:44:21 -080053template <typename Host>
54struct AllocScope {};
55
56template <>
57struct AllocScope<VkInstance> {
Jesse Hall3fbc8562015-11-29 22:10:52 -080058 static const VkSystemAllocationScope kScope =
59 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE;
Jesse Hall03b6fe12015-11-24 12:44:21 -080060};
61
62template <>
63struct AllocScope<VkDevice> {
Jesse Hall3fbc8562015-11-29 22:10:52 -080064 static const VkSystemAllocationScope kScope =
65 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE;
Jesse Hall03b6fe12015-11-24 12:44:21 -080066};
67
Jesse Hall1356b0d2015-11-23 17:24:58 -080068template <typename T, typename Host>
Jesse Halld7b994a2015-09-07 14:17:37 -070069class VulkanAllocator {
70 public:
71 typedef T value_type;
72
Jesse Hall1356b0d2015-11-23 17:24:58 -080073 explicit VulkanAllocator(Host host) : host_(host) {}
Jesse Halld7b994a2015-09-07 14:17:37 -070074
75 template <typename U>
Jesse Hall1356b0d2015-11-23 17:24:58 -080076 explicit VulkanAllocator(const VulkanAllocator<U, Host>& other)
77 : host_(other.host_) {}
Jesse Halld7b994a2015-09-07 14:17:37 -070078
79 T* allocate(size_t n) const {
Jesse Hall1356b0d2015-11-23 17:24:58 -080080 return static_cast<T*>(AllocMem(host_, n * sizeof(T), alignof(T),
Jesse Hall03b6fe12015-11-24 12:44:21 -080081 AllocScope<Host>::kScope));
Jesse Halld7b994a2015-09-07 14:17:37 -070082 }
Jesse Hall1356b0d2015-11-23 17:24:58 -080083 void deallocate(T* p, size_t) const { return FreeMem(host_, p); }
Jesse Halld7b994a2015-09-07 14:17:37 -070084
85 private:
Jesse Hall1356b0d2015-11-23 17:24:58 -080086 template <typename U, typename H>
Jesse Halld7b994a2015-09-07 14:17:37 -070087 friend class VulkanAllocator;
Jesse Hall1356b0d2015-11-23 17:24:58 -080088 Host host_;
Jesse Halld7b994a2015-09-07 14:17:37 -070089};
90
Jesse Hall1356b0d2015-11-23 17:24:58 -080091template <typename T, typename Host>
92std::shared_ptr<T> InitSharedPtr(Host host, T* obj) {
Jesse Halld7b994a2015-09-07 14:17:37 -070093 obj->common.incRef(&obj->common);
94 return std::shared_ptr<T>(obj, NativeBaseDeleter<T>(),
Jesse Hall1356b0d2015-11-23 17:24:58 -080095 VulkanAllocator<T, Host>(host));
Jesse Halld7b994a2015-09-07 14:17:37 -070096}
97
98// ----------------------------------------------------------------------------
99
Jesse Hall1356b0d2015-11-23 17:24:58 -0800100struct Surface {
Jesse Halld7b994a2015-09-07 14:17:37 -0700101 std::shared_ptr<ANativeWindow> window;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800102};
103
104VkSurfaceKHR HandleFromSurface(Surface* surface) {
105 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
106}
107
108Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800109 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800110}
111
112struct Swapchain {
113 Swapchain(Surface& surface_, uint32_t num_images_)
114 : surface(surface_), num_images(num_images_) {}
115
116 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700117 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) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800137 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700138}
139
140} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700141
142namespace vulkan {
143
Jesse Hall1356b0d2015-11-23 17:24:58 -0800144VkResult CreateAndroidSurfaceKHR(VkInstance instance,
145 ANativeWindow* window,
146 VkSurfaceKHR* out_surface) {
147 void* mem = AllocMem(instance, sizeof(Surface), alignof(Surface),
Jesse Hall3fbc8562015-11-29 22:10:52 -0800148 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800149 if (!mem)
150 return VK_ERROR_OUT_OF_HOST_MEMORY;
151 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700152
Jesse Hall1356b0d2015-11-23 17:24:58 -0800153 surface->window = InitSharedPtr(instance, window);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700154
Jesse Hall1356b0d2015-11-23 17:24:58 -0800155 // 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 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700167
Jesse Hall1356b0d2015-11-23 17:24:58 -0800168 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700169 return VK_SUCCESS;
170}
171
Jesse Hall1356b0d2015-11-23 17:24:58 -0800172void 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
Jesse Halla6429252015-11-29 18:59:42 -0800181VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
Jesse Hall1356b0d2015-11-23 17:24:58 -0800182 uint32_t /*queue_family*/,
Jesse Hallb00daad2015-11-29 19:46:20 -0800183 VkSurfaceKHR /*surface*/,
184 VkBool32* pSupported) {
185 *pSupported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800186 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800187}
188
Jesse Hallb00daad2015-11-29 19:46:20 -0800189VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
190 VkPhysicalDevice /*pdev*/,
191 VkSurfaceKHR surface,
192 VkSurfaceCapabilitiesKHR* capabilities) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700193 int err;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800194 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700195
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);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700201 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700202 }
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);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700207 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700208 }
209
Jesse Hallb00daad2015-11-29 19:46:20 -0800210 capabilities->currentExtent = VkExtent2D{width, height};
Jesse Halld7b994a2015-09-07 14:17:37 -0700211
212 // TODO(jessehall): Figure out what the min/max values should be.
Jesse Hallb00daad2015-11-29 19:46:20 -0800213 capabilities->minImageCount = 2;
214 capabilities->maxImageCount = 3;
Jesse Halld7b994a2015-09-07 14:17:37 -0700215
216 // TODO(jessehall): Figure out what the max extent should be. Maximum
217 // texture dimension maybe?
Jesse Hallb00daad2015-11-29 19:46:20 -0800218 capabilities->minImageExtent = VkExtent2D{1, 1};
219 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
Jesse Halld7b994a2015-09-07 14:17:37 -0700220
221 // TODO(jessehall): We can support all transforms, fix this once
222 // implemented.
Jesse Hallb00daad2015-11-29 19:46:20 -0800223 capabilities->supportedTransforms = VK_SURFACE_TRANSFORM_NONE_BIT_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -0700224
225 // TODO(jessehall): Implement based on NATIVE_WINDOW_TRANSFORM_HINT.
Jesse Hallb00daad2015-11-29 19:46:20 -0800226 capabilities->currentTransform = VK_SURFACE_TRANSFORM_NONE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -0700227
Jesse Hallb00daad2015-11-29 19:46:20 -0800228 capabilities->maxImageArraySize = 1;
Jesse Halld7b994a2015-09-07 14:17:37 -0700229
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
Jesse Hallb00daad2015-11-29 19:46:20 -0800236 capabilities->supportedUsageFlags =
Jesse Hall3fbc8562015-11-29 22:10:52 -0800237 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 |
Jesse Halld7b994a2015-09-07 14:17:37 -0700240 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
241
Jesse Hallb1352bc2015-09-04 16:12:33 -0700242 return VK_SUCCESS;
243}
244
Jesse Hallb00daad2015-11-29 19:46:20 -0800245VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice /*pdev*/,
246 VkSurfaceKHR /*surface*/,
247 uint32_t* count,
248 VkSurfaceFormatKHR* formats) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800249 // 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.
Jesse Halld7b994a2015-09-07 14:17:37 -0700254
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;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700269}
270
Jesse Hallb00daad2015-11-29 19:46:20 -0800271VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice /*pdev*/,
272 VkSurfaceKHR /*surface*/,
273 uint32_t* count,
274 VkPresentModeKHR* modes) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700275 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;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700288}
289
290VkResult CreateSwapchainKHR(VkDevice device,
291 const VkSwapchainCreateInfoKHR* create_info,
Jesse Halld7b994a2015-09-07 14:17:37 -0700292 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 --
Jesse Halld7b994a2015-09-07 14:17:37 -0700312
Jesse Hall1356b0d2015-11-23 17:24:58 -0800313 Surface& surface = *SurfaceFromHandle(create_info->surface);
Jesse Hall70f93352015-11-04 09:41:31 -0800314 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device);
315
Jesse Hall1356b0d2015-11-23 17:24:58 -0800316 err = native_window_set_buffers_dimensions(surface.window.get(),
Jesse Halld7b994a2015-09-07 14:17:37 -0700317 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);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700325 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700326 }
327
Jesse Hallf64ca122015-11-03 16:11:10 -0800328 err = native_window_set_scaling_mode(
Jesse Hall1356b0d2015-11-23 17:24:58 -0800329 surface.window.get(), NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Jesse Hallf64ca122015-11-03 16:11:10 -0800330 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);
Jesse Hallf64ca122015-11-03 16:11:10 -0800335 return VK_ERROR_INITIALIZATION_FAILED;
336 }
337
Jesse Halld7b994a2015-09-07 14:17:37 -0700338 uint32_t min_undequeued_buffers;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800339 err = surface.window->query(
340 surface.window.get(), NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
341 reinterpret_cast<int*>(&min_undequeued_buffers));
Jesse Halld7b994a2015-09-07 14:17:37 -0700342 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);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700346 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700347 }
348 uint32_t num_images =
349 (create_info->minImageCount - 1) + min_undequeued_buffers;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800350 err = native_window_set_buffer_count(surface.window.get(), num_images);
Jesse Halld7b994a2015-09-07 14:17:37 -0700351 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);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700356 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700357 }
358
Jesse Hall70f93352015-11-04 09:41:31 -0800359 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);
Jesse Hall70f93352015-11-04 09:41:31 -0800367 return VK_ERROR_INITIALIZATION_FAILED;
368 }
369 } else {
370 gralloc_usage = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
371 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800372 err = native_window_set_usage(surface.window.get(), gralloc_usage);
Jesse Hall70f93352015-11-04 09:41:31 -0800373 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);
Jesse Hall70f93352015-11-04 09:41:31 -0800377 return VK_ERROR_INITIALIZATION_FAILED;
378 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700379
380 // -- Allocate our Swapchain object --
381 // After this point, we must deallocate the swapchain on error.
382
Jesse Hall1356b0d2015-11-23 17:24:58 -0800383 void* mem = AllocMem(device, sizeof(Swapchain), alignof(Swapchain),
Jesse Hall3fbc8562015-11-29 22:10:52 -0800384 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800385 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -0700386 return VK_ERROR_OUT_OF_HOST_MEMORY;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800387 Swapchain* swapchain = new (mem) Swapchain(surface, num_images);
Jesse Halld7b994a2015-09-07 14:17:37 -0700388
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,
Jesse Halla15a4bf2015-11-19 22:48:02 -0800407 .arrayLayers = 1,
Jesse Halld7b994a2015-09-07 14:17:37 -0700408 .samples = 1,
409 .tiling = VK_IMAGE_TILING_OPTIMAL,
410 .usage = create_info->imageUsageFlags,
411 .flags = 0,
412 .sharingMode = create_info->sharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -0800413 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -0700414 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
415 };
416
Jesse Halld7b994a2015-09-07 14:17:37 -0700417 for (uint32_t i = 0; i < num_images; i++) {
418 Swapchain::Image& img = swapchain->images[i];
419
420 ANativeWindowBuffer* buffer;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800421 err = surface.window->dequeueBuffer(surface.window.get(), &buffer,
422 &img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700423 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);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700427 result = VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700428 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
Jesse Hall03b6fe12015-11-24 12:44:21 -0800440 result =
441 driver_vtbl.CreateImage(device, &image_create, nullptr, &img.image);
Jesse Halld7b994a2015-09-07 14:17:37 -0700442 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) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800457 surface.window->cancelBuffer(surface.window.get(), img.buffer.get(),
458 img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700459 img.dequeue_fence = -1;
460 img.dequeued = false;
461 }
462 if (result != VK_SUCCESS) {
463 if (img.image)
Jesse Hall03b6fe12015-11-24 12:44:21 -0800464 driver_vtbl.DestroyImage(device, img.image, nullptr);
Jesse Halld7b994a2015-09-07 14:17:37 -0700465 }
466 }
467
468 if (result != VK_SUCCESS) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700469 swapchain->~Swapchain();
Jesse Hall1356b0d2015-11-23 17:24:58 -0800470 FreeMem(device, swapchain);
Jesse Halld7b994a2015-09-07 14:17:37 -0700471 return result;
472 }
473
474 *swapchain_handle = HandleFromSwapchain(swapchain);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700475 return VK_SUCCESS;
476}
477
Jesse Halld7b994a2015-09-07 14:17:37 -0700478VkResult DestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain_handle) {
479 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device);
480 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800481 const std::shared_ptr<ANativeWindow>& window = swapchain->surface.window;
Jesse Halld7b994a2015-09-07 14:17:37 -0700482
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) {
Jesse Hall03b6fe12015-11-24 12:44:21 -0800492 driver_vtbl.DestroyImage(device, img.image, nullptr);
Jesse Halld7b994a2015-09-07 14:17:37 -0700493 }
494 }
495
Jesse Halld7b994a2015-09-07 14:17:37 -0700496 swapchain->~Swapchain();
Jesse Hall1356b0d2015-11-23 17:24:58 -0800497 FreeMem(device, swapchain);
Jesse Halld7b994a2015-09-07 14:17:37 -0700498
Jesse Hallb1352bc2015-09-04 16:12:33 -0700499 return VK_SUCCESS;
500}
501
Jesse Halld7b994a2015-09-07 14:17:37 -0700502VkResult GetSwapchainImagesKHR(VkDevice,
503 VkSwapchainKHR swapchain_handle,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700504 uint32_t* count,
Jesse Halld7b994a2015-09-07 14:17:37 -0700505 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;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700519}
520
521VkResult AcquireNextImageKHR(VkDevice device,
Jesse Halld7b994a2015-09-07 14:17:37 -0700522 VkSwapchainKHR swapchain_handle,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700523 uint64_t timeout,
524 VkSemaphore semaphore,
525 uint32_t* image_index) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700526 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800527 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700528 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;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800537 err = window->dequeueBuffer(window, &buffer, &fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700538 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);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700542 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700543 }
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");
Jesse Hall1356b0d2015-11-23 17:24:58 -0800555 window->cancelBuffer(window, buffer, fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700556#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);
Jesse Hallab9aeef2015-11-04 10:56:20 -0800573 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 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700583 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -0800584 // 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.
Jesse Hall1356b0d2015-11-23 17:24:58 -0800591 window->cancelBuffer(window, buffer, fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700592 swapchain.images[idx].dequeued = false;
593 swapchain.images[idx].dequeue_fence = -1;
594 return result;
595 }
596
597 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700598 return VK_SUCCESS;
599}
600
601VkResult QueuePresentKHR(VkQueue queue, VkPresentInfoKHR* present_info) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700602#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);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700608#pragma clang diagnostic pop
Jesse Halld7b994a2015-09-07 14:17:37 -0700609 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 =
Jesse Hall03b6fe12015-11-24 12:44:21 -0800615 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800616 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700617 uint32_t image_idx = present_info->imageIndices[sc];
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700618 Swapchain::Image& img = swapchain.images[image_idx];
Jesse Halld7b994a2015-09-07 14:17:37 -0700619 VkResult result;
620 int err;
621
Jesse Halld7b994a2015-09-07 14:17:37 -0700622 int fence = -1;
Jesse Hallab9aeef2015-11-04 10:56:20 -0800623 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 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700632 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -0800633 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
Jesse Halld7b994a2015-09-07 14:17:37 -0700634 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
Jesse Hall1356b0d2015-11-23 17:24:58 -0800643 err = window->queueBuffer(window, img.buffer.get(), fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700644 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)
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700649 final_result = VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700650 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}
Jesse Hallb1352bc2015-09-04 16:12:33 -0700662
663} // namespace vulkan