blob: e105922be265b9c6130e9145f4412255991346b1 [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>
Brian Anderson1049d1d2016-12-16 17:25:57 -080023#include <utils/Vector.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070024
Chia-I Wu4a6a9162016-03-26 07:17:34 +080025#include "driver.h"
Jesse Halld7b994a2015-09-07 14:17:37 -070026
Jesse Hall5ae3abb2015-10-08 14:00:22 -070027// TODO(jessehall): Currently we don't have a good error code for when a native
28// window operation fails. Just returning INITIALIZATION_FAILED for now. Later
29// versions (post SDK 0.9) of the API/extension have a better error code.
30// When updating to that version, audit all error returns.
Chia-I Wu62262232016-03-26 07:06:44 +080031namespace vulkan {
32namespace driver {
Jesse Hall5ae3abb2015-10-08 14:00:22 -070033
Jesse Halld7b994a2015-09-07 14:17:37 -070034namespace {
35
Jesse Hall55bc0972016-02-23 16:43:29 -080036const VkSurfaceTransformFlagsKHR kSupportedTransforms =
37 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
38 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
39 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
40 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
41 // TODO(jessehall): See TODO in TranslateNativeToVulkanTransform.
42 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
43 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
44 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
45 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
46 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
47
48VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
49 // Native and Vulkan transforms are isomorphic, but are represented
50 // differently. Vulkan transforms are built up of an optional horizontal
51 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
52 // transforms are built up from a horizontal flip, vertical flip, and
53 // 90-degree rotation, all optional but always in that order.
54
55 // TODO(jessehall): For now, only support pure rotations, not
56 // flip or flip-and-rotate, until I have more time to test them and build
57 // sample code. As far as I know we never actually use anything besides
58 // pure rotations anyway.
59
60 switch (native) {
61 case 0: // 0x0
62 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
63 // case NATIVE_WINDOW_TRANSFORM_FLIP_H: // 0x1
64 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
65 // case NATIVE_WINDOW_TRANSFORM_FLIP_V: // 0x2
66 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
67 case NATIVE_WINDOW_TRANSFORM_ROT_180: // FLIP_H | FLIP_V
68 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
69 case NATIVE_WINDOW_TRANSFORM_ROT_90: // 0x4
70 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
71 // case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
72 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
73 // case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
74 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
75 case NATIVE_WINDOW_TRANSFORM_ROT_270: // FLIP_H | FLIP_V | ROT_90
76 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
77 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
78 default:
79 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
80 }
81}
82
Jesse Hall178b6962016-02-24 15:39:50 -080083int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
84 switch (transform) {
85 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
86 return NATIVE_WINDOW_TRANSFORM_ROT_270;
87 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
88 return NATIVE_WINDOW_TRANSFORM_ROT_180;
89 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
90 return NATIVE_WINDOW_TRANSFORM_ROT_90;
91 // TODO(jessehall): See TODO in TranslateNativeToVulkanTransform.
92 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
93 // return NATIVE_WINDOW_TRANSFORM_FLIP_H;
94 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
95 // return NATIVE_WINDOW_TRANSFORM_FLIP_H |
96 // NATIVE_WINDOW_TRANSFORM_ROT_90;
97 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
98 // return NATIVE_WINDOW_TRANSFORM_FLIP_V;
99 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
100 // return NATIVE_WINDOW_TRANSFORM_FLIP_V |
101 // NATIVE_WINDOW_TRANSFORM_ROT_90;
102 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
103 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
104 default:
105 return 0;
106 }
107}
108
Ian Elliott8a977262017-01-19 09:05:58 -0700109class TimingInfo {
110 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800111 TimingInfo() = default;
112 TimingInfo(const VkPresentTimeGOOGLE* qp, uint64_t nativeFrameId)
Ian Elliott2c6355d2017-01-19 11:02:13 -0700113 : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
Brian Anderson1049d1d2016-12-16 17:25:57 -0800114 native_frame_id_(nativeFrameId) {}
115 bool ready() const {
Ian Elliott8a977262017-01-19 09:05:58 -0700116 return (timestamp_desired_present_time_ &&
117 timestamp_actual_present_time_ &&
118 timestamp_render_complete_time_ &&
119 timestamp_composition_latch_time_);
120 }
121 void calculate(uint64_t rdur) {
122 vals_.actualPresentTime = timestamp_actual_present_time_;
123 uint64_t margin = (timestamp_composition_latch_time_ -
124 timestamp_render_complete_time_);
125 // Calculate vals_.earliestPresentTime, and potentially adjust
126 // vals_.presentMargin. The initial value of vals_.earliestPresentTime
127 // is vals_.actualPresentTime. If we can subtract rdur (the duration
128 // of a refresh cycle) from vals_.earliestPresentTime (and also from
129 // vals_.presentMargin) and still leave a positive margin, then we can
130 // report to the application that it could have presented earlier than
131 // it did (per the extension specification). If for some reason, we
132 // can do this subtraction repeatedly, we do, since
133 // vals_.earliestPresentTime really is supposed to be the "earliest".
134 uint64_t early_time = vals_.actualPresentTime;
135 while ((margin > rdur) &&
136 ((early_time - rdur) > timestamp_composition_latch_time_)) {
137 early_time -= rdur;
138 margin -= rdur;
139 }
140 vals_.earliestPresentTime = early_time;
141 vals_.presentMargin = margin;
142 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800143 void get_values(VkPastPresentationTimingGOOGLE* values) const {
144 *values = vals_;
145 }
Ian Elliott8a977262017-01-19 09:05:58 -0700146
147 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800148 VkPastPresentationTimingGOOGLE vals_ { 0, 0, 0, 0, 0 };
Ian Elliott8a977262017-01-19 09:05:58 -0700149
Brian Anderson1049d1d2016-12-16 17:25:57 -0800150 uint64_t native_frame_id_ { 0 };
151 uint64_t timestamp_desired_present_time_ { 0 };
152 uint64_t timestamp_actual_present_time_ { 0 };
153 uint64_t timestamp_render_complete_time_ { 0 };
154 uint64_t timestamp_composition_latch_time_ { 0 };
Ian Elliott8a977262017-01-19 09:05:58 -0700155};
156
Jesse Halld7b994a2015-09-07 14:17:37 -0700157// ----------------------------------------------------------------------------
158
Jesse Hall1356b0d2015-11-23 17:24:58 -0800159struct Surface {
Chia-I Wue8e689f2016-04-18 08:21:31 +0800160 android::sp<ANativeWindow> window;
Jesse Halldc225072016-05-30 22:40:14 -0700161 VkSwapchainKHR swapchain_handle;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800162};
163
164VkSurfaceKHR HandleFromSurface(Surface* surface) {
165 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
166}
167
168Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800169 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800170}
171
Ian Elliott8a977262017-01-19 09:05:58 -0700172// Maximum number of TimingInfo structs to keep per swapchain:
173enum { MAX_TIMING_INFOS = 10 };
174// Minimum number of frames to look for in the past (so we don't cause
175// syncronous requests to Surface Flinger):
176enum { MIN_NUM_FRAMES_AGO = 5 };
177
Jesse Hall1356b0d2015-11-23 17:24:58 -0800178struct Swapchain {
Ian Elliottffedb652017-02-14 10:58:30 -0700179 Swapchain(Surface& surface_,
180 uint32_t num_images_,
181 VkPresentModeKHR present_mode)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700182 : surface(surface_),
183 num_images(num_images_),
Ian Elliottffedb652017-02-14 10:58:30 -0700184 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
Ian Elliott8a977262017-01-19 09:05:58 -0700185 frame_timestamps_enabled(false) {
Ian Elliott62c48c92017-01-20 13:13:20 -0700186 ANativeWindow* window = surface.window.get();
Ian Elliottbe833a22017-01-25 13:09:20 -0700187 int64_t rdur;
188 native_window_get_refresh_cycle_duration(
Ian Elliott62c48c92017-01-20 13:13:20 -0700189 window,
Ian Elliottbe833a22017-01-25 13:09:20 -0700190 &rdur);
191 refresh_duration = static_cast<uint64_t>(rdur);
Ian Elliott8a977262017-01-19 09:05:58 -0700192 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800193
194 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700195 uint32_t num_images;
Ian Elliottffedb652017-02-14 10:58:30 -0700196 bool mailbox_mode;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700197 bool frame_timestamps_enabled;
Ian Elliottbe833a22017-01-25 13:09:20 -0700198 uint64_t refresh_duration;
Jesse Halld7b994a2015-09-07 14:17:37 -0700199
200 struct Image {
201 Image() : image(VK_NULL_HANDLE), dequeue_fence(-1), dequeued(false) {}
202 VkImage image;
Chia-I Wue8e689f2016-04-18 08:21:31 +0800203 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700204 // The fence is only valid when the buffer is dequeued, and should be
205 // -1 any other time. When valid, we own the fd, and must ensure it is
206 // closed: either by closing it explicitly when queueing the buffer,
207 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
208 int dequeue_fence;
209 bool dequeued;
210 } images[android::BufferQueue::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700211
Brian Anderson1049d1d2016-12-16 17:25:57 -0800212 android::Vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700213};
214
215VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
216 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
217}
218
219Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800220 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700221}
222
Jesse Halldc225072016-05-30 22:40:14 -0700223void ReleaseSwapchainImage(VkDevice device,
224 ANativeWindow* window,
225 int release_fence,
226 Swapchain::Image& image) {
227 ALOG_ASSERT(release_fence == -1 || image.dequeued,
228 "ReleaseSwapchainImage: can't provide a release fence for "
229 "non-dequeued images");
230
231 if (image.dequeued) {
232 if (release_fence >= 0) {
233 // We get here from vkQueuePresentKHR. The application is
234 // responsible for creating an execution dependency chain from
235 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
236 // (release_fence), so we can drop the dequeue_fence here.
237 if (image.dequeue_fence >= 0)
238 close(image.dequeue_fence);
239 } else {
240 // We get here during swapchain destruction, or various serious
241 // error cases e.g. when we can't create the release_fence during
242 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
243 // have already signalled, since the swapchain images are supposed
244 // to be idle before the swapchain is destroyed. In error cases,
245 // there may be rendering in flight to the image, but since we
246 // weren't able to create a release_fence, waiting for the
247 // dequeue_fence is about the best we can do.
248 release_fence = image.dequeue_fence;
249 }
250 image.dequeue_fence = -1;
251
252 if (window) {
253 window->cancelBuffer(window, image.buffer.get(), release_fence);
254 } else {
255 if (release_fence >= 0) {
256 sync_wait(release_fence, -1 /* forever */);
257 close(release_fence);
258 }
259 }
260
261 image.dequeued = false;
262 }
263
264 if (image.image) {
265 GetData(device).driver.DestroyImage(device, image.image, nullptr);
266 image.image = VK_NULL_HANDLE;
267 }
268
269 image.buffer.clear();
270}
271
272void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
273 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
274 return;
Jesse Halldc225072016-05-30 22:40:14 -0700275 for (uint32_t i = 0; i < swapchain->num_images; i++) {
276 if (!swapchain->images[i].dequeued)
277 ReleaseSwapchainImage(device, nullptr, -1, swapchain->images[i]);
278 }
279 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700280 swapchain->timing.clear();
281}
282
283uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800284 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
285 return 0;
286 }
Ian Elliott8a977262017-01-19 09:05:58 -0700287
Brian Anderson1049d1d2016-12-16 17:25:57 -0800288 uint32_t num_ready = 0;
289 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
290 for (uint32_t i = 0; i < num_timings; i++) {
291 TimingInfo& ti = swapchain.timing.editItemAt(i);
292 if (ti.ready()) {
293 // This TimingInfo is ready to be reported to the user. Add it
294 // to the num_ready.
295 num_ready++;
296 continue;
297 }
298 // This TimingInfo is not yet ready to be reported to the user,
299 // and so we should look for any available timestamps that
300 // might make it ready.
301 int64_t desired_present_time = 0;
302 int64_t render_complete_time = 0;
303 int64_t composition_latch_time = 0;
304 int64_t actual_present_time = 0;
305 // Obtain timestamps:
306 int ret = native_window_get_frame_timestamps(
307 swapchain.surface.window.get(), ti.native_frame_id_,
308 &desired_present_time, &render_complete_time,
309 &composition_latch_time,
310 NULL, //&first_composition_start_time,
311 NULL, //&last_composition_start_time,
312 NULL, //&composition_finish_time,
313 // TODO(ianelliott): Maybe ask if this one is
314 // supported, at startup time (since it may not be
315 // supported):
316 &actual_present_time,
317 NULL, //&display_retire_time,
318 NULL, //&dequeue_ready_time,
319 NULL /*&reads_done_time*/);
320
321 if (ret != android::NO_ERROR) {
322 continue;
323 }
324
325 // Record the timestamp(s) we received, and then see if this TimingInfo
326 // is ready to be reported to the user:
327 ti.timestamp_desired_present_time_ =
328 static_cast<uint64_t>(desired_present_time);
329 ti.timestamp_actual_present_time_ =
330 static_cast<uint64_t>(actual_present_time);
331 ti.timestamp_render_complete_time_ =
332 static_cast<uint64_t>(render_complete_time);
333 ti.timestamp_composition_latch_time_ =
334 static_cast<uint64_t>(composition_latch_time);
335
336 if (ti.ready()) {
337 // The TimingInfo has received enough timestamps, and should now
338 // use those timestamps to calculate the info that should be
339 // reported to the user:
340 ti.calculate(swapchain.refresh_duration);
341 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700342 }
343 }
344 return num_ready;
345}
346
347// TODO(ianelliott): DEAL WITH RETURN VALUE (e.g. VK_INCOMPLETE)!!!
348void copy_ready_timings(Swapchain& swapchain,
349 uint32_t* count,
350 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800351 if (swapchain.timing.empty()) {
352 *count = 0;
353 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700354 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800355
356 size_t last_ready = swapchain.timing.size() - 1;
357 while (!swapchain.timing[last_ready].ready()) {
358 if (last_ready == 0) {
359 *count = 0;
360 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700361 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800362 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700363 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800364
365 uint32_t num_copied = 0;
366 size_t num_to_remove = 0;
367 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
368 const TimingInfo& ti = swapchain.timing[i];
369 if (ti.ready()) {
370 ti.get_values(&timings[num_copied]);
371 num_copied++;
372 }
373 num_to_remove++;
374 }
375
376 // Discard old frames that aren't ready if newer frames are ready.
377 // We don't expect to get the timing info for those old frames.
378 swapchain.timing.removeItemsAt(0, num_to_remove);
379
Ian Elliott8a977262017-01-19 09:05:58 -0700380 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700381}
382
Jesse Halld7b994a2015-09-07 14:17:37 -0700383} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700384
Jesse Halle1b12782015-11-30 11:27:32 -0800385VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800386VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800387 VkInstance instance,
388 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
389 const VkAllocationCallbacks* allocator,
390 VkSurfaceKHR* out_surface) {
Jesse Hall1f91d392015-12-11 16:28:44 -0800391 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800392 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800393 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
394 alignof(Surface),
395 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800396 if (!mem)
397 return VK_ERROR_OUT_OF_HOST_MEMORY;
398 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700399
Chia-I Wue8e689f2016-04-18 08:21:31 +0800400 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700401 surface->swapchain_handle = VK_NULL_HANDLE;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700402
Jesse Hall1356b0d2015-11-23 17:24:58 -0800403 // TODO(jessehall): Create and use NATIVE_WINDOW_API_VULKAN.
404 int err =
405 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
406 if (err != 0) {
407 // TODO(jessehall): Improve error reporting. Can we enumerate possible
408 // errors and translate them to valid Vulkan result codes?
409 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
410 err);
411 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800412 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800413 return VK_ERROR_INITIALIZATION_FAILED;
414 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700415
Jesse Hall1356b0d2015-11-23 17:24:58 -0800416 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700417 return VK_SUCCESS;
418}
419
Jesse Halle1b12782015-11-30 11:27:32 -0800420VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800421void DestroySurfaceKHR(VkInstance instance,
422 VkSurfaceKHR surface_handle,
423 const VkAllocationCallbacks* allocator) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800424 Surface* surface = SurfaceFromHandle(surface_handle);
425 if (!surface)
426 return;
427 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700428 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700429 "destroyed VkSurfaceKHR 0x%" PRIx64
430 " has active VkSwapchainKHR 0x%" PRIx64,
431 reinterpret_cast<uint64_t>(surface_handle),
432 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800433 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800434 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800435 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800436 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800437}
438
Jesse Halle1b12782015-11-30 11:27:32 -0800439VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800440VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
441 uint32_t /*queue_family*/,
442 VkSurfaceKHR /*surface*/,
443 VkBool32* supported) {
Jesse Hall0e74f002015-11-30 11:37:59 -0800444 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800445 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800446}
447
Jesse Halle1b12782015-11-30 11:27:32 -0800448VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800449VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Jesse Hallb00daad2015-11-29 19:46:20 -0800450 VkPhysicalDevice /*pdev*/,
451 VkSurfaceKHR surface,
452 VkSurfaceCapabilitiesKHR* capabilities) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700453 int err;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800454 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700455
456 int width, height;
457 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
458 if (err != 0) {
459 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
460 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700461 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700462 }
463 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
464 if (err != 0) {
465 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
466 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700467 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700468 }
469
Jesse Hall55bc0972016-02-23 16:43:29 -0800470 int transform_hint;
471 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
472 if (err != 0) {
473 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
474 strerror(-err), err);
475 return VK_ERROR_INITIALIZATION_FAILED;
476 }
477
Jesse Halld7b994a2015-09-07 14:17:37 -0700478 // TODO(jessehall): Figure out what the min/max values should be.
Jesse Hallb00daad2015-11-29 19:46:20 -0800479 capabilities->minImageCount = 2;
480 capabilities->maxImageCount = 3;
Jesse Halld7b994a2015-09-07 14:17:37 -0700481
Jesse Hallfe2662d2016-02-09 13:26:59 -0800482 capabilities->currentExtent =
483 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
484
Jesse Halld7b994a2015-09-07 14:17:37 -0700485 // TODO(jessehall): Figure out what the max extent should be. Maximum
486 // texture dimension maybe?
Jesse Hallb00daad2015-11-29 19:46:20 -0800487 capabilities->minImageExtent = VkExtent2D{1, 1};
488 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
Jesse Halld7b994a2015-09-07 14:17:37 -0700489
Jesse Hallfe2662d2016-02-09 13:26:59 -0800490 capabilities->maxImageArrayLayers = 1;
491
Jesse Hall55bc0972016-02-23 16:43:29 -0800492 capabilities->supportedTransforms = kSupportedTransforms;
493 capabilities->currentTransform =
494 TranslateNativeToVulkanTransform(transform_hint);
Jesse Halld7b994a2015-09-07 14:17:37 -0700495
Jesse Hallfe2662d2016-02-09 13:26:59 -0800496 // On Android, window composition is a WindowManager property, not something
497 // associated with the bufferqueue. It can't be changed from here.
498 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -0700499
500 // TODO(jessehall): I think these are right, but haven't thought hard about
501 // it. Do we need to query the driver for support of any of these?
502 // Currently not included:
Jesse Halld7b994a2015-09-07 14:17:37 -0700503 // - VK_IMAGE_USAGE_DEPTH_STENCIL_BIT: definitely not
504 // - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT: definitely not
Jesse Hallb00daad2015-11-29 19:46:20 -0800505 capabilities->supportedUsageFlags =
Jesse Hall3fbc8562015-11-29 22:10:52 -0800506 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
507 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
508 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
Jesse Halld7b994a2015-09-07 14:17:37 -0700509 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
510
Jesse Hallb1352bc2015-09-04 16:12:33 -0700511 return VK_SUCCESS;
512}
513
Jesse Halle1b12782015-11-30 11:27:32 -0800514VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800515VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice /*pdev*/,
516 VkSurfaceKHR /*surface*/,
517 uint32_t* count,
518 VkSurfaceFormatKHR* formats) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800519 // TODO(jessehall): Fill out the set of supported formats. Longer term, add
520 // a new gralloc method to query whether a (format, usage) pair is
521 // supported, and check that for each gralloc format that corresponds to a
522 // Vulkan format. Shorter term, just add a few more formats to the ones
523 // hardcoded below.
Jesse Halld7b994a2015-09-07 14:17:37 -0700524
525 const VkSurfaceFormatKHR kFormats[] = {
Jesse Hall26763382016-05-20 07:13:52 -0700526 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
527 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
528 {VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Jesse Halld7b994a2015-09-07 14:17:37 -0700529 };
530 const uint32_t kNumFormats = sizeof(kFormats) / sizeof(kFormats[0]);
531
532 VkResult result = VK_SUCCESS;
533 if (formats) {
534 if (*count < kNumFormats)
535 result = VK_INCOMPLETE;
Jesse Hall7331e222016-09-15 21:26:01 -0700536 *count = std::min(*count, kNumFormats);
537 std::copy(kFormats, kFormats + *count, formats);
538 } else {
539 *count = kNumFormats;
Jesse Halld7b994a2015-09-07 14:17:37 -0700540 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700541 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700542}
543
Jesse Halle1b12782015-11-30 11:27:32 -0800544VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +1300545VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Chia-I Wu62262232016-03-26 07:06:44 +0800546 VkSurfaceKHR /*surface*/,
547 uint32_t* count,
548 VkPresentModeKHR* modes) {
Chris Forbese8d79a62017-02-22 12:49:18 +1300549 android::Vector<VkPresentModeKHR> present_modes;
550 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
551 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
552
553 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
554 if (QueryPresentationProperties(pdev, &present_properties)) {
555 if (present_properties.sharedImage) {
556 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
557 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
558 }
559 }
560
561 uint32_t num_modes = uint32_t(present_modes.size());
Jesse Halld7b994a2015-09-07 14:17:37 -0700562
563 VkResult result = VK_SUCCESS;
564 if (modes) {
Chris Forbese8d79a62017-02-22 12:49:18 +1300565 if (*count < num_modes)
Jesse Halld7b994a2015-09-07 14:17:37 -0700566 result = VK_INCOMPLETE;
Chris Forbese8d79a62017-02-22 12:49:18 +1300567 *count = std::min(*count, num_modes);
568 std::copy(present_modes.begin(), present_modes.begin() + int(*count), modes);
Jesse Hall7331e222016-09-15 21:26:01 -0700569 } else {
Chris Forbese8d79a62017-02-22 12:49:18 +1300570 *count = num_modes;
Jesse Halld7b994a2015-09-07 14:17:37 -0700571 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700572 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700573}
574
Jesse Halle1b12782015-11-30 11:27:32 -0800575VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800576VkResult CreateSwapchainKHR(VkDevice device,
577 const VkSwapchainCreateInfoKHR* create_info,
578 const VkAllocationCallbacks* allocator,
579 VkSwapchainKHR* swapchain_handle) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700580 int err;
581 VkResult result = VK_SUCCESS;
582
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700583 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
584 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
585 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
586 " oldSwapchain=0x%" PRIx64,
587 reinterpret_cast<uint64_t>(create_info->surface),
588 create_info->minImageCount, create_info->imageFormat,
589 create_info->imageColorSpace, create_info->imageExtent.width,
590 create_info->imageExtent.height, create_info->imageUsage,
591 create_info->preTransform, create_info->presentMode,
592 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
593
Jesse Hall1f91d392015-12-11 16:28:44 -0800594 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800595 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800596
Jesse Hall42a9eec2016-06-03 12:39:49 -0700597 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -0700598 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -0800599 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700600 ALOGV_IF(create_info->imageColorSpace != VK_COLOR_SPACE_SRGB_NONLINEAR_KHR,
Jesse Halldc225072016-05-30 22:40:14 -0700601 "swapchain imageColorSpace=%u not supported",
602 create_info->imageColorSpace);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700603 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -0700604 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -0800605 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700606 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +1300607 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +1300608 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
609 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -0700610 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800611 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -0700612
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700613 Surface& surface = *SurfaceFromHandle(create_info->surface);
614
Jesse Halldc225072016-05-30 22:40:14 -0700615 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -0700616 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -0700617 " because it already has active swapchain 0x%" PRIx64
618 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
619 reinterpret_cast<uint64_t>(create_info->surface),
620 reinterpret_cast<uint64_t>(surface.swapchain_handle),
621 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
622 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
623 }
624 if (create_info->oldSwapchain != VK_NULL_HANDLE)
625 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
626
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700627 // -- Reset the native window --
628 // The native window might have been used previously, and had its properties
629 // changed from defaults. That will affect the answer we get for queries
630 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
631 // attempt such queries.
632
Jesse Halldc225072016-05-30 22:40:14 -0700633 // The native window only allows dequeueing all buffers before any have
634 // been queued, since after that point at least one is assumed to be in
635 // non-FREE state at any given time. Disconnecting and re-connecting
636 // orphans the previous buffers, getting us back to the state where we can
637 // dequeue all buffers.
638 err = native_window_api_disconnect(surface.window.get(),
639 NATIVE_WINDOW_API_EGL);
640 ALOGW_IF(err != 0, "native_window_api_disconnect failed: %s (%d)",
641 strerror(-err), err);
642 err =
643 native_window_api_connect(surface.window.get(), NATIVE_WINDOW_API_EGL);
644 ALOGW_IF(err != 0, "native_window_api_connect failed: %s (%d)",
645 strerror(-err), err);
646
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700647 err = native_window_set_buffer_count(surface.window.get(), 0);
648 if (err != 0) {
649 ALOGE("native_window_set_buffer_count(0) failed: %s (%d)",
650 strerror(-err), err);
651 return VK_ERROR_INITIALIZATION_FAILED;
652 }
653
654 err = surface.window->setSwapInterval(surface.window.get(), 1);
655 if (err != 0) {
656 // TODO(jessehall): Improve error reporting. Can we enumerate possible
657 // errors and translate them to valid Vulkan result codes?
658 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
659 strerror(-err), err);
660 return VK_ERROR_INITIALIZATION_FAILED;
661 }
662
Chris Forbesb8042d22017-01-18 18:07:05 +1300663 err = native_window_set_shared_buffer_mode(surface.window.get(), false);
664 if (err != 0) {
665 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
666 strerror(-err), err);
667 return VK_ERROR_INITIALIZATION_FAILED;
668 }
669
670 err = native_window_set_auto_refresh(surface.window.get(), false);
671 if (err != 0) {
672 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
673 strerror(-err), err);
674 return VK_ERROR_INITIALIZATION_FAILED;
675 }
676
Jesse Halld7b994a2015-09-07 14:17:37 -0700677 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -0700678
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800679 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -0800680
Jesse Hall517274a2016-02-10 00:07:18 -0800681 int native_format = HAL_PIXEL_FORMAT_RGBA_8888;
682 switch (create_info->imageFormat) {
683 case VK_FORMAT_R8G8B8A8_UNORM:
684 case VK_FORMAT_R8G8B8A8_SRGB:
685 native_format = HAL_PIXEL_FORMAT_RGBA_8888;
686 break;
687 case VK_FORMAT_R5G6B5_UNORM_PACK16:
688 native_format = HAL_PIXEL_FORMAT_RGB_565;
689 break;
690 default:
Jesse Hall42a9eec2016-06-03 12:39:49 -0700691 ALOGV("unsupported swapchain format %d", create_info->imageFormat);
Jesse Hall517274a2016-02-10 00:07:18 -0800692 break;
693 }
694 err = native_window_set_buffers_format(surface.window.get(), native_format);
695 if (err != 0) {
696 // TODO(jessehall): Improve error reporting. Can we enumerate possible
697 // errors and translate them to valid Vulkan result codes?
698 ALOGE("native_window_set_buffers_format(%d) failed: %s (%d)",
699 native_format, strerror(-err), err);
700 return VK_ERROR_INITIALIZATION_FAILED;
701 }
702 err = native_window_set_buffers_data_space(surface.window.get(),
703 HAL_DATASPACE_SRGB_LINEAR);
704 if (err != 0) {
705 // TODO(jessehall): Improve error reporting. Can we enumerate possible
706 // errors and translate them to valid Vulkan result codes?
707 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
708 HAL_DATASPACE_SRGB_LINEAR, strerror(-err), err);
709 return VK_ERROR_INITIALIZATION_FAILED;
710 }
711
Jesse Hall3dd678a2016-01-08 21:52:01 -0800712 err = native_window_set_buffers_dimensions(
713 surface.window.get(), static_cast<int>(create_info->imageExtent.width),
714 static_cast<int>(create_info->imageExtent.height));
Jesse Halld7b994a2015-09-07 14:17:37 -0700715 if (err != 0) {
716 // TODO(jessehall): Improve error reporting. Can we enumerate possible
717 // errors and translate them to valid Vulkan result codes?
718 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
719 create_info->imageExtent.width, create_info->imageExtent.height,
720 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700721 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700722 }
723
Jesse Hall178b6962016-02-24 15:39:50 -0800724 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
725 // applied during rendering. native_window_set_transform() expects the
726 // inverse: the transform the app is requesting that the compositor perform
727 // during composition. With native windows, pre-transform works by rendering
728 // with the same transform the compositor is applying (as in Vulkan), but
729 // then requesting the inverse transform, so that when the compositor does
730 // it's job the two transforms cancel each other out and the compositor ends
731 // up applying an identity transform to the app's buffer.
732 err = native_window_set_buffers_transform(
733 surface.window.get(),
734 InvertTransformToNative(create_info->preTransform));
735 if (err != 0) {
736 // TODO(jessehall): Improve error reporting. Can we enumerate possible
737 // errors and translate them to valid Vulkan result codes?
738 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
739 InvertTransformToNative(create_info->preTransform),
740 strerror(-err), err);
741 return VK_ERROR_INITIALIZATION_FAILED;
742 }
743
Jesse Hallf64ca122015-11-03 16:11:10 -0800744 err = native_window_set_scaling_mode(
Jesse Hall1356b0d2015-11-23 17:24:58 -0800745 surface.window.get(), NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Jesse Hallf64ca122015-11-03 16:11:10 -0800746 if (err != 0) {
747 // TODO(jessehall): Improve error reporting. Can we enumerate possible
748 // errors and translate them to valid Vulkan result codes?
749 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
750 strerror(-err), err);
Jesse Hallf64ca122015-11-03 16:11:10 -0800751 return VK_ERROR_INITIALIZATION_FAILED;
752 }
753
Jesse Halle6080bf2016-02-28 20:58:50 -0800754 int query_value;
755 err = surface.window->query(surface.window.get(),
756 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
757 &query_value);
758 if (err != 0 || query_value < 0) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700759 // TODO(jessehall): Improve error reporting. Can we enumerate possible
760 // errors and translate them to valid Vulkan result codes?
Jesse Halle6080bf2016-02-28 20:58:50 -0800761 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
762 query_value);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700763 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700764 }
Jesse Halle6080bf2016-02-28 20:58:50 -0800765 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800766 // The MIN_UNDEQUEUED_BUFFERS query doesn't know whether we'll be using
767 // async mode or not, and assumes not. But in async mode, the BufferQueue
768 // requires an extra undequeued buffer.
769 // See BufferQueueCore::getMinUndequeuedBufferCountLocked().
770 if (create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR)
771 min_undequeued_buffers += 1;
772
Jesse Halld7b994a2015-09-07 14:17:37 -0700773 uint32_t num_images =
774 (create_info->minImageCount - 1) + min_undequeued_buffers;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800775 err = native_window_set_buffer_count(surface.window.get(), num_images);
Jesse Halld7b994a2015-09-07 14:17:37 -0700776 if (err != 0) {
777 // TODO(jessehall): Improve error reporting. Can we enumerate possible
778 // errors and translate them to valid Vulkan result codes?
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700779 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", num_images,
780 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700781 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700782 }
783
Chris Forbes8c47dc92017-01-12 11:13:58 +1300784 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes1d5f68c2017-01-31 10:17:01 +1300785 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
786 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Chris Forbes4da65b92017-01-31 11:48:50 +1300787 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Chris Forbesb8042d22017-01-18 18:07:05 +1300788
789 err = native_window_set_shared_buffer_mode(surface.window.get(), true);
790 if (err != 0) {
791 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
792 return VK_ERROR_INITIALIZATION_FAILED;
793 }
794 }
795
Chris Forbes1d5f68c2017-01-31 10:17:01 +1300796 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Chris Forbesb8042d22017-01-18 18:07:05 +1300797 err = native_window_set_auto_refresh(surface.window.get(), true);
798 if (err != 0) {
799 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
800 return VK_ERROR_INITIALIZATION_FAILED;
801 }
Chris Forbesb4421522017-01-18 16:57:02 +1300802 }
803
Jesse Hall70f93352015-11-04 09:41:31 -0800804 int gralloc_usage = 0;
Chris Forbes8c47dc92017-01-12 11:13:58 +1300805 if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
Jesse Halld1abd742017-02-09 21:45:51 -0800806 uint64_t consumer_usage, producer_usage;
Kalle Raitafc00a1d2017-02-22 13:05:45 -0800807 uint32_t driver_version = GetData(device).driver_version;
808 if (driver_version == 256587285 || driver_version == 96011958) {
Jesse Hall85bb0c52017-02-09 22:13:02 -0800809 // HACK workaround for loader/driver mismatch during transition to
810 // vkGetSwapchainGrallocUsage2ANDROID.
811 typedef VkResult(VKAPI_PTR *
812 PFN_vkGetSwapchainGrallocUsage2ANDROID_HACK)(
813 VkDevice device, VkFormat format, VkImageUsageFlags imageUsage,
814 uint64_t * grallocConsumerUsage,
815 uint64_t * grallocProducerUsage);
816 auto get_swapchain_gralloc_usage =
817 reinterpret_cast<PFN_vkGetSwapchainGrallocUsage2ANDROID_HACK>(
818 dispatch.GetSwapchainGrallocUsage2ANDROID);
819 result = get_swapchain_gralloc_usage(
820 device, create_info->imageFormat, create_info->imageUsage,
821 &consumer_usage, &producer_usage);
822 } else {
823 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
824 device, create_info->imageFormat, create_info->imageUsage,
825 swapchain_image_usage, &consumer_usage, &producer_usage);
826 }
Chris Forbes8c47dc92017-01-12 11:13:58 +1300827 if (result != VK_SUCCESS) {
828 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
829 return VK_ERROR_INITIALIZATION_FAILED;
830 }
Jesse Halld1abd742017-02-09 21:45:51 -0800831 // TODO: This is the same translation done by Gralloc1On0Adapter.
832 // Remove it once ANativeWindow has been updated to take gralloc1-style
833 // usages.
834 gralloc_usage =
835 static_cast<int>(consumer_usage) | static_cast<int>(producer_usage);
Chris Forbes8c47dc92017-01-12 11:13:58 +1300836 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
Jesse Hall1f91d392015-12-11 16:28:44 -0800837 result = dispatch.GetSwapchainGrallocUsageANDROID(
Jesse Hallf4ab2b12015-11-30 16:04:55 -0800838 device, create_info->imageFormat, create_info->imageUsage,
Jesse Hall70f93352015-11-04 09:41:31 -0800839 &gralloc_usage);
840 if (result != VK_SUCCESS) {
841 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Jesse Hall70f93352015-11-04 09:41:31 -0800842 return VK_ERROR_INITIALIZATION_FAILED;
843 }
Jesse Hall70f93352015-11-04 09:41:31 -0800844 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800845 err = native_window_set_usage(surface.window.get(), gralloc_usage);
Jesse Hall70f93352015-11-04 09:41:31 -0800846 if (err != 0) {
847 // TODO(jessehall): Improve error reporting. Can we enumerate possible
848 // errors and translate them to valid Vulkan result codes?
849 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Jesse Hall70f93352015-11-04 09:41:31 -0800850 return VK_ERROR_INITIALIZATION_FAILED;
851 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700852
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700853 int swap_interval =
854 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
855 err = surface.window->setSwapInterval(surface.window.get(), swap_interval);
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800856 if (err != 0) {
857 // TODO(jessehall): Improve error reporting. Can we enumerate possible
858 // errors and translate them to valid Vulkan result codes?
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700859 ALOGE("native_window->setSwapInterval(%d) failed: %s (%d)",
860 swap_interval, strerror(-err), err);
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800861 return VK_ERROR_INITIALIZATION_FAILED;
862 }
863
Jesse Halld7b994a2015-09-07 14:17:37 -0700864 // -- Allocate our Swapchain object --
865 // After this point, we must deallocate the swapchain on error.
866
Jesse Hall1f91d392015-12-11 16:28:44 -0800867 void* mem = allocator->pfnAllocation(allocator->pUserData,
868 sizeof(Swapchain), alignof(Swapchain),
869 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800870 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -0700871 return VK_ERROR_OUT_OF_HOST_MEMORY;
Ian Elliottffedb652017-02-14 10:58:30 -0700872 Swapchain* swapchain =
873 new (mem) Swapchain(surface, num_images, create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -0700874
875 // -- Dequeue all buffers and create a VkImage for each --
876 // Any failures during or after this must cancel the dequeued buffers.
877
Chris Forbesb56287a2017-01-12 14:28:58 +1300878 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
879#pragma clang diagnostic push
880#pragma clang diagnostic ignored "-Wold-style-cast"
881 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
882#pragma clang diagnostic pop
883 .pNext = nullptr,
884 .usage = swapchain_image_usage,
885 };
Jesse Halld7b994a2015-09-07 14:17:37 -0700886 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -0700887#pragma clang diagnostic push
888#pragma clang diagnostic ignored "-Wold-style-cast"
889 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
890#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +1300891 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -0700892 };
893 VkImageCreateInfo image_create = {
894 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
895 .pNext = &image_native_buffer,
896 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -0800897 .format = create_info->imageFormat,
Jesse Halld7b994a2015-09-07 14:17:37 -0700898 .extent = {0, 0, 1},
899 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -0800900 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -0800901 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -0700902 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -0800903 .usage = create_info->imageUsage,
Jesse Halld7b994a2015-09-07 14:17:37 -0700904 .flags = 0,
Jesse Hallf4ab2b12015-11-30 16:04:55 -0800905 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -0800906 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -0700907 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
908 };
909
Jesse Halld7b994a2015-09-07 14:17:37 -0700910 for (uint32_t i = 0; i < num_images; i++) {
911 Swapchain::Image& img = swapchain->images[i];
912
913 ANativeWindowBuffer* buffer;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800914 err = surface.window->dequeueBuffer(surface.window.get(), &buffer,
915 &img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700916 if (err != 0) {
917 // TODO(jessehall): Improve error reporting. Can we enumerate
918 // possible errors and translate them to valid Vulkan result codes?
919 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700920 result = VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700921 break;
922 }
Chia-I Wue8e689f2016-04-18 08:21:31 +0800923 img.buffer = buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700924 img.dequeued = true;
925
926 image_create.extent =
Jesse Hall3dd678a2016-01-08 21:52:01 -0800927 VkExtent3D{static_cast<uint32_t>(img.buffer->width),
928 static_cast<uint32_t>(img.buffer->height),
929 1};
Jesse Halld7b994a2015-09-07 14:17:37 -0700930 image_native_buffer.handle = img.buffer->handle;
931 image_native_buffer.stride = img.buffer->stride;
932 image_native_buffer.format = img.buffer->format;
933 image_native_buffer.usage = img.buffer->usage;
Jesse Halld1abd742017-02-09 21:45:51 -0800934 // TODO: Adjust once ANativeWindowBuffer supports gralloc1-style usage.
935 // For now, this is the same translation Gralloc1On0Adapter does.
936 image_native_buffer.usage2.consumer =
937 static_cast<uint64_t>(img.buffer->usage);
938 image_native_buffer.usage2.producer =
939 static_cast<uint64_t>(img.buffer->usage);
Jesse Halld7b994a2015-09-07 14:17:37 -0700940
Jesse Hall03b6fe12015-11-24 12:44:21 -0800941 result =
Jesse Hall1f91d392015-12-11 16:28:44 -0800942 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
Jesse Halld7b994a2015-09-07 14:17:37 -0700943 if (result != VK_SUCCESS) {
944 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
945 break;
946 }
947 }
948
949 // -- Cancel all buffers, returning them to the queue --
950 // If an error occurred before, also destroy the VkImage and release the
951 // buffer reference. Otherwise, we retain a strong reference to the buffer.
952 //
953 // TODO(jessehall): The error path here is the same as DestroySwapchain,
954 // but not the non-error path. Should refactor/unify.
955 for (uint32_t i = 0; i < num_images; i++) {
956 Swapchain::Image& img = swapchain->images[i];
957 if (img.dequeued) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800958 surface.window->cancelBuffer(surface.window.get(), img.buffer.get(),
959 img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700960 img.dequeue_fence = -1;
961 img.dequeued = false;
962 }
963 if (result != VK_SUCCESS) {
964 if (img.image)
Jesse Hall1f91d392015-12-11 16:28:44 -0800965 dispatch.DestroyImage(device, img.image, nullptr);
Jesse Halld7b994a2015-09-07 14:17:37 -0700966 }
967 }
968
969 if (result != VK_SUCCESS) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700970 swapchain->~Swapchain();
Jesse Hall1f91d392015-12-11 16:28:44 -0800971 allocator->pfnFree(allocator->pUserData, swapchain);
Jesse Halld7b994a2015-09-07 14:17:37 -0700972 return result;
973 }
974
Jesse Halldc225072016-05-30 22:40:14 -0700975 surface.swapchain_handle = HandleFromSwapchain(swapchain);
976 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700977 return VK_SUCCESS;
978}
979
Jesse Halle1b12782015-11-30 11:27:32 -0800980VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800981void DestroySwapchainKHR(VkDevice device,
982 VkSwapchainKHR swapchain_handle,
983 const VkAllocationCallbacks* allocator) {
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800984 const auto& dispatch = GetData(device).driver;
Jesse Halld7b994a2015-09-07 14:17:37 -0700985 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
Daniel Kochd78c2e82016-12-13 18:45:13 -0500986 if (!swapchain)
987 return;
Jesse Hall42a9eec2016-06-03 12:39:49 -0700988 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
989 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
Jesse Halld7b994a2015-09-07 14:17:37 -0700990
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700991 if (swapchain->frame_timestamps_enabled) {
992 native_window_enable_frame_timestamps(window, false);
993 }
Jesse Halldc225072016-05-30 22:40:14 -0700994 for (uint32_t i = 0; i < swapchain->num_images; i++)
995 ReleaseSwapchainImage(device, window, -1, swapchain->images[i]);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700996 if (active)
Jesse Halldc225072016-05-30 22:40:14 -0700997 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Jesse Hall1f91d392015-12-11 16:28:44 -0800998 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800999 allocator = &GetData(device).allocator;
Jesse Halld7b994a2015-09-07 14:17:37 -07001000 swapchain->~Swapchain();
Jesse Hall1f91d392015-12-11 16:28:44 -08001001 allocator->pfnFree(allocator->pUserData, swapchain);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001002}
1003
Jesse Halle1b12782015-11-30 11:27:32 -08001004VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001005VkResult GetSwapchainImagesKHR(VkDevice,
1006 VkSwapchainKHR swapchain_handle,
1007 uint32_t* count,
1008 VkImage* images) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001009 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07001010 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
1011 "getting images for non-active swapchain 0x%" PRIx64
1012 "; only dequeued image handles are valid",
1013 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07001014 VkResult result = VK_SUCCESS;
1015 if (images) {
1016 uint32_t n = swapchain.num_images;
1017 if (*count < swapchain.num_images) {
1018 n = *count;
1019 result = VK_INCOMPLETE;
1020 }
1021 for (uint32_t i = 0; i < n; i++)
1022 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07001023 *count = n;
1024 } else {
1025 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07001026 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001027 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001028}
1029
Jesse Halle1b12782015-11-30 11:27:32 -08001030VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001031VkResult AcquireNextImageKHR(VkDevice device,
1032 VkSwapchainKHR swapchain_handle,
1033 uint64_t timeout,
1034 VkSemaphore semaphore,
1035 VkFence vk_fence,
1036 uint32_t* image_index) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001037 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001038 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07001039 VkResult result;
1040 int err;
1041
Jesse Halldc225072016-05-30 22:40:14 -07001042 if (swapchain.surface.swapchain_handle != swapchain_handle)
1043 return VK_ERROR_OUT_OF_DATE_KHR;
1044
Jesse Halld7b994a2015-09-07 14:17:37 -07001045 ALOGW_IF(
1046 timeout != UINT64_MAX,
1047 "vkAcquireNextImageKHR: non-infinite timeouts not yet implemented");
1048
1049 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08001050 int fence_fd;
1051 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001052 if (err != 0) {
1053 // TODO(jessehall): Improve error reporting. Can we enumerate possible
1054 // errors and translate them to valid Vulkan result codes?
1055 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -07001056 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -07001057 }
1058
1059 uint32_t idx;
1060 for (idx = 0; idx < swapchain.num_images; idx++) {
1061 if (swapchain.images[idx].buffer.get() == buffer) {
1062 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08001063 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07001064 break;
1065 }
1066 }
1067 if (idx == swapchain.num_images) {
1068 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08001069 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001070 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001071 }
1072
1073 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08001074 if (fence_fd != -1) {
1075 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001076 if (fence_clone == -1) {
1077 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
1078 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08001079 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07001080 }
1081 }
1082
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001083 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08001084 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001085 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001086 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
1087 // even if the call fails. We could close it ourselves on failure, but
1088 // that would create a race condition if the driver closes it on a
1089 // failure path: some other thread might create an fd with the same
1090 // number between the time the driver closes it and the time we close
1091 // it. We must assume one of: the driver *always* closes it even on
1092 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08001093 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001094 swapchain.images[idx].dequeued = false;
1095 swapchain.images[idx].dequeue_fence = -1;
1096 return result;
1097 }
1098
1099 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001100 return VK_SUCCESS;
1101}
1102
Jesse Halldc225072016-05-30 22:40:14 -07001103static VkResult WorstPresentResult(VkResult a, VkResult b) {
1104 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
1105 // (in spec version 1.0.14).
1106 static const VkResult kWorstToBest[] = {
1107 VK_ERROR_DEVICE_LOST,
1108 VK_ERROR_SURFACE_LOST_KHR,
1109 VK_ERROR_OUT_OF_DATE_KHR,
1110 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1111 VK_ERROR_OUT_OF_HOST_MEMORY,
1112 VK_SUBOPTIMAL_KHR,
1113 };
1114 for (auto result : kWorstToBest) {
1115 if (a == result || b == result)
1116 return result;
1117 }
1118 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
1119 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
1120 return a != VK_SUCCESS ? a : b;
1121}
1122
Jesse Halle1b12782015-11-30 11:27:32 -08001123VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001124VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001125 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
1126 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
1127 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07001128
Jesse Halldc225072016-05-30 22:40:14 -07001129 VkDevice device = GetData(queue).driver_device;
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001130 const auto& dispatch = GetData(queue).driver;
Jesse Halld7b994a2015-09-07 14:17:37 -07001131 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07001132
Ian Elliottcb351132016-12-13 10:30:40 -07001133 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001134 const VkPresentRegionsKHR* present_regions = nullptr;
1135 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07001136 const VkPresentRegionsKHR* next =
1137 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
1138 while (next) {
1139 switch (next->sType) {
1140 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
1141 present_regions = next;
1142 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07001143 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001144 present_times =
1145 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
1146 break;
Ian Elliottcb351132016-12-13 10:30:40 -07001147 default:
1148 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
1149 next->sType);
1150 break;
1151 }
1152 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
1153 }
1154 ALOGV_IF(
1155 present_regions &&
1156 present_regions->swapchainCount != present_info->swapchainCount,
1157 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001158 ALOGV_IF(present_times &&
1159 present_times->swapchainCount != present_info->swapchainCount,
1160 "VkPresentTimesInfoGOOGLE::swapchainCount != "
1161 "VkPresentInfo::swapchainCount");
Ian Elliottcb351132016-12-13 10:30:40 -07001162 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001163 (present_regions) ? present_regions->pRegions : nullptr;
1164 const VkPresentTimeGOOGLE* times =
1165 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07001166 const VkAllocationCallbacks* allocator = &GetData(device).allocator;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001167 android_native_rect_t* rects = nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07001168 uint32_t nrects = 0;
1169
Jesse Halld7b994a2015-09-07 14:17:37 -07001170 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
1171 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08001172 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001173 uint32_t image_idx = present_info->pImageIndices[sc];
Jesse Hall5ae3abb2015-10-08 14:00:22 -07001174 Swapchain::Image& img = swapchain.images[image_idx];
Ian Elliottffedb652017-02-14 10:58:30 -07001175 const VkPresentRegionKHR* region =
1176 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001177 const VkPresentTimeGOOGLE* time = (times) ? &times[sc] : nullptr;
Jesse Halldc225072016-05-30 22:40:14 -07001178 VkResult swapchain_result = VK_SUCCESS;
Jesse Halld7b994a2015-09-07 14:17:37 -07001179 VkResult result;
1180 int err;
1181
Jesse Halld7b994a2015-09-07 14:17:37 -07001182 int fence = -1;
Jesse Hall275d76c2016-01-08 22:39:16 -08001183 result = dispatch.QueueSignalReleaseImageANDROID(
1184 queue, present_info->waitSemaphoreCount,
1185 present_info->pWaitSemaphores, img.image, &fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001186 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001187 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
Jesse Halldc225072016-05-30 22:40:14 -07001188 swapchain_result = result;
Jesse Halld7b994a2015-09-07 14:17:37 -07001189 }
1190
Jesse Halldc225072016-05-30 22:40:14 -07001191 if (swapchain.surface.swapchain_handle ==
1192 present_info->pSwapchains[sc]) {
1193 ANativeWindow* window = swapchain.surface.window.get();
1194 if (swapchain_result == VK_SUCCESS) {
Ian Elliottcb351132016-12-13 10:30:40 -07001195 if (region) {
1196 // Process the incremental-present hint for this swapchain:
1197 uint32_t rcount = region->rectangleCount;
1198 if (rcount > nrects) {
1199 android_native_rect_t* new_rects =
1200 static_cast<android_native_rect_t*>(
1201 allocator->pfnReallocation(
1202 allocator->pUserData, rects,
1203 sizeof(android_native_rect_t) * rcount,
1204 alignof(android_native_rect_t),
1205 VK_SYSTEM_ALLOCATION_SCOPE_COMMAND));
1206 if (new_rects) {
1207 rects = new_rects;
1208 nrects = rcount;
1209 } else {
1210 rcount = 0; // Ignore the hint for this swapchain
1211 }
1212 }
1213 for (uint32_t r = 0; r < rcount; ++r) {
1214 if (region->pRectangles[r].layer > 0) {
1215 ALOGV(
1216 "vkQueuePresentKHR ignoring invalid layer "
1217 "(%u); using layer 0 instead",
1218 region->pRectangles[r].layer);
1219 }
1220 int x = region->pRectangles[r].offset.x;
1221 int y = region->pRectangles[r].offset.y;
1222 int width = static_cast<int>(
1223 region->pRectangles[r].extent.width);
1224 int height = static_cast<int>(
1225 region->pRectangles[r].extent.height);
1226 android_native_rect_t* cur_rect = &rects[r];
1227 cur_rect->left = x;
1228 cur_rect->top = y + height;
1229 cur_rect->right = x + width;
1230 cur_rect->bottom = y;
1231 }
1232 native_window_set_surface_damage(window, rects, rcount);
1233 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001234 if (time) {
1235 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07001236 ALOGV(
1237 "Calling "
1238 "native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001239 native_window_enable_frame_timestamps(window, true);
1240 swapchain.frame_timestamps_enabled = true;
1241 }
Brian Anderson1049d1d2016-12-16 17:25:57 -08001242
1243 // Record the nativeFrameId so it can be later correlated to
1244 // this present.
1245 uint64_t nativeFrameId = 0;
1246 err = native_window_get_next_frame_id(
1247 window, &nativeFrameId);
1248 if (err != android::NO_ERROR) {
1249 ALOGE("Failed to get next native frame ID.");
1250 }
1251
1252 // Add a new timing record with the user's presentID and
1253 // the nativeFrameId.
1254 swapchain.timing.push_back(TimingInfo(time, nativeFrameId));
1255 while (swapchain.timing.size() > MAX_TIMING_INFOS) {
Ian Elliott8a977262017-01-19 09:05:58 -07001256 swapchain.timing.removeAt(0);
1257 }
1258 if (time->desiredPresentTime) {
1259 // Set the desiredPresentTime:
1260 ALOGV(
1261 "Calling "
1262 "native_window_set_buffers_timestamp(%" PRId64 ")",
1263 time->desiredPresentTime);
1264 native_window_set_buffers_timestamp(
1265 window,
1266 static_cast<int64_t>(time->desiredPresentTime));
1267 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001268 }
Jesse Halldc225072016-05-30 22:40:14 -07001269 err = window->queueBuffer(window, img.buffer.get(), fence);
1270 // queueBuffer always closes fence, even on error
1271 if (err != 0) {
1272 // TODO(jessehall): What now? We should probably cancel the
1273 // buffer, I guess?
1274 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
1275 swapchain_result = WorstPresentResult(
1276 swapchain_result, VK_ERROR_OUT_OF_DATE_KHR);
1277 }
1278 if (img.dequeue_fence >= 0) {
1279 close(img.dequeue_fence);
1280 img.dequeue_fence = -1;
1281 }
1282 img.dequeued = false;
1283 }
1284 if (swapchain_result != VK_SUCCESS) {
1285 ReleaseSwapchainImage(device, window, fence, img);
1286 OrphanSwapchain(device, &swapchain);
1287 }
1288 } else {
1289 ReleaseSwapchainImage(device, nullptr, fence, img);
1290 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001291 }
1292
Jesse Halla9e57032015-11-30 01:03:10 -08001293 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07001294 present_info->pResults[sc] = swapchain_result;
1295
1296 if (swapchain_result != final_result)
1297 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07001298 }
Ian Elliottcb351132016-12-13 10:30:40 -07001299 if (rects) {
1300 allocator->pfnFree(allocator->pUserData, rects);
1301 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001302
1303 return final_result;
1304}
Jesse Hallb1352bc2015-09-04 16:12:33 -07001305
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001306VKAPI_ATTR
1307VkResult GetRefreshCycleDurationGOOGLE(
1308 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07001309 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001310 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Ian Elliott62c48c92017-01-20 13:13:20 -07001311 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001312 VkResult result = VK_SUCCESS;
1313
Ian Elliottbe833a22017-01-25 13:09:20 -07001314 pDisplayTimingProperties->refreshDuration = swapchain.refresh_duration;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001315
1316 return result;
1317}
1318
1319VKAPI_ATTR
1320VkResult GetPastPresentationTimingGOOGLE(
1321 VkDevice,
1322 VkSwapchainKHR swapchain_handle,
1323 uint32_t* count,
1324 VkPastPresentationTimingGOOGLE* timings) {
1325 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
1326 ANativeWindow* window = swapchain.surface.window.get();
1327 VkResult result = VK_SUCCESS;
1328
1329 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07001330 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001331 native_window_enable_frame_timestamps(window, true);
1332 swapchain.frame_timestamps_enabled = true;
1333 }
1334
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001335 if (timings) {
Ian Elliott8a977262017-01-19 09:05:58 -07001336 // TODO(ianelliott): plumb return value (e.g. VK_INCOMPLETE)
1337 copy_ready_timings(swapchain, count, timings);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001338 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07001339 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001340 }
1341
1342 return result;
1343}
1344
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13001345VKAPI_ATTR
1346VkResult GetSwapchainStatusKHR(
1347 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13001348 VkSwapchainKHR swapchain_handle) {
1349 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13001350 VkResult result = VK_SUCCESS;
1351
Chris Forbes4e18ba82017-01-20 12:50:17 +13001352 if (swapchain.surface.swapchain_handle != swapchain_handle) {
1353 return VK_ERROR_OUT_OF_DATE_KHR;
1354 }
1355
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13001356 // TODO(chrisforbes): Implement this function properly
1357
1358 return result;
1359}
1360
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07001361VKAPI_ATTR void SetHdrMetadataEXT(
1362 VkDevice device,
1363 uint32_t swapchainCount,
1364 const VkSwapchainKHR* pSwapchains,
1365 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
1366 // TODO: courtneygo: implement actual function
1367 (void)device;
1368 (void)swapchainCount;
1369 (void)pSwapchains;
1370 (void)pHdrMetadataEXTs;
1371 return;
1372}
1373
Chia-I Wu62262232016-03-26 07:06:44 +08001374} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07001375} // namespace vulkan