blob: 87d2a60dfa685070c290eed1bf29c877abeeeeaa [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>
Ian Elliott8a977262017-01-19 09:05:58 -070023#include <utils/SortedVector.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:
Ian Elliott2c6355d2017-01-19 11:02:13 -0700111 TimingInfo()
112 : vals_{0, 0, 0, 0, 0},
113 timestamp_desired_present_time_(0),
114 timestamp_actual_present_time_(0),
115 timestamp_render_complete_time_(0),
116 timestamp_composition_latch_time_(0) {}
117 TimingInfo(const VkPresentTimeGOOGLE* qp)
118 : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
119 timestamp_desired_present_time_(0),
120 timestamp_actual_present_time_(0),
121 timestamp_render_complete_time_(0),
122 timestamp_composition_latch_time_(0) {}
Ian Elliott8a977262017-01-19 09:05:58 -0700123 bool ready() {
124 return (timestamp_desired_present_time_ &&
125 timestamp_actual_present_time_ &&
126 timestamp_render_complete_time_ &&
127 timestamp_composition_latch_time_);
128 }
129 void calculate(uint64_t rdur) {
130 vals_.actualPresentTime = timestamp_actual_present_time_;
131 uint64_t margin = (timestamp_composition_latch_time_ -
132 timestamp_render_complete_time_);
133 // Calculate vals_.earliestPresentTime, and potentially adjust
134 // vals_.presentMargin. The initial value of vals_.earliestPresentTime
135 // is vals_.actualPresentTime. If we can subtract rdur (the duration
136 // of a refresh cycle) from vals_.earliestPresentTime (and also from
137 // vals_.presentMargin) and still leave a positive margin, then we can
138 // report to the application that it could have presented earlier than
139 // it did (per the extension specification). If for some reason, we
140 // can do this subtraction repeatedly, we do, since
141 // vals_.earliestPresentTime really is supposed to be the "earliest".
142 uint64_t early_time = vals_.actualPresentTime;
143 while ((margin > rdur) &&
144 ((early_time - rdur) > timestamp_composition_latch_time_)) {
145 early_time -= rdur;
146 margin -= rdur;
147 }
148 vals_.earliestPresentTime = early_time;
149 vals_.presentMargin = margin;
150 }
151 void get_values(VkPastPresentationTimingGOOGLE* values) { *values = vals_; }
152
153 public:
154 VkPastPresentationTimingGOOGLE vals_;
155
156 uint64_t timestamp_desired_present_time_;
157 uint64_t timestamp_actual_present_time_;
158 uint64_t timestamp_render_complete_time_;
159 uint64_t timestamp_composition_latch_time_;
160};
161
162static inline int compare_type(const TimingInfo& lhs, const TimingInfo& rhs) {
163 // TODO(ianelliott): Change this from presentID to the frame ID once
164 // brianderson lands the appropriate patch:
165 if (lhs.vals_.presentID < rhs.vals_.presentID)
166 return -1;
167 if (lhs.vals_.presentID > rhs.vals_.presentID)
168 return 1;
169 return 0;
170}
171
Jesse Halld7b994a2015-09-07 14:17:37 -0700172// ----------------------------------------------------------------------------
173
Jesse Hall1356b0d2015-11-23 17:24:58 -0800174struct Surface {
Chia-I Wue8e689f2016-04-18 08:21:31 +0800175 android::sp<ANativeWindow> window;
Jesse Halldc225072016-05-30 22:40:14 -0700176 VkSwapchainKHR swapchain_handle;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800177};
178
179VkSurfaceKHR HandleFromSurface(Surface* surface) {
180 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
181}
182
183Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800184 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800185}
186
Ian Elliott8a977262017-01-19 09:05:58 -0700187// Maximum number of TimingInfo structs to keep per swapchain:
188enum { MAX_TIMING_INFOS = 10 };
189// Minimum number of frames to look for in the past (so we don't cause
190// syncronous requests to Surface Flinger):
191enum { MIN_NUM_FRAMES_AGO = 5 };
192
Jesse Hall1356b0d2015-11-23 17:24:58 -0800193struct Swapchain {
Ian Elliottffedb652017-02-14 10:58:30 -0700194 Swapchain(Surface& surface_,
195 uint32_t num_images_,
196 VkPresentModeKHR present_mode)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700197 : surface(surface_),
198 num_images(num_images_),
Ian Elliottffedb652017-02-14 10:58:30 -0700199 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
Ian Elliott8a977262017-01-19 09:05:58 -0700200 frame_timestamps_enabled(false) {
201 timing.clear();
Ian Elliott62c48c92017-01-20 13:13:20 -0700202 ANativeWindow* window = surface.window.get();
Ian Elliottbe833a22017-01-25 13:09:20 -0700203 int64_t rdur;
204 native_window_get_refresh_cycle_duration(
Ian Elliott62c48c92017-01-20 13:13:20 -0700205 window,
Ian Elliottbe833a22017-01-25 13:09:20 -0700206 &rdur);
207 refresh_duration = static_cast<uint64_t>(rdur);
Ian Elliott8a977262017-01-19 09:05:58 -0700208 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800209
210 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700211 uint32_t num_images;
Ian Elliottffedb652017-02-14 10:58:30 -0700212 bool mailbox_mode;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700213 bool frame_timestamps_enabled;
Ian Elliottbe833a22017-01-25 13:09:20 -0700214 uint64_t refresh_duration;
Jesse Halld7b994a2015-09-07 14:17:37 -0700215
216 struct Image {
217 Image() : image(VK_NULL_HANDLE), dequeue_fence(-1), dequeued(false) {}
218 VkImage image;
Chia-I Wue8e689f2016-04-18 08:21:31 +0800219 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700220 // The fence is only valid when the buffer is dequeued, and should be
221 // -1 any other time. When valid, we own the fd, and must ensure it is
222 // closed: either by closing it explicitly when queueing the buffer,
223 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
224 int dequeue_fence;
225 bool dequeued;
226 } images[android::BufferQueue::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700227
228 android::SortedVector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700229};
230
231VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
232 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
233}
234
235Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800236 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700237}
238
Jesse Halldc225072016-05-30 22:40:14 -0700239void ReleaseSwapchainImage(VkDevice device,
240 ANativeWindow* window,
241 int release_fence,
242 Swapchain::Image& image) {
243 ALOG_ASSERT(release_fence == -1 || image.dequeued,
244 "ReleaseSwapchainImage: can't provide a release fence for "
245 "non-dequeued images");
246
247 if (image.dequeued) {
248 if (release_fence >= 0) {
249 // We get here from vkQueuePresentKHR. The application is
250 // responsible for creating an execution dependency chain from
251 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
252 // (release_fence), so we can drop the dequeue_fence here.
253 if (image.dequeue_fence >= 0)
254 close(image.dequeue_fence);
255 } else {
256 // We get here during swapchain destruction, or various serious
257 // error cases e.g. when we can't create the release_fence during
258 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
259 // have already signalled, since the swapchain images are supposed
260 // to be idle before the swapchain is destroyed. In error cases,
261 // there may be rendering in flight to the image, but since we
262 // weren't able to create a release_fence, waiting for the
263 // dequeue_fence is about the best we can do.
264 release_fence = image.dequeue_fence;
265 }
266 image.dequeue_fence = -1;
267
268 if (window) {
269 window->cancelBuffer(window, image.buffer.get(), release_fence);
270 } else {
271 if (release_fence >= 0) {
272 sync_wait(release_fence, -1 /* forever */);
273 close(release_fence);
274 }
275 }
276
277 image.dequeued = false;
278 }
279
280 if (image.image) {
281 GetData(device).driver.DestroyImage(device, image.image, nullptr);
282 image.image = VK_NULL_HANDLE;
283 }
284
285 image.buffer.clear();
286}
287
288void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
289 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
290 return;
Jesse Halldc225072016-05-30 22:40:14 -0700291 for (uint32_t i = 0; i < swapchain->num_images; i++) {
292 if (!swapchain->images[i].dequeued)
293 ReleaseSwapchainImage(device, nullptr, -1, swapchain->images[i]);
294 }
295 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700296 swapchain->timing.clear();
297}
298
299uint32_t get_num_ready_timings(Swapchain& swapchain) {
300 uint32_t num_ready = 0;
301 uint32_t num_timings = static_cast<uint32_t>(swapchain.timing.size());
302 uint32_t frames_ago = num_timings;
303 for (uint32_t i = 0; i < num_timings; i++) {
304 TimingInfo* ti = &swapchain.timing.editItemAt(i);
305 if (ti) {
306 if (ti->ready()) {
307 // This TimingInfo is ready to be reported to the user. Add it
308 // to the num_ready.
309 num_ready++;
310 } else {
311 // This TimingInfo is not yet ready to be reported to the user,
312 // and so we should look for any available timestamps that
313 // might make it ready.
314 int64_t desired_present_time = 0;
315 int64_t render_complete_time = 0;
316 int64_t composition_latch_time = 0;
317 int64_t actual_present_time = 0;
318 for (uint32_t f = MIN_NUM_FRAMES_AGO; f < frames_ago; f++) {
319 // Obtain timestamps:
320 int ret = native_window_get_frame_timestamps(
321 swapchain.surface.window.get(), f,
322 &desired_present_time, &render_complete_time,
323 &composition_latch_time,
324 NULL, //&first_composition_start_time,
325 NULL, //&last_composition_start_time,
326 NULL, //&composition_finish_time,
327 // TODO(ianelliott): Maybe ask if this one is
328 // supported, at startup time (since it may not be
329 // supported):
330 &actual_present_time,
331 NULL, //&display_retire_time,
332 NULL, //&dequeue_ready_time,
333 NULL /*&reads_done_time*/);
334 if (ret) {
335 break;
336 } else if (!ret) {
337 // We obtained at least one valid timestamp. See if it
338 // is for the present represented by this TimingInfo:
339 if (static_cast<uint64_t>(desired_present_time) ==
340 ti->vals_.desiredPresentTime) {
341 // Record the timestamp(s) we received, and then
342 // see if this TimingInfo is ready to be reported
343 // to the user:
344 ti->timestamp_desired_present_time_ =
345 static_cast<uint64_t>(desired_present_time);
346 ti->timestamp_actual_present_time_ =
347 static_cast<uint64_t>(actual_present_time);
348 ti->timestamp_render_complete_time_ =
349 static_cast<uint64_t>(render_complete_time);
350 ti->timestamp_composition_latch_time_ =
351 static_cast<uint64_t>(composition_latch_time);
352
353 if (ti->ready()) {
354 // The TimingInfo has received enough
355 // timestamps, and should now use those
356 // timestamps to calculate the info that should
357 // be reported to the user:
358 //
Ian Elliottbe833a22017-01-25 13:09:20 -0700359 ti->calculate(swapchain.refresh_duration);
Ian Elliott8a977262017-01-19 09:05:58 -0700360 num_ready++;
361 }
362 break;
363 }
364 }
365 }
366 }
367 }
368 }
369 return num_ready;
370}
371
372// TODO(ianelliott): DEAL WITH RETURN VALUE (e.g. VK_INCOMPLETE)!!!
373void copy_ready_timings(Swapchain& swapchain,
374 uint32_t* count,
375 VkPastPresentationTimingGOOGLE* timings) {
376 uint32_t num_copied = 0;
377 uint32_t num_timings = static_cast<uint32_t>(swapchain.timing.size());
378 if (*count < num_timings) {
379 num_timings = *count;
380 }
381 for (uint32_t i = 0; i < num_timings; i++) {
382 TimingInfo* ti = &swapchain.timing.editItemAt(i);
383 if (ti && ti->ready()) {
384 ti->get_values(&timings[num_copied]);
385 num_copied++;
386 // We only report the values for a given present once, so remove
387 // them from swapchain.timing:
388 //
389 // TODO(ianelliott): SEE WHAT HAPPENS TO THE LOOP WHEN THE
390 // FOLLOWING IS DONE:
391 swapchain.timing.removeAt(i);
392 i--;
393 num_timings--;
394 if (*count == num_copied) {
395 break;
396 }
397 }
398 }
399 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700400}
401
Jesse Halld7b994a2015-09-07 14:17:37 -0700402} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700403
Jesse Halle1b12782015-11-30 11:27:32 -0800404VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800405VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800406 VkInstance instance,
407 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
408 const VkAllocationCallbacks* allocator,
409 VkSurfaceKHR* out_surface) {
Jesse Hall1f91d392015-12-11 16:28:44 -0800410 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800411 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800412 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
413 alignof(Surface),
414 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800415 if (!mem)
416 return VK_ERROR_OUT_OF_HOST_MEMORY;
417 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700418
Chia-I Wue8e689f2016-04-18 08:21:31 +0800419 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700420 surface->swapchain_handle = VK_NULL_HANDLE;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700421
Jesse Hall1356b0d2015-11-23 17:24:58 -0800422 // TODO(jessehall): Create and use NATIVE_WINDOW_API_VULKAN.
423 int err =
424 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
425 if (err != 0) {
426 // TODO(jessehall): Improve error reporting. Can we enumerate possible
427 // errors and translate them to valid Vulkan result codes?
428 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
429 err);
430 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800431 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800432 return VK_ERROR_INITIALIZATION_FAILED;
433 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700434
Jesse Hall1356b0d2015-11-23 17:24:58 -0800435 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700436 return VK_SUCCESS;
437}
438
Jesse Halle1b12782015-11-30 11:27:32 -0800439VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800440void DestroySurfaceKHR(VkInstance instance,
441 VkSurfaceKHR surface_handle,
442 const VkAllocationCallbacks* allocator) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800443 Surface* surface = SurfaceFromHandle(surface_handle);
444 if (!surface)
445 return;
446 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700447 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700448 "destroyed VkSurfaceKHR 0x%" PRIx64
449 " has active VkSwapchainKHR 0x%" PRIx64,
450 reinterpret_cast<uint64_t>(surface_handle),
451 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800452 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800453 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800454 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800455 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800456}
457
Jesse Halle1b12782015-11-30 11:27:32 -0800458VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800459VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
460 uint32_t /*queue_family*/,
461 VkSurfaceKHR /*surface*/,
462 VkBool32* supported) {
Jesse Hall0e74f002015-11-30 11:37:59 -0800463 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800464 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800465}
466
Jesse Halle1b12782015-11-30 11:27:32 -0800467VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800468VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Jesse Hallb00daad2015-11-29 19:46:20 -0800469 VkPhysicalDevice /*pdev*/,
470 VkSurfaceKHR surface,
471 VkSurfaceCapabilitiesKHR* capabilities) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700472 int err;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800473 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700474
475 int width, height;
476 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
477 if (err != 0) {
478 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
479 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700480 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700481 }
482 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
483 if (err != 0) {
484 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
485 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700486 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700487 }
488
Jesse Hall55bc0972016-02-23 16:43:29 -0800489 int transform_hint;
490 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
491 if (err != 0) {
492 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
493 strerror(-err), err);
494 return VK_ERROR_INITIALIZATION_FAILED;
495 }
496
Jesse Halld7b994a2015-09-07 14:17:37 -0700497 // TODO(jessehall): Figure out what the min/max values should be.
Jesse Hallb00daad2015-11-29 19:46:20 -0800498 capabilities->minImageCount = 2;
499 capabilities->maxImageCount = 3;
Jesse Halld7b994a2015-09-07 14:17:37 -0700500
Jesse Hallfe2662d2016-02-09 13:26:59 -0800501 capabilities->currentExtent =
502 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
503
Jesse Halld7b994a2015-09-07 14:17:37 -0700504 // TODO(jessehall): Figure out what the max extent should be. Maximum
505 // texture dimension maybe?
Jesse Hallb00daad2015-11-29 19:46:20 -0800506 capabilities->minImageExtent = VkExtent2D{1, 1};
507 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
Jesse Halld7b994a2015-09-07 14:17:37 -0700508
Jesse Hallfe2662d2016-02-09 13:26:59 -0800509 capabilities->maxImageArrayLayers = 1;
510
Jesse Hall55bc0972016-02-23 16:43:29 -0800511 capabilities->supportedTransforms = kSupportedTransforms;
512 capabilities->currentTransform =
513 TranslateNativeToVulkanTransform(transform_hint);
Jesse Halld7b994a2015-09-07 14:17:37 -0700514
Jesse Hallfe2662d2016-02-09 13:26:59 -0800515 // On Android, window composition is a WindowManager property, not something
516 // associated with the bufferqueue. It can't be changed from here.
517 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -0700518
519 // TODO(jessehall): I think these are right, but haven't thought hard about
520 // it. Do we need to query the driver for support of any of these?
521 // Currently not included:
Jesse Halld7b994a2015-09-07 14:17:37 -0700522 // - VK_IMAGE_USAGE_DEPTH_STENCIL_BIT: definitely not
523 // - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT: definitely not
Jesse Hallb00daad2015-11-29 19:46:20 -0800524 capabilities->supportedUsageFlags =
Jesse Hall3fbc8562015-11-29 22:10:52 -0800525 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
526 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
527 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
Jesse Halld7b994a2015-09-07 14:17:37 -0700528 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
529
Jesse Hallb1352bc2015-09-04 16:12:33 -0700530 return VK_SUCCESS;
531}
532
Jesse Halle1b12782015-11-30 11:27:32 -0800533VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800534VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice /*pdev*/,
535 VkSurfaceKHR /*surface*/,
536 uint32_t* count,
537 VkSurfaceFormatKHR* formats) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800538 // TODO(jessehall): Fill out the set of supported formats. Longer term, add
539 // a new gralloc method to query whether a (format, usage) pair is
540 // supported, and check that for each gralloc format that corresponds to a
541 // Vulkan format. Shorter term, just add a few more formats to the ones
542 // hardcoded below.
Jesse Halld7b994a2015-09-07 14:17:37 -0700543
544 const VkSurfaceFormatKHR kFormats[] = {
Jesse Hall26763382016-05-20 07:13:52 -0700545 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
546 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
547 {VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Jesse Halld7b994a2015-09-07 14:17:37 -0700548 };
549 const uint32_t kNumFormats = sizeof(kFormats) / sizeof(kFormats[0]);
550
551 VkResult result = VK_SUCCESS;
552 if (formats) {
553 if (*count < kNumFormats)
554 result = VK_INCOMPLETE;
Jesse Hall7331e222016-09-15 21:26:01 -0700555 *count = std::min(*count, kNumFormats);
556 std::copy(kFormats, kFormats + *count, formats);
557 } else {
558 *count = kNumFormats;
Jesse Halld7b994a2015-09-07 14:17:37 -0700559 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700560 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700561}
562
Jesse Halle1b12782015-11-30 11:27:32 -0800563VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800564VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice /*pdev*/,
565 VkSurfaceKHR /*surface*/,
566 uint32_t* count,
567 VkPresentModeKHR* modes) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700568 const VkPresentModeKHR kModes[] = {
569 VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
Chris Forbes980ad052017-01-18 16:55:07 +1300570 // TODO(chrisforbes): should only expose this if the driver can.
Chris Forbese3066e92017-02-08 09:59:36 +1300571 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR,
572 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR,
Jesse Halld7b994a2015-09-07 14:17:37 -0700573 };
574 const uint32_t kNumModes = sizeof(kModes) / sizeof(kModes[0]);
575
576 VkResult result = VK_SUCCESS;
577 if (modes) {
578 if (*count < kNumModes)
579 result = VK_INCOMPLETE;
Jesse Hall7331e222016-09-15 21:26:01 -0700580 *count = std::min(*count, kNumModes);
581 std::copy(kModes, kModes + *count, modes);
582 } else {
583 *count = kNumModes;
Jesse Halld7b994a2015-09-07 14:17:37 -0700584 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700585 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700586}
587
Jesse Halle1b12782015-11-30 11:27:32 -0800588VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800589VkResult CreateSwapchainKHR(VkDevice device,
590 const VkSwapchainCreateInfoKHR* create_info,
591 const VkAllocationCallbacks* allocator,
592 VkSwapchainKHR* swapchain_handle) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700593 int err;
594 VkResult result = VK_SUCCESS;
595
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700596 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
597 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
598 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
599 " oldSwapchain=0x%" PRIx64,
600 reinterpret_cast<uint64_t>(create_info->surface),
601 create_info->minImageCount, create_info->imageFormat,
602 create_info->imageColorSpace, create_info->imageExtent.width,
603 create_info->imageExtent.height, create_info->imageUsage,
604 create_info->preTransform, create_info->presentMode,
605 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
606
Jesse Hall1f91d392015-12-11 16:28:44 -0800607 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800608 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800609
Jesse Hall42a9eec2016-06-03 12:39:49 -0700610 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -0700611 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -0800612 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700613 ALOGV_IF(create_info->imageColorSpace != VK_COLOR_SPACE_SRGB_NONLINEAR_KHR,
Jesse Halldc225072016-05-30 22:40:14 -0700614 "swapchain imageColorSpace=%u not supported",
615 create_info->imageColorSpace);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700616 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -0700617 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -0800618 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700619 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +1300620 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +1300621 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
622 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -0700623 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800624 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -0700625
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700626 Surface& surface = *SurfaceFromHandle(create_info->surface);
627
Jesse Halldc225072016-05-30 22:40:14 -0700628 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -0700629 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -0700630 " because it already has active swapchain 0x%" PRIx64
631 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
632 reinterpret_cast<uint64_t>(create_info->surface),
633 reinterpret_cast<uint64_t>(surface.swapchain_handle),
634 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
635 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
636 }
637 if (create_info->oldSwapchain != VK_NULL_HANDLE)
638 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
639
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700640 // -- Reset the native window --
641 // The native window might have been used previously, and had its properties
642 // changed from defaults. That will affect the answer we get for queries
643 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
644 // attempt such queries.
645
Jesse Halldc225072016-05-30 22:40:14 -0700646 // The native window only allows dequeueing all buffers before any have
647 // been queued, since after that point at least one is assumed to be in
648 // non-FREE state at any given time. Disconnecting and re-connecting
649 // orphans the previous buffers, getting us back to the state where we can
650 // dequeue all buffers.
651 err = native_window_api_disconnect(surface.window.get(),
652 NATIVE_WINDOW_API_EGL);
653 ALOGW_IF(err != 0, "native_window_api_disconnect failed: %s (%d)",
654 strerror(-err), err);
655 err =
656 native_window_api_connect(surface.window.get(), NATIVE_WINDOW_API_EGL);
657 ALOGW_IF(err != 0, "native_window_api_connect failed: %s (%d)",
658 strerror(-err), err);
659
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700660 err = native_window_set_buffer_count(surface.window.get(), 0);
661 if (err != 0) {
662 ALOGE("native_window_set_buffer_count(0) failed: %s (%d)",
663 strerror(-err), err);
664 return VK_ERROR_INITIALIZATION_FAILED;
665 }
666
667 err = surface.window->setSwapInterval(surface.window.get(), 1);
668 if (err != 0) {
669 // TODO(jessehall): Improve error reporting. Can we enumerate possible
670 // errors and translate them to valid Vulkan result codes?
671 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
672 strerror(-err), err);
673 return VK_ERROR_INITIALIZATION_FAILED;
674 }
675
Chris Forbesb8042d22017-01-18 18:07:05 +1300676 err = native_window_set_shared_buffer_mode(surface.window.get(), false);
677 if (err != 0) {
678 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
679 strerror(-err), err);
680 return VK_ERROR_INITIALIZATION_FAILED;
681 }
682
683 err = native_window_set_auto_refresh(surface.window.get(), false);
684 if (err != 0) {
685 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
686 strerror(-err), err);
687 return VK_ERROR_INITIALIZATION_FAILED;
688 }
689
Jesse Halld7b994a2015-09-07 14:17:37 -0700690 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -0700691
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800692 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -0800693
Jesse Hall517274a2016-02-10 00:07:18 -0800694 int native_format = HAL_PIXEL_FORMAT_RGBA_8888;
695 switch (create_info->imageFormat) {
696 case VK_FORMAT_R8G8B8A8_UNORM:
697 case VK_FORMAT_R8G8B8A8_SRGB:
698 native_format = HAL_PIXEL_FORMAT_RGBA_8888;
699 break;
700 case VK_FORMAT_R5G6B5_UNORM_PACK16:
701 native_format = HAL_PIXEL_FORMAT_RGB_565;
702 break;
703 default:
Jesse Hall42a9eec2016-06-03 12:39:49 -0700704 ALOGV("unsupported swapchain format %d", create_info->imageFormat);
Jesse Hall517274a2016-02-10 00:07:18 -0800705 break;
706 }
707 err = native_window_set_buffers_format(surface.window.get(), native_format);
708 if (err != 0) {
709 // TODO(jessehall): Improve error reporting. Can we enumerate possible
710 // errors and translate them to valid Vulkan result codes?
711 ALOGE("native_window_set_buffers_format(%d) failed: %s (%d)",
712 native_format, strerror(-err), err);
713 return VK_ERROR_INITIALIZATION_FAILED;
714 }
715 err = native_window_set_buffers_data_space(surface.window.get(),
716 HAL_DATASPACE_SRGB_LINEAR);
717 if (err != 0) {
718 // TODO(jessehall): Improve error reporting. Can we enumerate possible
719 // errors and translate them to valid Vulkan result codes?
720 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
721 HAL_DATASPACE_SRGB_LINEAR, strerror(-err), err);
722 return VK_ERROR_INITIALIZATION_FAILED;
723 }
724
Jesse Hall3dd678a2016-01-08 21:52:01 -0800725 err = native_window_set_buffers_dimensions(
726 surface.window.get(), static_cast<int>(create_info->imageExtent.width),
727 static_cast<int>(create_info->imageExtent.height));
Jesse Halld7b994a2015-09-07 14:17:37 -0700728 if (err != 0) {
729 // TODO(jessehall): Improve error reporting. Can we enumerate possible
730 // errors and translate them to valid Vulkan result codes?
731 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
732 create_info->imageExtent.width, create_info->imageExtent.height,
733 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700734 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700735 }
736
Jesse Hall178b6962016-02-24 15:39:50 -0800737 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
738 // applied during rendering. native_window_set_transform() expects the
739 // inverse: the transform the app is requesting that the compositor perform
740 // during composition. With native windows, pre-transform works by rendering
741 // with the same transform the compositor is applying (as in Vulkan), but
742 // then requesting the inverse transform, so that when the compositor does
743 // it's job the two transforms cancel each other out and the compositor ends
744 // up applying an identity transform to the app's buffer.
745 err = native_window_set_buffers_transform(
746 surface.window.get(),
747 InvertTransformToNative(create_info->preTransform));
748 if (err != 0) {
749 // TODO(jessehall): Improve error reporting. Can we enumerate possible
750 // errors and translate them to valid Vulkan result codes?
751 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
752 InvertTransformToNative(create_info->preTransform),
753 strerror(-err), err);
754 return VK_ERROR_INITIALIZATION_FAILED;
755 }
756
Jesse Hallf64ca122015-11-03 16:11:10 -0800757 err = native_window_set_scaling_mode(
Jesse Hall1356b0d2015-11-23 17:24:58 -0800758 surface.window.get(), NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Jesse Hallf64ca122015-11-03 16:11:10 -0800759 if (err != 0) {
760 // TODO(jessehall): Improve error reporting. Can we enumerate possible
761 // errors and translate them to valid Vulkan result codes?
762 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
763 strerror(-err), err);
Jesse Hallf64ca122015-11-03 16:11:10 -0800764 return VK_ERROR_INITIALIZATION_FAILED;
765 }
766
Jesse Halle6080bf2016-02-28 20:58:50 -0800767 int query_value;
768 err = surface.window->query(surface.window.get(),
769 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
770 &query_value);
771 if (err != 0 || query_value < 0) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700772 // TODO(jessehall): Improve error reporting. Can we enumerate possible
773 // errors and translate them to valid Vulkan result codes?
Jesse Halle6080bf2016-02-28 20:58:50 -0800774 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
775 query_value);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700776 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700777 }
Jesse Halle6080bf2016-02-28 20:58:50 -0800778 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800779 // The MIN_UNDEQUEUED_BUFFERS query doesn't know whether we'll be using
780 // async mode or not, and assumes not. But in async mode, the BufferQueue
781 // requires an extra undequeued buffer.
782 // See BufferQueueCore::getMinUndequeuedBufferCountLocked().
783 if (create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR)
784 min_undequeued_buffers += 1;
785
Jesse Halld7b994a2015-09-07 14:17:37 -0700786 uint32_t num_images =
787 (create_info->minImageCount - 1) + min_undequeued_buffers;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800788 err = native_window_set_buffer_count(surface.window.get(), num_images);
Jesse Halld7b994a2015-09-07 14:17:37 -0700789 if (err != 0) {
790 // TODO(jessehall): Improve error reporting. Can we enumerate possible
791 // errors and translate them to valid Vulkan result codes?
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700792 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", num_images,
793 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700794 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700795 }
796
Chris Forbes8c47dc92017-01-12 11:13:58 +1300797 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes1d5f68c2017-01-31 10:17:01 +1300798 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
799 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Chris Forbes4da65b92017-01-31 11:48:50 +1300800 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Chris Forbesb8042d22017-01-18 18:07:05 +1300801
802 err = native_window_set_shared_buffer_mode(surface.window.get(), true);
803 if (err != 0) {
804 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
805 return VK_ERROR_INITIALIZATION_FAILED;
806 }
807 }
808
Chris Forbes1d5f68c2017-01-31 10:17:01 +1300809 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Chris Forbesb8042d22017-01-18 18:07:05 +1300810 err = native_window_set_auto_refresh(surface.window.get(), true);
811 if (err != 0) {
812 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
813 return VK_ERROR_INITIALIZATION_FAILED;
814 }
Chris Forbesb4421522017-01-18 16:57:02 +1300815 }
816
Jesse Hall70f93352015-11-04 09:41:31 -0800817 int gralloc_usage = 0;
Chris Forbes8c47dc92017-01-12 11:13:58 +1300818 if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
Jesse Halld1abd742017-02-09 21:45:51 -0800819 uint64_t consumer_usage, producer_usage;
Jesse Hall85bb0c52017-02-09 22:13:02 -0800820 if (GetData(device).driver_version == 256587285) {
821 // HACK workaround for loader/driver mismatch during transition to
822 // vkGetSwapchainGrallocUsage2ANDROID.
823 typedef VkResult(VKAPI_PTR *
824 PFN_vkGetSwapchainGrallocUsage2ANDROID_HACK)(
825 VkDevice device, VkFormat format, VkImageUsageFlags imageUsage,
826 uint64_t * grallocConsumerUsage,
827 uint64_t * grallocProducerUsage);
828 auto get_swapchain_gralloc_usage =
829 reinterpret_cast<PFN_vkGetSwapchainGrallocUsage2ANDROID_HACK>(
830 dispatch.GetSwapchainGrallocUsage2ANDROID);
831 result = get_swapchain_gralloc_usage(
832 device, create_info->imageFormat, create_info->imageUsage,
833 &consumer_usage, &producer_usage);
834 } else {
835 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
836 device, create_info->imageFormat, create_info->imageUsage,
837 swapchain_image_usage, &consumer_usage, &producer_usage);
838 }
Chris Forbes8c47dc92017-01-12 11:13:58 +1300839 if (result != VK_SUCCESS) {
840 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
841 return VK_ERROR_INITIALIZATION_FAILED;
842 }
Jesse Halld1abd742017-02-09 21:45:51 -0800843 // TODO: This is the same translation done by Gralloc1On0Adapter.
844 // Remove it once ANativeWindow has been updated to take gralloc1-style
845 // usages.
846 gralloc_usage =
847 static_cast<int>(consumer_usage) | static_cast<int>(producer_usage);
Chris Forbes8c47dc92017-01-12 11:13:58 +1300848 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
Jesse Hall1f91d392015-12-11 16:28:44 -0800849 result = dispatch.GetSwapchainGrallocUsageANDROID(
Jesse Hallf4ab2b12015-11-30 16:04:55 -0800850 device, create_info->imageFormat, create_info->imageUsage,
Jesse Hall70f93352015-11-04 09:41:31 -0800851 &gralloc_usage);
852 if (result != VK_SUCCESS) {
853 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Jesse Hall70f93352015-11-04 09:41:31 -0800854 return VK_ERROR_INITIALIZATION_FAILED;
855 }
Jesse Hall70f93352015-11-04 09:41:31 -0800856 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800857 err = native_window_set_usage(surface.window.get(), gralloc_usage);
Jesse Hall70f93352015-11-04 09:41:31 -0800858 if (err != 0) {
859 // TODO(jessehall): Improve error reporting. Can we enumerate possible
860 // errors and translate them to valid Vulkan result codes?
861 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Jesse Hall70f93352015-11-04 09:41:31 -0800862 return VK_ERROR_INITIALIZATION_FAILED;
863 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700864
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700865 int swap_interval =
866 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
867 err = surface.window->setSwapInterval(surface.window.get(), swap_interval);
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800868 if (err != 0) {
869 // TODO(jessehall): Improve error reporting. Can we enumerate possible
870 // errors and translate them to valid Vulkan result codes?
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700871 ALOGE("native_window->setSwapInterval(%d) failed: %s (%d)",
872 swap_interval, strerror(-err), err);
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800873 return VK_ERROR_INITIALIZATION_FAILED;
874 }
875
Jesse Halld7b994a2015-09-07 14:17:37 -0700876 // -- Allocate our Swapchain object --
877 // After this point, we must deallocate the swapchain on error.
878
Jesse Hall1f91d392015-12-11 16:28:44 -0800879 void* mem = allocator->pfnAllocation(allocator->pUserData,
880 sizeof(Swapchain), alignof(Swapchain),
881 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800882 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -0700883 return VK_ERROR_OUT_OF_HOST_MEMORY;
Ian Elliottffedb652017-02-14 10:58:30 -0700884 Swapchain* swapchain =
885 new (mem) Swapchain(surface, num_images, create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -0700886
887 // -- Dequeue all buffers and create a VkImage for each --
888 // Any failures during or after this must cancel the dequeued buffers.
889
Chris Forbesb56287a2017-01-12 14:28:58 +1300890 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
891#pragma clang diagnostic push
892#pragma clang diagnostic ignored "-Wold-style-cast"
893 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
894#pragma clang diagnostic pop
895 .pNext = nullptr,
896 .usage = swapchain_image_usage,
897 };
Jesse Halld7b994a2015-09-07 14:17:37 -0700898 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -0700899#pragma clang diagnostic push
900#pragma clang diagnostic ignored "-Wold-style-cast"
901 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
902#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +1300903 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -0700904 };
905 VkImageCreateInfo image_create = {
906 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
907 .pNext = &image_native_buffer,
908 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -0800909 .format = create_info->imageFormat,
Jesse Halld7b994a2015-09-07 14:17:37 -0700910 .extent = {0, 0, 1},
911 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -0800912 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -0800913 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -0700914 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -0800915 .usage = create_info->imageUsage,
Jesse Halld7b994a2015-09-07 14:17:37 -0700916 .flags = 0,
Jesse Hallf4ab2b12015-11-30 16:04:55 -0800917 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -0800918 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -0700919 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
920 };
921
Jesse Halld7b994a2015-09-07 14:17:37 -0700922 for (uint32_t i = 0; i < num_images; i++) {
923 Swapchain::Image& img = swapchain->images[i];
924
925 ANativeWindowBuffer* buffer;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800926 err = surface.window->dequeueBuffer(surface.window.get(), &buffer,
927 &img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700928 if (err != 0) {
929 // TODO(jessehall): Improve error reporting. Can we enumerate
930 // possible errors and translate them to valid Vulkan result codes?
931 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700932 result = VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700933 break;
934 }
Chia-I Wue8e689f2016-04-18 08:21:31 +0800935 img.buffer = buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700936 img.dequeued = true;
937
938 image_create.extent =
Jesse Hall3dd678a2016-01-08 21:52:01 -0800939 VkExtent3D{static_cast<uint32_t>(img.buffer->width),
940 static_cast<uint32_t>(img.buffer->height),
941 1};
Jesse Halld7b994a2015-09-07 14:17:37 -0700942 image_native_buffer.handle = img.buffer->handle;
943 image_native_buffer.stride = img.buffer->stride;
944 image_native_buffer.format = img.buffer->format;
945 image_native_buffer.usage = img.buffer->usage;
Jesse Halld1abd742017-02-09 21:45:51 -0800946 // TODO: Adjust once ANativeWindowBuffer supports gralloc1-style usage.
947 // For now, this is the same translation Gralloc1On0Adapter does.
948 image_native_buffer.usage2.consumer =
949 static_cast<uint64_t>(img.buffer->usage);
950 image_native_buffer.usage2.producer =
951 static_cast<uint64_t>(img.buffer->usage);
Jesse Halld7b994a2015-09-07 14:17:37 -0700952
Jesse Hall03b6fe12015-11-24 12:44:21 -0800953 result =
Jesse Hall1f91d392015-12-11 16:28:44 -0800954 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
Jesse Halld7b994a2015-09-07 14:17:37 -0700955 if (result != VK_SUCCESS) {
956 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
957 break;
958 }
959 }
960
961 // -- Cancel all buffers, returning them to the queue --
962 // If an error occurred before, also destroy the VkImage and release the
963 // buffer reference. Otherwise, we retain a strong reference to the buffer.
964 //
965 // TODO(jessehall): The error path here is the same as DestroySwapchain,
966 // but not the non-error path. Should refactor/unify.
967 for (uint32_t i = 0; i < num_images; i++) {
968 Swapchain::Image& img = swapchain->images[i];
969 if (img.dequeued) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800970 surface.window->cancelBuffer(surface.window.get(), img.buffer.get(),
971 img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700972 img.dequeue_fence = -1;
973 img.dequeued = false;
974 }
975 if (result != VK_SUCCESS) {
976 if (img.image)
Jesse Hall1f91d392015-12-11 16:28:44 -0800977 dispatch.DestroyImage(device, img.image, nullptr);
Jesse Halld7b994a2015-09-07 14:17:37 -0700978 }
979 }
980
981 if (result != VK_SUCCESS) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700982 swapchain->~Swapchain();
Jesse Hall1f91d392015-12-11 16:28:44 -0800983 allocator->pfnFree(allocator->pUserData, swapchain);
Jesse Halld7b994a2015-09-07 14:17:37 -0700984 return result;
985 }
986
Jesse Halldc225072016-05-30 22:40:14 -0700987 surface.swapchain_handle = HandleFromSwapchain(swapchain);
988 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700989 return VK_SUCCESS;
990}
991
Jesse Halle1b12782015-11-30 11:27:32 -0800992VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800993void DestroySwapchainKHR(VkDevice device,
994 VkSwapchainKHR swapchain_handle,
995 const VkAllocationCallbacks* allocator) {
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800996 const auto& dispatch = GetData(device).driver;
Jesse Halld7b994a2015-09-07 14:17:37 -0700997 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
Daniel Kochd78c2e82016-12-13 18:45:13 -0500998 if (!swapchain)
999 return;
Jesse Hall42a9eec2016-06-03 12:39:49 -07001000 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1001 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
Jesse Halld7b994a2015-09-07 14:17:37 -07001002
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001003 if (swapchain->frame_timestamps_enabled) {
1004 native_window_enable_frame_timestamps(window, false);
1005 }
Jesse Halldc225072016-05-30 22:40:14 -07001006 for (uint32_t i = 0; i < swapchain->num_images; i++)
1007 ReleaseSwapchainImage(device, window, -1, swapchain->images[i]);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001008 if (active)
Jesse Halldc225072016-05-30 22:40:14 -07001009 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Jesse Hall1f91d392015-12-11 16:28:44 -08001010 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001011 allocator = &GetData(device).allocator;
Jesse Halld7b994a2015-09-07 14:17:37 -07001012 swapchain->~Swapchain();
Jesse Hall1f91d392015-12-11 16:28:44 -08001013 allocator->pfnFree(allocator->pUserData, swapchain);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001014}
1015
Jesse Halle1b12782015-11-30 11:27:32 -08001016VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001017VkResult GetSwapchainImagesKHR(VkDevice,
1018 VkSwapchainKHR swapchain_handle,
1019 uint32_t* count,
1020 VkImage* images) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001021 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07001022 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
1023 "getting images for non-active swapchain 0x%" PRIx64
1024 "; only dequeued image handles are valid",
1025 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07001026 VkResult result = VK_SUCCESS;
1027 if (images) {
1028 uint32_t n = swapchain.num_images;
1029 if (*count < swapchain.num_images) {
1030 n = *count;
1031 result = VK_INCOMPLETE;
1032 }
1033 for (uint32_t i = 0; i < n; i++)
1034 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07001035 *count = n;
1036 } else {
1037 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07001038 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001039 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001040}
1041
Jesse Halle1b12782015-11-30 11:27:32 -08001042VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001043VkResult AcquireNextImageKHR(VkDevice device,
1044 VkSwapchainKHR swapchain_handle,
1045 uint64_t timeout,
1046 VkSemaphore semaphore,
1047 VkFence vk_fence,
1048 uint32_t* image_index) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001049 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001050 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07001051 VkResult result;
1052 int err;
1053
Jesse Halldc225072016-05-30 22:40:14 -07001054 if (swapchain.surface.swapchain_handle != swapchain_handle)
1055 return VK_ERROR_OUT_OF_DATE_KHR;
1056
Jesse Halld7b994a2015-09-07 14:17:37 -07001057 ALOGW_IF(
1058 timeout != UINT64_MAX,
1059 "vkAcquireNextImageKHR: non-infinite timeouts not yet implemented");
1060
1061 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08001062 int fence_fd;
1063 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001064 if (err != 0) {
1065 // TODO(jessehall): Improve error reporting. Can we enumerate possible
1066 // errors and translate them to valid Vulkan result codes?
1067 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -07001068 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -07001069 }
1070
1071 uint32_t idx;
1072 for (idx = 0; idx < swapchain.num_images; idx++) {
1073 if (swapchain.images[idx].buffer.get() == buffer) {
1074 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08001075 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07001076 break;
1077 }
1078 }
1079 if (idx == swapchain.num_images) {
1080 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08001081 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001082 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001083 }
1084
1085 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08001086 if (fence_fd != -1) {
1087 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001088 if (fence_clone == -1) {
1089 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
1090 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08001091 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07001092 }
1093 }
1094
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001095 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08001096 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001097 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001098 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
1099 // even if the call fails. We could close it ourselves on failure, but
1100 // that would create a race condition if the driver closes it on a
1101 // failure path: some other thread might create an fd with the same
1102 // number between the time the driver closes it and the time we close
1103 // it. We must assume one of: the driver *always* closes it even on
1104 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08001105 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001106 swapchain.images[idx].dequeued = false;
1107 swapchain.images[idx].dequeue_fence = -1;
1108 return result;
1109 }
1110
1111 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001112 return VK_SUCCESS;
1113}
1114
Jesse Halldc225072016-05-30 22:40:14 -07001115static VkResult WorstPresentResult(VkResult a, VkResult b) {
1116 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
1117 // (in spec version 1.0.14).
1118 static const VkResult kWorstToBest[] = {
1119 VK_ERROR_DEVICE_LOST,
1120 VK_ERROR_SURFACE_LOST_KHR,
1121 VK_ERROR_OUT_OF_DATE_KHR,
1122 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1123 VK_ERROR_OUT_OF_HOST_MEMORY,
1124 VK_SUBOPTIMAL_KHR,
1125 };
1126 for (auto result : kWorstToBest) {
1127 if (a == result || b == result)
1128 return result;
1129 }
1130 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
1131 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
1132 return a != VK_SUCCESS ? a : b;
1133}
1134
Jesse Halle1b12782015-11-30 11:27:32 -08001135VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001136VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001137 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
1138 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
1139 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07001140
Jesse Halldc225072016-05-30 22:40:14 -07001141 VkDevice device = GetData(queue).driver_device;
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001142 const auto& dispatch = GetData(queue).driver;
Jesse Halld7b994a2015-09-07 14:17:37 -07001143 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07001144
Ian Elliottcb351132016-12-13 10:30:40 -07001145 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001146 const VkPresentRegionsKHR* present_regions = nullptr;
1147 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07001148 const VkPresentRegionsKHR* next =
1149 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
1150 while (next) {
1151 switch (next->sType) {
1152 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
1153 present_regions = next;
1154 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07001155 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001156 present_times =
1157 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
1158 break;
Ian Elliottcb351132016-12-13 10:30:40 -07001159 default:
1160 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
1161 next->sType);
1162 break;
1163 }
1164 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
1165 }
1166 ALOGV_IF(
1167 present_regions &&
1168 present_regions->swapchainCount != present_info->swapchainCount,
1169 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001170 ALOGV_IF(present_times &&
1171 present_times->swapchainCount != present_info->swapchainCount,
1172 "VkPresentTimesInfoGOOGLE::swapchainCount != "
1173 "VkPresentInfo::swapchainCount");
Ian Elliottcb351132016-12-13 10:30:40 -07001174 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001175 (present_regions) ? present_regions->pRegions : nullptr;
1176 const VkPresentTimeGOOGLE* times =
1177 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07001178 const VkAllocationCallbacks* allocator = &GetData(device).allocator;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001179 android_native_rect_t* rects = nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07001180 uint32_t nrects = 0;
1181
Jesse Halld7b994a2015-09-07 14:17:37 -07001182 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
1183 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08001184 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001185 uint32_t image_idx = present_info->pImageIndices[sc];
Jesse Hall5ae3abb2015-10-08 14:00:22 -07001186 Swapchain::Image& img = swapchain.images[image_idx];
Ian Elliottffedb652017-02-14 10:58:30 -07001187 const VkPresentRegionKHR* region =
1188 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001189 const VkPresentTimeGOOGLE* time = (times) ? &times[sc] : nullptr;
Jesse Halldc225072016-05-30 22:40:14 -07001190 VkResult swapchain_result = VK_SUCCESS;
Jesse Halld7b994a2015-09-07 14:17:37 -07001191 VkResult result;
1192 int err;
1193
Jesse Halld7b994a2015-09-07 14:17:37 -07001194 int fence = -1;
Jesse Hall275d76c2016-01-08 22:39:16 -08001195 result = dispatch.QueueSignalReleaseImageANDROID(
1196 queue, present_info->waitSemaphoreCount,
1197 present_info->pWaitSemaphores, img.image, &fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001198 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001199 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
Jesse Halldc225072016-05-30 22:40:14 -07001200 swapchain_result = result;
Jesse Halld7b994a2015-09-07 14:17:37 -07001201 }
1202
Jesse Halldc225072016-05-30 22:40:14 -07001203 if (swapchain.surface.swapchain_handle ==
1204 present_info->pSwapchains[sc]) {
1205 ANativeWindow* window = swapchain.surface.window.get();
1206 if (swapchain_result == VK_SUCCESS) {
Ian Elliottcb351132016-12-13 10:30:40 -07001207 if (region) {
1208 // Process the incremental-present hint for this swapchain:
1209 uint32_t rcount = region->rectangleCount;
1210 if (rcount > nrects) {
1211 android_native_rect_t* new_rects =
1212 static_cast<android_native_rect_t*>(
1213 allocator->pfnReallocation(
1214 allocator->pUserData, rects,
1215 sizeof(android_native_rect_t) * rcount,
1216 alignof(android_native_rect_t),
1217 VK_SYSTEM_ALLOCATION_SCOPE_COMMAND));
1218 if (new_rects) {
1219 rects = new_rects;
1220 nrects = rcount;
1221 } else {
1222 rcount = 0; // Ignore the hint for this swapchain
1223 }
1224 }
1225 for (uint32_t r = 0; r < rcount; ++r) {
1226 if (region->pRectangles[r].layer > 0) {
1227 ALOGV(
1228 "vkQueuePresentKHR ignoring invalid layer "
1229 "(%u); using layer 0 instead",
1230 region->pRectangles[r].layer);
1231 }
1232 int x = region->pRectangles[r].offset.x;
1233 int y = region->pRectangles[r].offset.y;
1234 int width = static_cast<int>(
1235 region->pRectangles[r].extent.width);
1236 int height = static_cast<int>(
1237 region->pRectangles[r].extent.height);
1238 android_native_rect_t* cur_rect = &rects[r];
1239 cur_rect->left = x;
1240 cur_rect->top = y + height;
1241 cur_rect->right = x + width;
1242 cur_rect->bottom = y;
1243 }
1244 native_window_set_surface_damage(window, rects, rcount);
1245 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001246 if (time) {
1247 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07001248 ALOGV(
1249 "Calling "
1250 "native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001251 native_window_enable_frame_timestamps(window, true);
1252 swapchain.frame_timestamps_enabled = true;
1253 }
Ian Elliott8a977262017-01-19 09:05:58 -07001254 // Record this presentID and desiredPresentTime so it can
1255 // be later correlated to this present.
1256 TimingInfo timing_record(time);
1257 swapchain.timing.add(timing_record);
1258 uint32_t num_timings =
1259 static_cast<uint32_t>(swapchain.timing.size());
1260 if (num_timings > MAX_TIMING_INFOS) {
1261 swapchain.timing.removeAt(0);
1262 }
1263 if (time->desiredPresentTime) {
1264 // Set the desiredPresentTime:
1265 ALOGV(
1266 "Calling "
1267 "native_window_set_buffers_timestamp(%" PRId64 ")",
1268 time->desiredPresentTime);
1269 native_window_set_buffers_timestamp(
1270 window,
1271 static_cast<int64_t>(time->desiredPresentTime));
1272 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001273 }
Jesse Halldc225072016-05-30 22:40:14 -07001274 err = window->queueBuffer(window, img.buffer.get(), fence);
1275 // queueBuffer always closes fence, even on error
1276 if (err != 0) {
1277 // TODO(jessehall): What now? We should probably cancel the
1278 // buffer, I guess?
1279 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
1280 swapchain_result = WorstPresentResult(
1281 swapchain_result, VK_ERROR_OUT_OF_DATE_KHR);
1282 }
1283 if (img.dequeue_fence >= 0) {
1284 close(img.dequeue_fence);
1285 img.dequeue_fence = -1;
1286 }
1287 img.dequeued = false;
1288 }
1289 if (swapchain_result != VK_SUCCESS) {
1290 ReleaseSwapchainImage(device, window, fence, img);
1291 OrphanSwapchain(device, &swapchain);
1292 }
1293 } else {
1294 ReleaseSwapchainImage(device, nullptr, fence, img);
1295 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001296 }
1297
Jesse Halla9e57032015-11-30 01:03:10 -08001298 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07001299 present_info->pResults[sc] = swapchain_result;
1300
1301 if (swapchain_result != final_result)
1302 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07001303 }
Ian Elliottcb351132016-12-13 10:30:40 -07001304 if (rects) {
1305 allocator->pfnFree(allocator->pUserData, rects);
1306 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001307
1308 return final_result;
1309}
Jesse Hallb1352bc2015-09-04 16:12:33 -07001310
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001311VKAPI_ATTR
1312VkResult GetRefreshCycleDurationGOOGLE(
1313 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07001314 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001315 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Ian Elliott62c48c92017-01-20 13:13:20 -07001316 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001317 VkResult result = VK_SUCCESS;
1318
Ian Elliottbe833a22017-01-25 13:09:20 -07001319 pDisplayTimingProperties->refreshDuration = swapchain.refresh_duration;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001320
1321 return result;
1322}
1323
1324VKAPI_ATTR
1325VkResult GetPastPresentationTimingGOOGLE(
1326 VkDevice,
1327 VkSwapchainKHR swapchain_handle,
1328 uint32_t* count,
1329 VkPastPresentationTimingGOOGLE* timings) {
1330 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
1331 ANativeWindow* window = swapchain.surface.window.get();
1332 VkResult result = VK_SUCCESS;
1333
1334 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07001335 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001336 native_window_enable_frame_timestamps(window, true);
1337 swapchain.frame_timestamps_enabled = true;
1338 }
1339
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001340 if (timings) {
Ian Elliott8a977262017-01-19 09:05:58 -07001341 // TODO(ianelliott): plumb return value (e.g. VK_INCOMPLETE)
1342 copy_ready_timings(swapchain, count, timings);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001343 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07001344 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001345 }
1346
1347 return result;
1348}
1349
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13001350VKAPI_ATTR
1351VkResult GetSwapchainStatusKHR(
1352 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13001353 VkSwapchainKHR swapchain_handle) {
1354 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13001355 VkResult result = VK_SUCCESS;
1356
Chris Forbes4e18ba82017-01-20 12:50:17 +13001357 if (swapchain.surface.swapchain_handle != swapchain_handle) {
1358 return VK_ERROR_OUT_OF_DATE_KHR;
1359 }
1360
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13001361 // TODO(chrisforbes): Implement this function properly
1362
1363 return result;
1364}
1365
Chia-I Wu62262232016-03-26 07:06:44 +08001366} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07001367} // namespace vulkan