blob: 1afa86cfac69b7c6e5ae492b9d1dacef23021d53 [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 {
179 Swapchain(Surface& surface_, uint32_t num_images_)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700180 : surface(surface_),
181 num_images(num_images_),
Ian Elliott8a977262017-01-19 09:05:58 -0700182 frame_timestamps_enabled(false) {
Ian Elliott62c48c92017-01-20 13:13:20 -0700183 ANativeWindow* window = surface.window.get();
Ian Elliottbe833a22017-01-25 13:09:20 -0700184 int64_t rdur;
185 native_window_get_refresh_cycle_duration(
Ian Elliott62c48c92017-01-20 13:13:20 -0700186 window,
Ian Elliottbe833a22017-01-25 13:09:20 -0700187 &rdur);
188 refresh_duration = static_cast<uint64_t>(rdur);
Ian Elliott8a977262017-01-19 09:05:58 -0700189 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800190
191 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700192 uint32_t num_images;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700193 bool frame_timestamps_enabled;
Ian Elliottbe833a22017-01-25 13:09:20 -0700194 uint64_t refresh_duration;
Jesse Halld7b994a2015-09-07 14:17:37 -0700195
196 struct Image {
197 Image() : image(VK_NULL_HANDLE), dequeue_fence(-1), dequeued(false) {}
198 VkImage image;
Chia-I Wue8e689f2016-04-18 08:21:31 +0800199 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700200 // The fence is only valid when the buffer is dequeued, and should be
201 // -1 any other time. When valid, we own the fd, and must ensure it is
202 // closed: either by closing it explicitly when queueing the buffer,
203 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
204 int dequeue_fence;
205 bool dequeued;
206 } images[android::BufferQueue::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700207
Brian Anderson1049d1d2016-12-16 17:25:57 -0800208 android::Vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700209};
210
211VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
212 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
213}
214
215Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800216 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700217}
218
Jesse Halldc225072016-05-30 22:40:14 -0700219void ReleaseSwapchainImage(VkDevice device,
220 ANativeWindow* window,
221 int release_fence,
222 Swapchain::Image& image) {
223 ALOG_ASSERT(release_fence == -1 || image.dequeued,
224 "ReleaseSwapchainImage: can't provide a release fence for "
225 "non-dequeued images");
226
227 if (image.dequeued) {
228 if (release_fence >= 0) {
229 // We get here from vkQueuePresentKHR. The application is
230 // responsible for creating an execution dependency chain from
231 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
232 // (release_fence), so we can drop the dequeue_fence here.
233 if (image.dequeue_fence >= 0)
234 close(image.dequeue_fence);
235 } else {
236 // We get here during swapchain destruction, or various serious
237 // error cases e.g. when we can't create the release_fence during
238 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
239 // have already signalled, since the swapchain images are supposed
240 // to be idle before the swapchain is destroyed. In error cases,
241 // there may be rendering in flight to the image, but since we
242 // weren't able to create a release_fence, waiting for the
243 // dequeue_fence is about the best we can do.
244 release_fence = image.dequeue_fence;
245 }
246 image.dequeue_fence = -1;
247
248 if (window) {
249 window->cancelBuffer(window, image.buffer.get(), release_fence);
250 } else {
251 if (release_fence >= 0) {
252 sync_wait(release_fence, -1 /* forever */);
253 close(release_fence);
254 }
255 }
256
257 image.dequeued = false;
258 }
259
260 if (image.image) {
261 GetData(device).driver.DestroyImage(device, image.image, nullptr);
262 image.image = VK_NULL_HANDLE;
263 }
264
265 image.buffer.clear();
266}
267
268void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
269 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
270 return;
Jesse Halldc225072016-05-30 22:40:14 -0700271 for (uint32_t i = 0; i < swapchain->num_images; i++) {
272 if (!swapchain->images[i].dequeued)
273 ReleaseSwapchainImage(device, nullptr, -1, swapchain->images[i]);
274 }
275 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700276 swapchain->timing.clear();
277}
278
279uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800280 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
281 return 0;
282 }
Ian Elliott8a977262017-01-19 09:05:58 -0700283
Brian Anderson1049d1d2016-12-16 17:25:57 -0800284 uint32_t num_ready = 0;
285 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
286 for (uint32_t i = 0; i < num_timings; i++) {
287 TimingInfo& ti = swapchain.timing.editItemAt(i);
288 if (ti.ready()) {
289 // This TimingInfo is ready to be reported to the user. Add it
290 // to the num_ready.
291 num_ready++;
292 continue;
293 }
294 // This TimingInfo is not yet ready to be reported to the user,
295 // and so we should look for any available timestamps that
296 // might make it ready.
297 int64_t desired_present_time = 0;
298 int64_t render_complete_time = 0;
299 int64_t composition_latch_time = 0;
300 int64_t actual_present_time = 0;
301 // Obtain timestamps:
302 int ret = native_window_get_frame_timestamps(
303 swapchain.surface.window.get(), ti.native_frame_id_,
304 &desired_present_time, &render_complete_time,
305 &composition_latch_time,
306 NULL, //&first_composition_start_time,
307 NULL, //&last_composition_start_time,
308 NULL, //&composition_finish_time,
309 // TODO(ianelliott): Maybe ask if this one is
310 // supported, at startup time (since it may not be
311 // supported):
312 &actual_present_time,
313 NULL, //&display_retire_time,
314 NULL, //&dequeue_ready_time,
315 NULL /*&reads_done_time*/);
316
317 if (ret != android::NO_ERROR) {
318 continue;
319 }
320
321 // Record the timestamp(s) we received, and then see if this TimingInfo
322 // is ready to be reported to the user:
323 ti.timestamp_desired_present_time_ =
324 static_cast<uint64_t>(desired_present_time);
325 ti.timestamp_actual_present_time_ =
326 static_cast<uint64_t>(actual_present_time);
327 ti.timestamp_render_complete_time_ =
328 static_cast<uint64_t>(render_complete_time);
329 ti.timestamp_composition_latch_time_ =
330 static_cast<uint64_t>(composition_latch_time);
331
332 if (ti.ready()) {
333 // The TimingInfo has received enough timestamps, and should now
334 // use those timestamps to calculate the info that should be
335 // reported to the user:
336 ti.calculate(swapchain.refresh_duration);
337 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700338 }
339 }
340 return num_ready;
341}
342
343// TODO(ianelliott): DEAL WITH RETURN VALUE (e.g. VK_INCOMPLETE)!!!
344void copy_ready_timings(Swapchain& swapchain,
345 uint32_t* count,
346 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800347 if (swapchain.timing.empty()) {
348 *count = 0;
349 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700350 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800351
352 size_t last_ready = swapchain.timing.size() - 1;
353 while (!swapchain.timing[last_ready].ready()) {
354 if (last_ready == 0) {
355 *count = 0;
356 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700357 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800358 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700359 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800360
361 uint32_t num_copied = 0;
362 size_t num_to_remove = 0;
363 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
364 const TimingInfo& ti = swapchain.timing[i];
365 if (ti.ready()) {
366 ti.get_values(&timings[num_copied]);
367 num_copied++;
368 }
369 num_to_remove++;
370 }
371
372 // Discard old frames that aren't ready if newer frames are ready.
373 // We don't expect to get the timing info for those old frames.
374 swapchain.timing.removeItemsAt(0, num_to_remove);
375
Ian Elliott8a977262017-01-19 09:05:58 -0700376 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700377}
378
Jesse Halld7b994a2015-09-07 14:17:37 -0700379} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700380
Jesse Halle1b12782015-11-30 11:27:32 -0800381VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800382VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800383 VkInstance instance,
384 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
385 const VkAllocationCallbacks* allocator,
386 VkSurfaceKHR* out_surface) {
Jesse Hall1f91d392015-12-11 16:28:44 -0800387 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800388 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800389 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
390 alignof(Surface),
391 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800392 if (!mem)
393 return VK_ERROR_OUT_OF_HOST_MEMORY;
394 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700395
Chia-I Wue8e689f2016-04-18 08:21:31 +0800396 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700397 surface->swapchain_handle = VK_NULL_HANDLE;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700398
Jesse Hall1356b0d2015-11-23 17:24:58 -0800399 // TODO(jessehall): Create and use NATIVE_WINDOW_API_VULKAN.
400 int err =
401 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
402 if (err != 0) {
403 // TODO(jessehall): Improve error reporting. Can we enumerate possible
404 // errors and translate them to valid Vulkan result codes?
405 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
406 err);
407 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800408 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800409 return VK_ERROR_INITIALIZATION_FAILED;
410 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700411
Jesse Hall1356b0d2015-11-23 17:24:58 -0800412 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700413 return VK_SUCCESS;
414}
415
Jesse Halle1b12782015-11-30 11:27:32 -0800416VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800417void DestroySurfaceKHR(VkInstance instance,
418 VkSurfaceKHR surface_handle,
419 const VkAllocationCallbacks* allocator) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800420 Surface* surface = SurfaceFromHandle(surface_handle);
421 if (!surface)
422 return;
423 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700424 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700425 "destroyed VkSurfaceKHR 0x%" PRIx64
426 " has active VkSwapchainKHR 0x%" PRIx64,
427 reinterpret_cast<uint64_t>(surface_handle),
428 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800429 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800430 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800431 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800432 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800433}
434
Jesse Halle1b12782015-11-30 11:27:32 -0800435VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800436VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
437 uint32_t /*queue_family*/,
438 VkSurfaceKHR /*surface*/,
439 VkBool32* supported) {
Jesse Hall0e74f002015-11-30 11:37:59 -0800440 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800441 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800442}
443
Jesse Halle1b12782015-11-30 11:27:32 -0800444VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800445VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Jesse Hallb00daad2015-11-29 19:46:20 -0800446 VkPhysicalDevice /*pdev*/,
447 VkSurfaceKHR surface,
448 VkSurfaceCapabilitiesKHR* capabilities) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700449 int err;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800450 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -0700451
452 int width, height;
453 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
454 if (err != 0) {
455 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
456 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700457 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700458 }
459 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
460 if (err != 0) {
461 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
462 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700463 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700464 }
465
Jesse Hall55bc0972016-02-23 16:43:29 -0800466 int transform_hint;
467 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
468 if (err != 0) {
469 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
470 strerror(-err), err);
471 return VK_ERROR_INITIALIZATION_FAILED;
472 }
473
Jesse Halld7b994a2015-09-07 14:17:37 -0700474 // TODO(jessehall): Figure out what the min/max values should be.
Jesse Hallb00daad2015-11-29 19:46:20 -0800475 capabilities->minImageCount = 2;
476 capabilities->maxImageCount = 3;
Jesse Halld7b994a2015-09-07 14:17:37 -0700477
Jesse Hallfe2662d2016-02-09 13:26:59 -0800478 capabilities->currentExtent =
479 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
480
Jesse Halld7b994a2015-09-07 14:17:37 -0700481 // TODO(jessehall): Figure out what the max extent should be. Maximum
482 // texture dimension maybe?
Jesse Hallb00daad2015-11-29 19:46:20 -0800483 capabilities->minImageExtent = VkExtent2D{1, 1};
484 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
Jesse Halld7b994a2015-09-07 14:17:37 -0700485
Jesse Hallfe2662d2016-02-09 13:26:59 -0800486 capabilities->maxImageArrayLayers = 1;
487
Jesse Hall55bc0972016-02-23 16:43:29 -0800488 capabilities->supportedTransforms = kSupportedTransforms;
489 capabilities->currentTransform =
490 TranslateNativeToVulkanTransform(transform_hint);
Jesse Halld7b994a2015-09-07 14:17:37 -0700491
Jesse Hallfe2662d2016-02-09 13:26:59 -0800492 // On Android, window composition is a WindowManager property, not something
493 // associated with the bufferqueue. It can't be changed from here.
494 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -0700495
496 // TODO(jessehall): I think these are right, but haven't thought hard about
497 // it. Do we need to query the driver for support of any of these?
498 // Currently not included:
Jesse Halld7b994a2015-09-07 14:17:37 -0700499 // - VK_IMAGE_USAGE_DEPTH_STENCIL_BIT: definitely not
500 // - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT: definitely not
Jesse Hallb00daad2015-11-29 19:46:20 -0800501 capabilities->supportedUsageFlags =
Jesse Hall3fbc8562015-11-29 22:10:52 -0800502 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
503 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
504 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
Jesse Halld7b994a2015-09-07 14:17:37 -0700505 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
506
Jesse Hallb1352bc2015-09-04 16:12:33 -0700507 return VK_SUCCESS;
508}
509
Jesse Halle1b12782015-11-30 11:27:32 -0800510VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800511VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice /*pdev*/,
512 VkSurfaceKHR /*surface*/,
513 uint32_t* count,
514 VkSurfaceFormatKHR* formats) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800515 // TODO(jessehall): Fill out the set of supported formats. Longer term, add
516 // a new gralloc method to query whether a (format, usage) pair is
517 // supported, and check that for each gralloc format that corresponds to a
518 // Vulkan format. Shorter term, just add a few more formats to the ones
519 // hardcoded below.
Jesse Halld7b994a2015-09-07 14:17:37 -0700520
521 const VkSurfaceFormatKHR kFormats[] = {
Jesse Hall26763382016-05-20 07:13:52 -0700522 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
523 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
524 {VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Jesse Halld7b994a2015-09-07 14:17:37 -0700525 };
526 const uint32_t kNumFormats = sizeof(kFormats) / sizeof(kFormats[0]);
527
528 VkResult result = VK_SUCCESS;
529 if (formats) {
530 if (*count < kNumFormats)
531 result = VK_INCOMPLETE;
Jesse Hall7331e222016-09-15 21:26:01 -0700532 *count = std::min(*count, kNumFormats);
533 std::copy(kFormats, kFormats + *count, formats);
534 } else {
535 *count = kNumFormats;
Jesse Halld7b994a2015-09-07 14:17:37 -0700536 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700537 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700538}
539
Jesse Halle1b12782015-11-30 11:27:32 -0800540VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800541VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice /*pdev*/,
542 VkSurfaceKHR /*surface*/,
543 uint32_t* count,
544 VkPresentModeKHR* modes) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700545 const VkPresentModeKHR kModes[] = {
546 VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
Chris Forbes980ad052017-01-18 16:55:07 +1300547 // TODO(chrisforbes): should only expose this if the driver can.
Chris Forbes1d5f68c2017-01-31 10:17:01 +1300548 VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR,
549 VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR,
Jesse Halld7b994a2015-09-07 14:17:37 -0700550 };
551 const uint32_t kNumModes = sizeof(kModes) / sizeof(kModes[0]);
552
553 VkResult result = VK_SUCCESS;
554 if (modes) {
555 if (*count < kNumModes)
556 result = VK_INCOMPLETE;
Jesse Hall7331e222016-09-15 21:26:01 -0700557 *count = std::min(*count, kNumModes);
558 std::copy(kModes, kModes + *count, modes);
559 } else {
560 *count = kNumModes;
Jesse Halld7b994a2015-09-07 14:17:37 -0700561 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700562 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700563}
564
Jesse Halle1b12782015-11-30 11:27:32 -0800565VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800566VkResult CreateSwapchainKHR(VkDevice device,
567 const VkSwapchainCreateInfoKHR* create_info,
568 const VkAllocationCallbacks* allocator,
569 VkSwapchainKHR* swapchain_handle) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700570 int err;
571 VkResult result = VK_SUCCESS;
572
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700573 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
574 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
575 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
576 " oldSwapchain=0x%" PRIx64,
577 reinterpret_cast<uint64_t>(create_info->surface),
578 create_info->minImageCount, create_info->imageFormat,
579 create_info->imageColorSpace, create_info->imageExtent.width,
580 create_info->imageExtent.height, create_info->imageUsage,
581 create_info->preTransform, create_info->presentMode,
582 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
583
Jesse Hall1f91d392015-12-11 16:28:44 -0800584 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800585 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800586
Jesse Hall42a9eec2016-06-03 12:39:49 -0700587 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -0700588 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -0800589 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700590 ALOGV_IF(create_info->imageColorSpace != VK_COLOR_SPACE_SRGB_NONLINEAR_KHR,
Jesse Halldc225072016-05-30 22:40:14 -0700591 "swapchain imageColorSpace=%u not supported",
592 create_info->imageColorSpace);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700593 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -0700594 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -0800595 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700596 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +1300597 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +1300598 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
599 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -0700600 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800601 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -0700602
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700603 Surface& surface = *SurfaceFromHandle(create_info->surface);
604
Jesse Halldc225072016-05-30 22:40:14 -0700605 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -0700606 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -0700607 " because it already has active swapchain 0x%" PRIx64
608 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
609 reinterpret_cast<uint64_t>(create_info->surface),
610 reinterpret_cast<uint64_t>(surface.swapchain_handle),
611 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
612 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
613 }
614 if (create_info->oldSwapchain != VK_NULL_HANDLE)
615 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
616
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700617 // -- Reset the native window --
618 // The native window might have been used previously, and had its properties
619 // changed from defaults. That will affect the answer we get for queries
620 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
621 // attempt such queries.
622
Jesse Halldc225072016-05-30 22:40:14 -0700623 // The native window only allows dequeueing all buffers before any have
624 // been queued, since after that point at least one is assumed to be in
625 // non-FREE state at any given time. Disconnecting and re-connecting
626 // orphans the previous buffers, getting us back to the state where we can
627 // dequeue all buffers.
628 err = native_window_api_disconnect(surface.window.get(),
629 NATIVE_WINDOW_API_EGL);
630 ALOGW_IF(err != 0, "native_window_api_disconnect failed: %s (%d)",
631 strerror(-err), err);
632 err =
633 native_window_api_connect(surface.window.get(), NATIVE_WINDOW_API_EGL);
634 ALOGW_IF(err != 0, "native_window_api_connect failed: %s (%d)",
635 strerror(-err), err);
636
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700637 err = native_window_set_buffer_count(surface.window.get(), 0);
638 if (err != 0) {
639 ALOGE("native_window_set_buffer_count(0) failed: %s (%d)",
640 strerror(-err), err);
641 return VK_ERROR_INITIALIZATION_FAILED;
642 }
643
644 err = surface.window->setSwapInterval(surface.window.get(), 1);
645 if (err != 0) {
646 // TODO(jessehall): Improve error reporting. Can we enumerate possible
647 // errors and translate them to valid Vulkan result codes?
648 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
649 strerror(-err), err);
650 return VK_ERROR_INITIALIZATION_FAILED;
651 }
652
Chris Forbesb8042d22017-01-18 18:07:05 +1300653 err = native_window_set_shared_buffer_mode(surface.window.get(), false);
654 if (err != 0) {
655 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
656 strerror(-err), err);
657 return VK_ERROR_INITIALIZATION_FAILED;
658 }
659
660 err = native_window_set_auto_refresh(surface.window.get(), false);
661 if (err != 0) {
662 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
663 strerror(-err), err);
664 return VK_ERROR_INITIALIZATION_FAILED;
665 }
666
Jesse Halld7b994a2015-09-07 14:17:37 -0700667 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -0700668
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800669 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -0800670
Jesse Hall517274a2016-02-10 00:07:18 -0800671 int native_format = HAL_PIXEL_FORMAT_RGBA_8888;
672 switch (create_info->imageFormat) {
673 case VK_FORMAT_R8G8B8A8_UNORM:
674 case VK_FORMAT_R8G8B8A8_SRGB:
675 native_format = HAL_PIXEL_FORMAT_RGBA_8888;
676 break;
677 case VK_FORMAT_R5G6B5_UNORM_PACK16:
678 native_format = HAL_PIXEL_FORMAT_RGB_565;
679 break;
680 default:
Jesse Hall42a9eec2016-06-03 12:39:49 -0700681 ALOGV("unsupported swapchain format %d", create_info->imageFormat);
Jesse Hall517274a2016-02-10 00:07:18 -0800682 break;
683 }
684 err = native_window_set_buffers_format(surface.window.get(), native_format);
685 if (err != 0) {
686 // TODO(jessehall): Improve error reporting. Can we enumerate possible
687 // errors and translate them to valid Vulkan result codes?
688 ALOGE("native_window_set_buffers_format(%d) failed: %s (%d)",
689 native_format, strerror(-err), err);
690 return VK_ERROR_INITIALIZATION_FAILED;
691 }
692 err = native_window_set_buffers_data_space(surface.window.get(),
693 HAL_DATASPACE_SRGB_LINEAR);
694 if (err != 0) {
695 // TODO(jessehall): Improve error reporting. Can we enumerate possible
696 // errors and translate them to valid Vulkan result codes?
697 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
698 HAL_DATASPACE_SRGB_LINEAR, strerror(-err), err);
699 return VK_ERROR_INITIALIZATION_FAILED;
700 }
701
Jesse Hall3dd678a2016-01-08 21:52:01 -0800702 err = native_window_set_buffers_dimensions(
703 surface.window.get(), static_cast<int>(create_info->imageExtent.width),
704 static_cast<int>(create_info->imageExtent.height));
Jesse Halld7b994a2015-09-07 14:17:37 -0700705 if (err != 0) {
706 // TODO(jessehall): Improve error reporting. Can we enumerate possible
707 // errors and translate them to valid Vulkan result codes?
708 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
709 create_info->imageExtent.width, create_info->imageExtent.height,
710 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700711 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700712 }
713
Jesse Hall178b6962016-02-24 15:39:50 -0800714 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
715 // applied during rendering. native_window_set_transform() expects the
716 // inverse: the transform the app is requesting that the compositor perform
717 // during composition. With native windows, pre-transform works by rendering
718 // with the same transform the compositor is applying (as in Vulkan), but
719 // then requesting the inverse transform, so that when the compositor does
720 // it's job the two transforms cancel each other out and the compositor ends
721 // up applying an identity transform to the app's buffer.
722 err = native_window_set_buffers_transform(
723 surface.window.get(),
724 InvertTransformToNative(create_info->preTransform));
725 if (err != 0) {
726 // TODO(jessehall): Improve error reporting. Can we enumerate possible
727 // errors and translate them to valid Vulkan result codes?
728 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
729 InvertTransformToNative(create_info->preTransform),
730 strerror(-err), err);
731 return VK_ERROR_INITIALIZATION_FAILED;
732 }
733
Jesse Hallf64ca122015-11-03 16:11:10 -0800734 err = native_window_set_scaling_mode(
Jesse Hall1356b0d2015-11-23 17:24:58 -0800735 surface.window.get(), NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Jesse Hallf64ca122015-11-03 16:11:10 -0800736 if (err != 0) {
737 // TODO(jessehall): Improve error reporting. Can we enumerate possible
738 // errors and translate them to valid Vulkan result codes?
739 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
740 strerror(-err), err);
Jesse Hallf64ca122015-11-03 16:11:10 -0800741 return VK_ERROR_INITIALIZATION_FAILED;
742 }
743
Jesse Halle6080bf2016-02-28 20:58:50 -0800744 int query_value;
745 err = surface.window->query(surface.window.get(),
746 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
747 &query_value);
748 if (err != 0 || query_value < 0) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700749 // TODO(jessehall): Improve error reporting. Can we enumerate possible
750 // errors and translate them to valid Vulkan result codes?
Jesse Halle6080bf2016-02-28 20:58:50 -0800751 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
752 query_value);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700753 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700754 }
Jesse Halle6080bf2016-02-28 20:58:50 -0800755 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800756 // The MIN_UNDEQUEUED_BUFFERS query doesn't know whether we'll be using
757 // async mode or not, and assumes not. But in async mode, the BufferQueue
758 // requires an extra undequeued buffer.
759 // See BufferQueueCore::getMinUndequeuedBufferCountLocked().
760 if (create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR)
761 min_undequeued_buffers += 1;
762
Jesse Halld7b994a2015-09-07 14:17:37 -0700763 uint32_t num_images =
764 (create_info->minImageCount - 1) + min_undequeued_buffers;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800765 err = native_window_set_buffer_count(surface.window.get(), num_images);
Jesse Halld7b994a2015-09-07 14:17:37 -0700766 if (err != 0) {
767 // TODO(jessehall): Improve error reporting. Can we enumerate possible
768 // errors and translate them to valid Vulkan result codes?
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700769 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", num_images,
770 strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700771 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700772 }
773
Chris Forbes8c47dc92017-01-12 11:13:58 +1300774 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes1d5f68c2017-01-31 10:17:01 +1300775 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
776 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Chris Forbes4da65b92017-01-31 11:48:50 +1300777 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Chris Forbesb8042d22017-01-18 18:07:05 +1300778
779 err = native_window_set_shared_buffer_mode(surface.window.get(), true);
780 if (err != 0) {
781 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
782 return VK_ERROR_INITIALIZATION_FAILED;
783 }
784 }
785
Chris Forbes1d5f68c2017-01-31 10:17:01 +1300786 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Chris Forbesb8042d22017-01-18 18:07:05 +1300787 err = native_window_set_auto_refresh(surface.window.get(), true);
788 if (err != 0) {
789 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
790 return VK_ERROR_INITIALIZATION_FAILED;
791 }
Chris Forbesb4421522017-01-18 16:57:02 +1300792 }
793
Jesse Hall70f93352015-11-04 09:41:31 -0800794 int gralloc_usage = 0;
Chris Forbes8c47dc92017-01-12 11:13:58 +1300795 if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
796 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
797 device, create_info->imageFormat, create_info->imageUsage,
798 swapchain_image_usage, &gralloc_usage);
799 if (result != VK_SUCCESS) {
800 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
801 return VK_ERROR_INITIALIZATION_FAILED;
802 }
803 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
Jesse Hall1f91d392015-12-11 16:28:44 -0800804 result = dispatch.GetSwapchainGrallocUsageANDROID(
Jesse Hallf4ab2b12015-11-30 16:04:55 -0800805 device, create_info->imageFormat, create_info->imageUsage,
Jesse Hall70f93352015-11-04 09:41:31 -0800806 &gralloc_usage);
807 if (result != VK_SUCCESS) {
808 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Jesse Hall70f93352015-11-04 09:41:31 -0800809 return VK_ERROR_INITIALIZATION_FAILED;
810 }
811 } else {
812 gralloc_usage = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
813 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800814 err = native_window_set_usage(surface.window.get(), gralloc_usage);
Jesse Hall70f93352015-11-04 09:41:31 -0800815 if (err != 0) {
816 // TODO(jessehall): Improve error reporting. Can we enumerate possible
817 // errors and translate them to valid Vulkan result codes?
818 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Jesse Hall70f93352015-11-04 09:41:31 -0800819 return VK_ERROR_INITIALIZATION_FAILED;
820 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700821
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700822 int swap_interval =
823 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
824 err = surface.window->setSwapInterval(surface.window.get(), swap_interval);
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800825 if (err != 0) {
826 // TODO(jessehall): Improve error reporting. Can we enumerate possible
827 // errors and translate them to valid Vulkan result codes?
Jesse Hall3d1c82a2016-04-22 15:28:29 -0700828 ALOGE("native_window->setSwapInterval(%d) failed: %s (%d)",
829 swap_interval, strerror(-err), err);
Jesse Hall0ae0dce2016-02-09 22:13:34 -0800830 return VK_ERROR_INITIALIZATION_FAILED;
831 }
832
Jesse Halld7b994a2015-09-07 14:17:37 -0700833 // -- Allocate our Swapchain object --
834 // After this point, we must deallocate the swapchain on error.
835
Jesse Hall1f91d392015-12-11 16:28:44 -0800836 void* mem = allocator->pfnAllocation(allocator->pUserData,
837 sizeof(Swapchain), alignof(Swapchain),
838 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800839 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -0700840 return VK_ERROR_OUT_OF_HOST_MEMORY;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800841 Swapchain* swapchain = new (mem) Swapchain(surface, num_images);
Jesse Halld7b994a2015-09-07 14:17:37 -0700842
843 // -- Dequeue all buffers and create a VkImage for each --
844 // Any failures during or after this must cancel the dequeued buffers.
845
Chris Forbesb56287a2017-01-12 14:28:58 +1300846 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
847#pragma clang diagnostic push
848#pragma clang diagnostic ignored "-Wold-style-cast"
849 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
850#pragma clang diagnostic pop
851 .pNext = nullptr,
852 .usage = swapchain_image_usage,
853 };
Jesse Halld7b994a2015-09-07 14:17:37 -0700854 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -0700855#pragma clang diagnostic push
856#pragma clang diagnostic ignored "-Wold-style-cast"
857 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
858#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +1300859 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -0700860 };
861 VkImageCreateInfo image_create = {
862 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
863 .pNext = &image_native_buffer,
864 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -0800865 .format = create_info->imageFormat,
Jesse Halld7b994a2015-09-07 14:17:37 -0700866 .extent = {0, 0, 1},
867 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -0800868 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -0800869 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -0700870 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -0800871 .usage = create_info->imageUsage,
Jesse Halld7b994a2015-09-07 14:17:37 -0700872 .flags = 0,
Jesse Hallf4ab2b12015-11-30 16:04:55 -0800873 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -0800874 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -0700875 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
876 };
877
Jesse Halld7b994a2015-09-07 14:17:37 -0700878 for (uint32_t i = 0; i < num_images; i++) {
879 Swapchain::Image& img = swapchain->images[i];
880
881 ANativeWindowBuffer* buffer;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800882 err = surface.window->dequeueBuffer(surface.window.get(), &buffer,
883 &img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700884 if (err != 0) {
885 // TODO(jessehall): Improve error reporting. Can we enumerate
886 // possible errors and translate them to valid Vulkan result codes?
887 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -0700888 result = VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -0700889 break;
890 }
Chia-I Wue8e689f2016-04-18 08:21:31 +0800891 img.buffer = buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700892 img.dequeued = true;
893
894 image_create.extent =
Jesse Hall3dd678a2016-01-08 21:52:01 -0800895 VkExtent3D{static_cast<uint32_t>(img.buffer->width),
896 static_cast<uint32_t>(img.buffer->height),
897 1};
Jesse Halld7b994a2015-09-07 14:17:37 -0700898 image_native_buffer.handle = img.buffer->handle;
899 image_native_buffer.stride = img.buffer->stride;
900 image_native_buffer.format = img.buffer->format;
901 image_native_buffer.usage = img.buffer->usage;
902
Jesse Hall03b6fe12015-11-24 12:44:21 -0800903 result =
Jesse Hall1f91d392015-12-11 16:28:44 -0800904 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
Jesse Halld7b994a2015-09-07 14:17:37 -0700905 if (result != VK_SUCCESS) {
906 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
907 break;
908 }
909 }
910
911 // -- Cancel all buffers, returning them to the queue --
912 // If an error occurred before, also destroy the VkImage and release the
913 // buffer reference. Otherwise, we retain a strong reference to the buffer.
914 //
915 // TODO(jessehall): The error path here is the same as DestroySwapchain,
916 // but not the non-error path. Should refactor/unify.
917 for (uint32_t i = 0; i < num_images; i++) {
918 Swapchain::Image& img = swapchain->images[i];
919 if (img.dequeued) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800920 surface.window->cancelBuffer(surface.window.get(), img.buffer.get(),
921 img.dequeue_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -0700922 img.dequeue_fence = -1;
923 img.dequeued = false;
924 }
925 if (result != VK_SUCCESS) {
926 if (img.image)
Jesse Hall1f91d392015-12-11 16:28:44 -0800927 dispatch.DestroyImage(device, img.image, nullptr);
Jesse Halld7b994a2015-09-07 14:17:37 -0700928 }
929 }
930
931 if (result != VK_SUCCESS) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700932 swapchain->~Swapchain();
Jesse Hall1f91d392015-12-11 16:28:44 -0800933 allocator->pfnFree(allocator->pUserData, swapchain);
Jesse Halld7b994a2015-09-07 14:17:37 -0700934 return result;
935 }
936
Jesse Halldc225072016-05-30 22:40:14 -0700937 surface.swapchain_handle = HandleFromSwapchain(swapchain);
938 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700939 return VK_SUCCESS;
940}
941
Jesse Halle1b12782015-11-30 11:27:32 -0800942VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800943void DestroySwapchainKHR(VkDevice device,
944 VkSwapchainKHR swapchain_handle,
945 const VkAllocationCallbacks* allocator) {
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800946 const auto& dispatch = GetData(device).driver;
Jesse Halld7b994a2015-09-07 14:17:37 -0700947 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
Daniel Kochd78c2e82016-12-13 18:45:13 -0500948 if (!swapchain)
949 return;
Jesse Hall42a9eec2016-06-03 12:39:49 -0700950 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
951 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
Jesse Halld7b994a2015-09-07 14:17:37 -0700952
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700953 if (swapchain->frame_timestamps_enabled) {
954 native_window_enable_frame_timestamps(window, false);
955 }
Jesse Halldc225072016-05-30 22:40:14 -0700956 for (uint32_t i = 0; i < swapchain->num_images; i++)
957 ReleaseSwapchainImage(device, window, -1, swapchain->images[i]);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700958 if (active)
Jesse Halldc225072016-05-30 22:40:14 -0700959 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Jesse Hall1f91d392015-12-11 16:28:44 -0800960 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800961 allocator = &GetData(device).allocator;
Jesse Halld7b994a2015-09-07 14:17:37 -0700962 swapchain->~Swapchain();
Jesse Hall1f91d392015-12-11 16:28:44 -0800963 allocator->pfnFree(allocator->pUserData, swapchain);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700964}
965
Jesse Halle1b12782015-11-30 11:27:32 -0800966VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800967VkResult GetSwapchainImagesKHR(VkDevice,
968 VkSwapchainKHR swapchain_handle,
969 uint32_t* count,
970 VkImage* images) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700971 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -0700972 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
973 "getting images for non-active swapchain 0x%" PRIx64
974 "; only dequeued image handles are valid",
975 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -0700976 VkResult result = VK_SUCCESS;
977 if (images) {
978 uint32_t n = swapchain.num_images;
979 if (*count < swapchain.num_images) {
980 n = *count;
981 result = VK_INCOMPLETE;
982 }
983 for (uint32_t i = 0; i < n; i++)
984 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -0700985 *count = n;
986 } else {
987 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -0700988 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700989 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700990}
991
Jesse Halle1b12782015-11-30 11:27:32 -0800992VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800993VkResult AcquireNextImageKHR(VkDevice device,
994 VkSwapchainKHR swapchain_handle,
995 uint64_t timeout,
996 VkSemaphore semaphore,
997 VkFence vk_fence,
998 uint32_t* image_index) {
Jesse Halld7b994a2015-09-07 14:17:37 -0700999 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001000 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07001001 VkResult result;
1002 int err;
1003
Jesse Halldc225072016-05-30 22:40:14 -07001004 if (swapchain.surface.swapchain_handle != swapchain_handle)
1005 return VK_ERROR_OUT_OF_DATE_KHR;
1006
Jesse Halld7b994a2015-09-07 14:17:37 -07001007 ALOGW_IF(
1008 timeout != UINT64_MAX,
1009 "vkAcquireNextImageKHR: non-infinite timeouts not yet implemented");
1010
1011 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08001012 int fence_fd;
1013 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001014 if (err != 0) {
1015 // TODO(jessehall): Improve error reporting. Can we enumerate possible
1016 // errors and translate them to valid Vulkan result codes?
1017 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Jesse Hall5ae3abb2015-10-08 14:00:22 -07001018 return VK_ERROR_INITIALIZATION_FAILED;
Jesse Halld7b994a2015-09-07 14:17:37 -07001019 }
1020
1021 uint32_t idx;
1022 for (idx = 0; idx < swapchain.num_images; idx++) {
1023 if (swapchain.images[idx].buffer.get() == buffer) {
1024 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08001025 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07001026 break;
1027 }
1028 }
1029 if (idx == swapchain.num_images) {
1030 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08001031 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001032 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001033 }
1034
1035 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08001036 if (fence_fd != -1) {
1037 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001038 if (fence_clone == -1) {
1039 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
1040 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08001041 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07001042 }
1043 }
1044
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001045 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08001046 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001047 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001048 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
1049 // even if the call fails. We could close it ourselves on failure, but
1050 // that would create a race condition if the driver closes it on a
1051 // failure path: some other thread might create an fd with the same
1052 // number between the time the driver closes it and the time we close
1053 // it. We must assume one of: the driver *always* closes it even on
1054 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08001055 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001056 swapchain.images[idx].dequeued = false;
1057 swapchain.images[idx].dequeue_fence = -1;
1058 return result;
1059 }
1060
1061 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001062 return VK_SUCCESS;
1063}
1064
Jesse Halldc225072016-05-30 22:40:14 -07001065static VkResult WorstPresentResult(VkResult a, VkResult b) {
1066 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
1067 // (in spec version 1.0.14).
1068 static const VkResult kWorstToBest[] = {
1069 VK_ERROR_DEVICE_LOST,
1070 VK_ERROR_SURFACE_LOST_KHR,
1071 VK_ERROR_OUT_OF_DATE_KHR,
1072 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1073 VK_ERROR_OUT_OF_HOST_MEMORY,
1074 VK_SUBOPTIMAL_KHR,
1075 };
1076 for (auto result : kWorstToBest) {
1077 if (a == result || b == result)
1078 return result;
1079 }
1080 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
1081 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
1082 return a != VK_SUCCESS ? a : b;
1083}
1084
Jesse Halle1b12782015-11-30 11:27:32 -08001085VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001086VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001087 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
1088 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
1089 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07001090
Jesse Halldc225072016-05-30 22:40:14 -07001091 VkDevice device = GetData(queue).driver_device;
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001092 const auto& dispatch = GetData(queue).driver;
Jesse Halld7b994a2015-09-07 14:17:37 -07001093 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07001094
Ian Elliottcb351132016-12-13 10:30:40 -07001095 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001096 const VkPresentRegionsKHR* present_regions = nullptr;
1097 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07001098 const VkPresentRegionsKHR* next =
1099 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
1100 while (next) {
1101 switch (next->sType) {
1102 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
1103 present_regions = next;
1104 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07001105 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001106 present_times =
1107 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
1108 break;
Ian Elliottcb351132016-12-13 10:30:40 -07001109 default:
1110 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
1111 next->sType);
1112 break;
1113 }
1114 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
1115 }
1116 ALOGV_IF(
1117 present_regions &&
1118 present_regions->swapchainCount != present_info->swapchainCount,
1119 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001120 ALOGV_IF(present_times &&
1121 present_times->swapchainCount != present_info->swapchainCount,
1122 "VkPresentTimesInfoGOOGLE::swapchainCount != "
1123 "VkPresentInfo::swapchainCount");
Ian Elliottcb351132016-12-13 10:30:40 -07001124 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001125 (present_regions) ? present_regions->pRegions : nullptr;
1126 const VkPresentTimeGOOGLE* times =
1127 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07001128 const VkAllocationCallbacks* allocator = &GetData(device).allocator;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001129 android_native_rect_t* rects = nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07001130 uint32_t nrects = 0;
1131
Jesse Halld7b994a2015-09-07 14:17:37 -07001132 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
1133 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08001134 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001135 uint32_t image_idx = present_info->pImageIndices[sc];
Jesse Hall5ae3abb2015-10-08 14:00:22 -07001136 Swapchain::Image& img = swapchain.images[image_idx];
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001137 const VkPresentRegionKHR* region = (regions) ? &regions[sc] : nullptr;
1138 const VkPresentTimeGOOGLE* time = (times) ? &times[sc] : nullptr;
Jesse Halldc225072016-05-30 22:40:14 -07001139 VkResult swapchain_result = VK_SUCCESS;
Jesse Halld7b994a2015-09-07 14:17:37 -07001140 VkResult result;
1141 int err;
1142
Jesse Halld7b994a2015-09-07 14:17:37 -07001143 int fence = -1;
Jesse Hall275d76c2016-01-08 22:39:16 -08001144 result = dispatch.QueueSignalReleaseImageANDROID(
1145 queue, present_info->waitSemaphoreCount,
1146 present_info->pWaitSemaphores, img.image, &fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001147 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001148 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
Jesse Halldc225072016-05-30 22:40:14 -07001149 swapchain_result = result;
Jesse Halld7b994a2015-09-07 14:17:37 -07001150 }
1151
Jesse Halldc225072016-05-30 22:40:14 -07001152 if (swapchain.surface.swapchain_handle ==
1153 present_info->pSwapchains[sc]) {
1154 ANativeWindow* window = swapchain.surface.window.get();
1155 if (swapchain_result == VK_SUCCESS) {
Ian Elliottcb351132016-12-13 10:30:40 -07001156 if (region) {
1157 // Process the incremental-present hint for this swapchain:
1158 uint32_t rcount = region->rectangleCount;
1159 if (rcount > nrects) {
1160 android_native_rect_t* new_rects =
1161 static_cast<android_native_rect_t*>(
1162 allocator->pfnReallocation(
1163 allocator->pUserData, rects,
1164 sizeof(android_native_rect_t) * rcount,
1165 alignof(android_native_rect_t),
1166 VK_SYSTEM_ALLOCATION_SCOPE_COMMAND));
1167 if (new_rects) {
1168 rects = new_rects;
1169 nrects = rcount;
1170 } else {
1171 rcount = 0; // Ignore the hint for this swapchain
1172 }
1173 }
1174 for (uint32_t r = 0; r < rcount; ++r) {
1175 if (region->pRectangles[r].layer > 0) {
1176 ALOGV(
1177 "vkQueuePresentKHR ignoring invalid layer "
1178 "(%u); using layer 0 instead",
1179 region->pRectangles[r].layer);
1180 }
1181 int x = region->pRectangles[r].offset.x;
1182 int y = region->pRectangles[r].offset.y;
1183 int width = static_cast<int>(
1184 region->pRectangles[r].extent.width);
1185 int height = static_cast<int>(
1186 region->pRectangles[r].extent.height);
1187 android_native_rect_t* cur_rect = &rects[r];
1188 cur_rect->left = x;
1189 cur_rect->top = y + height;
1190 cur_rect->right = x + width;
1191 cur_rect->bottom = y;
1192 }
1193 native_window_set_surface_damage(window, rects, rcount);
1194 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001195 if (time) {
1196 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07001197 ALOGV(
1198 "Calling "
1199 "native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001200 native_window_enable_frame_timestamps(window, true);
1201 swapchain.frame_timestamps_enabled = true;
1202 }
Brian Anderson1049d1d2016-12-16 17:25:57 -08001203
1204 // Record the nativeFrameId so it can be later correlated to
1205 // this present.
1206 uint64_t nativeFrameId = 0;
1207 err = native_window_get_next_frame_id(
1208 window, &nativeFrameId);
1209 if (err != android::NO_ERROR) {
1210 ALOGE("Failed to get next native frame ID.");
1211 }
1212
1213 // Add a new timing record with the user's presentID and
1214 // the nativeFrameId.
1215 swapchain.timing.push_back(TimingInfo(time, nativeFrameId));
1216 while (swapchain.timing.size() > MAX_TIMING_INFOS) {
Ian Elliott8a977262017-01-19 09:05:58 -07001217 swapchain.timing.removeAt(0);
1218 }
1219 if (time->desiredPresentTime) {
1220 // Set the desiredPresentTime:
1221 ALOGV(
1222 "Calling "
1223 "native_window_set_buffers_timestamp(%" PRId64 ")",
1224 time->desiredPresentTime);
1225 native_window_set_buffers_timestamp(
1226 window,
1227 static_cast<int64_t>(time->desiredPresentTime));
1228 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001229 }
Jesse Halldc225072016-05-30 22:40:14 -07001230 err = window->queueBuffer(window, img.buffer.get(), fence);
1231 // queueBuffer always closes fence, even on error
1232 if (err != 0) {
1233 // TODO(jessehall): What now? We should probably cancel the
1234 // buffer, I guess?
1235 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
1236 swapchain_result = WorstPresentResult(
1237 swapchain_result, VK_ERROR_OUT_OF_DATE_KHR);
1238 }
1239 if (img.dequeue_fence >= 0) {
1240 close(img.dequeue_fence);
1241 img.dequeue_fence = -1;
1242 }
1243 img.dequeued = false;
1244 }
1245 if (swapchain_result != VK_SUCCESS) {
1246 ReleaseSwapchainImage(device, window, fence, img);
1247 OrphanSwapchain(device, &swapchain);
1248 }
1249 } else {
1250 ReleaseSwapchainImage(device, nullptr, fence, img);
1251 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001252 }
1253
Jesse Halla9e57032015-11-30 01:03:10 -08001254 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07001255 present_info->pResults[sc] = swapchain_result;
1256
1257 if (swapchain_result != final_result)
1258 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07001259 }
Ian Elliottcb351132016-12-13 10:30:40 -07001260 if (rects) {
1261 allocator->pfnFree(allocator->pUserData, rects);
1262 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001263
1264 return final_result;
1265}
Jesse Hallb1352bc2015-09-04 16:12:33 -07001266
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001267VKAPI_ATTR
1268VkResult GetRefreshCycleDurationGOOGLE(
1269 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07001270 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001271 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Ian Elliott62c48c92017-01-20 13:13:20 -07001272 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001273 VkResult result = VK_SUCCESS;
1274
Ian Elliottbe833a22017-01-25 13:09:20 -07001275 pDisplayTimingProperties->refreshDuration = swapchain.refresh_duration;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001276
1277 return result;
1278}
1279
1280VKAPI_ATTR
1281VkResult GetPastPresentationTimingGOOGLE(
1282 VkDevice,
1283 VkSwapchainKHR swapchain_handle,
1284 uint32_t* count,
1285 VkPastPresentationTimingGOOGLE* timings) {
1286 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
1287 ANativeWindow* window = swapchain.surface.window.get();
1288 VkResult result = VK_SUCCESS;
1289
1290 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07001291 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001292 native_window_enable_frame_timestamps(window, true);
1293 swapchain.frame_timestamps_enabled = true;
1294 }
1295
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001296 if (timings) {
Ian Elliott8a977262017-01-19 09:05:58 -07001297 // TODO(ianelliott): plumb return value (e.g. VK_INCOMPLETE)
1298 copy_ready_timings(swapchain, count, timings);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001299 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07001300 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001301 }
1302
1303 return result;
1304}
1305
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13001306VKAPI_ATTR
1307VkResult GetSwapchainStatusKHR(
1308 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13001309 VkSwapchainKHR swapchain_handle) {
1310 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13001311 VkResult result = VK_SUCCESS;
1312
Chris Forbes4e18ba82017-01-20 12:50:17 +13001313 if (swapchain.surface.swapchain_handle != swapchain_handle) {
1314 return VK_ERROR_OUT_OF_DATE_KHR;
1315 }
1316
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13001317 // TODO(chrisforbes): Implement this function properly
1318
1319 return result;
1320}
1321
Chia-I Wu62262232016-03-26 07:06:44 +08001322} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07001323} // namespace vulkan