OSDN Git Service

libgui: Check slot received from IGBP in Surface am: ac93b3a30e am: 7cb9cd3df2 am...
[android-x86/frameworks-native.git] / vulkan / libvulkan / swapchain.cpp
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
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
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;
113     TimingInfo(const VkPresentTimeGOOGLE* qp, uint64_t nativeFrameId)
114         : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
115           native_frame_id_(nativeFrameId) {}
116     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     }
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     }
164     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
186 VkSurfaceKHR HandleFromSurface(Surface* surface) {
187     return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
188 }
189
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 {
201     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 {
224         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
238 VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
239     return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
240 }
241
242 Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
243     return reinterpret_cast<Swapchain*>(handle);
244 }
245
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
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
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)!!!
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
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
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
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
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
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
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
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
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
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
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
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         // TODO: Adjust once ANativeWindowBuffer supports gralloc1-style usage.
1096         // For now, this is the same translation Gralloc1On0Adapter does.
1097         image_native_buffer.usage2.consumer =
1098             static_cast<uint64_t>(img.buffer->usage);
1099         image_native_buffer.usage2.producer =
1100             static_cast<uint64_t>(img.buffer->usage);
1101
1102         result =
1103             dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1104         if (result != VK_SUCCESS) {
1105             ALOGD("vkCreateImage w/ native buffer failed: %u", result);
1106             break;
1107         }
1108     }
1109
1110     // -- Cancel all buffers, returning them to the queue --
1111     // If an error occurred before, also destroy the VkImage and release the
1112     // buffer reference. Otherwise, we retain a strong reference to the buffer.
1113     //
1114     // TODO(jessehall): The error path here is the same as DestroySwapchain,
1115     // but not the non-error path. Should refactor/unify.
1116     if (!swapchain->shared) {
1117         for (uint32_t i = 0; i < num_images; i++) {
1118             Swapchain::Image& img = swapchain->images[i];
1119             if (img.dequeued) {
1120                 surface.window->cancelBuffer(surface.window.get(), img.buffer.get(),
1121                                              img.dequeue_fence);
1122                 img.dequeue_fence = -1;
1123                 img.dequeued = false;
1124             }
1125             if (result != VK_SUCCESS) {
1126                 if (img.image)
1127                     dispatch.DestroyImage(device, img.image, nullptr);
1128             }
1129         }
1130     }
1131
1132     if (result != VK_SUCCESS) {
1133         swapchain->~Swapchain();
1134         allocator->pfnFree(allocator->pUserData, swapchain);
1135         return result;
1136     }
1137
1138     surface.swapchain_handle = HandleFromSwapchain(swapchain);
1139     *swapchain_handle = surface.swapchain_handle;
1140     return VK_SUCCESS;
1141 }
1142
1143 VKAPI_ATTR
1144 void DestroySwapchainKHR(VkDevice device,
1145                          VkSwapchainKHR swapchain_handle,
1146                          const VkAllocationCallbacks* allocator) {
1147     const auto& dispatch = GetData(device).driver;
1148     Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1149     if (!swapchain)
1150         return;
1151     bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1152     ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1153
1154     if (swapchain->frame_timestamps_enabled) {
1155         native_window_enable_frame_timestamps(window, false);
1156     }
1157     for (uint32_t i = 0; i < swapchain->num_images; i++)
1158         ReleaseSwapchainImage(device, window, -1, swapchain->images[i]);
1159     if (active)
1160         swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1161     if (!allocator)
1162         allocator = &GetData(device).allocator;
1163     swapchain->~Swapchain();
1164     allocator->pfnFree(allocator->pUserData, swapchain);
1165 }
1166
1167 VKAPI_ATTR
1168 VkResult GetSwapchainImagesKHR(VkDevice,
1169                                VkSwapchainKHR swapchain_handle,
1170                                uint32_t* count,
1171                                VkImage* images) {
1172     Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
1173     ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
1174              "getting images for non-active swapchain 0x%" PRIx64
1175              "; only dequeued image handles are valid",
1176              reinterpret_cast<uint64_t>(swapchain_handle));
1177     VkResult result = VK_SUCCESS;
1178     if (images) {
1179         uint32_t n = swapchain.num_images;
1180         if (*count < swapchain.num_images) {
1181             n = *count;
1182             result = VK_INCOMPLETE;
1183         }
1184         for (uint32_t i = 0; i < n; i++)
1185             images[i] = swapchain.images[i].image;
1186         *count = n;
1187     } else {
1188         *count = swapchain.num_images;
1189     }
1190     return result;
1191 }
1192
1193 VKAPI_ATTR
1194 VkResult AcquireNextImageKHR(VkDevice device,
1195                              VkSwapchainKHR swapchain_handle,
1196                              uint64_t timeout,
1197                              VkSemaphore semaphore,
1198                              VkFence vk_fence,
1199                              uint32_t* image_index) {
1200     Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
1201     ANativeWindow* window = swapchain.surface.window.get();
1202     VkResult result;
1203     int err;
1204
1205     if (swapchain.surface.swapchain_handle != swapchain_handle)
1206         return VK_ERROR_OUT_OF_DATE_KHR;
1207
1208     ALOGW_IF(
1209         timeout != UINT64_MAX,
1210         "vkAcquireNextImageKHR: non-infinite timeouts not yet implemented");
1211
1212     if (swapchain.shared) {
1213         // In shared mode, we keep the buffer dequeued all the time, so we don't
1214         // want to dequeue a buffer here. Instead, just ask the driver to ensure
1215         // the semaphore and fence passed to us will be signalled.
1216         *image_index = 0;
1217         result = GetData(device).driver.AcquireImageANDROID(
1218                 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
1219         return result;
1220     }
1221
1222     ANativeWindowBuffer* buffer;
1223     int fence_fd;
1224     err = window->dequeueBuffer(window, &buffer, &fence_fd);
1225     if (err != 0) {
1226         // TODO(jessehall): Improve error reporting. Can we enumerate possible
1227         // errors and translate them to valid Vulkan result codes?
1228         ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
1229         return VK_ERROR_SURFACE_LOST_KHR;
1230     }
1231
1232     uint32_t idx;
1233     for (idx = 0; idx < swapchain.num_images; idx++) {
1234         if (swapchain.images[idx].buffer.get() == buffer) {
1235             swapchain.images[idx].dequeued = true;
1236             swapchain.images[idx].dequeue_fence = fence_fd;
1237             break;
1238         }
1239     }
1240     if (idx == swapchain.num_images) {
1241         ALOGE("dequeueBuffer returned unrecognized buffer");
1242         window->cancelBuffer(window, buffer, fence_fd);
1243         return VK_ERROR_OUT_OF_DATE_KHR;
1244     }
1245
1246     int fence_clone = -1;
1247     if (fence_fd != -1) {
1248         fence_clone = dup(fence_fd);
1249         if (fence_clone == -1) {
1250             ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
1251                   strerror(errno), errno);
1252             sync_wait(fence_fd, -1 /* forever */);
1253         }
1254     }
1255
1256     result = GetData(device).driver.AcquireImageANDROID(
1257         device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
1258     if (result != VK_SUCCESS) {
1259         // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
1260         // even if the call fails. We could close it ourselves on failure, but
1261         // that would create a race condition if the driver closes it on a
1262         // failure path: some other thread might create an fd with the same
1263         // number between the time the driver closes it and the time we close
1264         // it. We must assume one of: the driver *always* closes it even on
1265         // failure, or *never* closes it on failure.
1266         window->cancelBuffer(window, buffer, fence_fd);
1267         swapchain.images[idx].dequeued = false;
1268         swapchain.images[idx].dequeue_fence = -1;
1269         return result;
1270     }
1271
1272     *image_index = idx;
1273     return VK_SUCCESS;
1274 }
1275
1276 static VkResult WorstPresentResult(VkResult a, VkResult b) {
1277     // See the error ranking for vkQueuePresentKHR at the end of section 29.6
1278     // (in spec version 1.0.14).
1279     static const VkResult kWorstToBest[] = {
1280         VK_ERROR_DEVICE_LOST,
1281         VK_ERROR_SURFACE_LOST_KHR,
1282         VK_ERROR_OUT_OF_DATE_KHR,
1283         VK_ERROR_OUT_OF_DEVICE_MEMORY,
1284         VK_ERROR_OUT_OF_HOST_MEMORY,
1285         VK_SUBOPTIMAL_KHR,
1286     };
1287     for (auto result : kWorstToBest) {
1288         if (a == result || b == result)
1289             return result;
1290     }
1291     ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
1292     ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
1293     return a != VK_SUCCESS ? a : b;
1294 }
1295
1296 VKAPI_ATTR
1297 VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
1298     ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
1299              "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
1300              present_info->sType);
1301
1302     VkDevice device = GetData(queue).driver_device;
1303     const auto& dispatch = GetData(queue).driver;
1304     VkResult final_result = VK_SUCCESS;
1305
1306     // Look at the pNext chain for supported extension structs:
1307     const VkPresentRegionsKHR* present_regions = nullptr;
1308     const VkPresentTimesInfoGOOGLE* present_times = nullptr;
1309     const VkPresentRegionsKHR* next =
1310         reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
1311     while (next) {
1312         switch (next->sType) {
1313             case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
1314                 present_regions = next;
1315                 break;
1316             case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
1317                 present_times =
1318                     reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
1319                 break;
1320             default:
1321                 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
1322                       next->sType);
1323                 break;
1324         }
1325         next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
1326     }
1327     ALOGV_IF(
1328         present_regions &&
1329             present_regions->swapchainCount != present_info->swapchainCount,
1330         "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
1331     ALOGV_IF(present_times &&
1332                  present_times->swapchainCount != present_info->swapchainCount,
1333              "VkPresentTimesInfoGOOGLE::swapchainCount != "
1334              "VkPresentInfo::swapchainCount");
1335     const VkPresentRegionKHR* regions =
1336         (present_regions) ? present_regions->pRegions : nullptr;
1337     const VkPresentTimeGOOGLE* times =
1338         (present_times) ? present_times->pTimes : nullptr;
1339     const VkAllocationCallbacks* allocator = &GetData(device).allocator;
1340     android_native_rect_t* rects = nullptr;
1341     uint32_t nrects = 0;
1342
1343     for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
1344         Swapchain& swapchain =
1345             *SwapchainFromHandle(present_info->pSwapchains[sc]);
1346         uint32_t image_idx = present_info->pImageIndices[sc];
1347         Swapchain::Image& img = swapchain.images[image_idx];
1348         const VkPresentRegionKHR* region =
1349             (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr;
1350         const VkPresentTimeGOOGLE* time = (times) ? &times[sc] : nullptr;
1351         VkResult swapchain_result = VK_SUCCESS;
1352         VkResult result;
1353         int err;
1354
1355         int fence = -1;
1356         result = dispatch.QueueSignalReleaseImageANDROID(
1357             queue, present_info->waitSemaphoreCount,
1358             present_info->pWaitSemaphores, img.image, &fence);
1359         if (result != VK_SUCCESS) {
1360             ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
1361             swapchain_result = result;
1362         }
1363
1364         if (swapchain.surface.swapchain_handle ==
1365             present_info->pSwapchains[sc]) {
1366             ANativeWindow* window = swapchain.surface.window.get();
1367             if (swapchain_result == VK_SUCCESS) {
1368                 if (region) {
1369                     // Process the incremental-present hint for this swapchain:
1370                     uint32_t rcount = region->rectangleCount;
1371                     if (rcount > nrects) {
1372                         android_native_rect_t* new_rects =
1373                             static_cast<android_native_rect_t*>(
1374                                 allocator->pfnReallocation(
1375                                     allocator->pUserData, rects,
1376                                     sizeof(android_native_rect_t) * rcount,
1377                                     alignof(android_native_rect_t),
1378                                     VK_SYSTEM_ALLOCATION_SCOPE_COMMAND));
1379                         if (new_rects) {
1380                             rects = new_rects;
1381                             nrects = rcount;
1382                         } else {
1383                             rcount = 0;  // Ignore the hint for this swapchain
1384                         }
1385                     }
1386                     for (uint32_t r = 0; r < rcount; ++r) {
1387                         if (region->pRectangles[r].layer > 0) {
1388                             ALOGV(
1389                                 "vkQueuePresentKHR ignoring invalid layer "
1390                                 "(%u); using layer 0 instead",
1391                                 region->pRectangles[r].layer);
1392                         }
1393                         int x = region->pRectangles[r].offset.x;
1394                         int y = region->pRectangles[r].offset.y;
1395                         int width = static_cast<int>(
1396                             region->pRectangles[r].extent.width);
1397                         int height = static_cast<int>(
1398                             region->pRectangles[r].extent.height);
1399                         android_native_rect_t* cur_rect = &rects[r];
1400                         cur_rect->left = x;
1401                         cur_rect->top = y + height;
1402                         cur_rect->right = x + width;
1403                         cur_rect->bottom = y;
1404                     }
1405                     native_window_set_surface_damage(window, rects, rcount);
1406                 }
1407                 if (time) {
1408                     if (!swapchain.frame_timestamps_enabled) {
1409                         ALOGV(
1410                             "Calling "
1411                             "native_window_enable_frame_timestamps(true)");
1412                         native_window_enable_frame_timestamps(window, true);
1413                         swapchain.frame_timestamps_enabled = true;
1414                     }
1415
1416                     // Record the nativeFrameId so it can be later correlated to
1417                     // this present.
1418                     uint64_t nativeFrameId = 0;
1419                     err = native_window_get_next_frame_id(
1420                             window, &nativeFrameId);
1421                     if (err != android::NO_ERROR) {
1422                         ALOGE("Failed to get next native frame ID.");
1423                     }
1424
1425                     // Add a new timing record with the user's presentID and
1426                     // the nativeFrameId.
1427                     swapchain.timing.push_back(TimingInfo(time, nativeFrameId));
1428                     while (swapchain.timing.size() > MAX_TIMING_INFOS) {
1429                         swapchain.timing.removeAt(0);
1430                     }
1431                     if (time->desiredPresentTime) {
1432                         // Set the desiredPresentTime:
1433                         ALOGV(
1434                             "Calling "
1435                             "native_window_set_buffers_timestamp(%" PRId64 ")",
1436                             time->desiredPresentTime);
1437                         native_window_set_buffers_timestamp(
1438                             window,
1439                             static_cast<int64_t>(time->desiredPresentTime));
1440                     }
1441                 }
1442
1443                 err = window->queueBuffer(window, img.buffer.get(), fence);
1444                 // queueBuffer always closes fence, even on error
1445                 if (err != 0) {
1446                     // TODO(jessehall): What now? We should probably cancel the
1447                     // buffer, I guess?
1448                     ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
1449                     swapchain_result = WorstPresentResult(
1450                         swapchain_result, VK_ERROR_OUT_OF_DATE_KHR);
1451                 }
1452                 if (img.dequeue_fence >= 0) {
1453                     close(img.dequeue_fence);
1454                     img.dequeue_fence = -1;
1455                 }
1456                 img.dequeued = false;
1457
1458                 // If the swapchain is in shared mode, immediately dequeue the
1459                 // buffer so it can be presented again without an intervening
1460                 // call to AcquireNextImageKHR. We expect to get the same buffer
1461                 // back from every call to dequeueBuffer in this mode.
1462                 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
1463                     ANativeWindowBuffer* buffer;
1464                     int fence_fd;
1465                     err = window->dequeueBuffer(window, &buffer, &fence_fd);
1466                     if (err != 0) {
1467                         ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
1468                         swapchain_result = WorstPresentResult(swapchain_result,
1469                             VK_ERROR_SURFACE_LOST_KHR);
1470                     }
1471                     else if (img.buffer != buffer) {
1472                         ALOGE("got wrong image back for shared swapchain");
1473                         swapchain_result = WorstPresentResult(swapchain_result,
1474                             VK_ERROR_SURFACE_LOST_KHR);
1475                     }
1476                     else {
1477                         img.dequeue_fence = fence_fd;
1478                         img.dequeued = true;
1479                     }
1480                 }
1481             }
1482             if (swapchain_result != VK_SUCCESS) {
1483                 ReleaseSwapchainImage(device, window, fence, img);
1484                 OrphanSwapchain(device, &swapchain);
1485             }
1486         } else {
1487             ReleaseSwapchainImage(device, nullptr, fence, img);
1488             swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
1489         }
1490
1491         if (present_info->pResults)
1492             present_info->pResults[sc] = swapchain_result;
1493
1494         if (swapchain_result != final_result)
1495             final_result = WorstPresentResult(final_result, swapchain_result);
1496     }
1497     if (rects) {
1498         allocator->pfnFree(allocator->pUserData, rects);
1499     }
1500
1501     return final_result;
1502 }
1503
1504 VKAPI_ATTR
1505 VkResult GetRefreshCycleDurationGOOGLE(
1506     VkDevice,
1507     VkSwapchainKHR swapchain_handle,
1508     VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
1509     Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
1510     VkResult result = VK_SUCCESS;
1511
1512     pDisplayTimingProperties->refreshDuration =
1513             static_cast<uint64_t>(swapchain.refresh_duration);
1514
1515     return result;
1516 }
1517
1518 VKAPI_ATTR
1519 VkResult GetPastPresentationTimingGOOGLE(
1520     VkDevice,
1521     VkSwapchainKHR swapchain_handle,
1522     uint32_t* count,
1523     VkPastPresentationTimingGOOGLE* timings) {
1524     Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
1525     ANativeWindow* window = swapchain.surface.window.get();
1526     VkResult result = VK_SUCCESS;
1527
1528     if (!swapchain.frame_timestamps_enabled) {
1529         ALOGV("Calling native_window_enable_frame_timestamps(true)");
1530         native_window_enable_frame_timestamps(window, true);
1531         swapchain.frame_timestamps_enabled = true;
1532     }
1533
1534     if (timings) {
1535         // TODO(ianelliott): plumb return value (e.g. VK_INCOMPLETE)
1536         copy_ready_timings(swapchain, count, timings);
1537     } else {
1538         *count = get_num_ready_timings(swapchain);
1539     }
1540
1541     return result;
1542 }
1543
1544 VKAPI_ATTR
1545 VkResult GetSwapchainStatusKHR(
1546     VkDevice,
1547     VkSwapchainKHR swapchain_handle) {
1548     Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
1549     VkResult result = VK_SUCCESS;
1550
1551     if (swapchain.surface.swapchain_handle != swapchain_handle) {
1552         return VK_ERROR_OUT_OF_DATE_KHR;
1553     }
1554
1555     // TODO(chrisforbes): Implement this function properly
1556
1557     return result;
1558 }
1559
1560 VKAPI_ATTR void SetHdrMetadataEXT(
1561     VkDevice device,
1562     uint32_t swapchainCount,
1563     const VkSwapchainKHR* pSwapchains,
1564     const VkHdrMetadataEXT* pHdrMetadataEXTs) {
1565     // TODO: courtneygo: implement actual function
1566     (void)device;
1567     (void)swapchainCount;
1568     (void)pSwapchains;
1569     (void)pHdrMetadataEXTs;
1570     return;
1571 }
1572
1573 }  // namespace driver
1574 }  // namespace vulkan