blob: ff02b3512ca2629e5e0a6c148653ede0b513e1ad [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 Halle1b12782015-11-30 11:27:32 -0800144VKAPI_ATTR
Jesse Hall1356b0d2015-11-23 17:24:58 -0800145VkResult CreateAndroidSurfaceKHR(VkInstance instance,
146 ANativeWindow* window,
Jesse Hall0e74f002015-11-30 11:37:59 -0800147 const VkAllocationCallbacks* /*allocator*/,
Jesse Hall1356b0d2015-11-23 17:24:58 -0800148 VkSurfaceKHR* out_surface) {
149 void* mem = AllocMem(instance, sizeof(Surface), alignof(Surface),
Jesse Hall3fbc8562015-11-29 22:10:52 -0800150 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800151 if (!mem)
152 return VK_ERROR_OUT_OF_HOST_MEMORY;
153 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700154
Jesse Hall1356b0d2015-11-23 17:24:58 -0800155 surface->window = InitSharedPtr(instance, window);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700156
Jesse Hall1356b0d2015-11-23 17:24:58 -0800157 // TODO(jessehall): Create and use NATIVE_WINDOW_API_VULKAN.
158 int err =
159 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
160 if (err != 0) {
161 // TODO(jessehall): Improve error reporting. Can we enumerate possible
162 // errors and translate them to valid Vulkan result codes?
163 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
164 err);
165 surface->~Surface();
166 FreeMem(instance, surface);
167 return VK_ERROR_INITIALIZATION_FAILED;
168 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700169
Jesse Hall1356b0d2015-11-23 17:24:58 -0800170 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700171 return VK_SUCCESS;
172}
173
Jesse Halle1b12782015-11-30 11:27:32 -0800174VKAPI_ATTR
Jesse Hall0e74f002015-11-30 11:37:59 -0800175void DestroySurfaceKHR(VkInstance instance,
176 VkSurfaceKHR surface_handle,
177 const VkAllocationCallbacks* /*allocator*/) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800178 Surface* surface = SurfaceFromHandle(surface_handle);
179 if (!surface)
180 return;
181 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
182 surface->~Surface();
183 FreeMem(instance, surface);
184}
185
Jesse Halle1b12782015-11-30 11:27:32 -0800186VKAPI_ATTR
Jesse Halla6429252015-11-29 18:59:42 -0800187VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
Jesse Hall1356b0d2015-11-23 17:24:58 -0800188 uint32_t /*queue_family*/,
Jesse Hallb00daad2015-11-29 19:46:20 -0800189 VkSurfaceKHR /*surface*/,
Jesse Hall0e74f002015-11-30 11:37:59 -0800190 VkBool32* supported) {
191 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800192 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800193}
194
Jesse Halle1b12782015-11-30 11:27:32 -0800195VKAPI_ATTR
Jesse Hallb00daad2015-11-29 19:46:20 -0800196VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
197 VkPhysicalDevice /*pdev*/,
198 VkSurfaceKHR surface,
199 VkSurfaceCapabilitiesKHR* capabilities) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700200 int err;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800201 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700202
203 int width, height;
204 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
205 if (err != 0) {
206 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
207 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700208 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700209 }
210 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
211 if (err != 0) {
212 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
213 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700214 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700215 }
216
Jesse Hallb00daad2015-11-29 19:46:20 -0800217 capabilities->currentExtent = VkExtent2D{width, height};
Jesse Halld7b994a2015-09-07 14:17:37 -0700218
219 // TODO(jessehall): Figure out what the min/max values should be.
Jesse Hallb00daad2015-11-29 19:46:20 -0800220 capabilities->minImageCount = 2;
221 capabilities->maxImageCount = 3;
Jesse Halld7b994a2015-09-07 14:17:37 -0700222
223 // TODO(jessehall): Figure out what the max extent should be. Maximum
224 // texture dimension maybe?
Jesse Hallb00daad2015-11-29 19:46:20 -0800225 capabilities->minImageExtent = VkExtent2D{1, 1};
226 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
Jesse Halld7b994a2015-09-07 14:17:37 -0700227
228 // TODO(jessehall): We can support all transforms, fix this once
229 // implemented.
Jesse Hallb00daad2015-11-29 19:46:20 -0800230 capabilities->supportedTransforms = VK_SURFACE_TRANSFORM_NONE_BIT_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -0700231
232 // TODO(jessehall): Implement based on NATIVE_WINDOW_TRANSFORM_HINT.
Jesse Hallb00daad2015-11-29 19:46:20 -0800233 capabilities->currentTransform = VK_SURFACE_TRANSFORM_NONE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -0700234
Jesse Hallb00daad2015-11-29 19:46:20 -0800235 capabilities->maxImageArraySize = 1;
Jesse Halld7b994a2015-09-07 14:17:37 -0700236
237 // TODO(jessehall): I think these are right, but haven't thought hard about
238 // it. Do we need to query the driver for support of any of these?
239 // Currently not included:
240 // - VK_IMAGE_USAGE_GENERAL: maybe? does this imply cpu mappable?
241 // - VK_IMAGE_USAGE_DEPTH_STENCIL_BIT: definitely not
242 // - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT: definitely not
Jesse Hallb00daad2015-11-29 19:46:20 -0800243 capabilities->supportedUsageFlags =
Jesse Hall3fbc8562015-11-29 22:10:52 -0800244 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
245 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
246 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
Jesse Halld7b994a2015-09-07 14:17:37 -0700247 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
248
Jesse Hallb1352bc2015-09-04 16:12:33 -0700249 return VK_SUCCESS;
250}
251
Jesse Halle1b12782015-11-30 11:27:32 -0800252VKAPI_ATTR
Jesse Hallb00daad2015-11-29 19:46:20 -0800253VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice /*pdev*/,
254 VkSurfaceKHR /*surface*/,
255 uint32_t* count,
256 VkSurfaceFormatKHR* formats) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800257 // TODO(jessehall): Fill out the set of supported formats. Longer term, add
258 // a new gralloc method to query whether a (format, usage) pair is
259 // supported, and check that for each gralloc format that corresponds to a
260 // Vulkan format. Shorter term, just add a few more formats to the ones
261 // hardcoded below.
Jesse Halld7b994a2015-09-07 14:17:37 -0700262
263 const VkSurfaceFormatKHR kFormats[] = {
264 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLORSPACE_SRGB_NONLINEAR_KHR},
265 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLORSPACE_SRGB_NONLINEAR_KHR},
266 };
267 const uint32_t kNumFormats = sizeof(kFormats) / sizeof(kFormats[0]);
268
269 VkResult result = VK_SUCCESS;
270 if (formats) {
271 if (*count < kNumFormats)
272 result = VK_INCOMPLETE;
273 std::copy(kFormats, kFormats + std::min(*count, kNumFormats), formats);
274 }
275 *count = kNumFormats;
276 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700277}
278
Jesse Halle1b12782015-11-30 11:27:32 -0800279VKAPI_ATTR
Jesse Hallb00daad2015-11-29 19:46:20 -0800280VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice /*pdev*/,
281 VkSurfaceKHR /*surface*/,
282 uint32_t* count,
283 VkPresentModeKHR* modes) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700284 const VkPresentModeKHR kModes[] = {
285 VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
286 };
287 const uint32_t kNumModes = sizeof(kModes) / sizeof(kModes[0]);
288
289 VkResult result = VK_SUCCESS;
290 if (modes) {
291 if (*count < kNumModes)
292 result = VK_INCOMPLETE;
293 std::copy(kModes, kModes + std::min(*count, kNumModes), modes);
294 }
295 *count = kNumModes;
296 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700297}
298
Jesse Halle1b12782015-11-30 11:27:32 -0800299VKAPI_ATTR
Jesse Hallb1352bc2015-09-04 16:12:33 -0700300VkResult CreateSwapchainKHR(VkDevice device,
301 const VkSwapchainCreateInfoKHR* create_info,
Jesse Hall0e74f002015-11-30 11:37:59 -0800302 const VkAllocationCallbacks* /*allocator*/,
Jesse Halld7b994a2015-09-07 14:17:37 -0700303 VkSwapchainKHR* swapchain_handle) {
304 int err;
305 VkResult result = VK_SUCCESS;
306
307 ALOGV_IF(create_info->imageArraySize != 1,
308 "Swapchain imageArraySize (%u) != 1 not supported",
309 create_info->imageArraySize);
310
311 ALOGE_IF(create_info->imageFormat != VK_FORMAT_R8G8B8A8_UNORM,
312 "swapchain formats other than R8G8B8A8_UNORM not yet implemented");
313 ALOGE_IF(create_info->imageColorSpace != VK_COLORSPACE_SRGB_NONLINEAR_KHR,
314 "color spaces other than SRGB_NONLINEAR not yet implemented");
315 ALOGE_IF(create_info->oldSwapchain,
316 "swapchain re-creation not yet implemented");
317 ALOGE_IF(create_info->preTransform != VK_SURFACE_TRANSFORM_NONE_KHR,
318 "swapchain preTransform not yet implemented");
319 ALOGE_IF(create_info->presentMode != VK_PRESENT_MODE_FIFO_KHR,
320 "present modes other than FIFO are not yet implemented");
321
322 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -0700323
Jesse Hall1356b0d2015-11-23 17:24:58 -0800324 Surface& surface = *SurfaceFromHandle(create_info->surface);
Jesse Hall70f93352015-11-04 09:41:31 -0800325 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device);
326
Jesse Hall1356b0d2015-11-23 17:24:58 -0800327 err = native_window_set_buffers_dimensions(surface.window.get(),
Jesse Halld7b994a2015-09-07 14:17:37 -0700328 create_info->imageExtent.width,
329 create_info->imageExtent.height);
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_buffers_dimensions(%d,%d) failed: %s (%d)",
334 create_info->imageExtent.width, create_info->imageExtent.height,
335 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700336 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700337 }
338
Jesse Hallf64ca122015-11-03 16:11:10 -0800339 err = native_window_set_scaling_mode(
Jesse Hall1356b0d2015-11-23 17:24:58 -0800340 surface.window.get(), NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Jesse Hallf64ca122015-11-03 16:11:10 -0800341 if (err != 0) {
342 // TODO(jessehall): Improve error reporting. Can we enumerate possible
343 // errors and translate them to valid Vulkan result codes?
344 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
345 strerror(-err), err);
Jesse Hallf64ca122015-11-03 16:11:10 -0800346 return VK_ERROR_INITIALIZATION_FAILED;
347 }
348
Jesse Halld7b994a2015-09-07 14:17:37 -0700349 uint32_t min_undequeued_buffers;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800350 err = surface.window->query(
351 surface.window.get(), NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
352 reinterpret_cast<int*>(&min_undequeued_buffers));
Jesse Halld7b994a2015-09-07 14:17:37 -0700353 if (err != 0) {
354 // TODO(jessehall): Improve error reporting. Can we enumerate possible
355 // errors and translate them to valid Vulkan result codes?
356 ALOGE("window->query failed: %s (%d)", strerror(-err), err);
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;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800361 err = native_window_set_buffer_count(surface.window.get(), num_images);
Jesse Halld7b994a2015-09-07 14:17:37 -0700362 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);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700367 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700368 }
369
Jesse Hall70f93352015-11-04 09:41:31 -0800370 int gralloc_usage = 0;
371 // TODO(jessehall): Remove conditional once all drivers have been updated
372 if (driver_vtbl.GetSwapchainGrallocUsageANDROID) {
373 result = driver_vtbl.GetSwapchainGrallocUsageANDROID(
374 device, create_info->imageFormat, create_info->imageUsageFlags,
375 &gralloc_usage);
376 if (result != VK_SUCCESS) {
377 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Jesse Hall70f93352015-11-04 09:41:31 -0800378 return VK_ERROR_INITIALIZATION_FAILED;
379 }
380 } else {
381 gralloc_usage = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
382 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800383 err = native_window_set_usage(surface.window.get(), gralloc_usage);
Jesse Hall70f93352015-11-04 09:41:31 -0800384 if (err != 0) {
385 // TODO(jessehall): Improve error reporting. Can we enumerate possible
386 // errors and translate them to valid Vulkan result codes?
387 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Jesse Hall70f93352015-11-04 09:41:31 -0800388 return VK_ERROR_INITIALIZATION_FAILED;
389 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700390
391 // -- Allocate our Swapchain object --
392 // After this point, we must deallocate the swapchain on error.
393
Jesse Hall1356b0d2015-11-23 17:24:58 -0800394 void* mem = AllocMem(device, sizeof(Swapchain), alignof(Swapchain),
Jesse Hall3fbc8562015-11-29 22:10:52 -0800395 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800396 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -0700397 return VK_ERROR_OUT_OF_HOST_MEMORY;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800398 Swapchain* swapchain = new (mem) Swapchain(surface, num_images);
Jesse Halld7b994a2015-09-07 14:17:37 -0700399
400 // -- Dequeue all buffers and create a VkImage for each --
401 // Any failures during or after this must cancel the dequeued buffers.
402
403 VkNativeBufferANDROID image_native_buffer = {
404// TODO(jessehall): Figure out how to make extension headers not horrible.
405#pragma clang diagnostic push
406#pragma clang diagnostic ignored "-Wold-style-cast"
407 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
408#pragma clang diagnostic pop
409 .pNext = nullptr,
410 };
411 VkImageCreateInfo image_create = {
412 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
413 .pNext = &image_native_buffer,
414 .imageType = VK_IMAGE_TYPE_2D,
415 .format = VK_FORMAT_R8G8B8A8_UNORM, // TODO(jessehall)
416 .extent = {0, 0, 1},
417 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -0800418 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -0800419 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -0700420 .tiling = VK_IMAGE_TILING_OPTIMAL,
421 .usage = create_info->imageUsageFlags,
422 .flags = 0,
423 .sharingMode = create_info->sharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -0800424 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -0700425 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
426 };
427
Jesse Halld7b994a2015-09-07 14:17:37 -0700428 for (uint32_t i = 0; i < num_images; i++) {
429 Swapchain::Image& img = swapchain->images[i];
430
431 ANativeWindowBuffer* buffer;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800432 err = surface.window->dequeueBuffer(surface.window.get(), &buffer,
433 &img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700434 if (err != 0) {
435 // TODO(jessehall): Improve error reporting. Can we enumerate
436 // possible errors and translate them to valid Vulkan result codes?
437 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700438 result = VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700439 break;
440 }
441 img.buffer = InitSharedPtr(device, buffer);
442 img.dequeued = true;
443
444 image_create.extent =
445 VkExtent3D{img.buffer->width, img.buffer->height, 1};
446 image_native_buffer.handle = img.buffer->handle;
447 image_native_buffer.stride = img.buffer->stride;
448 image_native_buffer.format = img.buffer->format;
449 image_native_buffer.usage = img.buffer->usage;
450
Jesse Hall03b6fe12015-11-24 12:44:21 -0800451 result =
452 driver_vtbl.CreateImage(device, &image_create, nullptr, &img.image);
Jesse Halld7b994a2015-09-07 14:17:37 -0700453 if (result != VK_SUCCESS) {
454 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
455 break;
456 }
457 }
458
459 // -- Cancel all buffers, returning them to the queue --
460 // If an error occurred before, also destroy the VkImage and release the
461 // buffer reference. Otherwise, we retain a strong reference to the buffer.
462 //
463 // TODO(jessehall): The error path here is the same as DestroySwapchain,
464 // but not the non-error path. Should refactor/unify.
465 for (uint32_t i = 0; i < num_images; i++) {
466 Swapchain::Image& img = swapchain->images[i];
467 if (img.dequeued) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800468 surface.window->cancelBuffer(surface.window.get(), img.buffer.get(),
469 img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700470 img.dequeue_fence = -1;
471 img.dequeued = false;
472 }
473 if (result != VK_SUCCESS) {
474 if (img.image)
Jesse Hall03b6fe12015-11-24 12:44:21 -0800475 driver_vtbl.DestroyImage(device, img.image, nullptr);
Jesse Halld7b994a2015-09-07 14:17:37 -0700476 }
477 }
478
479 if (result != VK_SUCCESS) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700480 swapchain->~Swapchain();
Jesse Hall1356b0d2015-11-23 17:24:58 -0800481 FreeMem(device, swapchain);
Jesse Halld7b994a2015-09-07 14:17:37 -0700482 return result;
483 }
484
485 *swapchain_handle = HandleFromSwapchain(swapchain);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700486 return VK_SUCCESS;
487}
488
Jesse Halle1b12782015-11-30 11:27:32 -0800489VKAPI_ATTR
Jesse Hall0e74f002015-11-30 11:37:59 -0800490VkResult DestroySwapchainKHR(VkDevice device,
491 VkSwapchainKHR swapchain_handle,
492 const VkAllocationCallbacks* /*allocator*/) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700493 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device);
494 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800495 const std::shared_ptr<ANativeWindow>& window = swapchain->surface.window;
Jesse Halld7b994a2015-09-07 14:17:37 -0700496
497 for (uint32_t i = 0; i < swapchain->num_images; i++) {
498 Swapchain::Image& img = swapchain->images[i];
499 if (img.dequeued) {
500 window->cancelBuffer(window.get(), img.buffer.get(),
501 img.dequeue_fence);
502 img.dequeue_fence = -1;
503 img.dequeued = false;
504 }
505 if (img.image) {
Jesse Hall03b6fe12015-11-24 12:44:21 -0800506 driver_vtbl.DestroyImage(device, img.image, nullptr);
Jesse Halld7b994a2015-09-07 14:17:37 -0700507 }
508 }
509
Jesse Halld7b994a2015-09-07 14:17:37 -0700510 swapchain->~Swapchain();
Jesse Hall1356b0d2015-11-23 17:24:58 -0800511 FreeMem(device, swapchain);
Jesse Halld7b994a2015-09-07 14:17:37 -0700512
Jesse Hallb1352bc2015-09-04 16:12:33 -0700513 return VK_SUCCESS;
514}
515
Jesse Halle1b12782015-11-30 11:27:32 -0800516VKAPI_ATTR
Jesse Halld7b994a2015-09-07 14:17:37 -0700517VkResult GetSwapchainImagesKHR(VkDevice,
518 VkSwapchainKHR swapchain_handle,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700519 uint32_t* count,
Jesse Halld7b994a2015-09-07 14:17:37 -0700520 VkImage* images) {
521 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
522 VkResult result = VK_SUCCESS;
523 if (images) {
524 uint32_t n = swapchain.num_images;
525 if (*count < swapchain.num_images) {
526 n = *count;
527 result = VK_INCOMPLETE;
528 }
529 for (uint32_t i = 0; i < n; i++)
530 images[i] = swapchain.images[i].image;
531 }
532 *count = swapchain.num_images;
533 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700534}
535
Jesse Halle1b12782015-11-30 11:27:32 -0800536VKAPI_ATTR
Jesse Hallb1352bc2015-09-04 16:12:33 -0700537VkResult AcquireNextImageKHR(VkDevice device,
Jesse Halld7b994a2015-09-07 14:17:37 -0700538 VkSwapchainKHR swapchain_handle,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700539 uint64_t timeout,
540 VkSemaphore semaphore,
541 uint32_t* image_index) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700542 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800543 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700544 VkResult result;
545 int err;
546
547 ALOGW_IF(
548 timeout != UINT64_MAX,
549 "vkAcquireNextImageKHR: non-infinite timeouts not yet implemented");
550
551 ANativeWindowBuffer* buffer;
552 int fence;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800553 err = window->dequeueBuffer(window, &buffer, &fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700554 if (err != 0) {
555 // TODO(jessehall): Improve error reporting. Can we enumerate possible
556 // errors and translate them to valid Vulkan result codes?
557 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700558 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700559 }
560
561 uint32_t idx;
562 for (idx = 0; idx < swapchain.num_images; idx++) {
563 if (swapchain.images[idx].buffer.get() == buffer) {
564 swapchain.images[idx].dequeued = true;
565 swapchain.images[idx].dequeue_fence = fence;
566 break;
567 }
568 }
569 if (idx == swapchain.num_images) {
570 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall1356b0d2015-11-23 17:24:58 -0800571 window->cancelBuffer(window, buffer, fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700572 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -0700573 }
574
575 int fence_clone = -1;
576 if (fence != -1) {
577 fence_clone = dup(fence);
578 if (fence_clone == -1) {
579 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
580 strerror(errno), errno);
581 sync_wait(fence, -1 /* forever */);
582 }
583 }
584
585 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device);
Jesse Hallab9aeef2015-11-04 10:56:20 -0800586 if (driver_vtbl.AcquireImageANDROID) {
587 result = driver_vtbl.AcquireImageANDROID(
588 device, swapchain.images[idx].image, fence_clone, semaphore);
589 } else {
590 ALOG_ASSERT(driver_vtbl.ImportNativeFenceANDROID,
591 "Have neither vkAcquireImageANDROID nor "
592 "vkImportNativeFenceANDROID");
593 result = driver_vtbl.ImportNativeFenceANDROID(device, semaphore,
594 fence_clone);
595 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700596 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -0800597 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
598 // even if the call fails. We could close it ourselves on failure, but
599 // that would create a race condition if the driver closes it on a
600 // failure path: some other thread might create an fd with the same
601 // number between the time the driver closes it and the time we close
602 // it. We must assume one of: the driver *always* closes it even on
603 // failure, or *never* closes it on failure.
Jesse Hall1356b0d2015-11-23 17:24:58 -0800604 window->cancelBuffer(window, buffer, fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700605 swapchain.images[idx].dequeued = false;
606 swapchain.images[idx].dequeue_fence = -1;
607 return result;
608 }
609
610 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700611 return VK_SUCCESS;
612}
613
Jesse Halle1b12782015-11-30 11:27:32 -0800614VKAPI_ATTR
Jesse Hallb1352bc2015-09-04 16:12:33 -0700615VkResult QueuePresentKHR(VkQueue queue, VkPresentInfoKHR* present_info) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700616 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
617 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
618 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -0700619 ALOGV_IF(present_info->pNext, "VkPresentInfo::pNext != NULL");
620
621 const DeviceVtbl& driver_vtbl = GetDriverVtbl(queue);
622 VkResult final_result = VK_SUCCESS;
623 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
624 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -0800625 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800626 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700627 uint32_t image_idx = present_info->imageIndices[sc];
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700628 Swapchain::Image& img = swapchain.images[image_idx];
Jesse Halld7b994a2015-09-07 14:17:37 -0700629 VkResult result;
630 int err;
631
Jesse Halld7b994a2015-09-07 14:17:37 -0700632 int fence = -1;
Jesse Hallab9aeef2015-11-04 10:56:20 -0800633 if (driver_vtbl.QueueSignalReleaseImageANDROID) {
634 result = driver_vtbl.QueueSignalReleaseImageANDROID(
635 queue, img.image, &fence);
636 } else {
637 ALOG_ASSERT(driver_vtbl.QueueSignalNativeFenceANDROID,
638 "Have neither vkQueueSignalReleaseImageANDROID nor "
639 "vkQueueSignalNativeFenceANDROID");
640 result = driver_vtbl.QueueSignalNativeFenceANDROID(queue, &fence);
641 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700642 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -0800643 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
Jesse Halla9e57032015-11-30 01:03:10 -0800644 if (present_info->pResults)
645 present_info->pResults[sc] = result;
Jesse Halld7b994a2015-09-07 14:17:37 -0700646 if (final_result == VK_SUCCESS)
647 final_result = result;
648 // TODO(jessehall): What happens to the buffer here? Does the app
649 // still own it or not, i.e. should we cancel the buffer? Hard to
650 // do correctly without synchronizing, though I guess we could wait
651 // for the queue to idle.
652 continue;
653 }
654
Jesse Hall1356b0d2015-11-23 17:24:58 -0800655 err = window->queueBuffer(window, img.buffer.get(), fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700656 if (err != 0) {
657 // TODO(jessehall): What now? We should probably cancel the buffer,
658 // I guess?
659 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
Jesse Halla9e57032015-11-30 01:03:10 -0800660 if (present_info->pResults)
661 present_info->pResults[sc] = result;
Jesse Halld7b994a2015-09-07 14:17:37 -0700662 if (final_result == VK_SUCCESS)
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700663 final_result = VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700664 continue;
665 }
666
667 if (img.dequeue_fence != -1) {
668 close(img.dequeue_fence);
669 img.dequeue_fence = -1;
670 }
671 img.dequeued = false;
Jesse Halla9e57032015-11-30 01:03:10 -0800672
673 if (present_info->pResults)
674 present_info->pResults[sc] = VK_SUCCESS;
Jesse Halld7b994a2015-09-07 14:17:37 -0700675 }
676
677 return final_result;
678}
Jesse Hallb1352bc2015-09-04 16:12:33 -0700679
680} // namespace vulkan