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