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