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