swapchain.cpp revision 622622377a1ac71a81a88e335f170c4a08835f06
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
26// TODO(jessehall): Currently we don't have a good error code for when a native
27// window operation fails. Just returning INITIALIZATION_FAILED for now. Later
28// versions (post SDK 0.9) of the API/extension have a better error code.
29// When updating to that version, audit all error returns.
30namespace vulkan {
31namespace driver {
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
110const VkSurfaceTransformFlagsKHR kSupportedTransforms =
111    VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
112    VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
113    VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
114    VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
115    // TODO(jessehall): See TODO in TranslateNativeToVulkanTransform.
116    // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
117    // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
118    // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
119    // VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
120    VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
121
122VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
123    // Native and Vulkan transforms are isomorphic, but are represented
124    // differently. Vulkan transforms are built up of an optional horizontal
125    // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
126    // transforms are built up from a horizontal flip, vertical flip, and
127    // 90-degree rotation, all optional but always in that order.
128
129    // TODO(jessehall): For now, only support pure rotations, not
130    // flip or flip-and-rotate, until I have more time to test them and build
131    // sample code. As far as I know we never actually use anything besides
132    // pure rotations anyway.
133
134    switch (native) {
135        case 0:  // 0x0
136            return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
137        // case NATIVE_WINDOW_TRANSFORM_FLIP_H:  // 0x1
138        //     return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
139        // case NATIVE_WINDOW_TRANSFORM_FLIP_V:  // 0x2
140        //     return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
141        case NATIVE_WINDOW_TRANSFORM_ROT_180:  // FLIP_H | FLIP_V
142            return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
143        case NATIVE_WINDOW_TRANSFORM_ROT_90:  // 0x4
144            return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
145        // case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
146        //     return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
147        // case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
148        //     return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
149        case NATIVE_WINDOW_TRANSFORM_ROT_270:  // FLIP_H | FLIP_V | ROT_90
150            return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
151        case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
152        default:
153            return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
154    }
155}
156
157int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
158    switch (transform) {
159        case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
160            return NATIVE_WINDOW_TRANSFORM_ROT_270;
161        case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
162            return NATIVE_WINDOW_TRANSFORM_ROT_180;
163        case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
164            return NATIVE_WINDOW_TRANSFORM_ROT_90;
165        // TODO(jessehall): See TODO in TranslateNativeToVulkanTransform.
166        // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
167        //     return NATIVE_WINDOW_TRANSFORM_FLIP_H;
168        // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
169        //     return NATIVE_WINDOW_TRANSFORM_FLIP_H |
170        //            NATIVE_WINDOW_TRANSFORM_ROT_90;
171        // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
172        //     return NATIVE_WINDOW_TRANSFORM_FLIP_V;
173        // case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
174        //     return NATIVE_WINDOW_TRANSFORM_FLIP_V |
175        //            NATIVE_WINDOW_TRANSFORM_ROT_90;
176        case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
177        case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
178        default:
179            return 0;
180    }
181}
182
183// ----------------------------------------------------------------------------
184
185struct Surface {
186    std::shared_ptr<ANativeWindow> window;
187};
188
189VkSurfaceKHR HandleFromSurface(Surface* surface) {
190    return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
191}
192
193Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
194    return reinterpret_cast<Surface*>(handle);
195}
196
197struct Swapchain {
198    Swapchain(Surface& surface_, uint32_t num_images_)
199        : surface(surface_), num_images(num_images_) {}
200
201    Surface& surface;
202    uint32_t num_images;
203
204    struct Image {
205        Image() : image(VK_NULL_HANDLE), dequeue_fence(-1), dequeued(false) {}
206        VkImage image;
207        std::shared_ptr<ANativeWindowBuffer> buffer;
208        // The fence is only valid when the buffer is dequeued, and should be
209        // -1 any other time. When valid, we own the fd, and must ensure it is
210        // closed: either by closing it explicitly when queueing the buffer,
211        // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
212        int dequeue_fence;
213        bool dequeued;
214    } images[android::BufferQueue::NUM_BUFFER_SLOTS];
215};
216
217VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
218    return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
219}
220
221Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
222    return reinterpret_cast<Swapchain*>(handle);
223}
224
225}  // anonymous namespace
226
227VKAPI_ATTR
228VkResult CreateAndroidSurfaceKHR(
229    VkInstance instance,
230    const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
231    const VkAllocationCallbacks* allocator,
232    VkSurfaceKHR* out_surface) {
233    if (!allocator)
234        allocator = GetAllocator(instance);
235    void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
236                                         alignof(Surface),
237                                         VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
238    if (!mem)
239        return VK_ERROR_OUT_OF_HOST_MEMORY;
240    Surface* surface = new (mem) Surface;
241
242    surface->window = InitSharedPtr(instance, pCreateInfo->window);
243    if (!surface->window) {
244        ALOGE("surface creation failed: out of memory");
245        surface->~Surface();
246        allocator->pfnFree(allocator->pUserData, surface);
247        return VK_ERROR_OUT_OF_HOST_MEMORY;
248    }
249
250    // TODO(jessehall): Create and use NATIVE_WINDOW_API_VULKAN.
251    int err =
252        native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
253    if (err != 0) {
254        // TODO(jessehall): Improve error reporting. Can we enumerate possible
255        // errors and translate them to valid Vulkan result codes?
256        ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
257              err);
258        surface->~Surface();
259        allocator->pfnFree(allocator->pUserData, surface);
260        return VK_ERROR_INITIALIZATION_FAILED;
261    }
262
263    *out_surface = HandleFromSurface(surface);
264    return VK_SUCCESS;
265}
266
267VKAPI_ATTR
268void DestroySurfaceKHR(VkInstance instance,
269                       VkSurfaceKHR surface_handle,
270                       const VkAllocationCallbacks* allocator) {
271    Surface* surface = SurfaceFromHandle(surface_handle);
272    if (!surface)
273        return;
274    native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
275    surface->~Surface();
276    if (!allocator)
277        allocator = GetAllocator(instance);
278    allocator->pfnFree(allocator->pUserData, surface);
279}
280
281VKAPI_ATTR
282VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
283                                            uint32_t /*queue_family*/,
284                                            VkSurfaceKHR /*surface*/,
285                                            VkBool32* supported) {
286    *supported = VK_TRUE;
287    return VK_SUCCESS;
288}
289
290VKAPI_ATTR
291VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
292    VkPhysicalDevice /*pdev*/,
293    VkSurfaceKHR surface,
294    VkSurfaceCapabilitiesKHR* capabilities) {
295    int err;
296    ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
297
298    int width, height;
299    err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
300    if (err != 0) {
301        ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
302              strerror(-err), err);
303        return VK_ERROR_INITIALIZATION_FAILED;
304    }
305    err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
306    if (err != 0) {
307        ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
308              strerror(-err), err);
309        return VK_ERROR_INITIALIZATION_FAILED;
310    }
311
312    int transform_hint;
313    err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
314    if (err != 0) {
315        ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
316              strerror(-err), err);
317        return VK_ERROR_INITIALIZATION_FAILED;
318    }
319
320    // TODO(jessehall): Figure out what the min/max values should be.
321    capabilities->minImageCount = 2;
322    capabilities->maxImageCount = 3;
323
324    capabilities->currentExtent =
325        VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
326
327    // TODO(jessehall): Figure out what the max extent should be. Maximum
328    // texture dimension maybe?
329    capabilities->minImageExtent = VkExtent2D{1, 1};
330    capabilities->maxImageExtent = VkExtent2D{4096, 4096};
331
332    capabilities->maxImageArrayLayers = 1;
333
334    capabilities->supportedTransforms = kSupportedTransforms;
335    capabilities->currentTransform =
336        TranslateNativeToVulkanTransform(transform_hint);
337
338    // On Android, window composition is a WindowManager property, not something
339    // associated with the bufferqueue. It can't be changed from here.
340    capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
341
342    // TODO(jessehall): I think these are right, but haven't thought hard about
343    // it. Do we need to query the driver for support of any of these?
344    // Currently not included:
345    // - VK_IMAGE_USAGE_GENERAL: maybe? does this imply cpu mappable?
346    // - VK_IMAGE_USAGE_DEPTH_STENCIL_BIT: definitely not
347    // - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT: definitely not
348    capabilities->supportedUsageFlags =
349        VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
350        VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
351        VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
352        VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
353
354    return VK_SUCCESS;
355}
356
357VKAPI_ATTR
358VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice /*pdev*/,
359                                            VkSurfaceKHR /*surface*/,
360                                            uint32_t* count,
361                                            VkSurfaceFormatKHR* formats) {
362    // TODO(jessehall): Fill out the set of supported formats. Longer term, add
363    // a new gralloc method to query whether a (format, usage) pair is
364    // supported, and check that for each gralloc format that corresponds to a
365    // Vulkan format. Shorter term, just add a few more formats to the ones
366    // hardcoded below.
367
368    const VkSurfaceFormatKHR kFormats[] = {
369        {VK_FORMAT_R8G8B8A8_UNORM, VK_COLORSPACE_SRGB_NONLINEAR_KHR},
370        {VK_FORMAT_R8G8B8A8_SRGB, VK_COLORSPACE_SRGB_NONLINEAR_KHR},
371        {VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLORSPACE_SRGB_NONLINEAR_KHR},
372    };
373    const uint32_t kNumFormats = sizeof(kFormats) / sizeof(kFormats[0]);
374
375    VkResult result = VK_SUCCESS;
376    if (formats) {
377        if (*count < kNumFormats)
378            result = VK_INCOMPLETE;
379        std::copy(kFormats, kFormats + std::min(*count, kNumFormats), formats);
380    }
381    *count = kNumFormats;
382    return result;
383}
384
385VKAPI_ATTR
386VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice /*pdev*/,
387                                                 VkSurfaceKHR /*surface*/,
388                                                 uint32_t* count,
389                                                 VkPresentModeKHR* modes) {
390    const VkPresentModeKHR kModes[] = {
391        VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
392    };
393    const uint32_t kNumModes = sizeof(kModes) / sizeof(kModes[0]);
394
395    VkResult result = VK_SUCCESS;
396    if (modes) {
397        if (*count < kNumModes)
398            result = VK_INCOMPLETE;
399        std::copy(kModes, kModes + std::min(*count, kNumModes), modes);
400    }
401    *count = kNumModes;
402    return result;
403}
404
405VKAPI_ATTR
406VkResult CreateSwapchainKHR(VkDevice device,
407                            const VkSwapchainCreateInfoKHR* create_info,
408                            const VkAllocationCallbacks* allocator,
409                            VkSwapchainKHR* swapchain_handle) {
410    int err;
411    VkResult result = VK_SUCCESS;
412
413    if (!allocator)
414        allocator = GetAllocator(device);
415
416    ALOGV_IF(create_info->imageArrayLayers != 1,
417             "Swapchain imageArrayLayers (%u) != 1 not supported",
418             create_info->imageArrayLayers);
419
420    ALOGE_IF(create_info->imageColorSpace != VK_COLORSPACE_SRGB_NONLINEAR_KHR,
421             "color spaces other than SRGB_NONLINEAR not yet implemented");
422    ALOGE_IF(create_info->oldSwapchain,
423             "swapchain re-creation not yet implemented");
424    ALOGE_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
425             "swapchain preTransform %d not supported",
426             create_info->preTransform);
427    ALOGW_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
428               create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR),
429             "swapchain present mode %d not supported",
430             create_info->presentMode);
431
432    // -- Configure the native window --
433
434    Surface& surface = *SurfaceFromHandle(create_info->surface);
435    const auto& dispatch = GetDriverDispatch(device);
436
437    int native_format = HAL_PIXEL_FORMAT_RGBA_8888;
438    switch (create_info->imageFormat) {
439        case VK_FORMAT_R8G8B8A8_UNORM:
440        case VK_FORMAT_R8G8B8A8_SRGB:
441            native_format = HAL_PIXEL_FORMAT_RGBA_8888;
442            break;
443        case VK_FORMAT_R5G6B5_UNORM_PACK16:
444            native_format = HAL_PIXEL_FORMAT_RGB_565;
445            break;
446        default:
447            ALOGE("unsupported swapchain format %d", create_info->imageFormat);
448            break;
449    }
450    err = native_window_set_buffers_format(surface.window.get(), native_format);
451    if (err != 0) {
452        // TODO(jessehall): Improve error reporting. Can we enumerate possible
453        // errors and translate them to valid Vulkan result codes?
454        ALOGE("native_window_set_buffers_format(%d) failed: %s (%d)",
455              native_format, strerror(-err), err);
456        return VK_ERROR_INITIALIZATION_FAILED;
457    }
458    err = native_window_set_buffers_data_space(surface.window.get(),
459                                               HAL_DATASPACE_SRGB_LINEAR);
460    if (err != 0) {
461        // TODO(jessehall): Improve error reporting. Can we enumerate possible
462        // errors and translate them to valid Vulkan result codes?
463        ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
464              HAL_DATASPACE_SRGB_LINEAR, strerror(-err), err);
465        return VK_ERROR_INITIALIZATION_FAILED;
466    }
467
468    err = native_window_set_buffers_dimensions(
469        surface.window.get(), static_cast<int>(create_info->imageExtent.width),
470        static_cast<int>(create_info->imageExtent.height));
471    if (err != 0) {
472        // TODO(jessehall): Improve error reporting. Can we enumerate possible
473        // errors and translate them to valid Vulkan result codes?
474        ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
475              create_info->imageExtent.width, create_info->imageExtent.height,
476              strerror(-err), err);
477        return VK_ERROR_INITIALIZATION_FAILED;
478    }
479
480    // VkSwapchainCreateInfo::preTransform indicates the transformation the app
481    // applied during rendering. native_window_set_transform() expects the
482    // inverse: the transform the app is requesting that the compositor perform
483    // during composition. With native windows, pre-transform works by rendering
484    // with the same transform the compositor is applying (as in Vulkan), but
485    // then requesting the inverse transform, so that when the compositor does
486    // it's job the two transforms cancel each other out and the compositor ends
487    // up applying an identity transform to the app's buffer.
488    err = native_window_set_buffers_transform(
489        surface.window.get(),
490        InvertTransformToNative(create_info->preTransform));
491    if (err != 0) {
492        // TODO(jessehall): Improve error reporting. Can we enumerate possible
493        // errors and translate them to valid Vulkan result codes?
494        ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
495              InvertTransformToNative(create_info->preTransform),
496              strerror(-err), err);
497        return VK_ERROR_INITIALIZATION_FAILED;
498    }
499
500    err = native_window_set_scaling_mode(
501        surface.window.get(), NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
502    if (err != 0) {
503        // TODO(jessehall): Improve error reporting. Can we enumerate possible
504        // errors and translate them to valid Vulkan result codes?
505        ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
506              strerror(-err), err);
507        return VK_ERROR_INITIALIZATION_FAILED;
508    }
509
510    int query_value;
511    err = surface.window->query(surface.window.get(),
512                                NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
513                                &query_value);
514    if (err != 0 || query_value < 0) {
515        // TODO(jessehall): Improve error reporting. Can we enumerate possible
516        // errors and translate them to valid Vulkan result codes?
517        ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
518              query_value);
519        return VK_ERROR_INITIALIZATION_FAILED;
520    }
521    uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
522    // The MIN_UNDEQUEUED_BUFFERS query doesn't know whether we'll be using
523    // async mode or not, and assumes not. But in async mode, the BufferQueue
524    // requires an extra undequeued buffer.
525    // See BufferQueueCore::getMinUndequeuedBufferCountLocked().
526    if (create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR)
527        min_undequeued_buffers += 1;
528
529    uint32_t num_images =
530        (create_info->minImageCount - 1) + min_undequeued_buffers;
531    err = native_window_set_buffer_count(surface.window.get(), num_images);
532    if (err != 0) {
533        // TODO(jessehall): Improve error reporting. Can we enumerate possible
534        // errors and translate them to valid Vulkan result codes?
535        ALOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err),
536              err);
537        return VK_ERROR_INITIALIZATION_FAILED;
538    }
539
540    int gralloc_usage = 0;
541    // TODO(jessehall): Remove conditional once all drivers have been updated
542    if (dispatch.GetSwapchainGrallocUsageANDROID) {
543        result = dispatch.GetSwapchainGrallocUsageANDROID(
544            device, create_info->imageFormat, create_info->imageUsage,
545            &gralloc_usage);
546        if (result != VK_SUCCESS) {
547            ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
548            return VK_ERROR_INITIALIZATION_FAILED;
549        }
550    } else {
551        gralloc_usage = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
552    }
553    err = native_window_set_usage(surface.window.get(), gralloc_usage);
554    if (err != 0) {
555        // TODO(jessehall): Improve error reporting. Can we enumerate possible
556        // errors and translate them to valid Vulkan result codes?
557        ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
558        return VK_ERROR_INITIALIZATION_FAILED;
559    }
560
561    err = surface.window->setSwapInterval(
562        surface.window.get(),
563        create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1);
564    if (err != 0) {
565        // TODO(jessehall): Improve error reporting. Can we enumerate possible
566        // errors and translate them to valid Vulkan result codes?
567        ALOGE("native_window->setSwapInterval failed: %s (%d)", strerror(-err),
568              err);
569        return VK_ERROR_INITIALIZATION_FAILED;
570    }
571
572    // -- Allocate our Swapchain object --
573    // After this point, we must deallocate the swapchain on error.
574
575    void* mem = allocator->pfnAllocation(allocator->pUserData,
576                                         sizeof(Swapchain), alignof(Swapchain),
577                                         VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
578    if (!mem)
579        return VK_ERROR_OUT_OF_HOST_MEMORY;
580    Swapchain* swapchain = new (mem) Swapchain(surface, num_images);
581
582    // -- Dequeue all buffers and create a VkImage for each --
583    // Any failures during or after this must cancel the dequeued buffers.
584
585    VkNativeBufferANDROID image_native_buffer = {
586#pragma clang diagnostic push
587#pragma clang diagnostic ignored "-Wold-style-cast"
588        .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
589#pragma clang diagnostic pop
590        .pNext = nullptr,
591    };
592    VkImageCreateInfo image_create = {
593        .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
594        .pNext = &image_native_buffer,
595        .imageType = VK_IMAGE_TYPE_2D,
596        .format = create_info->imageFormat,
597        .extent = {0, 0, 1},
598        .mipLevels = 1,
599        .arrayLayers = 1,
600        .samples = VK_SAMPLE_COUNT_1_BIT,
601        .tiling = VK_IMAGE_TILING_OPTIMAL,
602        .usage = create_info->imageUsage,
603        .flags = 0,
604        .sharingMode = create_info->imageSharingMode,
605        .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
606        .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
607    };
608
609    for (uint32_t i = 0; i < num_images; i++) {
610        Swapchain::Image& img = swapchain->images[i];
611
612        ANativeWindowBuffer* buffer;
613        err = surface.window->dequeueBuffer(surface.window.get(), &buffer,
614                                            &img.dequeue_fence);
615        if (err != 0) {
616            // TODO(jessehall): Improve error reporting. Can we enumerate
617            // possible errors and translate them to valid Vulkan result codes?
618            ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
619            result = VK_ERROR_INITIALIZATION_FAILED;
620            break;
621        }
622        img.buffer = InitSharedPtr(device, buffer);
623        if (!img.buffer) {
624            ALOGE("swapchain creation failed: out of memory");
625            surface.window->cancelBuffer(surface.window.get(), buffer,
626                                         img.dequeue_fence);
627            result = VK_ERROR_OUT_OF_HOST_MEMORY;
628            break;
629        }
630        img.dequeued = true;
631
632        image_create.extent =
633            VkExtent3D{static_cast<uint32_t>(img.buffer->width),
634                       static_cast<uint32_t>(img.buffer->height),
635                       1};
636        image_native_buffer.handle = img.buffer->handle;
637        image_native_buffer.stride = img.buffer->stride;
638        image_native_buffer.format = img.buffer->format;
639        image_native_buffer.usage = img.buffer->usage;
640
641        result =
642            dispatch.CreateImage(device, &image_create, nullptr, &img.image);
643        if (result != VK_SUCCESS) {
644            ALOGD("vkCreateImage w/ native buffer failed: %u", result);
645            break;
646        }
647    }
648
649    // -- Cancel all buffers, returning them to the queue --
650    // If an error occurred before, also destroy the VkImage and release the
651    // buffer reference. Otherwise, we retain a strong reference to the buffer.
652    //
653    // TODO(jessehall): The error path here is the same as DestroySwapchain,
654    // but not the non-error path. Should refactor/unify.
655    for (uint32_t i = 0; i < num_images; i++) {
656        Swapchain::Image& img = swapchain->images[i];
657        if (img.dequeued) {
658            surface.window->cancelBuffer(surface.window.get(), img.buffer.get(),
659                                         img.dequeue_fence);
660            img.dequeue_fence = -1;
661            img.dequeued = false;
662        }
663        if (result != VK_SUCCESS) {
664            if (img.image)
665                dispatch.DestroyImage(device, img.image, nullptr);
666        }
667    }
668
669    if (result != VK_SUCCESS) {
670        swapchain->~Swapchain();
671        allocator->pfnFree(allocator->pUserData, swapchain);
672        return result;
673    }
674
675    *swapchain_handle = HandleFromSwapchain(swapchain);
676    return VK_SUCCESS;
677}
678
679VKAPI_ATTR
680void DestroySwapchainKHR(VkDevice device,
681                         VkSwapchainKHR swapchain_handle,
682                         const VkAllocationCallbacks* allocator) {
683    const auto& dispatch = GetDriverDispatch(device);
684    Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
685    const std::shared_ptr<ANativeWindow>& window = swapchain->surface.window;
686
687    for (uint32_t i = 0; i < swapchain->num_images; i++) {
688        Swapchain::Image& img = swapchain->images[i];
689        if (img.dequeued) {
690            window->cancelBuffer(window.get(), img.buffer.get(),
691                                 img.dequeue_fence);
692            img.dequeue_fence = -1;
693            img.dequeued = false;
694        }
695        if (img.image) {
696            dispatch.DestroyImage(device, img.image, nullptr);
697        }
698    }
699
700    if (!allocator)
701        allocator = GetAllocator(device);
702    swapchain->~Swapchain();
703    allocator->pfnFree(allocator->pUserData, swapchain);
704}
705
706VKAPI_ATTR
707VkResult GetSwapchainImagesKHR(VkDevice,
708                               VkSwapchainKHR swapchain_handle,
709                               uint32_t* count,
710                               VkImage* images) {
711    Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
712    VkResult result = VK_SUCCESS;
713    if (images) {
714        uint32_t n = swapchain.num_images;
715        if (*count < swapchain.num_images) {
716            n = *count;
717            result = VK_INCOMPLETE;
718        }
719        for (uint32_t i = 0; i < n; i++)
720            images[i] = swapchain.images[i].image;
721    }
722    *count = swapchain.num_images;
723    return result;
724}
725
726VKAPI_ATTR
727VkResult AcquireNextImageKHR(VkDevice device,
728                             VkSwapchainKHR swapchain_handle,
729                             uint64_t timeout,
730                             VkSemaphore semaphore,
731                             VkFence vk_fence,
732                             uint32_t* image_index) {
733    Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
734    ANativeWindow* window = swapchain.surface.window.get();
735    VkResult result;
736    int err;
737
738    ALOGW_IF(
739        timeout != UINT64_MAX,
740        "vkAcquireNextImageKHR: non-infinite timeouts not yet implemented");
741
742    ANativeWindowBuffer* buffer;
743    int fence_fd;
744    err = window->dequeueBuffer(window, &buffer, &fence_fd);
745    if (err != 0) {
746        // TODO(jessehall): Improve error reporting. Can we enumerate possible
747        // errors and translate them to valid Vulkan result codes?
748        ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
749        return VK_ERROR_INITIALIZATION_FAILED;
750    }
751
752    uint32_t idx;
753    for (idx = 0; idx < swapchain.num_images; idx++) {
754        if (swapchain.images[idx].buffer.get() == buffer) {
755            swapchain.images[idx].dequeued = true;
756            swapchain.images[idx].dequeue_fence = fence_fd;
757            break;
758        }
759    }
760    if (idx == swapchain.num_images) {
761        ALOGE("dequeueBuffer returned unrecognized buffer");
762        window->cancelBuffer(window, buffer, fence_fd);
763        return VK_ERROR_OUT_OF_DATE_KHR;
764    }
765
766    int fence_clone = -1;
767    if (fence_fd != -1) {
768        fence_clone = dup(fence_fd);
769        if (fence_clone == -1) {
770            ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
771                  strerror(errno), errno);
772            sync_wait(fence_fd, -1 /* forever */);
773        }
774    }
775
776    result = GetDriverDispatch(device).AcquireImageANDROID(
777        device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
778    if (result != VK_SUCCESS) {
779        // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
780        // even if the call fails. We could close it ourselves on failure, but
781        // that would create a race condition if the driver closes it on a
782        // failure path: some other thread might create an fd with the same
783        // number between the time the driver closes it and the time we close
784        // it. We must assume one of: the driver *always* closes it even on
785        // failure, or *never* closes it on failure.
786        window->cancelBuffer(window, buffer, fence_fd);
787        swapchain.images[idx].dequeued = false;
788        swapchain.images[idx].dequeue_fence = -1;
789        return result;
790    }
791
792    *image_index = idx;
793    return VK_SUCCESS;
794}
795
796VKAPI_ATTR
797VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
798    ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
799             "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
800             present_info->sType);
801    ALOGV_IF(present_info->pNext, "VkPresentInfo::pNext != NULL");
802
803    const auto& dispatch = GetDriverDispatch(queue);
804    VkResult final_result = VK_SUCCESS;
805    for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
806        Swapchain& swapchain =
807            *SwapchainFromHandle(present_info->pSwapchains[sc]);
808        ANativeWindow* window = swapchain.surface.window.get();
809        uint32_t image_idx = present_info->pImageIndices[sc];
810        Swapchain::Image& img = swapchain.images[image_idx];
811        VkResult result;
812        int err;
813
814        int fence = -1;
815        result = dispatch.QueueSignalReleaseImageANDROID(
816            queue, present_info->waitSemaphoreCount,
817            present_info->pWaitSemaphores, img.image, &fence);
818        if (result != VK_SUCCESS) {
819            ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
820            if (present_info->pResults)
821                present_info->pResults[sc] = result;
822            if (final_result == VK_SUCCESS)
823                final_result = result;
824            // TODO(jessehall): What happens to the buffer here? Does the app
825            // still own it or not, i.e. should we cancel the buffer? Hard to
826            // do correctly without synchronizing, though I guess we could wait
827            // for the queue to idle.
828            continue;
829        }
830
831        err = window->queueBuffer(window, img.buffer.get(), fence);
832        if (err != 0) {
833            // TODO(jessehall): What now? We should probably cancel the buffer,
834            // I guess?
835            ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
836            if (present_info->pResults)
837                present_info->pResults[sc] = result;
838            if (final_result == VK_SUCCESS)
839                final_result = VK_ERROR_INITIALIZATION_FAILED;
840            continue;
841        }
842
843        if (img.dequeue_fence != -1) {
844            close(img.dequeue_fence);
845            img.dequeue_fence = -1;
846        }
847        img.dequeued = false;
848
849        if (present_info->pResults)
850            present_info->pResults[sc] = VK_SUCCESS;
851    }
852
853    return final_result;
854}
855
856}  // namespace driver
857}  // namespace vulkan
858