blob: b49a06cdae34077e86c9d2e28771615de0e03b29 [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#include <algorithm>
Jesse Halld7b994a2015-09-07 14:17:37 -070018
Mark Salyzyn7823e122016-09-29 08:08:05 -070019#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070020#include <gui/BufferQueue.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070021#include <sync/sync.h>
Chia-I Wue8e689f2016-04-18 08:21:31 +080022#include <utils/StrongPointer.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070023
Chia-I Wu4a6a9162016-03-26 07:17:34 +080024#include "driver.h"
Jesse Halld7b994a2015-09-07 14:17:37 -070025
Jesse Hall5ae3abb2015-10-08 14:00:22 -070026// TODO(jessehall): Currently we don't have a good error code for when a native
27// window operation fails. Just returning INITIALIZATION_FAILED for now. Later
28// versions (post SDK 0.9) of the API/extension have a better error code.
29// When updating to that version, audit all error returns.
Chia-I Wu62262232016-03-26 07:06:44 +080030namespace vulkan {
31namespace driver {
Jesse Hall5ae3abb2015-10-08 14:00:22 -070032
Jesse Halld7b994a2015-09-07 14:17:37 -070033namespace {
34
Jesse Hall55bc0972016-02-23 16:43:29 -080035const VkSurfaceTransformFlagsKHR kSupportedTransforms =
36 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
37 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
38 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
39 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
40 // TODO(jessehall): See TODO in TranslateNativeToVulkanTransform.
41 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
42 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
43 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
44 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
45 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
46
47VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
48 // Native and Vulkan transforms are isomorphic, but are represented
49 // differently. Vulkan transforms are built up of an optional horizontal
50 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
51 // transforms are built up from a horizontal flip, vertical flip, and
52 // 90-degree rotation, all optional but always in that order.
53
54 // TODO(jessehall): For now, only support pure rotations, not
55 // flip or flip-and-rotate, until I have more time to test them and build
56 // sample code. As far as I know we never actually use anything besides
57 // pure rotations anyway.
58
59 switch (native) {
60 case 0: // 0x0
61 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
62 // case NATIVE_WINDOW_TRANSFORM_FLIP_H: // 0x1
63 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
64 // case NATIVE_WINDOW_TRANSFORM_FLIP_V: // 0x2
65 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
66 case NATIVE_WINDOW_TRANSFORM_ROT_180: // FLIP_H | FLIP_V
67 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
68 case NATIVE_WINDOW_TRANSFORM_ROT_90: // 0x4
69 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
70 // case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
71 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
72 // case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
73 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
74 case NATIVE_WINDOW_TRANSFORM_ROT_270: // FLIP_H | FLIP_V | ROT_90
75 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
76 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
77 default:
78 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
79 }
80}
81
Jesse Hall178b6962016-02-24 15:39:50 -080082int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
83 switch (transform) {
84 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
85 return NATIVE_WINDOW_TRANSFORM_ROT_270;
86 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
87 return NATIVE_WINDOW_TRANSFORM_ROT_180;
88 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
89 return NATIVE_WINDOW_TRANSFORM_ROT_90;
90 // TODO(jessehall): See TODO in TranslateNativeToVulkanTransform.
91 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
92 // return NATIVE_WINDOW_TRANSFORM_FLIP_H;
93 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
94 // return NATIVE_WINDOW_TRANSFORM_FLIP_H |
95 // NATIVE_WINDOW_TRANSFORM_ROT_90;
96 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
97 // return NATIVE_WINDOW_TRANSFORM_FLIP_V;
98 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
99 // return NATIVE_WINDOW_TRANSFORM_FLIP_V |
100 // NATIVE_WINDOW_TRANSFORM_ROT_90;
101 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
102 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
103 default:
104 return 0;
105 }
106}
107
Jesse Halld7b994a2015-09-07 14:17:37 -0700108// ----------------------------------------------------------------------------
109
Jesse Hall1356b0d2015-11-23 17:24:58 -0800110struct Surface {
Chia-I Wue8e689f2016-04-18 08:21:31 +0800111 android::sp<ANativeWindow> window;
Jesse Halldc225072016-05-30 22:40:14 -0700112 VkSwapchainKHR swapchain_handle;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800113};
114
115VkSurfaceKHR HandleFromSurface(Surface* surface) {
116 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
117}
118
119Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800120 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800121}
122
123struct Swapchain {
124 Swapchain(Surface& surface_, uint32_t num_images_)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700125 : surface(surface_),
126 num_images(num_images_),
127 frame_timestamps_enabled(false) {}
Jesse Hall1356b0d2015-11-23 17:24:58 -0800128
129 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700130 uint32_t num_images;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700131 bool frame_timestamps_enabled;
Jesse Halld7b994a2015-09-07 14:17:37 -0700132
133 struct Image {
134 Image() : image(VK_NULL_HANDLE), dequeue_fence(-1), dequeued(false) {}
135 VkImage image;
Chia-I Wue8e689f2016-04-18 08:21:31 +0800136 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700137 // The fence is only valid when the buffer is dequeued, and should be
138 // -1 any other time. When valid, we own the fd, and must ensure it is
139 // closed: either by closing it explicitly when queueing the buffer,
140 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
141 int dequeue_fence;
142 bool dequeued;
143 } images[android::BufferQueue::NUM_BUFFER_SLOTS];
144};
145
146VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
147 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
148}
149
150Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800151 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700152}
153
Jesse Halldc225072016-05-30 22:40:14 -0700154void ReleaseSwapchainImage(VkDevice device,
155 ANativeWindow* window,
156 int release_fence,
157 Swapchain::Image& image) {
158 ALOG_ASSERT(release_fence == -1 || image.dequeued,
159 "ReleaseSwapchainImage: can't provide a release fence for "
160 "non-dequeued images");
161
162 if (image.dequeued) {
163 if (release_fence >= 0) {
164 // We get here from vkQueuePresentKHR. The application is
165 // responsible for creating an execution dependency chain from
166 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
167 // (release_fence), so we can drop the dequeue_fence here.
168 if (image.dequeue_fence >= 0)
169 close(image.dequeue_fence);
170 } else {
171 // We get here during swapchain destruction, or various serious
172 // error cases e.g. when we can't create the release_fence during
173 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
174 // have already signalled, since the swapchain images are supposed
175 // to be idle before the swapchain is destroyed. In error cases,
176 // there may be rendering in flight to the image, but since we
177 // weren't able to create a release_fence, waiting for the
178 // dequeue_fence is about the best we can do.
179 release_fence = image.dequeue_fence;
180 }
181 image.dequeue_fence = -1;
182
183 if (window) {
184 window->cancelBuffer(window, image.buffer.get(), release_fence);
185 } else {
186 if (release_fence >= 0) {
187 sync_wait(release_fence, -1 /* forever */);
188 close(release_fence);
189 }
190 }
191
192 image.dequeued = false;
193 }
194
195 if (image.image) {
196 GetData(device).driver.DestroyImage(device, image.image, nullptr);
197 image.image = VK_NULL_HANDLE;
198 }
199
200 image.buffer.clear();
201}
202
203void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
204 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
205 return;
Jesse Halldc225072016-05-30 22:40:14 -0700206 for (uint32_t i = 0; i < swapchain->num_images; i++) {
207 if (!swapchain->images[i].dequeued)
208 ReleaseSwapchainImage(device, nullptr, -1, swapchain->images[i]);
209 }
210 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
211}
212
Jesse Halld7b994a2015-09-07 14:17:37 -0700213} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700214
Jesse Halle1b12782015-11-30 11:27:32 -0800215VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800216VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800217 VkInstance instance,
218 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
219 const VkAllocationCallbacks* allocator,
220 VkSurfaceKHR* out_surface) {
Jesse Hall1f91d392015-12-11 16:28:44 -0800221 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800222 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800223 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
224 alignof(Surface),
225 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800226 if (!mem)
227 return VK_ERROR_OUT_OF_HOST_MEMORY;
228 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700229
Chia-I Wue8e689f2016-04-18 08:21:31 +0800230 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700231 surface->swapchain_handle = VK_NULL_HANDLE;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700232
Jesse Hall1356b0d2015-11-23 17:24:58 -0800233 // TODO(jessehall): Create and use NATIVE_WINDOW_API_VULKAN.
234 int err =
235 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
236 if (err != 0) {
237 // TODO(jessehall): Improve error reporting. Can we enumerate possible
238 // errors and translate them to valid Vulkan result codes?
239 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
240 err);
241 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800242 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800243 return VK_ERROR_INITIALIZATION_FAILED;
244 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700245
Jesse Hall1356b0d2015-11-23 17:24:58 -0800246 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700247 return VK_SUCCESS;
248}
249
Jesse Halle1b12782015-11-30 11:27:32 -0800250VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800251void DestroySurfaceKHR(VkInstance instance,
252 VkSurfaceKHR surface_handle,
253 const VkAllocationCallbacks* allocator) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800254 Surface* surface = SurfaceFromHandle(surface_handle);
255 if (!surface)
256 return;
257 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700258 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700259 "destroyed VkSurfaceKHR 0x%" PRIx64
260 " has active VkSwapchainKHR 0x%" PRIx64,
261 reinterpret_cast<uint64_t>(surface_handle),
262 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800263 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800264 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800265 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800266 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800267}
268
Jesse Halle1b12782015-11-30 11:27:32 -0800269VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800270VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
271 uint32_t /*queue_family*/,
272 VkSurfaceKHR /*surface*/,
273 VkBool32* supported) {
Jesse Hall0e74f002015-11-30 11:37:59 -0800274 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800275 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800276}
277
Jesse Halle1b12782015-11-30 11:27:32 -0800278VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800279VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Jesse Hallb00daad2015-11-29 19:46:20 -0800280 VkPhysicalDevice /*pdev*/,
281 VkSurfaceKHR surface,
282 VkSurfaceCapabilitiesKHR* capabilities) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700283 int err;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800284 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700285
286 int width, height;
287 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
288 if (err != 0) {
289 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
290 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700291 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700292 }
293 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
294 if (err != 0) {
295 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
296 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700297 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700298 }
299
Jesse Hall55bc0972016-02-23 16:43:29 -0800300 int transform_hint;
301 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
302 if (err != 0) {
303 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
304 strerror(-err), err);
305 return VK_ERROR_INITIALIZATION_FAILED;
306 }
307
Jesse Halld7b994a2015-09-07 14:17:37 -0700308 // TODO(jessehall): Figure out what the min/max values should be.
Jesse Hallb00daad2015-11-29 19:46:20 -0800309 capabilities->minImageCount = 2;
310 capabilities->maxImageCount = 3;
Jesse Halld7b994a2015-09-07 14:17:37 -0700311
Jesse Hallfe2662d2016-02-09 13:26:59 -0800312 capabilities->currentExtent =
313 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
314
Jesse Halld7b994a2015-09-07 14:17:37 -0700315 // TODO(jessehall): Figure out what the max extent should be. Maximum
316 // texture dimension maybe?
Jesse Hallb00daad2015-11-29 19:46:20 -0800317 capabilities->minImageExtent = VkExtent2D{1, 1};
318 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
Jesse Halld7b994a2015-09-07 14:17:37 -0700319
Jesse Hallfe2662d2016-02-09 13:26:59 -0800320 capabilities->maxImageArrayLayers = 1;
321
Jesse Hall55bc0972016-02-23 16:43:29 -0800322 capabilities->supportedTransforms = kSupportedTransforms;
323 capabilities->currentTransform =
324 TranslateNativeToVulkanTransform(transform_hint);
Jesse Halld7b994a2015-09-07 14:17:37 -0700325
Jesse Hallfe2662d2016-02-09 13:26:59 -0800326 // On Android, window composition is a WindowManager property, not something
327 // associated with the bufferqueue. It can't be changed from here.
328 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -0700329
330 // TODO(jessehall): I think these are right, but haven't thought hard about
331 // it. Do we need to query the driver for support of any of these?
332 // Currently not included:
Jesse Halld7b994a2015-09-07 14:17:37 -0700333 // - VK_IMAGE_USAGE_DEPTH_STENCIL_BIT: definitely not
334 // - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT: definitely not
Jesse Hallb00daad2015-11-29 19:46:20 -0800335 capabilities->supportedUsageFlags =
Jesse Hall3fbc8562015-11-29 22:10:52 -0800336 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
337 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
338 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
Jesse Halld7b994a2015-09-07 14:17:37 -0700339 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
340
Jesse Hallb1352bc2015-09-04 16:12:33 -0700341 return VK_SUCCESS;
342}
343
Jesse Halle1b12782015-11-30 11:27:32 -0800344VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800345VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice /*pdev*/,
346 VkSurfaceKHR /*surface*/,
347 uint32_t* count,
348 VkSurfaceFormatKHR* formats) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800349 // TODO(jessehall): Fill out the set of supported formats. Longer term, add
350 // a new gralloc method to query whether a (format, usage) pair is
351 // supported, and check that for each gralloc format that corresponds to a
352 // Vulkan format. Shorter term, just add a few more formats to the ones
353 // hardcoded below.
Jesse Halld7b994a2015-09-07 14:17:37 -0700354
355 const VkSurfaceFormatKHR kFormats[] = {
Jesse Hall26763382016-05-20 07:13:52 -0700356 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
357 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
358 {VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Jesse Halld7b994a2015-09-07 14:17:37 -0700359 };
360 const uint32_t kNumFormats = sizeof(kFormats) / sizeof(kFormats[0]);
361
362 VkResult result = VK_SUCCESS;
363 if (formats) {
364 if (*count < kNumFormats)
365 result = VK_INCOMPLETE;
Jesse Hall7331e222016-09-15 21:26:01 -0700366 *count = std::min(*count, kNumFormats);
367 std::copy(kFormats, kFormats + *count, formats);
368 } else {
369 *count = kNumFormats;
Jesse Halld7b994a2015-09-07 14:17:37 -0700370 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700371 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700372}
373
Jesse Halle1b12782015-11-30 11:27:32 -0800374VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800375VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice /*pdev*/,
376 VkSurfaceKHR /*surface*/,
377 uint32_t* count,
378 VkPresentModeKHR* modes) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700379 const VkPresentModeKHR kModes[] = {
380 VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
381 };
382 const uint32_t kNumModes = sizeof(kModes) / sizeof(kModes[0]);
383
384 VkResult result = VK_SUCCESS;
385 if (modes) {
386 if (*count < kNumModes)
387 result = VK_INCOMPLETE;
Jesse Hall7331e222016-09-15 21:26:01 -0700388 *count = std::min(*count, kNumModes);
389 std::copy(kModes, kModes + *count, modes);
390 } else {
391 *count = kNumModes;
Jesse Halld7b994a2015-09-07 14:17:37 -0700392 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700393 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700394}
395
Jesse Halle1b12782015-11-30 11:27:32 -0800396VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800397VkResult CreateSwapchainKHR(VkDevice device,
398 const VkSwapchainCreateInfoKHR* create_info,
399 const VkAllocationCallbacks* allocator,
400 VkSwapchainKHR* swapchain_handle) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700401 int err;
402 VkResult result = VK_SUCCESS;
403
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700404 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
405 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
406 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
407 " oldSwapchain=0x%" PRIx64,
408 reinterpret_cast<uint64_t>(create_info->surface),
409 create_info->minImageCount, create_info->imageFormat,
410 create_info->imageColorSpace, create_info->imageExtent.width,
411 create_info->imageExtent.height, create_info->imageUsage,
412 create_info->preTransform, create_info->presentMode,
413 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
414
Jesse Hall1f91d392015-12-11 16:28:44 -0800415 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800416 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800417
Jesse Hall42a9eec2016-06-03 12:39:49 -0700418 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -0700419 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -0800420 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700421 ALOGV_IF(create_info->imageColorSpace != VK_COLOR_SPACE_SRGB_NONLINEAR_KHR,
Jesse Halldc225072016-05-30 22:40:14 -0700422 "swapchain imageColorSpace=%u not supported",
423 create_info->imageColorSpace);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700424 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -0700425 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -0800426 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700427 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800428 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR),
Jesse Halldc225072016-05-30 22:40:14 -0700429 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800430 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -0700431
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700432 Surface& surface = *SurfaceFromHandle(create_info->surface);
433
Jesse Halldc225072016-05-30 22:40:14 -0700434 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -0700435 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -0700436 " because it already has active swapchain 0x%" PRIx64
437 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
438 reinterpret_cast<uint64_t>(create_info->surface),
439 reinterpret_cast<uint64_t>(surface.swapchain_handle),
440 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
441 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
442 }
443 if (create_info->oldSwapchain != VK_NULL_HANDLE)
444 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
445
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700446 // -- Reset the native window --
447 // The native window might have been used previously, and had its properties
448 // changed from defaults. That will affect the answer we get for queries
449 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
450 // attempt such queries.
451
Jesse Halldc225072016-05-30 22:40:14 -0700452 // The native window only allows dequeueing all buffers before any have
453 // been queued, since after that point at least one is assumed to be in
454 // non-FREE state at any given time. Disconnecting and re-connecting
455 // orphans the previous buffers, getting us back to the state where we can
456 // dequeue all buffers.
457 err = native_window_api_disconnect(surface.window.get(),
458 NATIVE_WINDOW_API_EGL);
459 ALOGW_IF(err != 0, "native_window_api_disconnect failed: %s (%d)",
460 strerror(-err), err);
461 err =
462 native_window_api_connect(surface.window.get(), NATIVE_WINDOW_API_EGL);
463 ALOGW_IF(err != 0, "native_window_api_connect failed: %s (%d)",
464 strerror(-err), err);
465
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700466 err = native_window_set_buffer_count(surface.window.get(), 0);
467 if (err != 0) {
468 ALOGE("native_window_set_buffer_count(0) failed: %s (%d)",
469 strerror(-err), err);
470 return VK_ERROR_INITIALIZATION_FAILED;
471 }
472
473 err = surface.window->setSwapInterval(surface.window.get(), 1);
474 if (err != 0) {
475 // TODO(jessehall): Improve error reporting. Can we enumerate possible
476 // errors and translate them to valid Vulkan result codes?
477 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
478 strerror(-err), err);
479 return VK_ERROR_INITIALIZATION_FAILED;
480 }
481
Jesse Halld7b994a2015-09-07 14:17:37 -0700482 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -0700483
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800484 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -0800485
Jesse Hall517274a2016-02-10 00:07:18 -0800486 int native_format = HAL_PIXEL_FORMAT_RGBA_8888;
487 switch (create_info->imageFormat) {
488 case VK_FORMAT_R8G8B8A8_UNORM:
489 case VK_FORMAT_R8G8B8A8_SRGB:
490 native_format = HAL_PIXEL_FORMAT_RGBA_8888;
491 break;
492 case VK_FORMAT_R5G6B5_UNORM_PACK16:
493 native_format = HAL_PIXEL_FORMAT_RGB_565;
494 break;
495 default:
Jesse Hall42a9eec2016-06-03 12:39:49 -0700496 ALOGV("unsupported swapchain format %d", create_info->imageFormat);
Jesse Hall517274a2016-02-10 00:07:18 -0800497 break;
498 }
499 err = native_window_set_buffers_format(surface.window.get(), native_format);
500 if (err != 0) {
501 // TODO(jessehall): Improve error reporting. Can we enumerate possible
502 // errors and translate them to valid Vulkan result codes?
503 ALOGE("native_window_set_buffers_format(%d) failed: %s (%d)",
504 native_format, strerror(-err), err);
505 return VK_ERROR_INITIALIZATION_FAILED;
506 }
507 err = native_window_set_buffers_data_space(surface.window.get(),
508 HAL_DATASPACE_SRGB_LINEAR);
509 if (err != 0) {
510 // TODO(jessehall): Improve error reporting. Can we enumerate possible
511 // errors and translate them to valid Vulkan result codes?
512 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
513 HAL_DATASPACE_SRGB_LINEAR, strerror(-err), err);
514 return VK_ERROR_INITIALIZATION_FAILED;
515 }
516
Jesse Hall3dd678a2016-01-08 21:52:01 -0800517 err = native_window_set_buffers_dimensions(
518 surface.window.get(), static_cast<int>(create_info->imageExtent.width),
519 static_cast<int>(create_info->imageExtent.height));
Jesse Halld7b994a2015-09-07 14:17:37 -0700520 if (err != 0) {
521 // TODO(jessehall): Improve error reporting. Can we enumerate possible
522 // errors and translate them to valid Vulkan result codes?
523 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
524 create_info->imageExtent.width, create_info->imageExtent.height,
525 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700526 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700527 }
528
Jesse Hall178b6962016-02-24 15:39:50 -0800529 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
530 // applied during rendering. native_window_set_transform() expects the
531 // inverse: the transform the app is requesting that the compositor perform
532 // during composition. With native windows, pre-transform works by rendering
533 // with the same transform the compositor is applying (as in Vulkan), but
534 // then requesting the inverse transform, so that when the compositor does
535 // it's job the two transforms cancel each other out and the compositor ends
536 // up applying an identity transform to the app's buffer.
537 err = native_window_set_buffers_transform(
538 surface.window.get(),
539 InvertTransformToNative(create_info->preTransform));
540 if (err != 0) {
541 // TODO(jessehall): Improve error reporting. Can we enumerate possible
542 // errors and translate them to valid Vulkan result codes?
543 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
544 InvertTransformToNative(create_info->preTransform),
545 strerror(-err), err);
546 return VK_ERROR_INITIALIZATION_FAILED;
547 }
548
Jesse Hallf64ca122015-11-03 16:11:10 -0800549 err = native_window_set_scaling_mode(
Jesse Hall1356b0d2015-11-23 17:24:58 -0800550 surface.window.get(), NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Jesse Hallf64ca122015-11-03 16:11:10 -0800551 if (err != 0) {
552 // TODO(jessehall): Improve error reporting. Can we enumerate possible
553 // errors and translate them to valid Vulkan result codes?
554 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
555 strerror(-err), err);
Jesse Hallf64ca122015-11-03 16:11:10 -0800556 return VK_ERROR_INITIALIZATION_FAILED;
557 }
558
Jesse Halle6080bf2016-02-28 20:58:50 -0800559 int query_value;
560 err = surface.window->query(surface.window.get(),
561 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
562 &query_value);
563 if (err != 0 || query_value < 0) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700564 // TODO(jessehall): Improve error reporting. Can we enumerate possible
565 // errors and translate them to valid Vulkan result codes?
Jesse Halle6080bf2016-02-28 20:58:50 -0800566 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
567 query_value);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700568 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700569 }
Jesse Halle6080bf2016-02-28 20:58:50 -0800570 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800571 // The MIN_UNDEQUEUED_BUFFERS query doesn't know whether we'll be using
572 // async mode or not, and assumes not. But in async mode, the BufferQueue
573 // requires an extra undequeued buffer.
574 // See BufferQueueCore::getMinUndequeuedBufferCountLocked().
575 if (create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR)
576 min_undequeued_buffers += 1;
577
Jesse Halld7b994a2015-09-07 14:17:37 -0700578 uint32_t num_images =
579 (create_info->minImageCount - 1) + min_undequeued_buffers;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800580 err = native_window_set_buffer_count(surface.window.get(), num_images);
Jesse Halld7b994a2015-09-07 14:17:37 -0700581 if (err != 0) {
582 // TODO(jessehall): Improve error reporting. Can we enumerate possible
583 // errors and translate them to valid Vulkan result codes?
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700584 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", num_images,
585 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700586 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700587 }
588
Jesse Hall70f93352015-11-04 09:41:31 -0800589 int gralloc_usage = 0;
590 // TODO(jessehall): Remove conditional once all drivers have been updated
Jesse Hall1f91d392015-12-11 16:28:44 -0800591 if (dispatch.GetSwapchainGrallocUsageANDROID) {
592 result = dispatch.GetSwapchainGrallocUsageANDROID(
Jesse Hallf4ab2b12015-11-30 16:04:55 -0800593 device, create_info->imageFormat, create_info->imageUsage,
Jesse Hall70f93352015-11-04 09:41:31 -0800594 &gralloc_usage);
595 if (result != VK_SUCCESS) {
596 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Jesse Hall70f93352015-11-04 09:41:31 -0800597 return VK_ERROR_INITIALIZATION_FAILED;
598 }
599 } else {
600 gralloc_usage = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
601 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800602 err = native_window_set_usage(surface.window.get(), gralloc_usage);
Jesse Hall70f93352015-11-04 09:41:31 -0800603 if (err != 0) {
604 // TODO(jessehall): Improve error reporting. Can we enumerate possible
605 // errors and translate them to valid Vulkan result codes?
606 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Jesse Hall70f93352015-11-04 09:41:31 -0800607 return VK_ERROR_INITIALIZATION_FAILED;
608 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700609
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700610 int swap_interval =
611 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
612 err = surface.window->setSwapInterval(surface.window.get(), swap_interval);
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800613 if (err != 0) {
614 // TODO(jessehall): Improve error reporting. Can we enumerate possible
615 // errors and translate them to valid Vulkan result codes?
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700616 ALOGE("native_window->setSwapInterval(%d) failed: %s (%d)",
617 swap_interval, strerror(-err), err);
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800618 return VK_ERROR_INITIALIZATION_FAILED;
619 }
620
Jesse Halld7b994a2015-09-07 14:17:37 -0700621 // -- Allocate our Swapchain object --
622 // After this point, we must deallocate the swapchain on error.
623
Jesse Hall1f91d392015-12-11 16:28:44 -0800624 void* mem = allocator->pfnAllocation(allocator->pUserData,
625 sizeof(Swapchain), alignof(Swapchain),
626 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800627 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -0700628 return VK_ERROR_OUT_OF_HOST_MEMORY;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800629 Swapchain* swapchain = new (mem) Swapchain(surface, num_images);
Jesse Halld7b994a2015-09-07 14:17:37 -0700630
631 // -- Dequeue all buffers and create a VkImage for each --
632 // Any failures during or after this must cancel the dequeued buffers.
633
634 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -0700635#pragma clang diagnostic push
636#pragma clang diagnostic ignored "-Wold-style-cast"
637 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
638#pragma clang diagnostic pop
639 .pNext = nullptr,
640 };
641 VkImageCreateInfo image_create = {
642 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
643 .pNext = &image_native_buffer,
644 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -0800645 .format = create_info->imageFormat,
Jesse Halld7b994a2015-09-07 14:17:37 -0700646 .extent = {0, 0, 1},
647 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -0800648 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -0800649 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -0700650 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -0800651 .usage = create_info->imageUsage,
Jesse Halld7b994a2015-09-07 14:17:37 -0700652 .flags = 0,
Jesse Hallf4ab2b12015-11-30 16:04:55 -0800653 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -0800654 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -0700655 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
656 };
657
Jesse Halld7b994a2015-09-07 14:17:37 -0700658 for (uint32_t i = 0; i < num_images; i++) {
659 Swapchain::Image& img = swapchain->images[i];
660
661 ANativeWindowBuffer* buffer;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800662 err = surface.window->dequeueBuffer(surface.window.get(), &buffer,
663 &img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700664 if (err != 0) {
665 // TODO(jessehall): Improve error reporting. Can we enumerate
666 // possible errors and translate them to valid Vulkan result codes?
667 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700668 result = VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700669 break;
670 }
Chia-I Wue8e689f2016-04-18 08:21:31 +0800671 img.buffer = buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700672 img.dequeued = true;
673
674 image_create.extent =
Jesse Hall3dd678a2016-01-08 21:52:01 -0800675 VkExtent3D{static_cast<uint32_t>(img.buffer->width),
676 static_cast<uint32_t>(img.buffer->height),
677 1};
Jesse Halld7b994a2015-09-07 14:17:37 -0700678 image_native_buffer.handle = img.buffer->handle;
679 image_native_buffer.stride = img.buffer->stride;
680 image_native_buffer.format = img.buffer->format;
681 image_native_buffer.usage = img.buffer->usage;
682
Jesse Hall03b6fe12015-11-24 12:44:21 -0800683 result =
Jesse Hall1f91d392015-12-11 16:28:44 -0800684 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
Jesse Halld7b994a2015-09-07 14:17:37 -0700685 if (result != VK_SUCCESS) {
686 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
687 break;
688 }
689 }
690
691 // -- Cancel all buffers, returning them to the queue --
692 // If an error occurred before, also destroy the VkImage and release the
693 // buffer reference. Otherwise, we retain a strong reference to the buffer.
694 //
695 // TODO(jessehall): The error path here is the same as DestroySwapchain,
696 // but not the non-error path. Should refactor/unify.
697 for (uint32_t i = 0; i < num_images; i++) {
698 Swapchain::Image& img = swapchain->images[i];
699 if (img.dequeued) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800700 surface.window->cancelBuffer(surface.window.get(), img.buffer.get(),
701 img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700702 img.dequeue_fence = -1;
703 img.dequeued = false;
704 }
705 if (result != VK_SUCCESS) {
706 if (img.image)
Jesse Hall1f91d392015-12-11 16:28:44 -0800707 dispatch.DestroyImage(device, img.image, nullptr);
Jesse Halld7b994a2015-09-07 14:17:37 -0700708 }
709 }
710
711 if (result != VK_SUCCESS) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700712 swapchain->~Swapchain();
Jesse Hall1f91d392015-12-11 16:28:44 -0800713 allocator->pfnFree(allocator->pUserData, swapchain);
Jesse Halld7b994a2015-09-07 14:17:37 -0700714 return result;
715 }
716
Jesse Halldc225072016-05-30 22:40:14 -0700717 surface.swapchain_handle = HandleFromSwapchain(swapchain);
718 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700719 return VK_SUCCESS;
720}
721
Jesse Halle1b12782015-11-30 11:27:32 -0800722VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800723void DestroySwapchainKHR(VkDevice device,
724 VkSwapchainKHR swapchain_handle,
725 const VkAllocationCallbacks* allocator) {
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800726 const auto& dispatch = GetData(device).driver;
Jesse Halld7b994a2015-09-07 14:17:37 -0700727 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
Daniel Kochd78c2e82016-12-13 18:45:13 -0500728 if (!swapchain)
729 return;
Jesse Hall42a9eec2016-06-03 12:39:49 -0700730 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
731 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
Jesse Halld7b994a2015-09-07 14:17:37 -0700732
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700733 if (swapchain->frame_timestamps_enabled) {
734 native_window_enable_frame_timestamps(window, false);
735 }
Jesse Halldc225072016-05-30 22:40:14 -0700736 for (uint32_t i = 0; i < swapchain->num_images; i++)
737 ReleaseSwapchainImage(device, window, -1, swapchain->images[i]);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700738 if (active)
Jesse Halldc225072016-05-30 22:40:14 -0700739 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Jesse Hall1f91d392015-12-11 16:28:44 -0800740 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800741 allocator = &GetData(device).allocator;
Jesse Halld7b994a2015-09-07 14:17:37 -0700742 swapchain->~Swapchain();
Jesse Hall1f91d392015-12-11 16:28:44 -0800743 allocator->pfnFree(allocator->pUserData, swapchain);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700744}
745
Jesse Halle1b12782015-11-30 11:27:32 -0800746VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800747VkResult GetSwapchainImagesKHR(VkDevice,
748 VkSwapchainKHR swapchain_handle,
749 uint32_t* count,
750 VkImage* images) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700751 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -0700752 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
753 "getting images for non-active swapchain 0x%" PRIx64
754 "; only dequeued image handles are valid",
755 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -0700756 VkResult result = VK_SUCCESS;
757 if (images) {
758 uint32_t n = swapchain.num_images;
759 if (*count < swapchain.num_images) {
760 n = *count;
761 result = VK_INCOMPLETE;
762 }
763 for (uint32_t i = 0; i < n; i++)
764 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -0700765 *count = n;
766 } else {
767 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -0700768 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700769 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700770}
771
Jesse Halle1b12782015-11-30 11:27:32 -0800772VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800773VkResult AcquireNextImageKHR(VkDevice device,
774 VkSwapchainKHR swapchain_handle,
775 uint64_t timeout,
776 VkSemaphore semaphore,
777 VkFence vk_fence,
778 uint32_t* image_index) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700779 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800780 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700781 VkResult result;
782 int err;
783
Jesse Halldc225072016-05-30 22:40:14 -0700784 if (swapchain.surface.swapchain_handle != swapchain_handle)
785 return VK_ERROR_OUT_OF_DATE_KHR;
786
Jesse Halld7b994a2015-09-07 14:17:37 -0700787 ALOGW_IF(
788 timeout != UINT64_MAX,
789 "vkAcquireNextImageKHR: non-infinite timeouts not yet implemented");
790
791 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -0800792 int fence_fd;
793 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -0700794 if (err != 0) {
795 // TODO(jessehall): Improve error reporting. Can we enumerate possible
796 // errors and translate them to valid Vulkan result codes?
797 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700798 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700799 }
800
801 uint32_t idx;
802 for (idx = 0; idx < swapchain.num_images; idx++) {
803 if (swapchain.images[idx].buffer.get() == buffer) {
804 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -0800805 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -0700806 break;
807 }
808 }
809 if (idx == swapchain.num_images) {
810 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -0800811 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -0700812 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -0700813 }
814
815 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -0800816 if (fence_fd != -1) {
817 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -0700818 if (fence_clone == -1) {
819 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
820 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -0800821 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -0700822 }
823 }
824
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800825 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -0800826 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700827 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -0800828 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
829 // even if the call fails. We could close it ourselves on failure, but
830 // that would create a race condition if the driver closes it on a
831 // failure path: some other thread might create an fd with the same
832 // number between the time the driver closes it and the time we close
833 // it. We must assume one of: the driver *always* closes it even on
834 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -0800835 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -0700836 swapchain.images[idx].dequeued = false;
837 swapchain.images[idx].dequeue_fence = -1;
838 return result;
839 }
840
841 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700842 return VK_SUCCESS;
843}
844
Jesse Halldc225072016-05-30 22:40:14 -0700845static VkResult WorstPresentResult(VkResult a, VkResult b) {
846 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
847 // (in spec version 1.0.14).
848 static const VkResult kWorstToBest[] = {
849 VK_ERROR_DEVICE_LOST,
850 VK_ERROR_SURFACE_LOST_KHR,
851 VK_ERROR_OUT_OF_DATE_KHR,
852 VK_ERROR_OUT_OF_DEVICE_MEMORY,
853 VK_ERROR_OUT_OF_HOST_MEMORY,
854 VK_SUBOPTIMAL_KHR,
855 };
856 for (auto result : kWorstToBest) {
857 if (a == result || b == result)
858 return result;
859 }
860 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
861 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
862 return a != VK_SUCCESS ? a : b;
863}
864
Jesse Halle1b12782015-11-30 11:27:32 -0800865VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800866VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700867 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
868 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
869 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -0700870
Jesse Halldc225072016-05-30 22:40:14 -0700871 VkDevice device = GetData(queue).driver_device;
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800872 const auto& dispatch = GetData(queue).driver;
Jesse Halld7b994a2015-09-07 14:17:37 -0700873 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -0700874
Ian Elliottcb351132016-12-13 10:30:40 -0700875 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700876 const VkPresentRegionsKHR* present_regions = nullptr;
877 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -0700878 const VkPresentRegionsKHR* next =
879 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
880 while (next) {
881 switch (next->sType) {
882 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
883 present_regions = next;
884 break;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700885 case VK_STRUCTURE_TYPE_PRESENT_TIMES_GOOGLE:
886 present_times =
887 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
888 break;
Ian Elliottcb351132016-12-13 10:30:40 -0700889 default:
890 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
891 next->sType);
892 break;
893 }
894 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
895 }
896 ALOGV_IF(
897 present_regions &&
898 present_regions->swapchainCount != present_info->swapchainCount,
899 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700900 ALOGV_IF(present_times &&
901 present_times->swapchainCount != present_info->swapchainCount,
902 "VkPresentTimesInfoGOOGLE::swapchainCount != "
903 "VkPresentInfo::swapchainCount");
Ian Elliottcb351132016-12-13 10:30:40 -0700904 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700905 (present_regions) ? present_regions->pRegions : nullptr;
906 const VkPresentTimeGOOGLE* times =
907 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -0700908 const VkAllocationCallbacks* allocator = &GetData(device).allocator;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700909 android_native_rect_t* rects = nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -0700910 uint32_t nrects = 0;
911
Jesse Halld7b994a2015-09-07 14:17:37 -0700912 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
913 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -0800914 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Hallf4ab2b12015-11-30 16:04:55 -0800915 uint32_t image_idx = present_info->pImageIndices[sc];
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700916 Swapchain::Image& img = swapchain.images[image_idx];
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700917 const VkPresentRegionKHR* region = (regions) ? &regions[sc] : nullptr;
918 const VkPresentTimeGOOGLE* time = (times) ? &times[sc] : nullptr;
Jesse Halldc225072016-05-30 22:40:14 -0700919 VkResult swapchain_result = VK_SUCCESS;
Jesse Halld7b994a2015-09-07 14:17:37 -0700920 VkResult result;
921 int err;
922
Jesse Halld7b994a2015-09-07 14:17:37 -0700923 int fence = -1;
Jesse Hall275d76c2016-01-08 22:39:16 -0800924 result = dispatch.QueueSignalReleaseImageANDROID(
925 queue, present_info->waitSemaphoreCount,
926 present_info->pWaitSemaphores, img.image, &fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700927 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -0800928 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
Jesse Halldc225072016-05-30 22:40:14 -0700929 swapchain_result = result;
Jesse Halld7b994a2015-09-07 14:17:37 -0700930 }
931
Jesse Halldc225072016-05-30 22:40:14 -0700932 if (swapchain.surface.swapchain_handle ==
933 present_info->pSwapchains[sc]) {
934 ANativeWindow* window = swapchain.surface.window.get();
935 if (swapchain_result == VK_SUCCESS) {
Ian Elliottcb351132016-12-13 10:30:40 -0700936 if (region) {
937 // Process the incremental-present hint for this swapchain:
938 uint32_t rcount = region->rectangleCount;
939 if (rcount > nrects) {
940 android_native_rect_t* new_rects =
941 static_cast<android_native_rect_t*>(
942 allocator->pfnReallocation(
943 allocator->pUserData, rects,
944 sizeof(android_native_rect_t) * rcount,
945 alignof(android_native_rect_t),
946 VK_SYSTEM_ALLOCATION_SCOPE_COMMAND));
947 if (new_rects) {
948 rects = new_rects;
949 nrects = rcount;
950 } else {
951 rcount = 0; // Ignore the hint for this swapchain
952 }
953 }
954 for (uint32_t r = 0; r < rcount; ++r) {
955 if (region->pRectangles[r].layer > 0) {
956 ALOGV(
957 "vkQueuePresentKHR ignoring invalid layer "
958 "(%u); using layer 0 instead",
959 region->pRectangles[r].layer);
960 }
961 int x = region->pRectangles[r].offset.x;
962 int y = region->pRectangles[r].offset.y;
963 int width = static_cast<int>(
964 region->pRectangles[r].extent.width);
965 int height = static_cast<int>(
966 region->pRectangles[r].extent.height);
967 android_native_rect_t* cur_rect = &rects[r];
968 cur_rect->left = x;
969 cur_rect->top = y + height;
970 cur_rect->right = x + width;
971 cur_rect->bottom = y;
972 }
973 native_window_set_surface_damage(window, rects, rcount);
974 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700975 if (time) {
976 if (!swapchain.frame_timestamps_enabled) {
977 native_window_enable_frame_timestamps(window, true);
978 swapchain.frame_timestamps_enabled = true;
979 }
980 // TODO(ianelliott): need to store the presentID (and
981 // desiredPresentTime), so it can be later correlated to
982 // this present. Probably modify the following function
983 // (and below) to plumb a path to store it in FrameEvents
984 // code, on the producer side.
985 native_window_set_buffers_timestamp(
986 window, static_cast<int64_t>(time->desiredPresentTime));
987 }
Jesse Halldc225072016-05-30 22:40:14 -0700988 err = window->queueBuffer(window, img.buffer.get(), fence);
989 // queueBuffer always closes fence, even on error
990 if (err != 0) {
991 // TODO(jessehall): What now? We should probably cancel the
992 // buffer, I guess?
993 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
994 swapchain_result = WorstPresentResult(
995 swapchain_result, VK_ERROR_OUT_OF_DATE_KHR);
996 }
997 if (img.dequeue_fence >= 0) {
998 close(img.dequeue_fence);
999 img.dequeue_fence = -1;
1000 }
1001 img.dequeued = false;
1002 }
1003 if (swapchain_result != VK_SUCCESS) {
1004 ReleaseSwapchainImage(device, window, fence, img);
1005 OrphanSwapchain(device, &swapchain);
1006 }
1007 } else {
1008 ReleaseSwapchainImage(device, nullptr, fence, img);
1009 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001010 }
1011
Jesse Halla9e57032015-11-30 01:03:10 -08001012 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07001013 present_info->pResults[sc] = swapchain_result;
1014
1015 if (swapchain_result != final_result)
1016 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07001017 }
Ian Elliottcb351132016-12-13 10:30:40 -07001018 if (rects) {
1019 allocator->pfnFree(allocator->pUserData, rects);
1020 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001021
1022 return final_result;
1023}
Jesse Hallb1352bc2015-09-04 16:12:33 -07001024
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001025VKAPI_ATTR
1026VkResult GetRefreshCycleDurationGOOGLE(
1027 VkDevice,
1028 VkSwapchainKHR,
1029 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
1030 VkResult result = VK_SUCCESS;
1031
1032 // TODO(ianelliott): FULLY IMPLEMENT THIS FUNCTION!!!
1033 pDisplayTimingProperties->minRefreshDuration = 16666666666;
1034 pDisplayTimingProperties->maxRefreshDuration = 16666666666;
1035
1036 return result;
1037}
1038
1039VKAPI_ATTR
1040VkResult GetPastPresentationTimingGOOGLE(
1041 VkDevice,
1042 VkSwapchainKHR swapchain_handle,
1043 uint32_t* count,
1044 VkPastPresentationTimingGOOGLE* timings) {
1045 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
1046 ANativeWindow* window = swapchain.surface.window.get();
1047 VkResult result = VK_SUCCESS;
1048
1049 if (!swapchain.frame_timestamps_enabled) {
1050 native_window_enable_frame_timestamps(window, true);
1051 swapchain.frame_timestamps_enabled = true;
1052 }
1053
1054 // TODO(ianelliott): FULLY IMPLEMENT THIS FUNCTION!!!
1055 if (timings) {
1056 *count = 0;
1057 } else {
1058 *count = 0;
1059 }
1060
1061 return result;
1062}
1063
Chia-I Wu62262232016-03-26 07:06:44 +08001064} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07001065} // namespace vulkan