blob: 68136809101a86fe13865ddce840db2f6363e375 [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 Hall1356b0d2015-11-23 17:24:58 -080052template <typename T, typename Host>
Jesse Halld7b994a2015-09-07 14:17:37 -070053class VulkanAllocator {
54 public:
55 typedef T value_type;
56
Jesse Hall1356b0d2015-11-23 17:24:58 -080057 explicit VulkanAllocator(Host host) : host_(host) {}
Jesse Halld7b994a2015-09-07 14:17:37 -070058
59 template <typename U>
Jesse Hall1356b0d2015-11-23 17:24:58 -080060 explicit VulkanAllocator(const VulkanAllocator<U, Host>& other)
61 : host_(other.host_) {}
Jesse Halld7b994a2015-09-07 14:17:37 -070062
63 T* allocate(size_t n) const {
Jesse Hall1356b0d2015-11-23 17:24:58 -080064 return static_cast<T*>(AllocMem(host_, n * sizeof(T), alignof(T),
65 VK_SYSTEM_ALLOC_TYPE_INTERNAL));
Jesse Halld7b994a2015-09-07 14:17:37 -070066 }
Jesse Hall1356b0d2015-11-23 17:24:58 -080067 void deallocate(T* p, size_t) const { return FreeMem(host_, p); }
Jesse Halld7b994a2015-09-07 14:17:37 -070068
69 private:
Jesse Hall1356b0d2015-11-23 17:24:58 -080070 template <typename U, typename H>
Jesse Halld7b994a2015-09-07 14:17:37 -070071 friend class VulkanAllocator;
Jesse Hall1356b0d2015-11-23 17:24:58 -080072 Host host_;
Jesse Halld7b994a2015-09-07 14:17:37 -070073};
74
Jesse Hall1356b0d2015-11-23 17:24:58 -080075template <typename T, typename Host>
76std::shared_ptr<T> InitSharedPtr(Host host, T* obj) {
Jesse Halld7b994a2015-09-07 14:17:37 -070077 obj->common.incRef(&obj->common);
78 return std::shared_ptr<T>(obj, NativeBaseDeleter<T>(),
Jesse Hall1356b0d2015-11-23 17:24:58 -080079 VulkanAllocator<T, Host>(host));
Jesse Halld7b994a2015-09-07 14:17:37 -070080}
81
82// ----------------------------------------------------------------------------
83
Jesse Hall1356b0d2015-11-23 17:24:58 -080084struct Surface {
Jesse Halld7b994a2015-09-07 14:17:37 -070085 std::shared_ptr<ANativeWindow> window;
Jesse Hall1356b0d2015-11-23 17:24:58 -080086};
87
88VkSurfaceKHR HandleFromSurface(Surface* surface) {
89 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
90}
91
92Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
93 return reinterpret_cast<Surface*>(handle.handle);
94}
95
96struct Swapchain {
97 Swapchain(Surface& surface_, uint32_t num_images_)
98 : surface(surface_), num_images(num_images_) {}
99
100 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700101 uint32_t num_images;
102
103 struct Image {
104 Image() : image(VK_NULL_HANDLE), dequeue_fence(-1), dequeued(false) {}
105 VkImage image;
106 std::shared_ptr<ANativeWindowBuffer> buffer;
107 // The fence is only valid when the buffer is dequeued, and should be
108 // -1 any other time. When valid, we own the fd, and must ensure it is
109 // closed: either by closing it explicitly when queueing the buffer,
110 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
111 int dequeue_fence;
112 bool dequeued;
113 } images[android::BufferQueue::NUM_BUFFER_SLOTS];
114};
115
116VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
117 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
118}
119
120Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
121 return reinterpret_cast<Swapchain*>(handle.handle);
122}
123
124} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700125
126namespace vulkan {
127
Jesse Hall1356b0d2015-11-23 17:24:58 -0800128VkResult CreateAndroidSurfaceKHR(VkInstance instance,
129 ANativeWindow* window,
130 VkSurfaceKHR* out_surface) {
131 void* mem = AllocMem(instance, sizeof(Surface), alignof(Surface),
132 VK_SYSTEM_ALLOC_TYPE_API_OBJECT);
133 if (!mem)
134 return VK_ERROR_OUT_OF_HOST_MEMORY;
135 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700136
Jesse Hall1356b0d2015-11-23 17:24:58 -0800137 surface->window = InitSharedPtr(instance, window);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700138
Jesse Hall1356b0d2015-11-23 17:24:58 -0800139 // TODO(jessehall): Create and use NATIVE_WINDOW_API_VULKAN.
140 int err =
141 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
142 if (err != 0) {
143 // TODO(jessehall): Improve error reporting. Can we enumerate possible
144 // errors and translate them to valid Vulkan result codes?
145 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
146 err);
147 surface->~Surface();
148 FreeMem(instance, surface);
149 return VK_ERROR_INITIALIZATION_FAILED;
150 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700151
Jesse Hall1356b0d2015-11-23 17:24:58 -0800152 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700153 return VK_SUCCESS;
154}
155
Jesse Hall1356b0d2015-11-23 17:24:58 -0800156void DestroySurfaceKHR(VkInstance instance, VkSurfaceKHR surface_handle) {
157 Surface* surface = SurfaceFromHandle(surface_handle);
158 if (!surface)
159 return;
160 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
161 surface->~Surface();
162 FreeMem(instance, surface);
163}
164
165VkBool32 GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
166 uint32_t /*queue_family*/,
167 VkSurfaceKHR /*surface*/) {
168 return VK_TRUE;
169}
170
Jesse Halld7b994a2015-09-07 14:17:37 -0700171VkResult GetSurfacePropertiesKHR(VkDevice /*device*/,
Jesse Hall1356b0d2015-11-23 17:24:58 -0800172 VkSurfaceKHR surface,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700173 VkSurfacePropertiesKHR* properties) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700174 int err;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800175 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700176
177 int width, height;
178 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
179 if (err != 0) {
180 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
181 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700182 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700183 }
184 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
185 if (err != 0) {
186 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
187 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700188 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700189 }
190
Jesse Halld7b994a2015-09-07 14:17:37 -0700191 properties->currentExtent = VkExtent2D{width, height};
192
193 // TODO(jessehall): Figure out what the min/max values should be.
194 properties->minImageCount = 2;
195 properties->maxImageCount = 3;
196
197 // TODO(jessehall): Figure out what the max extent should be. Maximum
198 // texture dimension maybe?
199 properties->minImageExtent = VkExtent2D{1, 1};
200 properties->maxImageExtent = VkExtent2D{4096, 4096};
201
202 // TODO(jessehall): We can support all transforms, fix this once
203 // implemented.
204 properties->supportedTransforms = VK_SURFACE_TRANSFORM_NONE_BIT_KHR;
205
206 // TODO(jessehall): Implement based on NATIVE_WINDOW_TRANSFORM_HINT.
207 properties->currentTransform = VK_SURFACE_TRANSFORM_NONE_KHR;
208
209 properties->maxImageArraySize = 1;
210
211 // TODO(jessehall): I think these are right, but haven't thought hard about
212 // it. Do we need to query the driver for support of any of these?
213 // Currently not included:
214 // - VK_IMAGE_USAGE_GENERAL: maybe? does this imply cpu mappable?
215 // - VK_IMAGE_USAGE_DEPTH_STENCIL_BIT: definitely not
216 // - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT: definitely not
217 properties->supportedUsageFlags =
218 VK_IMAGE_USAGE_TRANSFER_SOURCE_BIT |
219 VK_IMAGE_USAGE_TRANSFER_DESTINATION_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
220 VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
221 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
222
Jesse Hallb1352bc2015-09-04 16:12:33 -0700223 return VK_SUCCESS;
224}
225
Jesse Halld7b994a2015-09-07 14:17:37 -0700226VkResult GetSurfaceFormatsKHR(VkDevice /*device*/,
Jesse Hall1356b0d2015-11-23 17:24:58 -0800227 VkSurfaceKHR /*surface*/,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700228 uint32_t* count,
229 VkSurfaceFormatKHR* formats) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800230 // TODO(jessehall): Fill out the set of supported formats. Longer term, add
231 // a new gralloc method to query whether a (format, usage) pair is
232 // supported, and check that for each gralloc format that corresponds to a
233 // Vulkan format. Shorter term, just add a few more formats to the ones
234 // hardcoded below.
Jesse Halld7b994a2015-09-07 14:17:37 -0700235
236 const VkSurfaceFormatKHR kFormats[] = {
237 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLORSPACE_SRGB_NONLINEAR_KHR},
238 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLORSPACE_SRGB_NONLINEAR_KHR},
239 };
240 const uint32_t kNumFormats = sizeof(kFormats) / sizeof(kFormats[0]);
241
242 VkResult result = VK_SUCCESS;
243 if (formats) {
244 if (*count < kNumFormats)
245 result = VK_INCOMPLETE;
246 std::copy(kFormats, kFormats + std::min(*count, kNumFormats), formats);
247 }
248 *count = kNumFormats;
249 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700250}
251
Jesse Hall1356b0d2015-11-23 17:24:58 -0800252VkResult GetSurfacePresentModesKHR(VkDevice /*device*/,
253 VkSurfaceKHR /*surface*/,
254 uint32_t* count,
255 VkPresentModeKHR* modes) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700256 const VkPresentModeKHR kModes[] = {
257 VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
258 };
259 const uint32_t kNumModes = sizeof(kModes) / sizeof(kModes[0]);
260
261 VkResult result = VK_SUCCESS;
262 if (modes) {
263 if (*count < kNumModes)
264 result = VK_INCOMPLETE;
265 std::copy(kModes, kModes + std::min(*count, kNumModes), modes);
266 }
267 *count = kNumModes;
268 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700269}
270
271VkResult CreateSwapchainKHR(VkDevice device,
272 const VkSwapchainCreateInfoKHR* create_info,
Jesse Halld7b994a2015-09-07 14:17:37 -0700273 VkSwapchainKHR* swapchain_handle) {
274 int err;
275 VkResult result = VK_SUCCESS;
276
277 ALOGV_IF(create_info->imageArraySize != 1,
278 "Swapchain imageArraySize (%u) != 1 not supported",
279 create_info->imageArraySize);
280
281 ALOGE_IF(create_info->imageFormat != VK_FORMAT_R8G8B8A8_UNORM,
282 "swapchain formats other than R8G8B8A8_UNORM not yet implemented");
283 ALOGE_IF(create_info->imageColorSpace != VK_COLORSPACE_SRGB_NONLINEAR_KHR,
284 "color spaces other than SRGB_NONLINEAR not yet implemented");
285 ALOGE_IF(create_info->oldSwapchain,
286 "swapchain re-creation not yet implemented");
287 ALOGE_IF(create_info->preTransform != VK_SURFACE_TRANSFORM_NONE_KHR,
288 "swapchain preTransform not yet implemented");
289 ALOGE_IF(create_info->presentMode != VK_PRESENT_MODE_FIFO_KHR,
290 "present modes other than FIFO are not yet implemented");
291
292 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -0700293
Jesse Hall1356b0d2015-11-23 17:24:58 -0800294 Surface& surface = *SurfaceFromHandle(create_info->surface);
Jesse Hall70f93352015-11-04 09:41:31 -0800295 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device);
296
Jesse Hall1356b0d2015-11-23 17:24:58 -0800297 err = native_window_set_buffers_dimensions(surface.window.get(),
Jesse Halld7b994a2015-09-07 14:17:37 -0700298 create_info->imageExtent.width,
299 create_info->imageExtent.height);
300 if (err != 0) {
301 // TODO(jessehall): Improve error reporting. Can we enumerate possible
302 // errors and translate them to valid Vulkan result codes?
303 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
304 create_info->imageExtent.width, create_info->imageExtent.height,
305 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700306 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700307 }
308
Jesse Hallf64ca122015-11-03 16:11:10 -0800309 err = native_window_set_scaling_mode(
Jesse Hall1356b0d2015-11-23 17:24:58 -0800310 surface.window.get(), NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Jesse Hallf64ca122015-11-03 16:11:10 -0800311 if (err != 0) {
312 // TODO(jessehall): Improve error reporting. Can we enumerate possible
313 // errors and translate them to valid Vulkan result codes?
314 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
315 strerror(-err), err);
Jesse Hallf64ca122015-11-03 16:11:10 -0800316 return VK_ERROR_INITIALIZATION_FAILED;
317 }
318
Jesse Halld7b994a2015-09-07 14:17:37 -0700319 uint32_t min_undequeued_buffers;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800320 err = surface.window->query(
321 surface.window.get(), NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
322 reinterpret_cast<int*>(&min_undequeued_buffers));
Jesse Halld7b994a2015-09-07 14:17:37 -0700323 if (err != 0) {
324 // TODO(jessehall): Improve error reporting. Can we enumerate possible
325 // errors and translate them to valid Vulkan result codes?
326 ALOGE("window->query failed: %s (%d)", strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700327 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700328 }
329 uint32_t num_images =
330 (create_info->minImageCount - 1) + min_undequeued_buffers;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800331 err = native_window_set_buffer_count(surface.window.get(), num_images);
Jesse Halld7b994a2015-09-07 14:17:37 -0700332 if (err != 0) {
333 // TODO(jessehall): Improve error reporting. Can we enumerate possible
334 // errors and translate them to valid Vulkan result codes?
335 ALOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err),
336 err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700337 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700338 }
339
Jesse Hall70f93352015-11-04 09:41:31 -0800340 int gralloc_usage = 0;
341 // TODO(jessehall): Remove conditional once all drivers have been updated
342 if (driver_vtbl.GetSwapchainGrallocUsageANDROID) {
343 result = driver_vtbl.GetSwapchainGrallocUsageANDROID(
344 device, create_info->imageFormat, create_info->imageUsageFlags,
345 &gralloc_usage);
346 if (result != VK_SUCCESS) {
347 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Jesse Hall70f93352015-11-04 09:41:31 -0800348 return VK_ERROR_INITIALIZATION_FAILED;
349 }
350 } else {
351 gralloc_usage = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
352 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800353 err = native_window_set_usage(surface.window.get(), gralloc_usage);
Jesse Hall70f93352015-11-04 09:41:31 -0800354 if (err != 0) {
355 // TODO(jessehall): Improve error reporting. Can we enumerate possible
356 // errors and translate them to valid Vulkan result codes?
357 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Jesse Hall70f93352015-11-04 09:41:31 -0800358 return VK_ERROR_INITIALIZATION_FAILED;
359 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700360
361 // -- Allocate our Swapchain object --
362 // After this point, we must deallocate the swapchain on error.
363
Jesse Hall1356b0d2015-11-23 17:24:58 -0800364 void* mem = AllocMem(device, sizeof(Swapchain), alignof(Swapchain),
365 VK_SYSTEM_ALLOC_TYPE_API_OBJECT);
366 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -0700367 return VK_ERROR_OUT_OF_HOST_MEMORY;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800368 Swapchain* swapchain = new (mem) Swapchain(surface, num_images);
Jesse Halld7b994a2015-09-07 14:17:37 -0700369
370 // -- Dequeue all buffers and create a VkImage for each --
371 // Any failures during or after this must cancel the dequeued buffers.
372
373 VkNativeBufferANDROID image_native_buffer = {
374// TODO(jessehall): Figure out how to make extension headers not horrible.
375#pragma clang diagnostic push
376#pragma clang diagnostic ignored "-Wold-style-cast"
377 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
378#pragma clang diagnostic pop
379 .pNext = nullptr,
380 };
381 VkImageCreateInfo image_create = {
382 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
383 .pNext = &image_native_buffer,
384 .imageType = VK_IMAGE_TYPE_2D,
385 .format = VK_FORMAT_R8G8B8A8_UNORM, // TODO(jessehall)
386 .extent = {0, 0, 1},
387 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -0800388 .arrayLayers = 1,
Jesse Halld7b994a2015-09-07 14:17:37 -0700389 .samples = 1,
390 .tiling = VK_IMAGE_TILING_OPTIMAL,
391 .usage = create_info->imageUsageFlags,
392 .flags = 0,
393 .sharingMode = create_info->sharingMode,
394 .queueFamilyCount = create_info->queueFamilyCount,
395 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
396 };
397
Jesse Halld7b994a2015-09-07 14:17:37 -0700398 for (uint32_t i = 0; i < num_images; i++) {
399 Swapchain::Image& img = swapchain->images[i];
400
401 ANativeWindowBuffer* buffer;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800402 err = surface.window->dequeueBuffer(surface.window.get(), &buffer,
403 &img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700404 if (err != 0) {
405 // TODO(jessehall): Improve error reporting. Can we enumerate
406 // possible errors and translate them to valid Vulkan result codes?
407 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700408 result = VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700409 break;
410 }
411 img.buffer = InitSharedPtr(device, buffer);
412 img.dequeued = true;
413
414 image_create.extent =
415 VkExtent3D{img.buffer->width, img.buffer->height, 1};
416 image_native_buffer.handle = img.buffer->handle;
417 image_native_buffer.stride = img.buffer->stride;
418 image_native_buffer.format = img.buffer->format;
419 image_native_buffer.usage = img.buffer->usage;
420
421 result = driver_vtbl.CreateImage(device, &image_create, &img.image);
422 if (result != VK_SUCCESS) {
423 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
424 break;
425 }
426 }
427
428 // -- Cancel all buffers, returning them to the queue --
429 // If an error occurred before, also destroy the VkImage and release the
430 // buffer reference. Otherwise, we retain a strong reference to the buffer.
431 //
432 // TODO(jessehall): The error path here is the same as DestroySwapchain,
433 // but not the non-error path. Should refactor/unify.
434 for (uint32_t i = 0; i < num_images; i++) {
435 Swapchain::Image& img = swapchain->images[i];
436 if (img.dequeued) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800437 surface.window->cancelBuffer(surface.window.get(), img.buffer.get(),
438 img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700439 img.dequeue_fence = -1;
440 img.dequeued = false;
441 }
442 if (result != VK_SUCCESS) {
443 if (img.image)
444 driver_vtbl.DestroyImage(device, img.image);
445 }
446 }
447
448 if (result != VK_SUCCESS) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700449 swapchain->~Swapchain();
Jesse Hall1356b0d2015-11-23 17:24:58 -0800450 FreeMem(device, swapchain);
Jesse Halld7b994a2015-09-07 14:17:37 -0700451 return result;
452 }
453
454 *swapchain_handle = HandleFromSwapchain(swapchain);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700455 return VK_SUCCESS;
456}
457
Jesse Halld7b994a2015-09-07 14:17:37 -0700458VkResult DestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain_handle) {
459 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device);
460 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800461 const std::shared_ptr<ANativeWindow>& window = swapchain->surface.window;
Jesse Halld7b994a2015-09-07 14:17:37 -0700462
463 for (uint32_t i = 0; i < swapchain->num_images; i++) {
464 Swapchain::Image& img = swapchain->images[i];
465 if (img.dequeued) {
466 window->cancelBuffer(window.get(), img.buffer.get(),
467 img.dequeue_fence);
468 img.dequeue_fence = -1;
469 img.dequeued = false;
470 }
471 if (img.image) {
472 driver_vtbl.DestroyImage(device, img.image);
473 }
474 }
475
Jesse Halld7b994a2015-09-07 14:17:37 -0700476 swapchain->~Swapchain();
Jesse Hall1356b0d2015-11-23 17:24:58 -0800477 FreeMem(device, swapchain);
Jesse Halld7b994a2015-09-07 14:17:37 -0700478
Jesse Hallb1352bc2015-09-04 16:12:33 -0700479 return VK_SUCCESS;
480}
481
Jesse Halld7b994a2015-09-07 14:17:37 -0700482VkResult GetSwapchainImagesKHR(VkDevice,
483 VkSwapchainKHR swapchain_handle,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700484 uint32_t* count,
Jesse Halld7b994a2015-09-07 14:17:37 -0700485 VkImage* images) {
486 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
487 VkResult result = VK_SUCCESS;
488 if (images) {
489 uint32_t n = swapchain.num_images;
490 if (*count < swapchain.num_images) {
491 n = *count;
492 result = VK_INCOMPLETE;
493 }
494 for (uint32_t i = 0; i < n; i++)
495 images[i] = swapchain.images[i].image;
496 }
497 *count = swapchain.num_images;
498 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700499}
500
501VkResult AcquireNextImageKHR(VkDevice device,
Jesse Halld7b994a2015-09-07 14:17:37 -0700502 VkSwapchainKHR swapchain_handle,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700503 uint64_t timeout,
504 VkSemaphore semaphore,
505 uint32_t* image_index) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700506 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800507 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700508 VkResult result;
509 int err;
510
511 ALOGW_IF(
512 timeout != UINT64_MAX,
513 "vkAcquireNextImageKHR: non-infinite timeouts not yet implemented");
514
515 ANativeWindowBuffer* buffer;
516 int fence;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800517 err = window->dequeueBuffer(window, &buffer, &fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700518 if (err != 0) {
519 // TODO(jessehall): Improve error reporting. Can we enumerate possible
520 // errors and translate them to valid Vulkan result codes?
521 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700522 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700523 }
524
525 uint32_t idx;
526 for (idx = 0; idx < swapchain.num_images; idx++) {
527 if (swapchain.images[idx].buffer.get() == buffer) {
528 swapchain.images[idx].dequeued = true;
529 swapchain.images[idx].dequeue_fence = fence;
530 break;
531 }
532 }
533 if (idx == swapchain.num_images) {
534 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall1356b0d2015-11-23 17:24:58 -0800535 window->cancelBuffer(window, buffer, fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700536#pragma clang diagnostic push
537#pragma clang diagnostic ignored "-Wold-style-cast"
538 return VK_ERROR_OUT_OF_DATE_KHR;
539#pragma clang diagnostic pop
540 }
541
542 int fence_clone = -1;
543 if (fence != -1) {
544 fence_clone = dup(fence);
545 if (fence_clone == -1) {
546 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
547 strerror(errno), errno);
548 sync_wait(fence, -1 /* forever */);
549 }
550 }
551
552 const DeviceVtbl& driver_vtbl = GetDriverVtbl(device);
Jesse Hallab9aeef2015-11-04 10:56:20 -0800553 if (driver_vtbl.AcquireImageANDROID) {
554 result = driver_vtbl.AcquireImageANDROID(
555 device, swapchain.images[idx].image, fence_clone, semaphore);
556 } else {
557 ALOG_ASSERT(driver_vtbl.ImportNativeFenceANDROID,
558 "Have neither vkAcquireImageANDROID nor "
559 "vkImportNativeFenceANDROID");
560 result = driver_vtbl.ImportNativeFenceANDROID(device, semaphore,
561 fence_clone);
562 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700563 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -0800564 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
565 // even if the call fails. We could close it ourselves on failure, but
566 // that would create a race condition if the driver closes it on a
567 // failure path: some other thread might create an fd with the same
568 // number between the time the driver closes it and the time we close
569 // it. We must assume one of: the driver *always* closes it even on
570 // failure, or *never* closes it on failure.
Jesse Hall1356b0d2015-11-23 17:24:58 -0800571 window->cancelBuffer(window, buffer, fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700572 swapchain.images[idx].dequeued = false;
573 swapchain.images[idx].dequeue_fence = -1;
574 return result;
575 }
576
577 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700578 return VK_SUCCESS;
579}
580
581VkResult QueuePresentKHR(VkQueue queue, VkPresentInfoKHR* present_info) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700582#pragma clang diagnostic push
583#pragma clang diagnostic ignored "-Wold-style-cast"
584#pragma clang diagnostic ignored "-Wsign-conversion"
585 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
586 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
587 present_info->sType);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700588#pragma clang diagnostic pop
Jesse Halld7b994a2015-09-07 14:17:37 -0700589 ALOGV_IF(present_info->pNext, "VkPresentInfo::pNext != NULL");
590
591 const DeviceVtbl& driver_vtbl = GetDriverVtbl(queue);
592 VkResult final_result = VK_SUCCESS;
593 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
594 Swapchain& swapchain =
595 *SwapchainFromHandle(present_info->swapchains[sc]);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800596 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700597 uint32_t image_idx = present_info->imageIndices[sc];
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700598 Swapchain::Image& img = swapchain.images[image_idx];
Jesse Halld7b994a2015-09-07 14:17:37 -0700599 VkResult result;
600 int err;
601
Jesse Halld7b994a2015-09-07 14:17:37 -0700602 int fence = -1;
Jesse Hallab9aeef2015-11-04 10:56:20 -0800603 if (driver_vtbl.QueueSignalReleaseImageANDROID) {
604 result = driver_vtbl.QueueSignalReleaseImageANDROID(
605 queue, img.image, &fence);
606 } else {
607 ALOG_ASSERT(driver_vtbl.QueueSignalNativeFenceANDROID,
608 "Have neither vkQueueSignalReleaseImageANDROID nor "
609 "vkQueueSignalNativeFenceANDROID");
610 result = driver_vtbl.QueueSignalNativeFenceANDROID(queue, &fence);
611 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700612 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -0800613 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
Jesse Halld7b994a2015-09-07 14:17:37 -0700614 if (final_result == VK_SUCCESS)
615 final_result = result;
616 // TODO(jessehall): What happens to the buffer here? Does the app
617 // still own it or not, i.e. should we cancel the buffer? Hard to
618 // do correctly without synchronizing, though I guess we could wait
619 // for the queue to idle.
620 continue;
621 }
622
Jesse Hall1356b0d2015-11-23 17:24:58 -0800623 err = window->queueBuffer(window, img.buffer.get(), fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700624 if (err != 0) {
625 // TODO(jessehall): What now? We should probably cancel the buffer,
626 // I guess?
627 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
628 if (final_result == VK_SUCCESS)
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700629 final_result = VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700630 continue;
631 }
632
633 if (img.dequeue_fence != -1) {
634 close(img.dequeue_fence);
635 img.dequeue_fence = -1;
636 }
637 img.dequeued = false;
638 }
639
640 return final_result;
641}
Jesse Hallb1352bc2015-09-04 16:12:33 -0700642
643} // namespace vulkan