1 /*
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
17 #include <algorithm>
18
19 #include <grallocusage/GrallocUsageConversion.h>
20 #include <log/log.h>
21 #include <ui/BufferQueueDefs.h>
22 #include <sync/sync.h>
23 #include <utils/StrongPointer.h>
24 #include <utils/Vector.h>
25
26 #include "driver.h"
27
28 // TODO(jessehall): Currently we don't have a good error code for when a native
29 // window operation fails. Just returning INITIALIZATION_FAILED for now. Later
30 // versions (post SDK 0.9) of the API/extension have a better error code.
31 // When updating to that version, audit all error returns.
32 namespace vulkan {
33 namespace driver {
34
35 namespace {
36
37 const VkSurfaceTransformFlagsKHR kSupportedTransforms =
38 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
39 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
40 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
41 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
42 // TODO(jessehall): See TODO in TranslateNativeToVulkanTransform.
43 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
44 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
45 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
46 // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
47 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
48
TranslateNativeToVulkanTransform(int native)49 VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
50 // Native and Vulkan transforms are isomorphic, but are represented
51 // differently. Vulkan transforms are built up of an optional horizontal
52 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
53 // transforms are built up from a horizontal flip, vertical flip, and
54 // 90-degree rotation, all optional but always in that order.
55
56 // TODO(jessehall): For now, only support pure rotations, not
57 // flip or flip-and-rotate, until I have more time to test them and build
58 // sample code. As far as I know we never actually use anything besides
59 // pure rotations anyway.
60
61 switch (native) {
62 case 0: // 0x0
63 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
64 // case NATIVE_WINDOW_TRANSFORM_FLIP_H: // 0x1
65 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
66 // case NATIVE_WINDOW_TRANSFORM_FLIP_V: // 0x2
67 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
68 case NATIVE_WINDOW_TRANSFORM_ROT_180: // FLIP_H | FLIP_V
69 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
70 case NATIVE_WINDOW_TRANSFORM_ROT_90: // 0x4
71 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
72 // case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
73 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
74 // case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
75 // return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
76 case NATIVE_WINDOW_TRANSFORM_ROT_270: // FLIP_H | FLIP_V | ROT_90
77 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
78 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
79 default:
80 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
81 }
82 }
83
InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform)84 int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
85 switch (transform) {
86 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
87 return NATIVE_WINDOW_TRANSFORM_ROT_270;
88 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
89 return NATIVE_WINDOW_TRANSFORM_ROT_180;
90 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
91 return NATIVE_WINDOW_TRANSFORM_ROT_90;
92 // TODO(jessehall): See TODO in TranslateNativeToVulkanTransform.
93 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
94 // return NATIVE_WINDOW_TRANSFORM_FLIP_H;
95 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
96 // return NATIVE_WINDOW_TRANSFORM_FLIP_H |
97 // NATIVE_WINDOW_TRANSFORM_ROT_90;
98 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
99 // return NATIVE_WINDOW_TRANSFORM_FLIP_V;
100 // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
101 // return NATIVE_WINDOW_TRANSFORM_FLIP_V |
102 // NATIVE_WINDOW_TRANSFORM_ROT_90;
103 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
104 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
105 default:
106 return 0;
107 }
108 }
109
110 class TimingInfo {
111 public:
112 TimingInfo() = default;
TimingInfo(const VkPresentTimeGOOGLE * qp,uint64_t nativeFrameId)113 TimingInfo(const VkPresentTimeGOOGLE* qp, uint64_t nativeFrameId)
114 : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
115 native_frame_id_(nativeFrameId) {}
ready() const116 bool ready() const {
117 return (timestamp_desired_present_time_ !=
118 NATIVE_WINDOW_TIMESTAMP_PENDING &&
119 timestamp_actual_present_time_ !=
120 NATIVE_WINDOW_TIMESTAMP_PENDING &&
121 timestamp_render_complete_time_ !=
122 NATIVE_WINDOW_TIMESTAMP_PENDING &&
123 timestamp_composition_latch_time_ !=
124 NATIVE_WINDOW_TIMESTAMP_PENDING);
125 }
calculate(int64_t rdur)126 void calculate(int64_t rdur) {
127 bool anyTimestampInvalid =
128 (timestamp_actual_present_time_ ==
129 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
130 (timestamp_render_complete_time_ ==
131 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
132 (timestamp_composition_latch_time_ ==
133 NATIVE_WINDOW_TIMESTAMP_INVALID);
134 if (anyTimestampInvalid) {
135 ALOGE("Unexpectedly received invalid timestamp.");
136 vals_.actualPresentTime = 0;
137 vals_.earliestPresentTime = 0;
138 vals_.presentMargin = 0;
139 return;
140 }
141
142 vals_.actualPresentTime =
143 static_cast<uint64_t>(timestamp_actual_present_time_);
144 int64_t margin = (timestamp_composition_latch_time_ -
145 timestamp_render_complete_time_);
146 // Calculate vals_.earliestPresentTime, and potentially adjust
147 // vals_.presentMargin. The initial value of vals_.earliestPresentTime
148 // is vals_.actualPresentTime. If we can subtract rdur (the duration
149 // of a refresh cycle) from vals_.earliestPresentTime (and also from
150 // vals_.presentMargin) and still leave a positive margin, then we can
151 // report to the application that it could have presented earlier than
152 // it did (per the extension specification). If for some reason, we
153 // can do this subtraction repeatedly, we do, since
154 // vals_.earliestPresentTime really is supposed to be the "earliest".
155 int64_t early_time = timestamp_actual_present_time_;
156 while ((margin > rdur) &&
157 ((early_time - rdur) > timestamp_composition_latch_time_)) {
158 early_time -= rdur;
159 margin -= rdur;
160 }
161 vals_.earliestPresentTime = static_cast<uint64_t>(early_time);
162 vals_.presentMargin = static_cast<uint64_t>(margin);
163 }
get_values(VkPastPresentationTimingGOOGLE * values) const164 void get_values(VkPastPresentationTimingGOOGLE* values) const {
165 *values = vals_;
166 }
167
168 public:
169 VkPastPresentationTimingGOOGLE vals_ { 0, 0, 0, 0, 0 };
170
171 uint64_t native_frame_id_ { 0 };
172 int64_t timestamp_desired_present_time_{ NATIVE_WINDOW_TIMESTAMP_PENDING };
173 int64_t timestamp_actual_present_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
174 int64_t timestamp_render_complete_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
175 int64_t timestamp_composition_latch_time_
176 { NATIVE_WINDOW_TIMESTAMP_PENDING };
177 };
178
179 // ----------------------------------------------------------------------------
180
181 struct Surface {
182 android::sp<ANativeWindow> window;
183 VkSwapchainKHR swapchain_handle;
184 };
185
HandleFromSurface(Surface * surface)186 VkSurfaceKHR HandleFromSurface(Surface* surface) {
187 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
188 }
189
SurfaceFromHandle(VkSurfaceKHR handle)190 Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
191 return reinterpret_cast<Surface*>(handle);
192 }
193
194 // Maximum number of TimingInfo structs to keep per swapchain:
195 enum { MAX_TIMING_INFOS = 10 };
196 // Minimum number of frames to look for in the past (so we don't cause
197 // syncronous requests to Surface Flinger):
198 enum { MIN_NUM_FRAMES_AGO = 5 };
199
200 struct Swapchain {
Swapchainvulkan::driver::__anon3017a7eb0111::Swapchain201 Swapchain(Surface& surface_,
202 uint32_t num_images_,
203 VkPresentModeKHR present_mode)
204 : surface(surface_),
205 num_images(num_images_),
206 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
207 frame_timestamps_enabled(false),
208 shared(present_mode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
209 present_mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
210 ANativeWindow* window = surface.window.get();
211 native_window_get_refresh_cycle_duration(
212 window,
213 &refresh_duration);
214 }
215
216 Surface& surface;
217 uint32_t num_images;
218 bool mailbox_mode;
219 bool frame_timestamps_enabled;
220 int64_t refresh_duration;
221 bool shared;
222
223 struct Image {
Imagevulkan::driver::__anon3017a7eb0111::Swapchain::Image224 Image() : image(VK_NULL_HANDLE), dequeue_fence(-1), dequeued(false) {}
225 VkImage image;
226 android::sp<ANativeWindowBuffer> buffer;
227 // The fence is only valid when the buffer is dequeued, and should be
228 // -1 any other time. When valid, we own the fd, and must ensure it is
229 // closed: either by closing it explicitly when queueing the buffer,
230 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
231 int dequeue_fence;
232 bool dequeued;
233 } images[android::BufferQueueDefs::NUM_BUFFER_SLOTS];
234
235 android::Vector<TimingInfo> timing;
236 };
237
HandleFromSwapchain(Swapchain * swapchain)238 VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
239 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
240 }
241
SwapchainFromHandle(VkSwapchainKHR handle)242 Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
243 return reinterpret_cast<Swapchain*>(handle);
244 }
245
ReleaseSwapchainImage(VkDevice device,ANativeWindow * window,int release_fence,Swapchain::Image & image)246 void ReleaseSwapchainImage(VkDevice device,
247 ANativeWindow* window,
248 int release_fence,
249 Swapchain::Image& image) {
250 ALOG_ASSERT(release_fence == -1 || image.dequeued,
251 "ReleaseSwapchainImage: can't provide a release fence for "
252 "non-dequeued images");
253
254 if (image.dequeued) {
255 if (release_fence >= 0) {
256 // We get here from vkQueuePresentKHR. The application is
257 // responsible for creating an execution dependency chain from
258 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
259 // (release_fence), so we can drop the dequeue_fence here.
260 if (image.dequeue_fence >= 0)
261 close(image.dequeue_fence);
262 } else {
263 // We get here during swapchain destruction, or various serious
264 // error cases e.g. when we can't create the release_fence during
265 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
266 // have already signalled, since the swapchain images are supposed
267 // to be idle before the swapchain is destroyed. In error cases,
268 // there may be rendering in flight to the image, but since we
269 // weren't able to create a release_fence, waiting for the
270 // dequeue_fence is about the best we can do.
271 release_fence = image.dequeue_fence;
272 }
273 image.dequeue_fence = -1;
274
275 if (window) {
276 window->cancelBuffer(window, image.buffer.get(), release_fence);
277 } else {
278 if (release_fence >= 0) {
279 sync_wait(release_fence, -1 /* forever */);
280 close(release_fence);
281 }
282 }
283
284 image.dequeued = false;
285 }
286
287 if (image.image) {
288 GetData(device).driver.DestroyImage(device, image.image, nullptr);
289 image.image = VK_NULL_HANDLE;
290 }
291
292 image.buffer.clear();
293 }
294
OrphanSwapchain(VkDevice device,Swapchain * swapchain)295 void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
296 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
297 return;
298 for (uint32_t i = 0; i < swapchain->num_images; i++) {
299 if (!swapchain->images[i].dequeued)
300 ReleaseSwapchainImage(device, nullptr, -1, swapchain->images[i]);
301 }
302 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
303 swapchain->timing.clear();
304 }
305
get_num_ready_timings(Swapchain & swapchain)306 uint32_t get_num_ready_timings(Swapchain& swapchain) {
307 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
308 return 0;
309 }
310
311 uint32_t num_ready = 0;
312 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
313 for (uint32_t i = 0; i < num_timings; i++) {
314 TimingInfo& ti = swapchain.timing.editItemAt(i);
315 if (ti.ready()) {
316 // This TimingInfo is ready to be reported to the user. Add it
317 // to the num_ready.
318 num_ready++;
319 continue;
320 }
321 // This TimingInfo is not yet ready to be reported to the user,
322 // and so we should look for any available timestamps that
323 // might make it ready.
324 int64_t desired_present_time = 0;
325 int64_t render_complete_time = 0;
326 int64_t composition_latch_time = 0;
327 int64_t actual_present_time = 0;
328 // Obtain timestamps:
329 int ret = native_window_get_frame_timestamps(
330 swapchain.surface.window.get(), ti.native_frame_id_,
331 &desired_present_time, &render_complete_time,
332 &composition_latch_time,
333 NULL, //&first_composition_start_time,
334 NULL, //&last_composition_start_time,
335 NULL, //&composition_finish_time,
336 // TODO(ianelliott): Maybe ask if this one is
337 // supported, at startup time (since it may not be
338 // supported):
339 &actual_present_time,
340 NULL, //&dequeue_ready_time,
341 NULL /*&reads_done_time*/);
342
343 if (ret != android::NO_ERROR) {
344 continue;
345 }
346
347 // Record the timestamp(s) we received, and then see if this TimingInfo
348 // is ready to be reported to the user:
349 ti.timestamp_desired_present_time_ = desired_present_time;
350 ti.timestamp_actual_present_time_ = actual_present_time;
351 ti.timestamp_render_complete_time_ = render_complete_time;
352 ti.timestamp_composition_latch_time_ = composition_latch_time;
353
354 if (ti.ready()) {
355 // The TimingInfo has received enough timestamps, and should now
356 // use those timestamps to calculate the info that should be
357 // reported to the user:
358 ti.calculate(swapchain.refresh_duration);
359 num_ready++;
360 }
361 }
362 return num_ready;
363 }
364
365 // TODO(ianelliott): DEAL WITH RETURN VALUE (e.g. VK_INCOMPLETE)!!!
copy_ready_timings(Swapchain & swapchain,uint32_t * count,VkPastPresentationTimingGOOGLE * timings)366 void copy_ready_timings(Swapchain& swapchain,
367 uint32_t* count,
368 VkPastPresentationTimingGOOGLE* timings) {
369 if (swapchain.timing.empty()) {
370 *count = 0;
371 return;
372 }
373
374 size_t last_ready = swapchain.timing.size() - 1;
375 while (!swapchain.timing[last_ready].ready()) {
376 if (last_ready == 0) {
377 *count = 0;
378 return;
379 }
380 last_ready--;
381 }
382
383 uint32_t num_copied = 0;
384 size_t num_to_remove = 0;
385 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
386 const TimingInfo& ti = swapchain.timing[i];
387 if (ti.ready()) {
388 ti.get_values(&timings[num_copied]);
389 num_copied++;
390 }
391 num_to_remove++;
392 }
393
394 // Discard old frames that aren't ready if newer frames are ready.
395 // We don't expect to get the timing info for those old frames.
396 swapchain.timing.removeItemsAt(0, num_to_remove);
397
398 *count = num_copied;
399 }
400
GetNativePixelFormat(VkFormat format)401 android_pixel_format GetNativePixelFormat(VkFormat format) {
402 android_pixel_format native_format = HAL_PIXEL_FORMAT_RGBA_8888;
403 switch (format) {
404 case VK_FORMAT_R8G8B8A8_UNORM:
405 case VK_FORMAT_R8G8B8A8_SRGB:
406 native_format = HAL_PIXEL_FORMAT_RGBA_8888;
407 break;
408 case VK_FORMAT_R5G6B5_UNORM_PACK16:
409 native_format = HAL_PIXEL_FORMAT_RGB_565;
410 break;
411 case VK_FORMAT_R16G16B16A16_SFLOAT:
412 native_format = HAL_PIXEL_FORMAT_RGBA_FP16;
413 break;
414 case VK_FORMAT_A2R10G10B10_UNORM_PACK32:
415 native_format = HAL_PIXEL_FORMAT_RGBA_1010102;
416 break;
417 default:
418 ALOGV("unsupported swapchain format %d", format);
419 break;
420 }
421 return native_format;
422 }
423
GetNativeDataspace(VkColorSpaceKHR colorspace)424 android_dataspace GetNativeDataspace(VkColorSpaceKHR colorspace) {
425 switch (colorspace) {
426 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
427 return HAL_DATASPACE_V0_SRGB;
428 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
429 return HAL_DATASPACE_DISPLAY_P3;
430 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
431 return HAL_DATASPACE_V0_SCRGB_LINEAR;
432 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
433 return HAL_DATASPACE_DCI_P3_LINEAR;
434 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
435 return HAL_DATASPACE_DCI_P3;
436 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
437 return HAL_DATASPACE_V0_SRGB_LINEAR;
438 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
439 return HAL_DATASPACE_V0_SRGB;
440 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
441 return HAL_DATASPACE_BT2020_LINEAR;
442 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
443 return static_cast<android_dataspace>(
444 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
445 HAL_DATASPACE_RANGE_FULL);
446 case VK_COLOR_SPACE_DOLBYVISION_EXT:
447 return static_cast<android_dataspace>(
448 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
449 HAL_DATASPACE_RANGE_FULL);
450 case VK_COLOR_SPACE_HDR10_HLG_EXT:
451 return static_cast<android_dataspace>(
452 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_HLG |
453 HAL_DATASPACE_RANGE_FULL);
454 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
455 return static_cast<android_dataspace>(
456 HAL_DATASPACE_STANDARD_ADOBE_RGB |
457 HAL_DATASPACE_TRANSFER_LINEAR | HAL_DATASPACE_RANGE_FULL);
458 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
459 return HAL_DATASPACE_ADOBE_RGB;
460
461 // Pass through is intended to allow app to provide data that is passed
462 // to the display system without modification.
463 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
464 return HAL_DATASPACE_ARBITRARY;
465
466 default:
467 // This indicates that we don't know about the
468 // dataspace specified and we should indicate that
469 // it's unsupported
470 return HAL_DATASPACE_UNKNOWN;
471 }
472 }
473
474 } // anonymous namespace
475
476 VKAPI_ATTR
CreateAndroidSurfaceKHR(VkInstance instance,const VkAndroidSurfaceCreateInfoKHR * pCreateInfo,const VkAllocationCallbacks * allocator,VkSurfaceKHR * out_surface)477 VkResult CreateAndroidSurfaceKHR(
478 VkInstance instance,
479 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
480 const VkAllocationCallbacks* allocator,
481 VkSurfaceKHR* out_surface) {
482 if (!allocator)
483 allocator = &GetData(instance).allocator;
484 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
485 alignof(Surface),
486 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
487 if (!mem)
488 return VK_ERROR_OUT_OF_HOST_MEMORY;
489 Surface* surface = new (mem) Surface;
490
491 surface->window = pCreateInfo->window;
492 surface->swapchain_handle = VK_NULL_HANDLE;
493
494 // TODO(jessehall): Create and use NATIVE_WINDOW_API_VULKAN.
495 int err =
496 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
497 if (err != 0) {
498 // TODO(jessehall): Improve error reporting. Can we enumerate possible
499 // errors and translate them to valid Vulkan result codes?
500 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
501 err);
502 surface->~Surface();
503 allocator->pfnFree(allocator->pUserData, surface);
504 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
505 }
506
507 *out_surface = HandleFromSurface(surface);
508 return VK_SUCCESS;
509 }
510
511 VKAPI_ATTR
DestroySurfaceKHR(VkInstance instance,VkSurfaceKHR surface_handle,const VkAllocationCallbacks * allocator)512 void DestroySurfaceKHR(VkInstance instance,
513 VkSurfaceKHR surface_handle,
514 const VkAllocationCallbacks* allocator) {
515 Surface* surface = SurfaceFromHandle(surface_handle);
516 if (!surface)
517 return;
518 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
519 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
520 "destroyed VkSurfaceKHR 0x%" PRIx64
521 " has active VkSwapchainKHR 0x%" PRIx64,
522 reinterpret_cast<uint64_t>(surface_handle),
523 reinterpret_cast<uint64_t>(surface->swapchain_handle));
524 surface->~Surface();
525 if (!allocator)
526 allocator = &GetData(instance).allocator;
527 allocator->pfnFree(allocator->pUserData, surface);
528 }
529
530 VKAPI_ATTR
GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice,uint32_t,VkSurfaceKHR,VkBool32 * supported)531 VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
532 uint32_t /*queue_family*/,
533 VkSurfaceKHR /*surface*/,
534 VkBool32* supported) {
535 *supported = VK_TRUE;
536 return VK_SUCCESS;
537 }
538
539 VKAPI_ATTR
GetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice,VkSurfaceKHR surface,VkSurfaceCapabilitiesKHR * capabilities)540 VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
541 VkPhysicalDevice /*pdev*/,
542 VkSurfaceKHR surface,
543 VkSurfaceCapabilitiesKHR* capabilities) {
544 int err;
545 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
546
547 int width, height;
548 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
549 if (err != 0) {
550 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
551 strerror(-err), err);
552 return VK_ERROR_SURFACE_LOST_KHR;
553 }
554 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
555 if (err != 0) {
556 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
557 strerror(-err), err);
558 return VK_ERROR_SURFACE_LOST_KHR;
559 }
560
561 int transform_hint;
562 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
563 if (err != 0) {
564 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
565 strerror(-err), err);
566 return VK_ERROR_SURFACE_LOST_KHR;
567 }
568
569 // TODO(jessehall): Figure out what the min/max values should be.
570 capabilities->minImageCount = 2;
571 capabilities->maxImageCount = 3;
572
573 capabilities->currentExtent =
574 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
575
576 // TODO(jessehall): Figure out what the max extent should be. Maximum
577 // texture dimension maybe?
578 capabilities->minImageExtent = VkExtent2D{1, 1};
579 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
580
581 capabilities->maxImageArrayLayers = 1;
582
583 capabilities->supportedTransforms = kSupportedTransforms;
584 capabilities->currentTransform =
585 TranslateNativeToVulkanTransform(transform_hint);
586
587 // On Android, window composition is a WindowManager property, not something
588 // associated with the bufferqueue. It can't be changed from here.
589 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
590
591 // TODO(jessehall): I think these are right, but haven't thought hard about
592 // it. Do we need to query the driver for support of any of these?
593 // Currently not included:
594 // - VK_IMAGE_USAGE_DEPTH_STENCIL_BIT: definitely not
595 // - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT: definitely not
596 capabilities->supportedUsageFlags =
597 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
598 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
599 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
600 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
601
602 return VK_SUCCESS;
603 }
604
605 VKAPI_ATTR
GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,VkSurfaceKHR surface_handle,uint32_t * count,VkSurfaceFormatKHR * formats)606 VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
607 VkSurfaceKHR surface_handle,
608 uint32_t* count,
609 VkSurfaceFormatKHR* formats) {
610 const InstanceData& instance_data = GetData(pdev);
611
612 // TODO(jessehall): Fill out the set of supported formats. Longer term, add
613 // a new gralloc method to query whether a (format, usage) pair is
614 // supported, and check that for each gralloc format that corresponds to a
615 // Vulkan format. Shorter term, just add a few more formats to the ones
616 // hardcoded below.
617
618 const VkSurfaceFormatKHR kFormats[] = {
619 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
620 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
621 {VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
622 };
623 const uint32_t kNumFormats = sizeof(kFormats) / sizeof(kFormats[0]);
624 uint32_t total_num_formats = kNumFormats;
625
626 bool wide_color_support = false;
627 Surface& surface = *SurfaceFromHandle(surface_handle);
628 int err = native_window_get_wide_color_support(surface.window.get(),
629 &wide_color_support);
630 if (err) {
631 // Not allowed to return a more sensible error code, so do this
632 return VK_ERROR_OUT_OF_HOST_MEMORY;
633 }
634 ALOGV("wide_color_support is: %d", wide_color_support);
635 wide_color_support =
636 wide_color_support &&
637 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
638
639 const VkSurfaceFormatKHR kWideColorFormats[] = {
640 {VK_FORMAT_R16G16B16A16_SFLOAT,
641 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT},
642 {VK_FORMAT_A2R10G10B10_UNORM_PACK32,
643 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT},
644 };
645 const uint32_t kNumWideColorFormats =
646 sizeof(kWideColorFormats) / sizeof(kWideColorFormats[0]);
647 if (wide_color_support) {
648 total_num_formats += kNumWideColorFormats;
649 }
650
651 VkResult result = VK_SUCCESS;
652 if (formats) {
653 uint32_t out_count = 0;
654 uint32_t transfer_count = 0;
655 if (*count < total_num_formats)
656 result = VK_INCOMPLETE;
657 transfer_count = std::min(*count, kNumFormats);
658 std::copy(kFormats, kFormats + transfer_count, formats);
659 out_count += transfer_count;
660 if (wide_color_support) {
661 transfer_count = std::min(*count - out_count, kNumWideColorFormats);
662 std::copy(kWideColorFormats, kWideColorFormats + transfer_count,
663 formats + out_count);
664 out_count += transfer_count;
665 }
666 *count = out_count;
667 } else {
668 *count = total_num_formats;
669 }
670 return result;
671 }
672
673 VKAPI_ATTR
GetPhysicalDeviceSurfaceCapabilities2KHR(VkPhysicalDevice physicalDevice,const VkPhysicalDeviceSurfaceInfo2KHR * pSurfaceInfo,VkSurfaceCapabilities2KHR * pSurfaceCapabilities)674 VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
675 VkPhysicalDevice physicalDevice,
676 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
677 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
678 VkResult result = GetPhysicalDeviceSurfaceCapabilitiesKHR(
679 physicalDevice, pSurfaceInfo->surface,
680 &pSurfaceCapabilities->surfaceCapabilities);
681
682 VkSurfaceCapabilities2KHR* caps = pSurfaceCapabilities;
683 while (caps->pNext) {
684 caps = reinterpret_cast<VkSurfaceCapabilities2KHR*>(caps->pNext);
685
686 switch (caps->sType) {
687 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
688 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
689 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(
690 caps);
691 // Claim same set of usage flags are supported for
692 // shared present modes as for other modes.
693 shared_caps->sharedPresentSupportedUsageFlags =
694 pSurfaceCapabilities->surfaceCapabilities
695 .supportedUsageFlags;
696 } break;
697
698 default:
699 // Ignore all other extension structs
700 break;
701 }
702 }
703
704 return result;
705 }
706
707 VKAPI_ATTR
GetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,const VkPhysicalDeviceSurfaceInfo2KHR * pSurfaceInfo,uint32_t * pSurfaceFormatCount,VkSurfaceFormat2KHR * pSurfaceFormats)708 VkResult GetPhysicalDeviceSurfaceFormats2KHR(
709 VkPhysicalDevice physicalDevice,
710 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
711 uint32_t* pSurfaceFormatCount,
712 VkSurfaceFormat2KHR* pSurfaceFormats) {
713 if (!pSurfaceFormats) {
714 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
715 pSurfaceInfo->surface,
716 pSurfaceFormatCount, nullptr);
717 } else {
718 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
719 // after the call.
720 android::Vector<VkSurfaceFormatKHR> surface_formats;
721 surface_formats.resize(*pSurfaceFormatCount);
722 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
723 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
724 &surface_formats.editItemAt(0));
725
726 if (result == VK_SUCCESS || result == VK_INCOMPLETE) {
727 // marshal results individually due to stride difference.
728 // completely ignore any chained extension structs.
729 uint32_t formats_to_marshal = *pSurfaceFormatCount;
730 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
731 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
732 }
733 }
734
735 return result;
736 }
737 }
738
739 VKAPI_ATTR
GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,VkSurfaceKHR,uint32_t * count,VkPresentModeKHR * modes)740 VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
741 VkSurfaceKHR /*surface*/,
742 uint32_t* count,
743 VkPresentModeKHR* modes) {
744 android::Vector<VkPresentModeKHR> present_modes;
745 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
746 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
747
748 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
749 if (QueryPresentationProperties(pdev, &present_properties)) {
750 if (present_properties.sharedImage) {
751 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
752 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
753 }
754 }
755
756 uint32_t num_modes = uint32_t(present_modes.size());
757
758 VkResult result = VK_SUCCESS;
759 if (modes) {
760 if (*count < num_modes)
761 result = VK_INCOMPLETE;
762 *count = std::min(*count, num_modes);
763 std::copy(present_modes.begin(), present_modes.begin() + int(*count), modes);
764 } else {
765 *count = num_modes;
766 }
767 return result;
768 }
769
770 VKAPI_ATTR
CreateSwapchainKHR(VkDevice device,const VkSwapchainCreateInfoKHR * create_info,const VkAllocationCallbacks * allocator,VkSwapchainKHR * swapchain_handle)771 VkResult CreateSwapchainKHR(VkDevice device,
772 const VkSwapchainCreateInfoKHR* create_info,
773 const VkAllocationCallbacks* allocator,
774 VkSwapchainKHR* swapchain_handle) {
775 int err;
776 VkResult result = VK_SUCCESS;
777
778 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
779 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
780 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
781 " oldSwapchain=0x%" PRIx64,
782 reinterpret_cast<uint64_t>(create_info->surface),
783 create_info->minImageCount, create_info->imageFormat,
784 create_info->imageColorSpace, create_info->imageExtent.width,
785 create_info->imageExtent.height, create_info->imageUsage,
786 create_info->preTransform, create_info->presentMode,
787 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
788
789 if (!allocator)
790 allocator = &GetData(device).allocator;
791
792 android_pixel_format native_pixel_format =
793 GetNativePixelFormat(create_info->imageFormat);
794 android_dataspace native_dataspace =
795 GetNativeDataspace(create_info->imageColorSpace);
796 if (native_dataspace == HAL_DATASPACE_UNKNOWN) {
797 ALOGE(
798 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
799 "failed: Unsupported color space",
800 create_info->imageColorSpace);
801 return VK_ERROR_INITIALIZATION_FAILED;
802 }
803
804 ALOGV_IF(create_info->imageArrayLayers != 1,
805 "swapchain imageArrayLayers=%u not supported",
806 create_info->imageArrayLayers);
807 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
808 "swapchain preTransform=%#x not supported",
809 create_info->preTransform);
810 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
811 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
812 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
813 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
814 "swapchain presentMode=%u not supported",
815 create_info->presentMode);
816
817 Surface& surface = *SurfaceFromHandle(create_info->surface);
818
819 if (surface.swapchain_handle != create_info->oldSwapchain) {
820 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
821 " because it already has active swapchain 0x%" PRIx64
822 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
823 reinterpret_cast<uint64_t>(create_info->surface),
824 reinterpret_cast<uint64_t>(surface.swapchain_handle),
825 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
826 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
827 }
828 if (create_info->oldSwapchain != VK_NULL_HANDLE)
829 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
830
831 // -- Reset the native window --
832 // The native window might have been used previously, and had its properties
833 // changed from defaults. That will affect the answer we get for queries
834 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
835 // attempt such queries.
836
837 // The native window only allows dequeueing all buffers before any have
838 // been queued, since after that point at least one is assumed to be in
839 // non-FREE state at any given time. Disconnecting and re-connecting
840 // orphans the previous buffers, getting us back to the state where we can
841 // dequeue all buffers.
842 err = native_window_api_disconnect(surface.window.get(),
843 NATIVE_WINDOW_API_EGL);
844 ALOGW_IF(err != 0, "native_window_api_disconnect failed: %s (%d)",
845 strerror(-err), err);
846 err =
847 native_window_api_connect(surface.window.get(), NATIVE_WINDOW_API_EGL);
848 ALOGW_IF(err != 0, "native_window_api_connect failed: %s (%d)",
849 strerror(-err), err);
850
851 err = native_window_set_buffer_count(surface.window.get(), 0);
852 if (err != 0) {
853 ALOGE("native_window_set_buffer_count(0) failed: %s (%d)",
854 strerror(-err), err);
855 return VK_ERROR_SURFACE_LOST_KHR;
856 }
857
858 int swap_interval =
859 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
860 err = surface.window->setSwapInterval(surface.window.get(), swap_interval);
861 if (err != 0) {
862 // TODO(jessehall): Improve error reporting. Can we enumerate possible
863 // errors and translate them to valid Vulkan result codes?
864 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
865 strerror(-err), err);
866 return VK_ERROR_SURFACE_LOST_KHR;
867 }
868
869 err = native_window_set_shared_buffer_mode(surface.window.get(), false);
870 if (err != 0) {
871 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
872 strerror(-err), err);
873 return VK_ERROR_SURFACE_LOST_KHR;
874 }
875
876 err = native_window_set_auto_refresh(surface.window.get(), false);
877 if (err != 0) {
878 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
879 strerror(-err), err);
880 return VK_ERROR_SURFACE_LOST_KHR;
881 }
882
883 // -- Configure the native window --
884
885 const auto& dispatch = GetData(device).driver;
886
887 err = native_window_set_buffers_format(surface.window.get(),
888 native_pixel_format);
889 if (err != 0) {
890 // TODO(jessehall): Improve error reporting. Can we enumerate possible
891 // errors and translate them to valid Vulkan result codes?
892 ALOGE("native_window_set_buffers_format(%d) failed: %s (%d)",
893 native_pixel_format, strerror(-err), err);
894 return VK_ERROR_SURFACE_LOST_KHR;
895 }
896 err = native_window_set_buffers_data_space(surface.window.get(),
897 native_dataspace);
898 if (err != 0) {
899 // TODO(jessehall): Improve error reporting. Can we enumerate possible
900 // errors and translate them to valid Vulkan result codes?
901 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
902 native_dataspace, strerror(-err), err);
903 return VK_ERROR_SURFACE_LOST_KHR;
904 }
905
906 err = native_window_set_buffers_dimensions(
907 surface.window.get(), static_cast<int>(create_info->imageExtent.width),
908 static_cast<int>(create_info->imageExtent.height));
909 if (err != 0) {
910 // TODO(jessehall): Improve error reporting. Can we enumerate possible
911 // errors and translate them to valid Vulkan result codes?
912 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
913 create_info->imageExtent.width, create_info->imageExtent.height,
914 strerror(-err), err);
915 return VK_ERROR_SURFACE_LOST_KHR;
916 }
917
918 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
919 // applied during rendering. native_window_set_transform() expects the
920 // inverse: the transform the app is requesting that the compositor perform
921 // during composition. With native windows, pre-transform works by rendering
922 // with the same transform the compositor is applying (as in Vulkan), but
923 // then requesting the inverse transform, so that when the compositor does
924 // it's job the two transforms cancel each other out and the compositor ends
925 // up applying an identity transform to the app's buffer.
926 err = native_window_set_buffers_transform(
927 surface.window.get(),
928 InvertTransformToNative(create_info->preTransform));
929 if (err != 0) {
930 // TODO(jessehall): Improve error reporting. Can we enumerate possible
931 // errors and translate them to valid Vulkan result codes?
932 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
933 InvertTransformToNative(create_info->preTransform),
934 strerror(-err), err);
935 return VK_ERROR_SURFACE_LOST_KHR;
936 }
937
938 err = native_window_set_scaling_mode(
939 surface.window.get(), NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
940 if (err != 0) {
941 // TODO(jessehall): Improve error reporting. Can we enumerate possible
942 // errors and translate them to valid Vulkan result codes?
943 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
944 strerror(-err), err);
945 return VK_ERROR_SURFACE_LOST_KHR;
946 }
947
948 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
949 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
950 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
951 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
952 err = native_window_set_shared_buffer_mode(surface.window.get(), true);
953 if (err != 0) {
954 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
955 return VK_ERROR_SURFACE_LOST_KHR;
956 }
957 }
958
959 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
960 err = native_window_set_auto_refresh(surface.window.get(), true);
961 if (err != 0) {
962 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
963 return VK_ERROR_SURFACE_LOST_KHR;
964 }
965 }
966
967 int query_value;
968 err = surface.window->query(surface.window.get(),
969 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
970 &query_value);
971 if (err != 0 || query_value < 0) {
972 // TODO(jessehall): Improve error reporting. Can we enumerate possible
973 // errors and translate them to valid Vulkan result codes?
974 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
975 query_value);
976 return VK_ERROR_SURFACE_LOST_KHR;
977 }
978 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
979 uint32_t num_images =
980 (create_info->minImageCount - 1) + min_undequeued_buffers;
981
982 // Lower layer insists that we have at least two buffers. This is wasteful
983 // and we'd like to relax it in the shared case, but not all the pieces are
984 // in place for that to work yet. Note we only lie to the lower layer-- we
985 // don't want to give the app back a swapchain with extra images (which they
986 // can't actually use!).
987 err = native_window_set_buffer_count(surface.window.get(), std::max(2u, num_images));
988 if (err != 0) {
989 // TODO(jessehall): Improve error reporting. Can we enumerate possible
990 // errors and translate them to valid Vulkan result codes?
991 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", num_images,
992 strerror(-err), err);
993 return VK_ERROR_SURFACE_LOST_KHR;
994 }
995
996 int gralloc_usage = 0;
997 if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
998 uint64_t consumer_usage, producer_usage;
999 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1000 device, create_info->imageFormat, create_info->imageUsage,
1001 swapchain_image_usage, &consumer_usage, &producer_usage);
1002 if (result != VK_SUCCESS) {
1003 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
1004 return VK_ERROR_SURFACE_LOST_KHR;
1005 }
1006 gralloc_usage =
1007 android_convertGralloc1To0Usage(producer_usage, consumer_usage);
1008 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
1009 result = dispatch.GetSwapchainGrallocUsageANDROID(
1010 device, create_info->imageFormat, create_info->imageUsage,
1011 &gralloc_usage);
1012 if (result != VK_SUCCESS) {
1013 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
1014 return VK_ERROR_SURFACE_LOST_KHR;
1015 }
1016 }
1017 err = native_window_set_usage(surface.window.get(), gralloc_usage);
1018 if (err != 0) {
1019 // TODO(jessehall): Improve error reporting. Can we enumerate possible
1020 // errors and translate them to valid Vulkan result codes?
1021 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
1022 return VK_ERROR_SURFACE_LOST_KHR;
1023 }
1024
1025 // -- Allocate our Swapchain object --
1026 // After this point, we must deallocate the swapchain on error.
1027
1028 void* mem = allocator->pfnAllocation(allocator->pUserData,
1029 sizeof(Swapchain), alignof(Swapchain),
1030 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1031 if (!mem)
1032 return VK_ERROR_OUT_OF_HOST_MEMORY;
1033 Swapchain* swapchain =
1034 new (mem) Swapchain(surface, num_images, create_info->presentMode);
1035
1036 // -- Dequeue all buffers and create a VkImage for each --
1037 // Any failures during or after this must cancel the dequeued buffers.
1038
1039 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1040 #pragma clang diagnostic push
1041 #pragma clang diagnostic ignored "-Wold-style-cast"
1042 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1043 #pragma clang diagnostic pop
1044 .pNext = nullptr,
1045 .usage = swapchain_image_usage,
1046 };
1047 VkNativeBufferANDROID image_native_buffer = {
1048 #pragma clang diagnostic push
1049 #pragma clang diagnostic ignored "-Wold-style-cast"
1050 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1051 #pragma clang diagnostic pop
1052 .pNext = &swapchain_image_create,
1053 };
1054 VkImageCreateInfo image_create = {
1055 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1056 .pNext = &image_native_buffer,
1057 .imageType = VK_IMAGE_TYPE_2D,
1058 .format = create_info->imageFormat,
1059 .extent = {0, 0, 1},
1060 .mipLevels = 1,
1061 .arrayLayers = 1,
1062 .samples = VK_SAMPLE_COUNT_1_BIT,
1063 .tiling = VK_IMAGE_TILING_OPTIMAL,
1064 .usage = create_info->imageUsage,
1065 .flags = 0,
1066 .sharingMode = create_info->imageSharingMode,
1067 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
1068 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1069 };
1070
1071 for (uint32_t i = 0; i < num_images; i++) {
1072 Swapchain::Image& img = swapchain->images[i];
1073
1074 ANativeWindowBuffer* buffer;
1075 err = surface.window->dequeueBuffer(surface.window.get(), &buffer,
1076 &img.dequeue_fence);
1077 if (err != 0) {
1078 // TODO(jessehall): Improve error reporting. Can we enumerate
1079 // possible errors and translate them to valid Vulkan result codes?
1080 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
1081 result = VK_ERROR_SURFACE_LOST_KHR;
1082 break;
1083 }
1084 img.buffer = buffer;
1085 img.dequeued = true;
1086
1087 image_create.extent =
1088 VkExtent3D{static_cast<uint32_t>(img.buffer->width),
1089 static_cast<uint32_t>(img.buffer->height),
1090 1};
1091 image_native_buffer.handle = img.buffer->handle;
1092 image_native_buffer.stride = img.buffer->stride;
1093 image_native_buffer.format = img.buffer->format;
1094 image_native_buffer.usage = img.buffer->usage;
1095 android_convertGralloc0To1Usage(img.buffer->usage,
1096 &image_native_buffer.usage2.producer,
1097 &image_native_buffer.usage2.consumer);
1098
1099 result =
1100 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1101 if (result != VK_SUCCESS) {
1102 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
1103 break;
1104 }
1105 }
1106
1107 // -- Cancel all buffers, returning them to the queue --
1108 // If an error occurred before, also destroy the VkImage and release the
1109 // buffer reference. Otherwise, we retain a strong reference to the buffer.
1110 //
1111 // TODO(jessehall): The error path here is the same as DestroySwapchain,
1112 // but not the non-error path. Should refactor/unify.
1113 if (!swapchain->shared) {
1114 for (uint32_t i = 0; i < num_images; i++) {
1115 Swapchain::Image& img = swapchain->images[i];
1116 if (img.dequeued) {
1117 surface.window->cancelBuffer(surface.window.get(), img.buffer.get(),
1118 img.dequeue_fence);
1119 img.dequeue_fence = -1;
1120 img.dequeued = false;
1121 }
1122 if (result != VK_SUCCESS) {
1123 if (img.image)
1124 dispatch.DestroyImage(device, img.image, nullptr);
1125 }
1126 }
1127 }
1128
1129 if (result != VK_SUCCESS) {
1130 swapchain->~Swapchain();
1131 allocator->pfnFree(allocator->pUserData, swapchain);
1132 return result;
1133 }
1134
1135 surface.swapchain_handle = HandleFromSwapchain(swapchain);
1136 *swapchain_handle = surface.swapchain_handle;
1137 return VK_SUCCESS;
1138 }
1139
1140 VKAPI_ATTR
DestroySwapchainKHR(VkDevice device,VkSwapchainKHR swapchain_handle,const VkAllocationCallbacks * allocator)1141 void DestroySwapchainKHR(VkDevice device,
1142 VkSwapchainKHR swapchain_handle,
1143 const VkAllocationCallbacks* allocator) {
1144 const auto& dispatch = GetData(device).driver;
1145 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1146 if (!swapchain)
1147 return;
1148 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1149 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1150
1151 if (swapchain->frame_timestamps_enabled) {
1152 native_window_enable_frame_timestamps(window, false);
1153 }
1154 for (uint32_t i = 0; i < swapchain->num_images; i++)
1155 ReleaseSwapchainImage(device, window, -1, swapchain->images[i]);
1156 if (active)
1157 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1158 if (!allocator)
1159 allocator = &GetData(device).allocator;
1160 swapchain->~Swapchain();
1161 allocator->pfnFree(allocator->pUserData, swapchain);
1162 }
1163
1164 VKAPI_ATTR
GetSwapchainImagesKHR(VkDevice,VkSwapchainKHR swapchain_handle,uint32_t * count,VkImage * images)1165 VkResult GetSwapchainImagesKHR(VkDevice,
1166 VkSwapchainKHR swapchain_handle,
1167 uint32_t* count,
1168 VkImage* images) {
1169 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
1170 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
1171 "getting images for non-active swapchain 0x%" PRIx64
1172 "; only dequeued image handles are valid",
1173 reinterpret_cast<uint64_t>(swapchain_handle));
1174 VkResult result = VK_SUCCESS;
1175 if (images) {
1176 uint32_t n = swapchain.num_images;
1177 if (*count < swapchain.num_images) {
1178 n = *count;
1179 result = VK_INCOMPLETE;
1180 }
1181 for (uint32_t i = 0; i < n; i++)
1182 images[i] = swapchain.images[i].image;
1183 *count = n;
1184 } else {
1185 *count = swapchain.num_images;
1186 }
1187 return result;
1188 }
1189
1190 VKAPI_ATTR
AcquireNextImageKHR(VkDevice device,VkSwapchainKHR swapchain_handle,uint64_t timeout,VkSemaphore semaphore,VkFence vk_fence,uint32_t * image_index)1191 VkResult AcquireNextImageKHR(VkDevice device,
1192 VkSwapchainKHR swapchain_handle,
1193 uint64_t timeout,
1194 VkSemaphore semaphore,
1195 VkFence vk_fence,
1196 uint32_t* image_index) {
1197 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
1198 ANativeWindow* window = swapchain.surface.window.get();
1199 VkResult result;
1200 int err;
1201
1202 if (swapchain.surface.swapchain_handle != swapchain_handle)
1203 return VK_ERROR_OUT_OF_DATE_KHR;
1204
1205 ALOGW_IF(
1206 timeout != UINT64_MAX,
1207 "vkAcquireNextImageKHR: non-infinite timeouts not yet implemented");
1208
1209 if (swapchain.shared) {
1210 // In shared mode, we keep the buffer dequeued all the time, so we don't
1211 // want to dequeue a buffer here. Instead, just ask the driver to ensure
1212 // the semaphore and fence passed to us will be signalled.
1213 *image_index = 0;
1214 result = GetData(device).driver.AcquireImageANDROID(
1215 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
1216 return result;
1217 }
1218
1219 ANativeWindowBuffer* buffer;
1220 int fence_fd;
1221 err = window->dequeueBuffer(window, &buffer, &fence_fd);
1222 if (err != 0) {
1223 // TODO(jessehall): Improve error reporting. Can we enumerate possible
1224 // errors and translate them to valid Vulkan result codes?
1225 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
1226 return VK_ERROR_SURFACE_LOST_KHR;
1227 }
1228
1229 uint32_t idx;
1230 for (idx = 0; idx < swapchain.num_images; idx++) {
1231 if (swapchain.images[idx].buffer.get() == buffer) {
1232 swapchain.images[idx].dequeued = true;
1233 swapchain.images[idx].dequeue_fence = fence_fd;
1234 break;
1235 }
1236 }
1237 if (idx == swapchain.num_images) {
1238 ALOGE("dequeueBuffer returned unrecognized buffer");
1239 window->cancelBuffer(window, buffer, fence_fd);
1240 return VK_ERROR_OUT_OF_DATE_KHR;
1241 }
1242
1243 int fence_clone = -1;
1244 if (fence_fd != -1) {
1245 fence_clone = dup(fence_fd);
1246 if (fence_clone == -1) {
1247 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
1248 strerror(errno), errno);
1249 sync_wait(fence_fd, -1 /* forever */);
1250 }
1251 }
1252
1253 result = GetData(device).driver.AcquireImageANDROID(
1254 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
1255 if (result != VK_SUCCESS) {
1256 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
1257 // even if the call fails. We could close it ourselves on failure, but
1258 // that would create a race condition if the driver closes it on a
1259 // failure path: some other thread might create an fd with the same
1260 // number between the time the driver closes it and the time we close
1261 // it. We must assume one of: the driver *always* closes it even on
1262 // failure, or *never* closes it on failure.
1263 window->cancelBuffer(window, buffer, fence_fd);
1264 swapchain.images[idx].dequeued = false;
1265 swapchain.images[idx].dequeue_fence = -1;
1266 return result;
1267 }
1268
1269 *image_index = idx;
1270 return VK_SUCCESS;
1271 }
1272
WorstPresentResult(VkResult a,VkResult b)1273 static VkResult WorstPresentResult(VkResult a, VkResult b) {
1274 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
1275 // (in spec version 1.0.14).
1276 static const VkResult kWorstToBest[] = {
1277 VK_ERROR_DEVICE_LOST,
1278 VK_ERROR_SURFACE_LOST_KHR,
1279 VK_ERROR_OUT_OF_DATE_KHR,
1280 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1281 VK_ERROR_OUT_OF_HOST_MEMORY,
1282 VK_SUBOPTIMAL_KHR,
1283 };
1284 for (auto result : kWorstToBest) {
1285 if (a == result || b == result)
1286 return result;
1287 }
1288 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
1289 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
1290 return a != VK_SUCCESS ? a : b;
1291 }
1292
1293 VKAPI_ATTR
QueuePresentKHR(VkQueue queue,const VkPresentInfoKHR * present_info)1294 VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
1295 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
1296 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
1297 present_info->sType);
1298
1299 VkDevice device = GetData(queue).driver_device;
1300 const auto& dispatch = GetData(queue).driver;
1301 VkResult final_result = VK_SUCCESS;
1302
1303 // Look at the pNext chain for supported extension structs:
1304 const VkPresentRegionsKHR* present_regions = nullptr;
1305 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
1306 const VkPresentRegionsKHR* next =
1307 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
1308 while (next) {
1309 switch (next->sType) {
1310 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
1311 present_regions = next;
1312 break;
1313 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
1314 present_times =
1315 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
1316 break;
1317 default:
1318 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
1319 next->sType);
1320 break;
1321 }
1322 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
1323 }
1324 ALOGV_IF(
1325 present_regions &&
1326 present_regions->swapchainCount != present_info->swapchainCount,
1327 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
1328 ALOGV_IF(present_times &&
1329 present_times->swapchainCount != present_info->swapchainCount,
1330 "VkPresentTimesInfoGOOGLE::swapchainCount != "
1331 "VkPresentInfo::swapchainCount");
1332 const VkPresentRegionKHR* regions =
1333 (present_regions) ? present_regions->pRegions : nullptr;
1334 const VkPresentTimeGOOGLE* times =
1335 (present_times) ? present_times->pTimes : nullptr;
1336 const VkAllocationCallbacks* allocator = &GetData(device).allocator;
1337 android_native_rect_t* rects = nullptr;
1338 uint32_t nrects = 0;
1339
1340 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
1341 Swapchain& swapchain =
1342 *SwapchainFromHandle(present_info->pSwapchains[sc]);
1343 uint32_t image_idx = present_info->pImageIndices[sc];
1344 Swapchain::Image& img = swapchain.images[image_idx];
1345 const VkPresentRegionKHR* region =
1346 (regions && !swapchain.mailbox_mode) ? ®ions[sc] : nullptr;
1347 const VkPresentTimeGOOGLE* time = (times) ? ×[sc] : nullptr;
1348 VkResult swapchain_result = VK_SUCCESS;
1349 VkResult result;
1350 int err;
1351
1352 int fence = -1;
1353 result = dispatch.QueueSignalReleaseImageANDROID(
1354 queue, present_info->waitSemaphoreCount,
1355 present_info->pWaitSemaphores, img.image, &fence);
1356 if (result != VK_SUCCESS) {
1357 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
1358 swapchain_result = result;
1359 }
1360
1361 if (swapchain.surface.swapchain_handle ==
1362 present_info->pSwapchains[sc]) {
1363 ANativeWindow* window = swapchain.surface.window.get();
1364 if (swapchain_result == VK_SUCCESS) {
1365 if (region) {
1366 // Process the incremental-present hint for this swapchain:
1367 uint32_t rcount = region->rectangleCount;
1368 if (rcount > nrects) {
1369 android_native_rect_t* new_rects =
1370 static_cast<android_native_rect_t*>(
1371 allocator->pfnReallocation(
1372 allocator->pUserData, rects,
1373 sizeof(android_native_rect_t) * rcount,
1374 alignof(android_native_rect_t),
1375 VK_SYSTEM_ALLOCATION_SCOPE_COMMAND));
1376 if (new_rects) {
1377 rects = new_rects;
1378 nrects = rcount;
1379 } else {
1380 rcount = 0; // Ignore the hint for this swapchain
1381 }
1382 }
1383 for (uint32_t r = 0; r < rcount; ++r) {
1384 if (region->pRectangles[r].layer > 0) {
1385 ALOGV(
1386 "vkQueuePresentKHR ignoring invalid layer "
1387 "(%u); using layer 0 instead",
1388 region->pRectangles[r].layer);
1389 }
1390 int x = region->pRectangles[r].offset.x;
1391 int y = region->pRectangles[r].offset.y;
1392 int width = static_cast<int>(
1393 region->pRectangles[r].extent.width);
1394 int height = static_cast<int>(
1395 region->pRectangles[r].extent.height);
1396 android_native_rect_t* cur_rect = &rects[r];
1397 cur_rect->left = x;
1398 cur_rect->top = y + height;
1399 cur_rect->right = x + width;
1400 cur_rect->bottom = y;
1401 }
1402 native_window_set_surface_damage(window, rects, rcount);
1403 }
1404 if (time) {
1405 if (!swapchain.frame_timestamps_enabled) {
1406 ALOGV(
1407 "Calling "
1408 "native_window_enable_frame_timestamps(true)");
1409 native_window_enable_frame_timestamps(window, true);
1410 swapchain.frame_timestamps_enabled = true;
1411 }
1412
1413 // Record the nativeFrameId so it can be later correlated to
1414 // this present.
1415 uint64_t nativeFrameId = 0;
1416 err = native_window_get_next_frame_id(
1417 window, &nativeFrameId);
1418 if (err != android::NO_ERROR) {
1419 ALOGE("Failed to get next native frame ID.");
1420 }
1421
1422 // Add a new timing record with the user's presentID and
1423 // the nativeFrameId.
1424 swapchain.timing.push_back(TimingInfo(time, nativeFrameId));
1425 while (swapchain.timing.size() > MAX_TIMING_INFOS) {
1426 swapchain.timing.removeAt(0);
1427 }
1428 if (time->desiredPresentTime) {
1429 // Set the desiredPresentTime:
1430 ALOGV(
1431 "Calling "
1432 "native_window_set_buffers_timestamp(%" PRId64 ")",
1433 time->desiredPresentTime);
1434 native_window_set_buffers_timestamp(
1435 window,
1436 static_cast<int64_t>(time->desiredPresentTime));
1437 }
1438 }
1439
1440 err = window->queueBuffer(window, img.buffer.get(), fence);
1441 // queueBuffer always closes fence, even on error
1442 if (err != 0) {
1443 // TODO(jessehall): What now? We should probably cancel the
1444 // buffer, I guess?
1445 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
1446 swapchain_result = WorstPresentResult(
1447 swapchain_result, VK_ERROR_OUT_OF_DATE_KHR);
1448 }
1449 if (img.dequeue_fence >= 0) {
1450 close(img.dequeue_fence);
1451 img.dequeue_fence = -1;
1452 }
1453 img.dequeued = false;
1454
1455 // If the swapchain is in shared mode, immediately dequeue the
1456 // buffer so it can be presented again without an intervening
1457 // call to AcquireNextImageKHR. We expect to get the same buffer
1458 // back from every call to dequeueBuffer in this mode.
1459 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
1460 ANativeWindowBuffer* buffer;
1461 int fence_fd;
1462 err = window->dequeueBuffer(window, &buffer, &fence_fd);
1463 if (err != 0) {
1464 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
1465 swapchain_result = WorstPresentResult(swapchain_result,
1466 VK_ERROR_SURFACE_LOST_KHR);
1467 }
1468 else if (img.buffer != buffer) {
1469 ALOGE("got wrong image back for shared swapchain");
1470 swapchain_result = WorstPresentResult(swapchain_result,
1471 VK_ERROR_SURFACE_LOST_KHR);
1472 }
1473 else {
1474 img.dequeue_fence = fence_fd;
1475 img.dequeued = true;
1476 }
1477 }
1478 }
1479 if (swapchain_result != VK_SUCCESS) {
1480 ReleaseSwapchainImage(device, window, fence, img);
1481 OrphanSwapchain(device, &swapchain);
1482 }
1483 } else {
1484 ReleaseSwapchainImage(device, nullptr, fence, img);
1485 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
1486 }
1487
1488 if (present_info->pResults)
1489 present_info->pResults[sc] = swapchain_result;
1490
1491 if (swapchain_result != final_result)
1492 final_result = WorstPresentResult(final_result, swapchain_result);
1493 }
1494 if (rects) {
1495 allocator->pfnFree(allocator->pUserData, rects);
1496 }
1497
1498 return final_result;
1499 }
1500
1501 VKAPI_ATTR
GetRefreshCycleDurationGOOGLE(VkDevice,VkSwapchainKHR swapchain_handle,VkRefreshCycleDurationGOOGLE * pDisplayTimingProperties)1502 VkResult GetRefreshCycleDurationGOOGLE(
1503 VkDevice,
1504 VkSwapchainKHR swapchain_handle,
1505 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
1506 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
1507 VkResult result = VK_SUCCESS;
1508
1509 pDisplayTimingProperties->refreshDuration =
1510 static_cast<uint64_t>(swapchain.refresh_duration);
1511
1512 return result;
1513 }
1514
1515 VKAPI_ATTR
GetPastPresentationTimingGOOGLE(VkDevice,VkSwapchainKHR swapchain_handle,uint32_t * count,VkPastPresentationTimingGOOGLE * timings)1516 VkResult GetPastPresentationTimingGOOGLE(
1517 VkDevice,
1518 VkSwapchainKHR swapchain_handle,
1519 uint32_t* count,
1520 VkPastPresentationTimingGOOGLE* timings) {
1521 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
1522 ANativeWindow* window = swapchain.surface.window.get();
1523 VkResult result = VK_SUCCESS;
1524
1525 if (!swapchain.frame_timestamps_enabled) {
1526 ALOGV("Calling native_window_enable_frame_timestamps(true)");
1527 native_window_enable_frame_timestamps(window, true);
1528 swapchain.frame_timestamps_enabled = true;
1529 }
1530
1531 if (timings) {
1532 // TODO(ianelliott): plumb return value (e.g. VK_INCOMPLETE)
1533 copy_ready_timings(swapchain, count, timings);
1534 } else {
1535 *count = get_num_ready_timings(swapchain);
1536 }
1537
1538 return result;
1539 }
1540
1541 VKAPI_ATTR
GetSwapchainStatusKHR(VkDevice,VkSwapchainKHR swapchain_handle)1542 VkResult GetSwapchainStatusKHR(
1543 VkDevice,
1544 VkSwapchainKHR swapchain_handle) {
1545 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
1546 VkResult result = VK_SUCCESS;
1547
1548 if (swapchain.surface.swapchain_handle != swapchain_handle) {
1549 return VK_ERROR_OUT_OF_DATE_KHR;
1550 }
1551
1552 // TODO(chrisforbes): Implement this function properly
1553
1554 return result;
1555 }
1556
SetHdrMetadataEXT(VkDevice device,uint32_t swapchainCount,const VkSwapchainKHR * pSwapchains,const VkHdrMetadataEXT * pHdrMetadataEXTs)1557 VKAPI_ATTR void SetHdrMetadataEXT(
1558 VkDevice device,
1559 uint32_t swapchainCount,
1560 const VkSwapchainKHR* pSwapchains,
1561 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
1562 // TODO: courtneygo: implement actual function
1563 (void)device;
1564 (void)swapchainCount;
1565 (void)pSwapchains;
1566 (void)pHdrMetadataEXTs;
1567 return;
1568 }
1569
1570 } // namespace driver
1571 } // namespace vulkan
1572