blob: f6ab081e8ebfa1bfa58ed624f81a4bfe32fcdaf4 [file] [log] [blame]
Jesse Hallb1352bc2015-09-04 16:12:33 -07001/*
2 * Copyright 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jesse Halld7b994a2015-09-07 14:17:37 -070017// #define LOG_NDEBUG 0
18
19#include <algorithm>
20#include <memory>
21
22#include <gui/BufferQueue.h>
Jesse Hallb1352bc2015-09-04 16:12:33 -070023#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070024#include <sync/sync.h>
25
26#include "loader.h"
27
28using namespace vulkan;
29
Jesse Hall5ae3abb2015-10-08 14:00:22 -070030// TODO(jessehall): Currently we don't have a good error code for when a native
31// window operation fails. Just returning INITIALIZATION_FAILED for now. Later
32// versions (post SDK 0.9) of the API/extension have a better error code.
33// When updating to that version, audit all error returns.
34
Jesse Halld7b994a2015-09-07 14:17:37 -070035namespace {
36
37// ----------------------------------------------------------------------------
38// These functions/classes form an adaptor that allows objects to be refcounted
39// by both android::sp<> and std::shared_ptr<> simultaneously, and delegates
40// allocation of the shared_ptr<> control structure to VkAllocCallbacks. The
41// platform holds a reference to the ANativeWindow using its embedded reference
42// count, and the ANativeWindow implementation holds references to the
43// ANativeWindowBuffers using their embedded reference counts, so the
44// shared_ptr *must* cooperate with these and hold at least one reference to
45// the object using the embedded reference count.
46
47template <typename T>
48struct NativeBaseDeleter {
49 void operator()(T* obj) { obj->common.decRef(&obj->common); }
50};
51
Jesse Hall03b6fe12015-11-24 12:44:21 -080052template <typename Host>
53struct AllocScope {};
54
55template <>
56struct AllocScope<VkInstance> {
57 static const VkSystemAllocScope kScope = VK_SYSTEM_ALLOC_SCOPE_INSTANCE;
58};
59
60template <>
61struct AllocScope<VkDevice> {
62 static const VkSystemAllocScope kScope = VK_SYSTEM_ALLOC_SCOPE_DEVICE;
63};
64
Jesse Hall1356b0d2015-11-23 17:24:58 -080065template <typename T, typename Host>
Jesse Halld7b994a2015-09-07 14:17:37 -070066class VulkanAllocator {
67 public:
68 typedef T value_type;
69
Jesse Hall1356b0d2015-11-23 17:24:58 -080070 explicit VulkanAllocator(Host host) : host_(host) {}
Jesse Halld7b994a2015-09-07 14:17:37 -070071
72 template <typename U>
Jesse Hall1356b0d2015-11-23 17:24:58 -080073 explicit VulkanAllocator(const VulkanAllocator<U, Host>& other)
74 : host_(other.host_) {}
Jesse Halld7b994a2015-09-07 14:17:37 -070075
76 T* allocate(size_t n) const {
Jesse Hall1356b0d2015-11-23 17:24:58 -080077 return static_cast<T*>(AllocMem(host_, n * sizeof(T), alignof(T),
Jesse Hall03b6fe12015-11-24 12:44:21 -080078 AllocScope<Host>::kScope));
Jesse Halld7b994a2015-09-07 14:17:37 -070079 }
Jesse Hall1356b0d2015-11-23 17:24:58 -080080 void deallocate(T* p, size_t) const { return FreeMem(host_, p); }
Jesse Halld7b994a2015-09-07 14:17:37 -070081
82 private:
Jesse Hall1356b0d2015-11-23 17:24:58 -080083 template <typename U, typename H>
Jesse Halld7b994a2015-09-07 14:17:37 -070084 friend class VulkanAllocator;
Jesse Hall1356b0d2015-11-23 17:24:58 -080085 Host host_;
Jesse Halld7b994a2015-09-07 14:17:37 -070086};
87
Jesse Hall1356b0d2015-11-23 17:24:58 -080088template <typename T, typename Host>
89std::shared_ptr<T> InitSharedPtr(Host host, T* obj) {
Jesse Halld7b994a2015-09-07 14:17:37 -070090 obj->common.incRef(&obj->common);
91 return std::shared_ptr<T>(obj, NativeBaseDeleter<T>(),
Jesse Hall1356b0d2015-11-23 17:24:58 -080092 VulkanAllocator<T, Host>(host));
Jesse Halld7b994a2015-09-07 14:17:37 -070093}
94
95// ----------------------------------------------------------------------------
96
Jesse Hall1356b0d2015-11-23 17:24:58 -080097struct Surface {
Jesse Halld7b994a2015-09-07 14:17:37 -070098 std::shared_ptr<ANativeWindow> window;
Jesse Hall1356b0d2015-11-23 17:24:58 -080099};
100
101VkSurfaceKHR HandleFromSurface(Surface* surface) {
102 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
103}
104
105Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800106 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800107}
108
109struct Swapchain {
110 Swapchain(Surface& surface_, uint32_t num_images_)
111 : surface(surface_), num_images(num_images_) {}
112
113 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700114 uint32_t num_images;
115
116 struct Image {
117 Image() : image(VK_NULL_HANDLE), dequeue_fence(-1), dequeued(false) {}
118 VkImage image;
119 std::shared_ptr<ANativeWindowBuffer> buffer;
120 // The fence is only valid when the buffer is dequeued, and should be
121 // -1 any other time. When valid, we own the fd, and must ensure it is
122 // closed: either by closing it explicitly when queueing the buffer,
123 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
124 int dequeue_fence;
125 bool dequeued;
126 } images[android::BufferQueue::NUM_BUFFER_SLOTS];
127};
128
129VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
130 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
131}
132
133Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800134 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700135}
136
137} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700138
139namespace vulkan {
140
Jesse Hall1356b0d2015-11-23 17:24:58 -0800141VkResult CreateAndroidSurfaceKHR(VkInstance instance,
142 ANativeWindow* window,
143 VkSurfaceKHR* out_surface) {
144 void* mem = AllocMem(instance, sizeof(Surface), alignof(Surface),
Jesse Hall03b6fe12015-11-24 12:44:21 -0800145 VK_SYSTEM_ALLOC_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800146 if (!mem)
147 return VK_ERROR_OUT_OF_HOST_MEMORY;
148 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700149
Jesse Hall1356b0d2015-11-23 17:24:58 -0800150 surface->window = InitSharedPtr(instance, window);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700151
Jesse Hall1356b0d2015-11-23 17:24:58 -0800152 // TODO(jessehall): Create and use NATIVE_WINDOW_API_VULKAN.
153 int err =
154 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
155 if (err != 0) {
156 // TODO(jessehall): Improve error reporting. Can we enumerate possible
157 // errors and translate them to valid Vulkan result codes?
158 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
159 err);
160 surface->~Surface();
161 FreeMem(instance, surface);
162 return VK_ERROR_INITIALIZATION_FAILED;
163 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700164
Jesse Hall1356b0d2015-11-23 17:24:58 -0800165 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700166 return VK_SUCCESS;
167}
168
Jesse Hall1356b0d2015-11-23 17:24:58 -0800169void DestroySurfaceKHR(VkInstance instance, VkSurfaceKHR surface_handle) {
170 Surface* surface = SurfaceFromHandle(surface_handle);
171 if (!surface)
172 return;
173 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
174 surface->~Surface();
175 FreeMem(instance, surface);
176}
177
178VkBool32 GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
179 uint32_t /*queue_family*/,
180 VkSurfaceKHR /*surface*/) {
181 return VK_TRUE;
182}
183
Jesse Halld7b994a2015-09-07 14:17:37 -0700184VkResult GetSurfacePropertiesKHR(VkDevice /*device*/,
Jesse Hall1356b0d2015-11-23 17:24:58 -0800185 VkSurfaceKHR surface,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700186 VkSurfacePropertiesKHR* properties) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700187 int err;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800188 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700189
190 int width, height;
191 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
192 if (err != 0) {
193 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
194 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700195 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700196 }
197 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
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
Jesse Halld7b994a2015-09-07 14:17:37 -0700204 properties->currentExtent = VkExtent2D{width, height};
205
206 // TODO(jessehall): Figure out what the min/max values should be.
207 properties->minImageCount = 2;
208 properties->maxImageCount = 3;
209
210 // TODO(jessehall): Figure out what the max extent should be. Maximum
211 // texture dimension maybe?
212 properties->minImageExtent = VkExtent2D{1, 1};
213 properties->maxImageExtent = VkExtent2D{4096, 4096};
214
215 // TODO(jessehall): We can support all transforms, fix this once
216 // implemented.
217 properties->supportedTransforms = VK_SURFACE_TRANSFORM_NONE_BIT_KHR;
218
219 // TODO(jessehall): Implement based on NATIVE_WINDOW_TRANSFORM_HINT.
220 properties->currentTransform = VK_SURFACE_TRANSFORM_NONE_KHR;
221
222 properties->maxImageArraySize = 1;
223
224 // TODO(jessehall): I think these are right, but haven't thought hard about
225 // it. Do we need to query the driver for support of any of these?
226 // Currently not included:
227 // - VK_IMAGE_USAGE_GENERAL: maybe? does this imply cpu mappable?
228 // - VK_IMAGE_USAGE_DEPTH_STENCIL_BIT: definitely not
229 // - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT: definitely not
230 properties->supportedUsageFlags =
231 VK_IMAGE_USAGE_TRANSFER_SOURCE_BIT |
232 VK_IMAGE_USAGE_TRANSFER_DESTINATION_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
233 VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
234 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
235
Jesse Hallb1352bc2015-09-04 16:12:33 -0700236 return VK_SUCCESS;
237}
238
Jesse Halld7b994a2015-09-07 14:17:37 -0700239VkResult GetSurfaceFormatsKHR(VkDevice /*device*/,
Jesse Hall1356b0d2015-11-23 17:24:58 -0800240 VkSurfaceKHR /*surface*/,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700241 uint32_t* count,
242 VkSurfaceFormatKHR* formats) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800243 // TODO(jessehall): Fill out the set of supported formats. Longer term, add
244 // a new gralloc method to query whether a (format, usage) pair is
245 // supported, and check that for each gralloc format that corresponds to a
246 // Vulkan format. Shorter term, just add a few more formats to the ones
247 // hardcoded below.
Jesse Halld7b994a2015-09-07 14:17:37 -0700248
249 const VkSurfaceFormatKHR kFormats[] = {
250 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLORSPACE_SRGB_NONLINEAR_KHR},
251 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLORSPACE_SRGB_NONLINEAR_KHR},
252 };
253 const uint32_t kNumFormats = sizeof(kFormats) / sizeof(kFormats[0]);
254
255 VkResult result = VK_SUCCESS;
256 if (formats) {
257 if (*count < kNumFormats)
258 result = VK_INCOMPLETE;
259 std::copy(kFormats, kFormats + std::min(*count, kNumFormats), formats);
260 }
261 *count = kNumFormats;
262 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700263}
264
Jesse Hall1356b0d2015-11-23 17:24:58 -0800265VkResult GetSurfacePresentModesKHR(VkDevice /*device*/,
266 VkSurfaceKHR /*surface*/,
267 uint32_t* count,
268 VkPresentModeKHR* modes) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700269 const VkPresentModeKHR kModes[] = {
270 VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
271 };
272 const uint32_t kNumModes = sizeof(kModes) / sizeof(kModes[0]);
273
274 VkResult result = VK_SUCCESS;
275 if (modes) {
276 if (*count < kNumModes)
277 result = VK_INCOMPLETE;
278 std::copy(kModes, kModes + std::min(*count, kNumModes), modes);
279 }
280 *count = kNumModes;
281 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700282}
283
284VkResult CreateSwapchainKHR(VkDevice device,
285 const VkSwapchainCreateInfoKHR* create_info,
Jesse Halld7b994a2015-09-07 14:17:37 -0700286 VkSwapchainKHR* swapchain_handle) {
287 int err;
288 VkResult result = VK_SUCCESS;
289
290 ALOGV_IF(create_info->imageArraySize != 1,
291 "Swapchain imageArraySize (%u) != 1 not supported",
292 create_info->imageArraySize);
293
294 ALOGE_IF(create_info->imageFormat != VK_FORMAT_R8G8B8A8_UNORM,
295 "swapchain formats other than R8G8B8A8_UNORM not yet implemented");
296 ALOGE_IF(create_info->imageColorSpace != VK_COLORSPACE_SRGB_NONLINEAR_KHR,
297 "color spaces other than SRGB_NONLINEAR not yet implemented");
298 ALOGE_IF(create_info->oldSwapchain,
299 "swapchain re-creation not yet implemented");
300 ALOGE_IF(create_info->preTransform != VK_SURFACE_TRANSFORM_NONE_KHR,
301 "swapchain preTransform not yet implemented");
302 ALOGE_IF(create_info->presentMode != VK_PRESENT_MODE_FIFO_KHR,
303 "present modes other than FIFO are not yet implemented");
304
305 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -0700306
Jesse Hall1356b0d2015-11-23 17:24:58 -0800307 Surface& surface = *SurfaceFromHandle(create_info->surface);
Jesse Hall70f93352015-11-04 09:41:31 -0800308 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device);
309
Jesse Hall1356b0d2015-11-23 17:24:58 -0800310 err = native_window_set_buffers_dimensions(surface.window.get(),
Jesse Halld7b994a2015-09-07 14:17:37 -0700311 create_info->imageExtent.width,
312 create_info->imageExtent.height);
313 if (err != 0) {
314 // TODO(jessehall): Improve error reporting. Can we enumerate possible
315 // errors and translate them to valid Vulkan result codes?
316 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
317 create_info->imageExtent.width, create_info->imageExtent.height,
318 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700319 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700320 }
321
Jesse Hallf64ca122015-11-03 16:11:10 -0800322 err = native_window_set_scaling_mode(
Jesse Hall1356b0d2015-11-23 17:24:58 -0800323 surface.window.get(), NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Jesse Hallf64ca122015-11-03 16:11:10 -0800324 if (err != 0) {
325 // TODO(jessehall): Improve error reporting. Can we enumerate possible
326 // errors and translate them to valid Vulkan result codes?
327 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
328 strerror(-err), err);
Jesse Hallf64ca122015-11-03 16:11:10 -0800329 return VK_ERROR_INITIALIZATION_FAILED;
330 }
331
Jesse Halld7b994a2015-09-07 14:17:37 -0700332 uint32_t min_undequeued_buffers;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800333 err = surface.window->query(
334 surface.window.get(), NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
335 reinterpret_cast<int*>(&min_undequeued_buffers));
Jesse Halld7b994a2015-09-07 14:17:37 -0700336 if (err != 0) {
337 // TODO(jessehall): Improve error reporting. Can we enumerate possible
338 // errors and translate them to valid Vulkan result codes?
339 ALOGE("window->query failed: %s (%d)", strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700340 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700341 }
342 uint32_t num_images =
343 (create_info->minImageCount - 1) + min_undequeued_buffers;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800344 err = native_window_set_buffer_count(surface.window.get(), num_images);
Jesse Halld7b994a2015-09-07 14:17:37 -0700345 if (err != 0) {
346 // TODO(jessehall): Improve error reporting. Can we enumerate possible
347 // errors and translate them to valid Vulkan result codes?
348 ALOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err),
349 err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700350 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700351 }
352
Jesse Hall70f93352015-11-04 09:41:31 -0800353 int gralloc_usage = 0;
354 // TODO(jessehall): Remove conditional once all drivers have been updated
355 if (driver_vtbl.GetSwapchainGrallocUsageANDROID) {
356 result = driver_vtbl.GetSwapchainGrallocUsageANDROID(
357 device, create_info->imageFormat, create_info->imageUsageFlags,
358 &gralloc_usage);
359 if (result != VK_SUCCESS) {
360 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Jesse Hall70f93352015-11-04 09:41:31 -0800361 return VK_ERROR_INITIALIZATION_FAILED;
362 }
363 } else {
364 gralloc_usage = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
365 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800366 err = native_window_set_usage(surface.window.get(), gralloc_usage);
Jesse Hall70f93352015-11-04 09:41:31 -0800367 if (err != 0) {
368 // TODO(jessehall): Improve error reporting. Can we enumerate possible
369 // errors and translate them to valid Vulkan result codes?
370 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Jesse Hall70f93352015-11-04 09:41:31 -0800371 return VK_ERROR_INITIALIZATION_FAILED;
372 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700373
374 // -- Allocate our Swapchain object --
375 // After this point, we must deallocate the swapchain on error.
376
Jesse Hall1356b0d2015-11-23 17:24:58 -0800377 void* mem = AllocMem(device, sizeof(Swapchain), alignof(Swapchain),
Jesse Hall03b6fe12015-11-24 12:44:21 -0800378 VK_SYSTEM_ALLOC_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800379 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -0700380 return VK_ERROR_OUT_OF_HOST_MEMORY;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800381 Swapchain* swapchain = new (mem) Swapchain(surface, num_images);
Jesse Halld7b994a2015-09-07 14:17:37 -0700382
383 // -- Dequeue all buffers and create a VkImage for each --
384 // Any failures during or after this must cancel the dequeued buffers.
385
386 VkNativeBufferANDROID image_native_buffer = {
387// TODO(jessehall): Figure out how to make extension headers not horrible.
388#pragma clang diagnostic push
389#pragma clang diagnostic ignored "-Wold-style-cast"
390 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
391#pragma clang diagnostic pop
392 .pNext = nullptr,
393 };
394 VkImageCreateInfo image_create = {
395 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
396 .pNext = &image_native_buffer,
397 .imageType = VK_IMAGE_TYPE_2D,
398 .format = VK_FORMAT_R8G8B8A8_UNORM, // TODO(jessehall)
399 .extent = {0, 0, 1},
400 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -0800401 .arrayLayers = 1,
Jesse Halld7b994a2015-09-07 14:17:37 -0700402 .samples = 1,
403 .tiling = VK_IMAGE_TILING_OPTIMAL,
404 .usage = create_info->imageUsageFlags,
405 .flags = 0,
406 .sharingMode = create_info->sharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -0800407 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -0700408 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
409 };
410
Jesse Halld7b994a2015-09-07 14:17:37 -0700411 for (uint32_t i = 0; i < num_images; i++) {
412 Swapchain::Image& img = swapchain->images[i];
413
414 ANativeWindowBuffer* buffer;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800415 err = surface.window->dequeueBuffer(surface.window.get(), &buffer,
416 &img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700417 if (err != 0) {
418 // TODO(jessehall): Improve error reporting. Can we enumerate
419 // possible errors and translate them to valid Vulkan result codes?
420 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700421 result = VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700422 break;
423 }
424 img.buffer = InitSharedPtr(device, buffer);
425 img.dequeued = true;
426
427 image_create.extent =
428 VkExtent3D{img.buffer->width, img.buffer->height, 1};
429 image_native_buffer.handle = img.buffer->handle;
430 image_native_buffer.stride = img.buffer->stride;
431 image_native_buffer.format = img.buffer->format;
432 image_native_buffer.usage = img.buffer->usage;
433
Jesse Hall03b6fe12015-11-24 12:44:21 -0800434 result =
435 driver_vtbl.CreateImage(device, &image_create, nullptr, &img.image);
Jesse Halld7b994a2015-09-07 14:17:37 -0700436 if (result != VK_SUCCESS) {
437 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
438 break;
439 }
440 }
441
442 // -- Cancel all buffers, returning them to the queue --
443 // If an error occurred before, also destroy the VkImage and release the
444 // buffer reference. Otherwise, we retain a strong reference to the buffer.
445 //
446 // TODO(jessehall): The error path here is the same as DestroySwapchain,
447 // but not the non-error path. Should refactor/unify.
448 for (uint32_t i = 0; i < num_images; i++) {
449 Swapchain::Image& img = swapchain->images[i];
450 if (img.dequeued) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800451 surface.window->cancelBuffer(surface.window.get(), img.buffer.get(),
452 img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700453 img.dequeue_fence = -1;
454 img.dequeued = false;
455 }
456 if (result != VK_SUCCESS) {
457 if (img.image)
Jesse Hall03b6fe12015-11-24 12:44:21 -0800458 driver_vtbl.DestroyImage(device, img.image, nullptr);
Jesse Halld7b994a2015-09-07 14:17:37 -0700459 }
460 }
461
462 if (result != VK_SUCCESS) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700463 swapchain->~Swapchain();
Jesse Hall1356b0d2015-11-23 17:24:58 -0800464 FreeMem(device, swapchain);
Jesse Halld7b994a2015-09-07 14:17:37 -0700465 return result;
466 }
467
468 *swapchain_handle = HandleFromSwapchain(swapchain);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700469 return VK_SUCCESS;
470}
471
Jesse Halld7b994a2015-09-07 14:17:37 -0700472VkResult DestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain_handle) {
473 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device);
474 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800475 const std::shared_ptr<ANativeWindow>& window = swapchain->surface.window;
Jesse Halld7b994a2015-09-07 14:17:37 -0700476
477 for (uint32_t i = 0; i < swapchain->num_images; i++) {
478 Swapchain::Image& img = swapchain->images[i];
479 if (img.dequeued) {
480 window->cancelBuffer(window.get(), img.buffer.get(),
481 img.dequeue_fence);
482 img.dequeue_fence = -1;
483 img.dequeued = false;
484 }
485 if (img.image) {
Jesse Hall03b6fe12015-11-24 12:44:21 -0800486 driver_vtbl.DestroyImage(device, img.image, nullptr);
Jesse Halld7b994a2015-09-07 14:17:37 -0700487 }
488 }
489
Jesse Halld7b994a2015-09-07 14:17:37 -0700490 swapchain->~Swapchain();
Jesse Hall1356b0d2015-11-23 17:24:58 -0800491 FreeMem(device, swapchain);
Jesse Halld7b994a2015-09-07 14:17:37 -0700492
Jesse Hallb1352bc2015-09-04 16:12:33 -0700493 return VK_SUCCESS;
494}
495
Jesse Halld7b994a2015-09-07 14:17:37 -0700496VkResult GetSwapchainImagesKHR(VkDevice,
497 VkSwapchainKHR swapchain_handle,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700498 uint32_t* count,
Jesse Halld7b994a2015-09-07 14:17:37 -0700499 VkImage* images) {
500 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
501 VkResult result = VK_SUCCESS;
502 if (images) {
503 uint32_t n = swapchain.num_images;
504 if (*count < swapchain.num_images) {
505 n = *count;
506 result = VK_INCOMPLETE;
507 }
508 for (uint32_t i = 0; i < n; i++)
509 images[i] = swapchain.images[i].image;
510 }
511 *count = swapchain.num_images;
512 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700513}
514
515VkResult AcquireNextImageKHR(VkDevice device,
Jesse Halld7b994a2015-09-07 14:17:37 -0700516 VkSwapchainKHR swapchain_handle,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700517 uint64_t timeout,
518 VkSemaphore semaphore,
519 uint32_t* image_index) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700520 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800521 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700522 VkResult result;
523 int err;
524
525 ALOGW_IF(
526 timeout != UINT64_MAX,
527 "vkAcquireNextImageKHR: non-infinite timeouts not yet implemented");
528
529 ANativeWindowBuffer* buffer;
530 int fence;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800531 err = window->dequeueBuffer(window, &buffer, &fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700532 if (err != 0) {
533 // TODO(jessehall): Improve error reporting. Can we enumerate possible
534 // errors and translate them to valid Vulkan result codes?
535 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700536 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700537 }
538
539 uint32_t idx;
540 for (idx = 0; idx < swapchain.num_images; idx++) {
541 if (swapchain.images[idx].buffer.get() == buffer) {
542 swapchain.images[idx].dequeued = true;
543 swapchain.images[idx].dequeue_fence = fence;
544 break;
545 }
546 }
547 if (idx == swapchain.num_images) {
548 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall1356b0d2015-11-23 17:24:58 -0800549 window->cancelBuffer(window, buffer, fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700550#pragma clang diagnostic push
551#pragma clang diagnostic ignored "-Wold-style-cast"
552 return VK_ERROR_OUT_OF_DATE_KHR;
553#pragma clang diagnostic pop
554 }
555
556 int fence_clone = -1;
557 if (fence != -1) {
558 fence_clone = dup(fence);
559 if (fence_clone == -1) {
560 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
561 strerror(errno), errno);
562 sync_wait(fence, -1 /* forever */);
563 }
564 }
565
566 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device);
Jesse Hallab9aeef2015-11-04 10:56:20 -0800567 if (driver_vtbl.AcquireImageANDROID) {
568 result = driver_vtbl.AcquireImageANDROID(
569 device, swapchain.images[idx].image, fence_clone, semaphore);
570 } else {
571 ALOG_ASSERT(driver_vtbl.ImportNativeFenceANDROID,
572 "Have neither vkAcquireImageANDROID nor "
573 "vkImportNativeFenceANDROID");
574 result = driver_vtbl.ImportNativeFenceANDROID(device, semaphore,
575 fence_clone);
576 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700577 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -0800578 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
579 // even if the call fails. We could close it ourselves on failure, but
580 // that would create a race condition if the driver closes it on a
581 // failure path: some other thread might create an fd with the same
582 // number between the time the driver closes it and the time we close
583 // it. We must assume one of: the driver *always* closes it even on
584 // failure, or *never* closes it on failure.
Jesse Hall1356b0d2015-11-23 17:24:58 -0800585 window->cancelBuffer(window, buffer, fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700586 swapchain.images[idx].dequeued = false;
587 swapchain.images[idx].dequeue_fence = -1;
588 return result;
589 }
590
591 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700592 return VK_SUCCESS;
593}
594
595VkResult QueuePresentKHR(VkQueue queue, VkPresentInfoKHR* present_info) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700596#pragma clang diagnostic push
597#pragma clang diagnostic ignored "-Wold-style-cast"
598#pragma clang diagnostic ignored "-Wsign-conversion"
599 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
600 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
601 present_info->sType);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700602#pragma clang diagnostic pop
Jesse Halld7b994a2015-09-07 14:17:37 -0700603 ALOGV_IF(present_info->pNext, "VkPresentInfo::pNext != NULL");
604
605 const DeviceVtbl& driver_vtbl = GetDriverVtbl(queue);
606 VkResult final_result = VK_SUCCESS;
607 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
608 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -0800609 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800610 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700611 uint32_t image_idx = present_info->imageIndices[sc];
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700612 Swapchain::Image& img = swapchain.images[image_idx];
Jesse Halld7b994a2015-09-07 14:17:37 -0700613 VkResult result;
614 int err;
615
Jesse Halld7b994a2015-09-07 14:17:37 -0700616 int fence = -1;
Jesse Hallab9aeef2015-11-04 10:56:20 -0800617 if (driver_vtbl.QueueSignalReleaseImageANDROID) {
618 result = driver_vtbl.QueueSignalReleaseImageANDROID(
619 queue, img.image, &fence);
620 } else {
621 ALOG_ASSERT(driver_vtbl.QueueSignalNativeFenceANDROID,
622 "Have neither vkQueueSignalReleaseImageANDROID nor "
623 "vkQueueSignalNativeFenceANDROID");
624 result = driver_vtbl.QueueSignalNativeFenceANDROID(queue, &fence);
625 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700626 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -0800627 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
Jesse Halld7b994a2015-09-07 14:17:37 -0700628 if (final_result == VK_SUCCESS)
629 final_result = result;
630 // TODO(jessehall): What happens to the buffer here? Does the app
631 // still own it or not, i.e. should we cancel the buffer? Hard to
632 // do correctly without synchronizing, though I guess we could wait
633 // for the queue to idle.
634 continue;
635 }
636
Jesse Hall1356b0d2015-11-23 17:24:58 -0800637 err = window->queueBuffer(window, img.buffer.get(), fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700638 if (err != 0) {
639 // TODO(jessehall): What now? We should probably cancel the buffer,
640 // I guess?
641 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
642 if (final_result == VK_SUCCESS)
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700643 final_result = VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700644 continue;
645 }
646
647 if (img.dequeue_fence != -1) {
648 close(img.dequeue_fence);
649 img.dequeue_fence = -1;
650 }
651 img.dequeued = false;
652 }
653
654 return final_result;
655}
Jesse Hallb1352bc2015-09-04 16:12:33 -0700656
657} // namespace vulkan