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