swapchain.cpp revision 148a1b45ff2c205f6aa9c46c7f039d29d877a35c
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#include <memory>
19
20#include <gui/BufferQueue.h>
21#include <log/log.h>
22#include <sync/sync.h>
23
24#include "loader.h"
25
26using namespace vulkan;
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
33namespace {
34
35// ----------------------------------------------------------------------------
36// These functions/classes form an adaptor that allows objects to be refcounted
37// by both android::sp<> and std::shared_ptr<> simultaneously, and delegates
38// allocation of the shared_ptr<> control structure to VkAllocationCallbacks.
39// The
40// platform holds a reference to the ANativeWindow using its embedded reference
41// count, and the ANativeWindow implementation holds references to the
42// ANativeWindowBuffers using their embedded reference counts, so the
43// shared_ptr *must* cooperate with these and hold at least one reference to
44// the object using the embedded reference count.
45
46template <typename T>
47struct NativeBaseDeleter {
48    void operator()(T* obj) { obj->common.decRef(&obj->common); }
49};
50
51template <typename Host>
52struct AllocScope {};
53
54template <>
55struct AllocScope<VkInstance> {
56    static const VkSystemAllocationScope kScope =
57        VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE;
58};
59
60template <>
61struct AllocScope<VkDevice> {
62    static const VkSystemAllocationScope kScope =
63        VK_SYSTEM_ALLOCATION_SCOPE_DEVICE;
64};
65
66template <typename T>
67class VulkanAllocator {
68   public:
69    typedef T value_type;
70
71    VulkanAllocator(const VkAllocationCallbacks& allocator,
72                    VkSystemAllocationScope scope)
73        : allocator_(allocator), scope_(scope) {}
74
75    template <typename U>
76    explicit VulkanAllocator(const VulkanAllocator<U>& other)
77        : allocator_(other.allocator_), scope_(other.scope_) {}
78
79    T* allocate(size_t n) const {
80        T* p = static_cast<T*>(allocator_.pfnAllocation(
81            allocator_.pUserData, n * sizeof(T), alignof(T), scope_));
82        if (!p)
83            throw std::bad_alloc();
84        return p;
85    }
86    void deallocate(T* p, size_t) const noexcept {
87        return allocator_.pfnFree(allocator_.pUserData, p);
88    }
89
90   private:
91    template <typename U>
92    friend class VulkanAllocator;
93    const VkAllocationCallbacks& allocator_;
94    const VkSystemAllocationScope scope_;
95};
96
97template <typename T, typename Host>
98std::shared_ptr<T> InitSharedPtr(Host host, T* obj) {
99    try {
100        obj->common.incRef(&obj->common);
101        return std::shared_ptr<T>(
102            obj, NativeBaseDeleter<T>(),
103            VulkanAllocator<T>(*GetAllocator(host), AllocScope<Host>::kScope));
104    } catch (std::bad_alloc&) {
105        obj->common.decRef(&obj->common);
106        return nullptr;
107    }
108}
109
110// ----------------------------------------------------------------------------
111
112struct Surface {
113    std::shared_ptr<ANativeWindow> window;
114};
115
116VkSurfaceKHR HandleFromSurface(Surface* surface) {
117    return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
118}
119
120Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
121    return reinterpret_cast<Surface*>(handle);
122}
123
124struct Swapchain {
125    Swapchain(Surface& surface_, uint32_t num_images_)
126        : surface(surface_), num_images(num_images_) {}
127
128    Surface& surface;
129    uint32_t num_images;
130
131    struct Image {
132        Image() : image(VK_NULL_HANDLE), dequeue_fence(-1), dequeued(false) {}
133        VkImage image;
134        std::shared_ptr<ANativeWindowBuffer> buffer;
135        // The fence is only valid when the buffer is dequeued, and should be
136        // -1 any other time. When valid, we own the fd, and must ensure it is
137        // closed: either by closing it explicitly when queueing the buffer,
138        // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
139        int dequeue_fence;
140        bool dequeued;
141    } images[android::BufferQueue::NUM_BUFFER_SLOTS];
142};
143
144VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
145    return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
146}
147
148Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
149    return reinterpret_cast<Swapchain*>(handle);
150}
151
152}  // anonymous namespace
153
154namespace vulkan {
155
156VKAPI_ATTR
157VkResult CreateAndroidSurfaceKHR_Bottom(
158    VkInstance instance,
159    const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
160    const VkAllocationCallbacks* allocator,
161    VkSurfaceKHR* out_surface) {
162    if (!allocator)
163        allocator = GetAllocator(instance);
164    void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
165                                         alignof(Surface),
166                                         VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
167    if (!mem)
168        return VK_ERROR_OUT_OF_HOST_MEMORY;
169    Surface* surface = new (mem) Surface;
170
171    surface->window = InitSharedPtr(instance, pCreateInfo->window);
172    if (!surface->window) {
173        ALOGE("surface creation failed: out of memory");
174        surface->~Surface();
175        allocator->pfnFree(allocator->pUserData, surface);
176        return VK_ERROR_OUT_OF_HOST_MEMORY;
177    }
178
179    // TODO(jessehall): Create and use NATIVE_WINDOW_API_VULKAN.
180    int err =
181        native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
182    if (err != 0) {
183        // TODO(jessehall): Improve error reporting. Can we enumerate possible
184        // errors and translate them to valid Vulkan result codes?
185        ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
186              err);
187        surface->~Surface();
188        allocator->pfnFree(allocator->pUserData, surface);
189        return VK_ERROR_INITIALIZATION_FAILED;
190    }
191
192    *out_surface = HandleFromSurface(surface);
193    return VK_SUCCESS;
194}
195
196VKAPI_ATTR
197void DestroySurfaceKHR_Bottom(VkInstance instance,
198                              VkSurfaceKHR surface_handle,
199                              const VkAllocationCallbacks* allocator) {
200    Surface* surface = SurfaceFromHandle(surface_handle);
201    if (!surface)
202        return;
203    native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
204    surface->~Surface();
205    if (!allocator)
206        allocator = GetAllocator(instance);
207    allocator->pfnFree(allocator->pUserData, surface);
208}
209
210VKAPI_ATTR
211VkResult GetPhysicalDeviceSurfaceSupportKHR_Bottom(VkPhysicalDevice /*pdev*/,
212                                                   uint32_t /*queue_family*/,
213                                                   VkSurfaceKHR /*surface*/,
214                                                   VkBool32* supported) {
215    *supported = VK_TRUE;
216    return VK_SUCCESS;
217}
218
219VKAPI_ATTR
220VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR_Bottom(
221    VkPhysicalDevice /*pdev*/,
222    VkSurfaceKHR surface,
223    VkSurfaceCapabilitiesKHR* capabilities) {
224    int err;
225    ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
226
227    int width, height;
228    err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
229    if (err != 0) {
230        ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
231              strerror(-err), err);
232        return VK_ERROR_INITIALIZATION_FAILED;
233    }
234    err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
235    if (err != 0) {
236        ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
237              strerror(-err), err);
238        return VK_ERROR_INITIALIZATION_FAILED;
239    }
240
241    // TODO(jessehall): Figure out what the min/max values should be.
242    capabilities->minImageCount = 2;
243    capabilities->maxImageCount = 3;
244
245    capabilities->currentExtent =
246        VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
247
248    // TODO(jessehall): Figure out what the max extent should be. Maximum
249    // texture dimension maybe?
250    capabilities->minImageExtent = VkExtent2D{1, 1};
251    capabilities->maxImageExtent = VkExtent2D{4096, 4096};
252
253    capabilities->maxImageArrayLayers = 1;
254
255    // TODO(jessehall): We can support all transforms, fix this once
256    // implemented.
257    capabilities->supportedTransforms = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
258
259    // TODO(jessehall): Implement based on NATIVE_WINDOW_TRANSFORM_HINT.
260    capabilities->currentTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
261
262    // On Android, window composition is a WindowManager property, not something
263    // associated with the bufferqueue. It can't be changed from here.
264    capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
265
266    // TODO(jessehall): I think these are right, but haven't thought hard about
267    // it. Do we need to query the driver for support of any of these?
268    // Currently not included:
269    // - VK_IMAGE_USAGE_GENERAL: maybe? does this imply cpu mappable?
270    // - VK_IMAGE_USAGE_DEPTH_STENCIL_BIT: definitely not
271    // - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT: definitely not
272    capabilities->supportedUsageFlags =
273        VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
274        VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
275        VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
276        VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
277
278    return VK_SUCCESS;
279}
280
281VKAPI_ATTR
282VkResult GetPhysicalDeviceSurfaceFormatsKHR_Bottom(
283    VkPhysicalDevice /*pdev*/,
284    VkSurfaceKHR /*surface*/,
285    uint32_t* count,
286    VkSurfaceFormatKHR* formats) {
287    // TODO(jessehall): Fill out the set of supported formats. Longer term, add
288    // a new gralloc method to query whether a (format, usage) pair is
289    // supported, and check that for each gralloc format that corresponds to a
290    // Vulkan format. Shorter term, just add a few more formats to the ones
291    // hardcoded below.
292
293    const VkSurfaceFormatKHR kFormats[] = {
294        {VK_FORMAT_R8G8B8A8_UNORM, VK_COLORSPACE_SRGB_NONLINEAR_KHR},
295        {VK_FORMAT_R8G8B8A8_SRGB, VK_COLORSPACE_SRGB_NONLINEAR_KHR},
296    };
297    const uint32_t kNumFormats = sizeof(kFormats) / sizeof(kFormats[0]);
298
299    VkResult result = VK_SUCCESS;
300    if (formats) {
301        if (*count < kNumFormats)
302            result = VK_INCOMPLETE;
303        std::copy(kFormats, kFormats + std::min(*count, kNumFormats), formats);
304    }
305    *count = kNumFormats;
306    return result;
307}
308
309VKAPI_ATTR
310VkResult GetPhysicalDeviceSurfacePresentModesKHR_Bottom(
311    VkPhysicalDevice /*pdev*/,
312    VkSurfaceKHR /*surface*/,
313    uint32_t* count,
314    VkPresentModeKHR* modes) {
315    const VkPresentModeKHR kModes[] = {
316        VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
317    };
318    const uint32_t kNumModes = sizeof(kModes) / sizeof(kModes[0]);
319
320    VkResult result = VK_SUCCESS;
321    if (modes) {
322        if (*count < kNumModes)
323            result = VK_INCOMPLETE;
324        std::copy(kModes, kModes + std::min(*count, kNumModes), modes);
325    }
326    *count = kNumModes;
327    return result;
328}
329
330VKAPI_ATTR
331VkResult CreateSwapchainKHR_Bottom(VkDevice device,
332                                   const VkSwapchainCreateInfoKHR* create_info,
333                                   const VkAllocationCallbacks* allocator,
334                                   VkSwapchainKHR* swapchain_handle) {
335    int err;
336    VkResult result = VK_SUCCESS;
337
338    if (!allocator)
339        allocator = GetAllocator(device);
340
341    ALOGV_IF(create_info->imageArrayLayers != 1,
342             "Swapchain imageArrayLayers (%u) != 1 not supported",
343             create_info->imageArrayLayers);
344
345    ALOGE_IF(create_info->imageFormat != VK_FORMAT_R8G8B8A8_UNORM,
346             "swapchain formats other than R8G8B8A8_UNORM not yet implemented");
347    ALOGE_IF(create_info->imageColorSpace != VK_COLORSPACE_SRGB_NONLINEAR_KHR,
348             "color spaces other than SRGB_NONLINEAR not yet implemented");
349    ALOGE_IF(create_info->oldSwapchain,
350             "swapchain re-creation not yet implemented");
351    ALOGE_IF(create_info->preTransform != VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR,
352             "swapchain preTransform not yet implemented");
353    ALOGW_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
354               create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR),
355             "swapchain present mode %d not supported",
356             create_info->presentMode);
357
358    // -- Configure the native window --
359
360    Surface& surface = *SurfaceFromHandle(create_info->surface);
361    const DriverDispatchTable& dispatch = GetDriverDispatch(device);
362
363    err = native_window_set_buffers_dimensions(
364        surface.window.get(), static_cast<int>(create_info->imageExtent.width),
365        static_cast<int>(create_info->imageExtent.height));
366    if (err != 0) {
367        // TODO(jessehall): Improve error reporting. Can we enumerate possible
368        // errors and translate them to valid Vulkan result codes?
369        ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
370              create_info->imageExtent.width, create_info->imageExtent.height,
371              strerror(-err), err);
372        return VK_ERROR_INITIALIZATION_FAILED;
373    }
374
375    err = native_window_set_scaling_mode(
376        surface.window.get(), NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
377    if (err != 0) {
378        // TODO(jessehall): Improve error reporting. Can we enumerate possible
379        // errors and translate them to valid Vulkan result codes?
380        ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
381              strerror(-err), err);
382        return VK_ERROR_INITIALIZATION_FAILED;
383    }
384
385    uint32_t min_undequeued_buffers;
386    err = surface.window->query(
387        surface.window.get(), NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
388        reinterpret_cast<int*>(&min_undequeued_buffers));
389    if (err != 0) {
390        // TODO(jessehall): Improve error reporting. Can we enumerate possible
391        // errors and translate them to valid Vulkan result codes?
392        ALOGE("window->query failed: %s (%d)", strerror(-err), err);
393        return VK_ERROR_INITIALIZATION_FAILED;
394    }
395    // The MIN_UNDEQUEUED_BUFFERS query doesn't know whether we'll be using
396    // async mode or not, and assumes not. But in async mode, the BufferQueue
397    // requires an extra undequeued buffer.
398    // See BufferQueueCore::getMinUndequeuedBufferCountLocked().
399    if (create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR)
400        min_undequeued_buffers += 1;
401
402    uint32_t num_images =
403        (create_info->minImageCount - 1) + min_undequeued_buffers;
404    err = native_window_set_buffer_count(surface.window.get(), num_images);
405    if (err != 0) {
406        // TODO(jessehall): Improve error reporting. Can we enumerate possible
407        // errors and translate them to valid Vulkan result codes?
408        ALOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err),
409              err);
410        return VK_ERROR_INITIALIZATION_FAILED;
411    }
412
413    int gralloc_usage = 0;
414    // TODO(jessehall): Remove conditional once all drivers have been updated
415    if (dispatch.GetSwapchainGrallocUsageANDROID) {
416        result = dispatch.GetSwapchainGrallocUsageANDROID(
417            device, create_info->imageFormat, create_info->imageUsage,
418            &gralloc_usage);
419        if (result != VK_SUCCESS) {
420            ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
421            return VK_ERROR_INITIALIZATION_FAILED;
422        }
423    } else {
424        gralloc_usage = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
425    }
426    err = native_window_set_usage(surface.window.get(), gralloc_usage);
427    if (err != 0) {
428        // TODO(jessehall): Improve error reporting. Can we enumerate possible
429        // errors and translate them to valid Vulkan result codes?
430        ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
431        return VK_ERROR_INITIALIZATION_FAILED;
432    }
433
434    err = surface.window->setSwapInterval(
435        surface.window.get(),
436        create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1);
437    if (err != 0) {
438        // TODO(jessehall): Improve error reporting. Can we enumerate possible
439        // errors and translate them to valid Vulkan result codes?
440        ALOGE("native_window->setSwapInterval failed: %s (%d)", strerror(-err),
441              err);
442        return VK_ERROR_INITIALIZATION_FAILED;
443    }
444
445    // -- Allocate our Swapchain object --
446    // After this point, we must deallocate the swapchain on error.
447
448    void* mem = allocator->pfnAllocation(allocator->pUserData,
449                                         sizeof(Swapchain), alignof(Swapchain),
450                                         VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
451    if (!mem)
452        return VK_ERROR_OUT_OF_HOST_MEMORY;
453    Swapchain* swapchain = new (mem) Swapchain(surface, num_images);
454
455    // -- Dequeue all buffers and create a VkImage for each --
456    // Any failures during or after this must cancel the dequeued buffers.
457
458    VkNativeBufferANDROID image_native_buffer = {
459#pragma clang diagnostic push
460#pragma clang diagnostic ignored "-Wold-style-cast"
461        .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
462#pragma clang diagnostic pop
463        .pNext = nullptr,
464    };
465    VkImageCreateInfo image_create = {
466        .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
467        .pNext = &image_native_buffer,
468        .imageType = VK_IMAGE_TYPE_2D,
469        .format = VK_FORMAT_R8G8B8A8_UNORM,  // TODO(jessehall)
470        .extent = {0, 0, 1},
471        .mipLevels = 1,
472        .arrayLayers = 1,
473        .samples = VK_SAMPLE_COUNT_1_BIT,
474        .tiling = VK_IMAGE_TILING_OPTIMAL,
475        .usage = create_info->imageUsage,
476        .flags = 0,
477        .sharingMode = create_info->imageSharingMode,
478        .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
479        .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
480    };
481
482    for (uint32_t i = 0; i < num_images; i++) {
483        Swapchain::Image& img = swapchain->images[i];
484
485        ANativeWindowBuffer* buffer;
486        err = surface.window->dequeueBuffer(surface.window.get(), &buffer,
487                                            &img.dequeue_fence);
488        if (err != 0) {
489            // TODO(jessehall): Improve error reporting. Can we enumerate
490            // possible errors and translate them to valid Vulkan result codes?
491            ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
492            result = VK_ERROR_INITIALIZATION_FAILED;
493            break;
494        }
495        img.buffer = InitSharedPtr(device, buffer);
496        if (!img.buffer) {
497            ALOGE("swapchain creation failed: out of memory");
498            surface.window->cancelBuffer(surface.window.get(), buffer,
499                                         img.dequeue_fence);
500            result = VK_ERROR_OUT_OF_HOST_MEMORY;
501            break;
502        }
503        img.dequeued = true;
504
505        image_create.extent =
506            VkExtent3D{static_cast<uint32_t>(img.buffer->width),
507                       static_cast<uint32_t>(img.buffer->height),
508                       1};
509        image_native_buffer.handle = img.buffer->handle;
510        image_native_buffer.stride = img.buffer->stride;
511        image_native_buffer.format = img.buffer->format;
512        image_native_buffer.usage = img.buffer->usage;
513
514        result =
515            dispatch.CreateImage(device, &image_create, nullptr, &img.image);
516        if (result != VK_SUCCESS) {
517            ALOGD("vkCreateImage w/ native buffer failed: %u", result);
518            break;
519        }
520    }
521
522    // -- Cancel all buffers, returning them to the queue --
523    // If an error occurred before, also destroy the VkImage and release the
524    // buffer reference. Otherwise, we retain a strong reference to the buffer.
525    //
526    // TODO(jessehall): The error path here is the same as DestroySwapchain,
527    // but not the non-error path. Should refactor/unify.
528    for (uint32_t i = 0; i < num_images; i++) {
529        Swapchain::Image& img = swapchain->images[i];
530        if (img.dequeued) {
531            surface.window->cancelBuffer(surface.window.get(), img.buffer.get(),
532                                         img.dequeue_fence);
533            img.dequeue_fence = -1;
534            img.dequeued = false;
535        }
536        if (result != VK_SUCCESS) {
537            if (img.image)
538                dispatch.DestroyImage(device, img.image, nullptr);
539        }
540    }
541
542    if (result != VK_SUCCESS) {
543        swapchain->~Swapchain();
544        allocator->pfnFree(allocator->pUserData, swapchain);
545        return result;
546    }
547
548    *swapchain_handle = HandleFromSwapchain(swapchain);
549    return VK_SUCCESS;
550}
551
552VKAPI_ATTR
553void DestroySwapchainKHR_Bottom(VkDevice device,
554                                VkSwapchainKHR swapchain_handle,
555                                const VkAllocationCallbacks* allocator) {
556    const DriverDispatchTable& dispatch = GetDriverDispatch(device);
557    Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
558    const std::shared_ptr<ANativeWindow>& window = swapchain->surface.window;
559
560    for (uint32_t i = 0; i < swapchain->num_images; i++) {
561        Swapchain::Image& img = swapchain->images[i];
562        if (img.dequeued) {
563            window->cancelBuffer(window.get(), img.buffer.get(),
564                                 img.dequeue_fence);
565            img.dequeue_fence = -1;
566            img.dequeued = false;
567        }
568        if (img.image) {
569            dispatch.DestroyImage(device, img.image, nullptr);
570        }
571    }
572
573    if (!allocator)
574        allocator = GetAllocator(device);
575    swapchain->~Swapchain();
576    allocator->pfnFree(allocator->pUserData, swapchain);
577}
578
579VKAPI_ATTR
580VkResult GetSwapchainImagesKHR_Bottom(VkDevice,
581                                      VkSwapchainKHR swapchain_handle,
582                                      uint32_t* count,
583                                      VkImage* images) {
584    Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
585    VkResult result = VK_SUCCESS;
586    if (images) {
587        uint32_t n = swapchain.num_images;
588        if (*count < swapchain.num_images) {
589            n = *count;
590            result = VK_INCOMPLETE;
591        }
592        for (uint32_t i = 0; i < n; i++)
593            images[i] = swapchain.images[i].image;
594    }
595    *count = swapchain.num_images;
596    return result;
597}
598
599VKAPI_ATTR
600VkResult AcquireNextImageKHR_Bottom(VkDevice device,
601                                    VkSwapchainKHR swapchain_handle,
602                                    uint64_t timeout,
603                                    VkSemaphore semaphore,
604                                    VkFence vk_fence,
605                                    uint32_t* image_index) {
606    Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
607    ANativeWindow* window = swapchain.surface.window.get();
608    VkResult result;
609    int err;
610
611    ALOGW_IF(
612        timeout != UINT64_MAX,
613        "vkAcquireNextImageKHR: non-infinite timeouts not yet implemented");
614
615    ANativeWindowBuffer* buffer;
616    int fence_fd;
617    err = window->dequeueBuffer(window, &buffer, &fence_fd);
618    if (err != 0) {
619        // TODO(jessehall): Improve error reporting. Can we enumerate possible
620        // errors and translate them to valid Vulkan result codes?
621        ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
622        return VK_ERROR_INITIALIZATION_FAILED;
623    }
624
625    uint32_t idx;
626    for (idx = 0; idx < swapchain.num_images; idx++) {
627        if (swapchain.images[idx].buffer.get() == buffer) {
628            swapchain.images[idx].dequeued = true;
629            swapchain.images[idx].dequeue_fence = fence_fd;
630            break;
631        }
632    }
633    if (idx == swapchain.num_images) {
634        ALOGE("dequeueBuffer returned unrecognized buffer");
635        window->cancelBuffer(window, buffer, fence_fd);
636        return VK_ERROR_OUT_OF_DATE_KHR;
637    }
638
639    int fence_clone = -1;
640    if (fence_fd != -1) {
641        fence_clone = dup(fence_fd);
642        if (fence_clone == -1) {
643            ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
644                  strerror(errno), errno);
645            sync_wait(fence_fd, -1 /* forever */);
646        }
647    }
648
649    result = GetDriverDispatch(device).AcquireImageANDROID(
650        device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
651    if (result != VK_SUCCESS) {
652        // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
653        // even if the call fails. We could close it ourselves on failure, but
654        // that would create a race condition if the driver closes it on a
655        // failure path: some other thread might create an fd with the same
656        // number between the time the driver closes it and the time we close
657        // it. We must assume one of: the driver *always* closes it even on
658        // failure, or *never* closes it on failure.
659        window->cancelBuffer(window, buffer, fence_fd);
660        swapchain.images[idx].dequeued = false;
661        swapchain.images[idx].dequeue_fence = -1;
662        return result;
663    }
664
665    *image_index = idx;
666    return VK_SUCCESS;
667}
668
669VKAPI_ATTR
670VkResult QueuePresentKHR_Bottom(VkQueue queue,
671                                const VkPresentInfoKHR* present_info) {
672    ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
673             "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
674             present_info->sType);
675    ALOGV_IF(present_info->pNext, "VkPresentInfo::pNext != NULL");
676
677    const DriverDispatchTable& dispatch = GetDriverDispatch(queue);
678    VkResult final_result = VK_SUCCESS;
679    for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
680        Swapchain& swapchain =
681            *SwapchainFromHandle(present_info->pSwapchains[sc]);
682        ANativeWindow* window = swapchain.surface.window.get();
683        uint32_t image_idx = present_info->pImageIndices[sc];
684        Swapchain::Image& img = swapchain.images[image_idx];
685        VkResult result;
686        int err;
687
688        int fence = -1;
689        result = dispatch.QueueSignalReleaseImageANDROID(
690            queue, present_info->waitSemaphoreCount,
691            present_info->pWaitSemaphores, img.image, &fence);
692        if (result != VK_SUCCESS) {
693            ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
694            if (present_info->pResults)
695                present_info->pResults[sc] = result;
696            if (final_result == VK_SUCCESS)
697                final_result = result;
698            // TODO(jessehall): What happens to the buffer here? Does the app
699            // still own it or not, i.e. should we cancel the buffer? Hard to
700            // do correctly without synchronizing, though I guess we could wait
701            // for the queue to idle.
702            continue;
703        }
704
705        err = window->queueBuffer(window, img.buffer.get(), fence);
706        if (err != 0) {
707            // TODO(jessehall): What now? We should probably cancel the buffer,
708            // I guess?
709            ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
710            if (present_info->pResults)
711                present_info->pResults[sc] = result;
712            if (final_result == VK_SUCCESS)
713                final_result = VK_ERROR_INITIALIZATION_FAILED;
714            continue;
715        }
716
717        if (img.dequeue_fence != -1) {
718            close(img.dequeue_fence);
719            img.dequeue_fence = -1;
720        }
721        img.dequeued = false;
722
723        if (present_info->pResults)
724            present_info->pResults[sc] = VK_SUCCESS;
725    }
726
727    return final_result;
728}
729
730}  // namespace vulkan
731