blob: fe3be45f78c538c1203767b7a34555ea816e4783 [file] [log] [blame]
Jesse Hallb1352bc2015-09-04 16:12:33 -07001/*
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
Yuxin Huf768e042024-02-08 22:15:06 +000017#include "vulkan/vulkan_core.h"
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
sergiuferentz47989332023-09-26 10:24:36 +000020#include <aidl/android/hardware/graphics/common/Dataspace.h>
Trevor David Blackf499b5a2023-07-14 17:30:41 +000021#include <aidl/android/hardware/graphics/common/PixelFormat.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070022#include <android/hardware/graphics/common/1.0/types.h>
Trevor David Blackd7320ef2023-08-23 21:21:51 +000023#include <android/hardware_buffer.h>
Jesse Hall79927812017-03-23 11:03:23 -070024#include <grallocusage/GrallocUsageConversion.h>
Yiwei Zhang69395cd2019-07-03 16:55:39 -070025#include <graphicsenv/GraphicsEnv.h>
John Reck97678d42022-08-23 11:24:51 -040026#include <hardware/gralloc.h>
27#include <hardware/gralloc1.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070028#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070029#include <sync/sync.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070030#include <system/window.h>
31#include <ui/BufferQueueDefs.h>
Chia-I Wue8e689f2016-04-18 08:21:31 +080032#include <utils/StrongPointer.h>
Yiwei Zhang705c2e62019-12-18 23:12:43 -080033#include <utils/Timers.h>
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080034#include <utils/Trace.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070035
36#include <algorithm>
37#include <unordered_set>
38#include <vector>
Jesse Halld7b994a2015-09-07 14:17:37 -070039
Chia-I Wu4a6a9162016-03-26 07:17:34 +080040#include "driver.h"
Jesse Halld7b994a2015-09-07 14:17:37 -070041
Trevor David Blackf499b5a2023-07-14 17:30:41 +000042using PixelFormat = aidl::android::hardware::graphics::common::PixelFormat;
sergiuferentz47989332023-09-26 10:24:36 +000043using DataSpace = aidl::android::hardware::graphics::common::Dataspace;
Daniel Kochf25f5bb2017-10-05 00:26:58 -040044using android::hardware::graphics::common::V1_0::BufferUsage;
45
Chia-I Wu62262232016-03-26 07:06:44 +080046namespace vulkan {
47namespace driver {
Jesse Hall5ae3abb2015-10-08 14:00:22 -070048
Jesse Halld7b994a2015-09-07 14:17:37 -070049namespace {
50
John Reck97678d42022-08-23 11:24:51 -040051static uint64_t convertGralloc1ToBufferUsage(uint64_t producerUsage,
52 uint64_t consumerUsage) {
53 static_assert(uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) ==
54 uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN),
55 "expected ConsumerUsage and ProducerUsage CPU_READ_OFTEN "
56 "bits to match");
57 uint64_t merged = producerUsage | consumerUsage;
58 if ((merged & (GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN)) ==
59 GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) {
60 merged &= ~uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN);
61 merged |= BufferUsage::CPU_READ_OFTEN;
62 }
63 if ((merged & (GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN)) ==
64 GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) {
65 merged &= ~uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN);
66 merged |= BufferUsage::CPU_WRITE_OFTEN;
67 }
68 return merged;
69}
70
Jesse Hall55bc0972016-02-23 16:43:29 -080071const VkSurfaceTransformFlagsKHR kSupportedTransforms =
72 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
73 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
74 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
75 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
Yiwei Zhang70a21962019-05-31 17:26:52 -070076 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
77 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
78 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
79 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
Jesse Hall55bc0972016-02-23 16:43:29 -080080 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
81
82VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
83 // Native and Vulkan transforms are isomorphic, but are represented
84 // differently. Vulkan transforms are built up of an optional horizontal
85 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
86 // transforms are built up from a horizontal flip, vertical flip, and
87 // 90-degree rotation, all optional but always in that order.
88
Jesse Hall55bc0972016-02-23 16:43:29 -080089 switch (native) {
Yiwei Zhang70a21962019-05-31 17:26:52 -070090 case 0:
Jesse Hall55bc0972016-02-23 16:43:29 -080091 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070092 case NATIVE_WINDOW_TRANSFORM_FLIP_H:
93 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
94 case NATIVE_WINDOW_TRANSFORM_FLIP_V:
95 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
96 case NATIVE_WINDOW_TRANSFORM_ROT_180:
Jesse Hall55bc0972016-02-23 16:43:29 -080097 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070098 case NATIVE_WINDOW_TRANSFORM_ROT_90:
Jesse Hall55bc0972016-02-23 16:43:29 -080099 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -0700100 case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
101 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
102 case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
103 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
104 case NATIVE_WINDOW_TRANSFORM_ROT_270:
Jesse Hall55bc0972016-02-23 16:43:29 -0800105 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
106 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
107 default:
108 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
109 }
110}
111
Yiwei Zhang70a21962019-05-31 17:26:52 -0700112int TranslateVulkanToNativeTransform(VkSurfaceTransformFlagBitsKHR transform) {
113 switch (transform) {
114 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
115 return NATIVE_WINDOW_TRANSFORM_ROT_90;
116 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
117 return NATIVE_WINDOW_TRANSFORM_ROT_180;
118 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
119 return NATIVE_WINDOW_TRANSFORM_ROT_270;
120 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
121 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
122 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
123 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
124 NATIVE_WINDOW_TRANSFORM_ROT_90;
125 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
126 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
127 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
128 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
129 NATIVE_WINDOW_TRANSFORM_ROT_90;
130 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
131 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
132 default:
133 return 0;
134 }
135}
136
Jesse Hall178b6962016-02-24 15:39:50 -0800137int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
138 switch (transform) {
139 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
140 return NATIVE_WINDOW_TRANSFORM_ROT_270;
141 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
142 return NATIVE_WINDOW_TRANSFORM_ROT_180;
143 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
144 return NATIVE_WINDOW_TRANSFORM_ROT_90;
Yiwei Zhang70a21962019-05-31 17:26:52 -0700145 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
146 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
147 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
148 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
149 NATIVE_WINDOW_TRANSFORM_ROT_90;
150 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
151 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
152 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
153 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
154 NATIVE_WINDOW_TRANSFORM_ROT_90;
Jesse Hall178b6962016-02-24 15:39:50 -0800155 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
156 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
157 default:
158 return 0;
159 }
160}
161
Ian Elliott8a977262017-01-19 09:05:58 -0700162class TimingInfo {
163 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800164 TimingInfo(const VkPresentTimeGOOGLE* qp, uint64_t nativeFrameId)
Ian Elliott2c6355d2017-01-19 11:02:13 -0700165 : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
Brian Anderson1049d1d2016-12-16 17:25:57 -0800166 native_frame_id_(nativeFrameId) {}
167 bool ready() const {
Brian Andersondc96fdf2017-03-20 16:54:25 -0700168 return (timestamp_desired_present_time_ !=
169 NATIVE_WINDOW_TIMESTAMP_PENDING &&
170 timestamp_actual_present_time_ !=
171 NATIVE_WINDOW_TIMESTAMP_PENDING &&
172 timestamp_render_complete_time_ !=
173 NATIVE_WINDOW_TIMESTAMP_PENDING &&
174 timestamp_composition_latch_time_ !=
175 NATIVE_WINDOW_TIMESTAMP_PENDING);
Ian Elliott8a977262017-01-19 09:05:58 -0700176 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700177 void calculate(int64_t rdur) {
178 bool anyTimestampInvalid =
179 (timestamp_actual_present_time_ ==
180 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
181 (timestamp_render_complete_time_ ==
182 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
183 (timestamp_composition_latch_time_ ==
184 NATIVE_WINDOW_TIMESTAMP_INVALID);
185 if (anyTimestampInvalid) {
186 ALOGE("Unexpectedly received invalid timestamp.");
187 vals_.actualPresentTime = 0;
188 vals_.earliestPresentTime = 0;
189 vals_.presentMargin = 0;
190 return;
191 }
192
193 vals_.actualPresentTime =
194 static_cast<uint64_t>(timestamp_actual_present_time_);
195 int64_t margin = (timestamp_composition_latch_time_ -
Ian Elliott8a977262017-01-19 09:05:58 -0700196 timestamp_render_complete_time_);
197 // Calculate vals_.earliestPresentTime, and potentially adjust
198 // vals_.presentMargin. The initial value of vals_.earliestPresentTime
199 // is vals_.actualPresentTime. If we can subtract rdur (the duration
200 // of a refresh cycle) from vals_.earliestPresentTime (and also from
201 // vals_.presentMargin) and still leave a positive margin, then we can
202 // report to the application that it could have presented earlier than
203 // it did (per the extension specification). If for some reason, we
204 // can do this subtraction repeatedly, we do, since
205 // vals_.earliestPresentTime really is supposed to be the "earliest".
Brian Andersondc96fdf2017-03-20 16:54:25 -0700206 int64_t early_time = timestamp_actual_present_time_;
Ian Elliott8a977262017-01-19 09:05:58 -0700207 while ((margin > rdur) &&
208 ((early_time - rdur) > timestamp_composition_latch_time_)) {
209 early_time -= rdur;
210 margin -= rdur;
211 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700212 vals_.earliestPresentTime = static_cast<uint64_t>(early_time);
213 vals_.presentMargin = static_cast<uint64_t>(margin);
Ian Elliott8a977262017-01-19 09:05:58 -0700214 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800215 void get_values(VkPastPresentationTimingGOOGLE* values) const {
216 *values = vals_;
217 }
Ian Elliott8a977262017-01-19 09:05:58 -0700218
219 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800220 VkPastPresentationTimingGOOGLE vals_ { 0, 0, 0, 0, 0 };
Ian Elliott8a977262017-01-19 09:05:58 -0700221
Brian Anderson1049d1d2016-12-16 17:25:57 -0800222 uint64_t native_frame_id_ { 0 };
Brian Andersondc96fdf2017-03-20 16:54:25 -0700223 int64_t timestamp_desired_present_time_{ NATIVE_WINDOW_TIMESTAMP_PENDING };
224 int64_t timestamp_actual_present_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
225 int64_t timestamp_render_complete_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
226 int64_t timestamp_composition_latch_time_
227 { NATIVE_WINDOW_TIMESTAMP_PENDING };
Ian Elliott8a977262017-01-19 09:05:58 -0700228};
229
Jesse Hall1356b0d2015-11-23 17:24:58 -0800230struct Surface {
Chia-I Wue8e689f2016-04-18 08:21:31 +0800231 android::sp<ANativeWindow> window;
Jesse Halldc225072016-05-30 22:40:14 -0700232 VkSwapchainKHR swapchain_handle;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700233 uint64_t consumer_usage;
Yiwei Zhang3b88f312023-04-18 23:11:35 +0000234
235 // Indicate whether this surface has been used by a swapchain, no matter the
236 // swapchain is still current or has been destroyed.
237 bool used_by_swapchain;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800238};
239
240VkSurfaceKHR HandleFromSurface(Surface* surface) {
241 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
242}
243
244Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800245 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800246}
247
Ian Elliott8a977262017-01-19 09:05:58 -0700248// Maximum number of TimingInfo structs to keep per swapchain:
249enum { MAX_TIMING_INFOS = 10 };
250// Minimum number of frames to look for in the past (so we don't cause
251// syncronous requests to Surface Flinger):
252enum { MIN_NUM_FRAMES_AGO = 5 };
253
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300254bool IsSharedPresentMode(VkPresentModeKHR mode) {
255 return mode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
256 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR;
257}
258
Jesse Hall1356b0d2015-11-23 17:24:58 -0800259struct Swapchain {
Ian Elliottffedb652017-02-14 10:58:30 -0700260 Swapchain(Surface& surface_,
261 uint32_t num_images_,
silence_dogood73597592019-05-23 16:57:37 -0700262 VkPresentModeKHR present_mode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000263 int pre_transform_,
264 int64_t refresh_duration_)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700265 : surface(surface_),
266 num_images(num_images_),
Ian Elliottffedb652017-02-14 10:58:30 -0700267 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
silence_dogood73597592019-05-23 16:57:37 -0700268 pre_transform(pre_transform_),
Chris Forbesf8835642017-03-30 19:31:40 +1300269 frame_timestamps_enabled(false),
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000270 refresh_duration(refresh_duration_),
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800271 acquire_next_image_timeout(-1),
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300272 shared(IsSharedPresentMode(present_mode)) {
Ian Elliott8a977262017-01-19 09:05:58 -0700273 }
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000274
275 VkResult get_refresh_duration(uint64_t& outRefreshDuration)
Ian Elliott3568bfe2019-05-03 15:54:46 -0600276 {
277 ANativeWindow* window = surface.window.get();
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000278 int err = native_window_get_refresh_cycle_duration(
Ian Elliott3568bfe2019-05-03 15:54:46 -0600279 window,
280 &refresh_duration);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000281 if (err != android::OK) {
282 ALOGE("%s:native_window_get_refresh_cycle_duration failed: %s (%d)",
283 __func__, strerror(-err), err );
284 return VK_ERROR_SURFACE_LOST_KHR;
285 }
286 outRefreshDuration = refresh_duration;
287 return VK_SUCCESS;
Ian Elliott3568bfe2019-05-03 15:54:46 -0600288 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800289
290 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700291 uint32_t num_images;
Ian Elliottffedb652017-02-14 10:58:30 -0700292 bool mailbox_mode;
silence_dogood73597592019-05-23 16:57:37 -0700293 int pre_transform;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700294 bool frame_timestamps_enabled;
Brian Andersondc96fdf2017-03-20 16:54:25 -0700295 int64_t refresh_duration;
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800296 nsecs_t acquire_next_image_timeout;
Chris Forbesf8835642017-03-30 19:31:40 +1300297 bool shared;
Jesse Halld7b994a2015-09-07 14:17:37 -0700298
299 struct Image {
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700300 Image()
301 : image(VK_NULL_HANDLE),
302 dequeue_fence(-1),
303 release_fence(-1),
304 dequeued(false) {}
Jesse Halld7b994a2015-09-07 14:17:37 -0700305 VkImage image;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000306 // If the image is bound to memory, an sp to the underlying gralloc buffer.
307 // Otherwise, nullptr; the image will be bound to memory as part of
308 // AcquireNextImage.
Chia-I Wue8e689f2016-04-18 08:21:31 +0800309 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700310 // The fence is only valid when the buffer is dequeued, and should be
311 // -1 any other time. When valid, we own the fd, and must ensure it is
312 // closed: either by closing it explicitly when queueing the buffer,
313 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
314 int dequeue_fence;
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700315 // This fence is a dup of the sync fd returned from the driver via
316 // vkQueueSignalReleaseImageANDROID upon vkQueuePresentKHR. We must
317 // ensure it is closed upon re-presenting or releasing the image.
318 int release_fence;
Jesse Halld7b994a2015-09-07 14:17:37 -0700319 bool dequeued;
Pawin Vongmasa6e1193a2017-03-07 13:08:40 -0800320 } images[android::BufferQueueDefs::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700321
Yiwei Zhang5e862202019-06-21 14:59:16 -0700322 std::vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700323};
324
325VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
326 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
327}
328
329Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800330 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700331}
332
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700333static bool IsFencePending(int fd) {
334 if (fd < 0)
335 return false;
336
337 errno = 0;
338 return sync_wait(fd, 0 /* timeout */) == -1 && errno == ETIME;
339}
340
Jesse Halldc225072016-05-30 22:40:14 -0700341void ReleaseSwapchainImage(VkDevice device,
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000342 bool shared_present,
Jesse Halldc225072016-05-30 22:40:14 -0700343 ANativeWindow* window,
344 int release_fence,
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700345 Swapchain::Image& image,
346 bool defer_if_pending) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700347 ATRACE_CALL();
348
Jesse Halldc225072016-05-30 22:40:14 -0700349 ALOG_ASSERT(release_fence == -1 || image.dequeued,
350 "ReleaseSwapchainImage: can't provide a release fence for "
351 "non-dequeued images");
352
353 if (image.dequeued) {
354 if (release_fence >= 0) {
355 // We get here from vkQueuePresentKHR. The application is
356 // responsible for creating an execution dependency chain from
357 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
358 // (release_fence), so we can drop the dequeue_fence here.
359 if (image.dequeue_fence >= 0)
360 close(image.dequeue_fence);
361 } else {
362 // We get here during swapchain destruction, or various serious
363 // error cases e.g. when we can't create the release_fence during
364 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
365 // have already signalled, since the swapchain images are supposed
366 // to be idle before the swapchain is destroyed. In error cases,
367 // there may be rendering in flight to the image, but since we
368 // weren't able to create a release_fence, waiting for the
369 // dequeue_fence is about the best we can do.
370 release_fence = image.dequeue_fence;
371 }
372 image.dequeue_fence = -1;
373
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000374 // It's invalid to call cancelBuffer on a shared buffer
375 if (window && !shared_present) {
Jesse Halldc225072016-05-30 22:40:14 -0700376 window->cancelBuffer(window, image.buffer.get(), release_fence);
377 } else {
378 if (release_fence >= 0) {
379 sync_wait(release_fence, -1 /* forever */);
380 close(release_fence);
381 }
382 }
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700383 release_fence = -1;
Jesse Halldc225072016-05-30 22:40:14 -0700384 image.dequeued = false;
385 }
386
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700387 if (defer_if_pending && IsFencePending(image.release_fence))
388 return;
389
390 if (image.release_fence >= 0) {
391 close(image.release_fence);
392 image.release_fence = -1;
393 }
394
Jesse Halldc225072016-05-30 22:40:14 -0700395 if (image.image) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700396 ATRACE_BEGIN("DestroyImage");
Jesse Halldc225072016-05-30 22:40:14 -0700397 GetData(device).driver.DestroyImage(device, image.image, nullptr);
Yiwei Zhang533cea92019-06-03 18:43:24 -0700398 ATRACE_END();
Jesse Halldc225072016-05-30 22:40:14 -0700399 image.image = VK_NULL_HANDLE;
400 }
401
402 image.buffer.clear();
403}
404
405void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
406 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
407 return;
Jesse Halldc225072016-05-30 22:40:14 -0700408 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000409 if (!swapchain->images[i].dequeued) {
410 ReleaseSwapchainImage(device, swapchain->shared, nullptr, -1,
411 swapchain->images[i], true);
412 }
Jesse Halldc225072016-05-30 22:40:14 -0700413 }
414 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700415 swapchain->timing.clear();
416}
417
418uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800419 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
420 return 0;
421 }
Ian Elliott8a977262017-01-19 09:05:58 -0700422
Brian Anderson1049d1d2016-12-16 17:25:57 -0800423 uint32_t num_ready = 0;
424 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
425 for (uint32_t i = 0; i < num_timings; i++) {
Yiwei Zhang5e862202019-06-21 14:59:16 -0700426 TimingInfo& ti = swapchain.timing[i];
Brian Anderson1049d1d2016-12-16 17:25:57 -0800427 if (ti.ready()) {
428 // This TimingInfo is ready to be reported to the user. Add it
429 // to the num_ready.
430 num_ready++;
431 continue;
432 }
433 // This TimingInfo is not yet ready to be reported to the user,
434 // and so we should look for any available timestamps that
435 // might make it ready.
436 int64_t desired_present_time = 0;
437 int64_t render_complete_time = 0;
438 int64_t composition_latch_time = 0;
439 int64_t actual_present_time = 0;
440 // Obtain timestamps:
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800441 int err = native_window_get_frame_timestamps(
Brian Anderson1049d1d2016-12-16 17:25:57 -0800442 swapchain.surface.window.get(), ti.native_frame_id_,
443 &desired_present_time, &render_complete_time,
444 &composition_latch_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700445 nullptr, //&first_composition_start_time,
446 nullptr, //&last_composition_start_time,
447 nullptr, //&composition_finish_time,
Brian Anderson1049d1d2016-12-16 17:25:57 -0800448 &actual_present_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700449 nullptr, //&dequeue_ready_time,
450 nullptr /*&reads_done_time*/);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800451
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800452 if (err != android::OK) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800453 continue;
454 }
455
456 // Record the timestamp(s) we received, and then see if this TimingInfo
457 // is ready to be reported to the user:
Brian Andersondc96fdf2017-03-20 16:54:25 -0700458 ti.timestamp_desired_present_time_ = desired_present_time;
459 ti.timestamp_actual_present_time_ = actual_present_time;
460 ti.timestamp_render_complete_time_ = render_complete_time;
461 ti.timestamp_composition_latch_time_ = composition_latch_time;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800462
463 if (ti.ready()) {
464 // The TimingInfo has received enough timestamps, and should now
465 // use those timestamps to calculate the info that should be
466 // reported to the user:
467 ti.calculate(swapchain.refresh_duration);
468 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700469 }
470 }
471 return num_ready;
472}
473
Ian Elliott8a977262017-01-19 09:05:58 -0700474void copy_ready_timings(Swapchain& swapchain,
475 uint32_t* count,
476 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800477 if (swapchain.timing.empty()) {
478 *count = 0;
479 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700480 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800481
482 size_t last_ready = swapchain.timing.size() - 1;
483 while (!swapchain.timing[last_ready].ready()) {
484 if (last_ready == 0) {
485 *count = 0;
486 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700487 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800488 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700489 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800490
491 uint32_t num_copied = 0;
Yiwei Zhang5e862202019-06-21 14:59:16 -0700492 int32_t num_to_remove = 0;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800493 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
494 const TimingInfo& ti = swapchain.timing[i];
495 if (ti.ready()) {
496 ti.get_values(&timings[num_copied]);
497 num_copied++;
498 }
499 num_to_remove++;
500 }
501
502 // Discard old frames that aren't ready if newer frames are ready.
503 // We don't expect to get the timing info for those old frames.
Yiwei Zhang5e862202019-06-21 14:59:16 -0700504 swapchain.timing.erase(swapchain.timing.begin(),
505 swapchain.timing.begin() + num_to_remove);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800506
Ian Elliott8a977262017-01-19 09:05:58 -0700507 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700508}
509
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000510PixelFormat GetNativePixelFormat(VkFormat format) {
511 PixelFormat native_format = PixelFormat::RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700512 switch (format) {
513 case VK_FORMAT_R8G8B8A8_UNORM:
514 case VK_FORMAT_R8G8B8A8_SRGB:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000515 native_format = PixelFormat::RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700516 break;
517 case VK_FORMAT_R5G6B5_UNORM_PACK16:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000518 native_format = PixelFormat::RGB_565;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700519 break;
520 case VK_FORMAT_R16G16B16A16_SFLOAT:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000521 native_format = PixelFormat::RGBA_FP16;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700522 break;
Yiwei Zhangc1ea8152019-02-05 15:11:32 -0800523 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000524 native_format = PixelFormat::RGBA_1010102;
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500525 break;
526 case VK_FORMAT_R8_UNORM:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000527 native_format = PixelFormat::R_8;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700528 break;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000529 case VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000530 native_format = PixelFormat::RGBA_10101010;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000531 break;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700532 default:
533 ALOGV("unsupported swapchain format %d", format);
534 break;
535 }
536 return native_format;
537}
538
sergiuferentz47989332023-09-26 10:24:36 +0000539DataSpace GetNativeDataspace(VkColorSpaceKHR colorspace,
540 PixelFormat pixelFormat) {
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700541 switch (colorspace) {
542 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
sergiuferentz47989332023-09-26 10:24:36 +0000543 return DataSpace::SRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700544 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000545 return DataSpace::DISPLAY_P3;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700546 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000547 return DataSpace::SCRGB_LINEAR;
Courtney Goeltzenleuchterb52abee2017-08-07 17:13:04 -0600548 case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000549 return DataSpace::SCRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700550 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000551 return DataSpace::DCI_P3_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700552 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000553 return DataSpace::DCI_P3;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700554 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000555 return DataSpace::SRGB_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700556 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000557 return DataSpace::SRGB;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600558 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
Sally Qiaa238972023-07-17 12:52:05 +0800559 if (pixelFormat == PixelFormat::RGBA_FP16) {
sergiuferentz47989332023-09-26 10:24:36 +0000560 return DataSpace::BT2020_LINEAR_EXTENDED;
Sally Qiaa238972023-07-17 12:52:05 +0800561 } else {
sergiuferentz47989332023-09-26 10:24:36 +0000562 return DataSpace::BT2020_LINEAR;
Sally Qiaa238972023-07-17 12:52:05 +0800563 }
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600564 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000565 return DataSpace::BT2020_PQ;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600566 case VK_COLOR_SPACE_DOLBYVISION_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000567 return DataSpace::BT2020_PQ;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600568 case VK_COLOR_SPACE_HDR10_HLG_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000569 return DataSpace::BT2020_HLG;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700570 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000571 return DataSpace::ADOBE_RGB_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700572 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000573 return DataSpace::ADOBE_RGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700574 // Pass through is intended to allow app to provide data that is passed
575 // to the display system without modification.
576 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000577 return DataSpace::ARBITRARY;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700578
579 default:
580 // This indicates that we don't know about the
581 // dataspace specified and we should indicate that
582 // it's unsupported
sergiuferentz47989332023-09-26 10:24:36 +0000583 return DataSpace::UNKNOWN;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700584 }
585}
586
Jesse Halld7b994a2015-09-07 14:17:37 -0700587} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700588
Jesse Halle1b12782015-11-30 11:27:32 -0800589VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800590VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800591 VkInstance instance,
592 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
593 const VkAllocationCallbacks* allocator,
594 VkSurfaceKHR* out_surface) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800595 ATRACE_CALL();
596
Jesse Hall1f91d392015-12-11 16:28:44 -0800597 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800598 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800599 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
600 alignof(Surface),
601 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800602 if (!mem)
603 return VK_ERROR_OUT_OF_HOST_MEMORY;
604 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700605
Chia-I Wue8e689f2016-04-18 08:21:31 +0800606 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700607 surface->swapchain_handle = VK_NULL_HANDLE;
Yiwei Zhang3b88f312023-04-18 23:11:35 +0000608 surface->used_by_swapchain = false;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700609 int err = native_window_get_consumer_usage(surface->window.get(),
610 &surface->consumer_usage);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800611 if (err != android::OK) {
Yiwei Zhang6435b322018-05-08 11:12:17 -0700612 ALOGE("native_window_get_consumer_usage() failed: %s (%d)",
613 strerror(-err), err);
614 surface->~Surface();
615 allocator->pfnFree(allocator->pUserData, surface);
Yiwei Zhang70a21962019-05-31 17:26:52 -0700616 return VK_ERROR_SURFACE_LOST_KHR;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700617 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700618
Yiwei Zhang6435b322018-05-08 11:12:17 -0700619 err =
Jesse Hall1356b0d2015-11-23 17:24:58 -0800620 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800621 if (err != android::OK) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800622 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
623 err);
624 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800625 allocator->pfnFree(allocator->pUserData, surface);
Mike Stroyan762c8132017-02-22 11:43:09 -0700626 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800627 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700628
Jesse Hall1356b0d2015-11-23 17:24:58 -0800629 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700630 return VK_SUCCESS;
631}
632
Jesse Halle1b12782015-11-30 11:27:32 -0800633VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800634void DestroySurfaceKHR(VkInstance instance,
635 VkSurfaceKHR surface_handle,
636 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800637 ATRACE_CALL();
638
Jesse Hall1356b0d2015-11-23 17:24:58 -0800639 Surface* surface = SurfaceFromHandle(surface_handle);
640 if (!surface)
641 return;
642 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700643 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700644 "destroyed VkSurfaceKHR 0x%" PRIx64
645 " has active VkSwapchainKHR 0x%" PRIx64,
646 reinterpret_cast<uint64_t>(surface_handle),
647 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800648 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800649 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800650 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800651 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800652}
653
Jesse Halle1b12782015-11-30 11:27:32 -0800654VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800655VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
656 uint32_t /*queue_family*/,
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000657 VkSurfaceKHR /*surface_handle*/,
Chia-I Wu62262232016-03-26 07:06:44 +0800658 VkBool32* supported) {
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000659 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800660 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800661}
662
Jesse Halle1b12782015-11-30 11:27:32 -0800663VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800664VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Ian Elliott1ce053f2022-03-16 09:49:53 -0600665 VkPhysicalDevice pdev,
Jesse Hallb00daad2015-11-29 19:46:20 -0800666 VkSurfaceKHR surface,
667 VkSurfaceCapabilitiesKHR* capabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800668 ATRACE_CALL();
669
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000670 // Implement in terms of GetPhysicalDeviceSurfaceCapabilities2KHR
671
672 VkPhysicalDeviceSurfaceInfo2KHR info2 = {
673 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
674 nullptr,
675 surface
676 };
677
678 VkSurfaceCapabilities2KHR caps2 = {
679 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
680 nullptr,
681 {},
682 };
683
684 VkResult result = GetPhysicalDeviceSurfaceCapabilities2KHR(pdev, &info2, &caps2);
685 *capabilities = caps2.surfaceCapabilities;
686 return result;
687}
688
689// Does the call-twice and VK_INCOMPLETE handling for querying lists
690// of things, where we already have the full set built in a vector.
691template <typename T>
692VkResult CopyWithIncomplete(std::vector<T> const& things,
693 T* callerPtr, uint32_t* callerCount) {
694 VkResult result = VK_SUCCESS;
695 if (callerPtr) {
696 if (things.size() > *callerCount)
697 result = VK_INCOMPLETE;
698 *callerCount = std::min(uint32_t(things.size()), *callerCount);
699 std::copy(things.begin(), things.begin() + *callerCount, callerPtr);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600700 } else {
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000701 *callerCount = things.size();
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800702 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000703 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700704}
705
Jesse Halle1b12782015-11-30 11:27:32 -0800706VKAPI_ATTR
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700707VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
708 VkSurfaceKHR surface_handle,
Chia-I Wu62262232016-03-26 07:06:44 +0800709 uint32_t* count,
710 VkSurfaceFormatKHR* formats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800711 ATRACE_CALL();
712
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700713 const InstanceData& instance_data = GetData(pdev);
714
Ian Elliott1ce053f2022-03-16 09:49:53 -0600715 uint64_t consumer_usage = 0;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000716 bool colorspace_ext =
Ian Elliottf6df08e2022-03-16 21:27:49 -0600717 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600718 if (surface_handle == VK_NULL_HANDLE) {
719 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
720 bool surfaceless_enabled =
721 instance_data.hook_extensions.test(surfaceless);
722 if (!surfaceless_enabled) {
723 return VK_ERROR_SURFACE_LOST_KHR;
724 }
Chris Forbesb1de3b12022-10-20 09:05:48 +1300725 // Support for VK_GOOGLE_surfaceless_query.
Ian Elliott1ce053f2022-03-16 09:49:53 -0600726
727 // TODO(b/203826952): research proper value; temporarily use the
728 // values seen on Pixel
729 consumer_usage = AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
730 } else {
731 Surface& surface = *SurfaceFromHandle(surface_handle);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600732 consumer_usage = surface.consumer_usage;
Ian Elliott6ba85d92022-02-18 16:44:58 -0700733 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700734
Charlie Lao324191f2019-12-13 11:03:16 -0800735 AHardwareBuffer_Desc desc = {};
736 desc.width = 1;
737 desc.height = 1;
738 desc.layers = 1;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600739 desc.usage = consumer_usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
Charlie Lao324191f2019-12-13 11:03:16 -0800740 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
741
742 // We must support R8G8B8A8
743 std::vector<VkSurfaceFormatKHR> all_formats = {
744 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000745 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000746 };
Charlie Lao324191f2019-12-13 11:03:16 -0800747
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000748 if (colorspace_ext) {
749 all_formats.emplace_back(VkSurfaceFormatKHR{
Jason Macnakca506332022-11-09 11:00:36 -0800750 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
751 all_formats.emplace_back(VkSurfaceFormatKHR{
752 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_PASS_THROUGH_EXT});
753 all_formats.emplace_back(VkSurfaceFormatKHR{
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000754 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_BT709_LINEAR_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800755 all_formats.emplace_back(VkSurfaceFormatKHR{
756 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
757 all_formats.emplace_back(VkSurfaceFormatKHR{
758 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
759 }
760
Ian Elliott1ce053f2022-03-16 09:49:53 -0600761 // NOTE: Any new formats that are added must be coordinated across different
762 // Android users. This includes the ANGLE team (a layered implementation of
763 // OpenGL-ES).
764
Charlie Lao324191f2019-12-13 11:03:16 -0800765 desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
766 if (AHardwareBuffer_isSupported(&desc)) {
767 all_formats.emplace_back(VkSurfaceFormatKHR{
768 VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800769 if (colorspace_ext) {
770 all_formats.emplace_back(
771 VkSurfaceFormatKHR{VK_FORMAT_R5G6B5_UNORM_PACK16,
772 VK_COLOR_SPACE_PASS_THROUGH_EXT});
773 }
Charlie Lao324191f2019-12-13 11:03:16 -0800774 }
775
776 desc.format = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
777 if (AHardwareBuffer_isSupported(&desc)) {
778 all_formats.emplace_back(VkSurfaceFormatKHR{
779 VK_FORMAT_R16G16B16A16_SFLOAT, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800780 if (colorspace_ext) {
781 all_formats.emplace_back(
782 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
783 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800784 all_formats.emplace_back(
785 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
786 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT});
787 all_formats.emplace_back(
788 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
789 VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT});
Yuxin Hud3ff5212024-02-06 02:39:19 +0000790 all_formats.emplace_back(
791 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
792 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
Yuxin Huf768e042024-02-08 22:15:06 +0000793 all_formats.emplace_back(
794 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
795 VK_COLOR_SPACE_DISPLAY_P3_LINEAR_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800796 }
797 }
798
799 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
800 if (AHardwareBuffer_isSupported(&desc)) {
801 all_formats.emplace_back(
802 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
803 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800804 if (colorspace_ext) {
805 all_formats.emplace_back(
806 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
807 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800808 all_formats.emplace_back(
809 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
810 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
811 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700812 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700813
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500814 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
815 if (AHardwareBuffer_isSupported(&desc)) {
Jason Macnakca506332022-11-09 11:00:36 -0800816 if (colorspace_ext) {
817 all_formats.emplace_back(VkSurfaceFormatKHR{
818 VK_FORMAT_R8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
819 }
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500820 }
821
Trevor David Black67e9b102023-03-07 05:28:15 +0000822 bool rgba10x6_formats_ext = false;
823 uint32_t exts_count;
824 const auto& driver = GetData(pdev).driver;
825 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
826 nullptr);
827 std::vector<VkExtensionProperties> props(exts_count);
828 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
829 props.data());
830 for (uint32_t i = 0; i < exts_count; i++) {
831 VkExtensionProperties prop = props[i];
832 if (strcmp(prop.extensionName,
833 VK_EXT_RGBA10X6_FORMATS_EXTENSION_NAME) == 0) {
834 rgba10x6_formats_ext = true;
835 }
836 }
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000837 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM;
Trevor David Black67e9b102023-03-07 05:28:15 +0000838 if (AHardwareBuffer_isSupported(&desc) && rgba10x6_formats_ext) {
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000839 all_formats.emplace_back(
840 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
841 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
842 if (colorspace_ext) {
843 all_formats.emplace_back(
844 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
845 VK_COLOR_SPACE_PASS_THROUGH_EXT});
846 all_formats.emplace_back(
847 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
848 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
849 }
850 }
851
Ian Elliott6ba85d92022-02-18 16:44:58 -0700852 // NOTE: Any new formats that are added must be coordinated across different
853 // Android users. This includes the ANGLE team (a layered implementation of
854 // OpenGL-ES).
855
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000856 return CopyWithIncomplete(all_formats, formats, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700857}
858
Jesse Halle1b12782015-11-30 11:27:32 -0800859VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300860VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
861 VkPhysicalDevice physicalDevice,
862 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
863 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800864 ATRACE_CALL();
865
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000866 auto surface = pSurfaceInfo->surface;
867 auto capabilities = &pSurfaceCapabilities->surfaceCapabilities;
Chris Forbes2452cf72017-03-16 16:30:17 +1300868
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000869 VkSurfacePresentModeEXT const *pPresentMode = nullptr;
870 for (auto pNext = reinterpret_cast<VkBaseInStructure const *>(pSurfaceInfo->pNext);
871 pNext; pNext = reinterpret_cast<VkBaseInStructure const *>(pNext->pNext)) {
872 switch (pNext->sType) {
873 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT:
874 pPresentMode = reinterpret_cast<VkSurfacePresentModeEXT const *>(pNext);
875 break;
Chris Forbes06bc0092017-03-16 16:46:05 +1300876
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000877 default:
878 break;
879 }
880 }
881
882 int err;
883 int width, height;
884 int transform_hint;
885 int max_buffer_count;
Trevor David Black1d3509e2023-06-08 00:17:40 +0000886 int min_undequeued_buffers;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000887 if (surface == VK_NULL_HANDLE) {
888 const InstanceData& instance_data = GetData(physicalDevice);
889 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
890 bool surfaceless_enabled =
891 instance_data.hook_extensions.test(surfaceless);
892 if (!surfaceless_enabled) {
893 // It is an error to pass a surface==VK_NULL_HANDLE unless the
894 // VK_GOOGLE_surfaceless_query extension is enabled
895 return VK_ERROR_SURFACE_LOST_KHR;
896 }
897 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
898 // extension for this function is for
899 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
900 // four values cannot be known without a surface. Default values will
901 // be supplied anyway, but cannot be relied upon.
902 width = 0xFFFFFFFF;
903 height = 0xFFFFFFFF;
904 transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
905 capabilities->minImageCount = 0xFFFFFFFF;
906 capabilities->maxImageCount = 0xFFFFFFFF;
907 } else {
908 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
909
910 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
911 if (err != android::OK) {
912 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
913 strerror(-err), err);
914 return VK_ERROR_SURFACE_LOST_KHR;
915 }
916 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
917 if (err != android::OK) {
918 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
919 strerror(-err), err);
920 return VK_ERROR_SURFACE_LOST_KHR;
921 }
922
923 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
924 &transform_hint);
925 if (err != android::OK) {
926 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
927 strerror(-err), err);
928 return VK_ERROR_SURFACE_LOST_KHR;
929 }
930
931 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
932 &max_buffer_count);
933 if (err != android::OK) {
934 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
935 strerror(-err), err);
936 return VK_ERROR_SURFACE_LOST_KHR;
937 }
938
Trevor David Black1d3509e2023-06-08 00:17:40 +0000939 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
940 &min_undequeued_buffers);
941 if (err != android::OK) {
942 ALOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d)",
943 strerror(-err), err);
944 return VK_ERROR_SURFACE_LOST_KHR;
945 }
946
Trevor David Blacke4d23b92023-09-26 20:30:42 +0000947 // Additional buffer count over min_undequeued_buffers in vulkan came from 2 total
948 // being technically enough for fifo (although a poor experience) vs 3 being the
949 // absolute minimum for mailbox to be useful. So min_undequeued_buffers + 2 is sensible
950 static constexpr int default_additional_buffers = 2;
951
Trevor David Blacka93e21f2023-08-30 23:42:20 +0000952 if(pPresentMode != nullptr) {
953 switch (pPresentMode->presentMode) {
954 case VK_PRESENT_MODE_IMMEDIATE_KHR:
955 ALOGE("Swapchain present mode VK_PRESENT_MODE_IMMEDIATE_KHR is not supported");
956 break;
957 case VK_PRESENT_MODE_MAILBOX_KHR:
958 case VK_PRESENT_MODE_FIFO_KHR:
Trevor David Blacke4d23b92023-09-26 20:30:42 +0000959 capabilities->minImageCount = std::min(max_buffer_count,
960 min_undequeued_buffers + default_additional_buffers);
Trevor David Blacka93e21f2023-08-30 23:42:20 +0000961 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
962 break;
963 case VK_PRESENT_MODE_FIFO_RELAXED_KHR:
964 ALOGE("Swapchain present mode VK_PRESENT_MODE_FIFO_RELEAXED_KHR "
965 "is not supported");
966 break;
967 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
968 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
969 capabilities->minImageCount = 1;
970 capabilities->maxImageCount = 1;
971 break;
972
973 default:
974 ALOGE("Unrecognized swapchain present mode %u is not supported",
975 pPresentMode->presentMode);
976 break;
977 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000978 } else {
Trevor David Blacke4d23b92023-09-26 20:30:42 +0000979 capabilities->minImageCount = std::min(max_buffer_count,
980 min_undequeued_buffers + default_additional_buffers);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000981 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
982 }
983 }
984
985 capabilities->currentExtent =
986 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
987
988 // TODO(http://b/134182502): Figure out what the max extent should be.
989 capabilities->minImageExtent = VkExtent2D{1, 1};
990 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
991
992 if (capabilities->maxImageExtent.height <
993 capabilities->currentExtent.height) {
994 capabilities->maxImageExtent.height =
995 capabilities->currentExtent.height;
996 }
997
998 if (capabilities->maxImageExtent.width <
999 capabilities->currentExtent.width) {
1000 capabilities->maxImageExtent.width = capabilities->currentExtent.width;
1001 }
1002
1003 capabilities->maxImageArrayLayers = 1;
1004
1005 capabilities->supportedTransforms = kSupportedTransforms;
1006 capabilities->currentTransform =
1007 TranslateNativeToVulkanTransform(transform_hint);
1008
1009 // On Android, window composition is a WindowManager property, not something
1010 // associated with the bufferqueue. It can't be changed from here.
1011 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
1012
1013 capabilities->supportedUsageFlags =
1014 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
1015 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
1016 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
1017 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
1018
1019 for (auto pNext = reinterpret_cast<VkBaseOutStructure*>(pSurfaceCapabilities->pNext);
1020 pNext; pNext = reinterpret_cast<VkBaseOutStructure*>(pNext->pNext)) {
1021
1022 switch (pNext->sType) {
Chris Forbes06bc0092017-03-16 16:46:05 +13001023 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
1024 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001025 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(pNext);
Chris Forbes06bc0092017-03-16 16:46:05 +13001026 // Claim same set of usage flags are supported for
1027 // shared present modes as for other modes.
1028 shared_caps->sharedPresentSupportedUsageFlags =
1029 pSurfaceCapabilities->surfaceCapabilities
1030 .supportedUsageFlags;
1031 } break;
1032
Ian Elliottbb67b242022-03-16 09:52:28 -06001033 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
1034 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001035 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(pNext);
Ian Elliottbb67b242022-03-16 09:52:28 -06001036 protected_caps->supportsProtected = VK_TRUE;
1037 } break;
1038
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001039 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_SCALING_CAPABILITIES_EXT: {
1040 VkSurfacePresentScalingCapabilitiesEXT* scaling_caps =
1041 reinterpret_cast<VkSurfacePresentScalingCapabilitiesEXT*>(pNext);
1042 // By default, Android stretches the buffer to fit the window,
1043 // without preserving aspect ratio. Other modes are technically possible
1044 // but consult with CoGS team before exposing them here!
1045 scaling_caps->supportedPresentScaling = VK_PRESENT_SCALING_STRETCH_BIT_EXT;
1046
1047 // Since we always scale, we don't support any gravity.
1048 scaling_caps->supportedPresentGravityX = 0;
1049 scaling_caps->supportedPresentGravityY = 0;
1050
1051 // Scaled image limits are just the basic image limits
1052 scaling_caps->minScaledImageExtent = capabilities->minImageExtent;
1053 scaling_caps->maxScaledImageExtent = capabilities->maxImageExtent;
1054 } break;
1055
1056 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT: {
1057 VkSurfacePresentModeCompatibilityEXT* mode_caps =
1058 reinterpret_cast<VkSurfacePresentModeCompatibilityEXT*>(pNext);
1059
1060 ALOG_ASSERT(pPresentMode,
1061 "querying VkSurfacePresentModeCompatibilityEXT "
1062 "requires VkSurfacePresentModeEXT to be provided");
1063 std::vector<VkPresentModeKHR> compatibleModes;
1064 compatibleModes.push_back(pPresentMode->presentMode);
1065
1066 switch (pPresentMode->presentMode) {
1067 // Shared modes are both compatible with each other.
1068 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
1069 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
1070 break;
1071 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
1072 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1073 break;
1074 default:
1075 // Other modes are only compatible with themselves.
1076 // TODO: consider whether switching between FIFO and MAILBOX is reasonable
1077 break;
1078 }
1079
1080 // Note: this does not generate VK_INCOMPLETE since we're nested inside
1081 // a larger query and there would be no way to determine exactly where it came from.
1082 CopyWithIncomplete(compatibleModes, mode_caps->pPresentModes,
1083 &mode_caps->presentModeCount);
1084 } break;
1085
Chris Forbes06bc0092017-03-16 16:46:05 +13001086 default:
1087 // Ignore all other extension structs
1088 break;
1089 }
1090 }
1091
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001092 return VK_SUCCESS;
Chris Forbes2452cf72017-03-16 16:30:17 +13001093}
1094
1095VKAPI_ATTR
1096VkResult GetPhysicalDeviceSurfaceFormats2KHR(
1097 VkPhysicalDevice physicalDevice,
1098 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
1099 uint32_t* pSurfaceFormatCount,
1100 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001101 ATRACE_CALL();
1102
Chris Forbes2452cf72017-03-16 16:30:17 +13001103 if (!pSurfaceFormats) {
1104 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
1105 pSurfaceInfo->surface,
1106 pSurfaceFormatCount, nullptr);
Trevor David Black929e9cd2022-11-22 04:12:19 +00001107 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001108
Trevor David Black929e9cd2022-11-22 04:12:19 +00001109 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
1110 // after the call.
1111 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
1112 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
1113 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
1114 surface_formats.data());
Trevor David Black2cc44682022-03-09 00:31:38 +00001115
Trevor David Black929e9cd2022-11-22 04:12:19 +00001116 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
1117 return result;
1118 }
Trevor David Black2cc44682022-03-09 00:31:38 +00001119
Trevor David Black929e9cd2022-11-22 04:12:19 +00001120 const auto& driver = GetData(physicalDevice).driver;
1121
1122 // marshal results individually due to stride difference.
1123 uint32_t formats_to_marshal = *pSurfaceFormatCount;
1124 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
1125 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
1126
1127 // Query the compression properties for the surface format
1128 VkSurfaceFormat2KHR* pSurfaceFormat = &pSurfaceFormats[i];
1129 while (pSurfaceFormat->pNext) {
1130 pSurfaceFormat =
1131 reinterpret_cast<VkSurfaceFormat2KHR*>(pSurfaceFormat->pNext);
1132 switch (pSurfaceFormat->sType) {
1133 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT: {
Trevor David Black2cc44682022-03-09 00:31:38 +00001134 VkImageCompressionPropertiesEXT* surfaceCompressionProps =
1135 reinterpret_cast<VkImageCompressionPropertiesEXT*>(
Trevor David Black929e9cd2022-11-22 04:12:19 +00001136 pSurfaceFormat);
Trevor David Black2cc44682022-03-09 00:31:38 +00001137
1138 if (surfaceCompressionProps &&
1139 driver.GetPhysicalDeviceImageFormatProperties2KHR) {
1140 VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = {};
1141 imageFormatInfo.sType =
1142 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
1143 imageFormatInfo.format =
1144 pSurfaceFormats[i].surfaceFormat.format;
Trevor David Blacka4298c92023-06-20 17:11:58 +00001145 imageFormatInfo.type = VK_IMAGE_TYPE_2D;
1146 imageFormatInfo.usage =
1147 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
Trevor David Black2cc44682022-03-09 00:31:38 +00001148 imageFormatInfo.pNext = nullptr;
1149
1150 VkImageCompressionControlEXT compressionControl = {};
1151 compressionControl.sType =
1152 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT;
1153 compressionControl.pNext = imageFormatInfo.pNext;
Trevor David Blacka4298c92023-06-20 17:11:58 +00001154 compressionControl.flags =
1155 VK_IMAGE_COMPRESSION_FIXED_RATE_DEFAULT_EXT;
Trevor David Black2cc44682022-03-09 00:31:38 +00001156
1157 imageFormatInfo.pNext = &compressionControl;
1158
1159 VkImageCompressionPropertiesEXT compressionProps = {};
1160 compressionProps.sType =
1161 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT;
1162 compressionProps.pNext = nullptr;
1163
1164 VkImageFormatProperties2KHR imageFormatProps = {};
1165 imageFormatProps.sType =
1166 VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
1167 imageFormatProps.pNext = &compressionProps;
1168
1169 VkResult compressionRes =
1170 driver.GetPhysicalDeviceImageFormatProperties2KHR(
1171 physicalDevice, &imageFormatInfo,
1172 &imageFormatProps);
1173 if (compressionRes == VK_SUCCESS) {
1174 surfaceCompressionProps->imageCompressionFlags =
1175 compressionProps.imageCompressionFlags;
1176 surfaceCompressionProps
1177 ->imageCompressionFixedRateFlags =
1178 compressionProps.imageCompressionFixedRateFlags;
1179 } else {
1180 return compressionRes;
1181 }
1182 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001183 } break;
1184
1185 default:
1186 // Ignore all other extension structs
1187 break;
Chris Forbes2452cf72017-03-16 16:30:17 +13001188 }
1189 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001190 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001191
1192 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +13001193}
1194
1195VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +13001196VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001197 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +08001198 uint32_t* count,
1199 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001200 ATRACE_CALL();
1201
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001202 int err;
1203 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -06001204 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -06001205 if (surface == VK_NULL_HANDLE) {
1206 const InstanceData& instance_data = GetData(pdev);
1207 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
1208 bool surfaceless_enabled =
1209 instance_data.hook_extensions.test(surfaceless);
1210 if (!surfaceless_enabled) {
1211 return VK_ERROR_SURFACE_LOST_KHR;
1212 }
1213 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
1214 // extension for this function is for
1215 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
1216 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
1217 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
Ian Elliott7e361142022-06-02 10:45:17 -06001218 // surface, and that cannot be relied upon. Therefore, don't return it.
Ian Elliott1ce053f2022-03-16 09:49:53 -06001219 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1220 } else {
1221 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1222
1223 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1224 &query_value);
1225 if (err != android::OK || query_value < 0) {
1226 ALOGE(
1227 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
1228 "value=%d",
1229 strerror(-err), err, query_value);
1230 return VK_ERROR_SURFACE_LOST_KHR;
1231 }
1232 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1233
1234 err =
1235 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
1236 if (err != android::OK || query_value < 0) {
1237 ALOGE(
1238 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
1239 strerror(-err), err, query_value);
1240 return VK_ERROR_SURFACE_LOST_KHR;
1241 }
1242 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
1243
1244 if (min_undequeued_buffers + 1 < max_buffer_count)
1245 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
1246 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1247 }
Chris Forbese8d79a62017-02-22 12:49:18 +13001248
1249 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -07001250 QueryPresentationProperties(pdev, &present_properties);
1251 if (present_properties.sharedImage) {
1252 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1253 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +13001254 }
1255
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001256 return CopyWithIncomplete(present_modes, modes, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001257}
1258
Jesse Halle1b12782015-11-30 11:27:32 -08001259VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001260VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001261 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001262 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001263 ATRACE_CALL();
1264
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001265 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
1266 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1267 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1268 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1269 pDeviceGroupPresentCapabilities->sType);
1270
1271 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1272 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1273
1274 // assume device group of size 1
1275 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1276 pDeviceGroupPresentCapabilities->modes =
1277 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1278
1279 return VK_SUCCESS;
1280}
1281
1282VKAPI_ATTR
1283VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001284 VkDevice,
1285 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001286 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001287 ATRACE_CALL();
1288
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001289 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1290 return VK_SUCCESS;
1291}
1292
1293VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001294VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001295 VkSurfaceKHR surface,
1296 uint32_t* pRectCount,
1297 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001298 ATRACE_CALL();
1299
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001300 if (!pRects) {
1301 *pRectCount = 1;
1302 } else {
1303 uint32_t count = std::min(*pRectCount, 1u);
1304 bool incomplete = *pRectCount < 1;
1305
1306 *pRectCount = count;
1307
1308 if (incomplete) {
1309 return VK_INCOMPLETE;
1310 }
1311
1312 int err;
1313 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1314
1315 int width = 0, height = 0;
1316 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001317 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001318 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1319 strerror(-err), err);
1320 }
1321 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001322 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001323 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1324 strerror(-err), err);
1325 }
1326
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001327 pRects[0].offset.x = 0;
1328 pRects[0].offset.y = 0;
1329 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1330 static_cast<uint32_t>(height)};
1331 }
1332 return VK_SUCCESS;
1333}
1334
Yiwei Zhang533cea92019-06-03 18:43:24 -07001335static void DestroySwapchainInternal(VkDevice device,
1336 VkSwapchainKHR swapchain_handle,
1337 const VkAllocationCallbacks* allocator) {
1338 ATRACE_CALL();
1339
1340 const auto& dispatch = GetData(device).driver;
1341 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1342 if (!swapchain) {
1343 return;
1344 }
1345
1346 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1347 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1348
1349 if (window && swapchain->frame_timestamps_enabled) {
1350 native_window_enable_frame_timestamps(window, false);
1351 }
1352
1353 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +00001354 ReleaseSwapchainImage(device, swapchain->shared, window, -1,
1355 swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001356 }
1357
1358 if (active) {
1359 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1360 }
1361
1362 if (!allocator) {
1363 allocator = &GetData(device).allocator;
1364 }
1365
1366 swapchain->~Swapchain();
1367 allocator->pfnFree(allocator->pUserData, swapchain);
1368}
1369
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001370static VkResult getProducerUsage(const VkDevice& device,
1371 const VkSwapchainCreateInfoKHR* create_info,
1372 const VkSwapchainImageUsageFlagsANDROID swapchain_image_usage,
1373 bool create_protected_swapchain,
1374 uint64_t* producer_usage) {
1375 // Get the physical device to query the appropriate producer usage
1376 const VkPhysicalDevice& pdev = GetData(device).driver_physical_device;
1377 const InstanceData& instance_data = GetData(pdev);
1378 const InstanceDriverTable& instance_dispatch = instance_data.driver;
Trevor David Black02926f52024-01-04 18:44:20 +00001379 if (instance_dispatch.GetPhysicalDeviceImageFormatProperties2 ||
1380 instance_dispatch.GetPhysicalDeviceImageFormatProperties2KHR) {
1381 // Look through the create_info pNext chain passed to createSwapchainKHR
1382 // for an image compression control struct.
1383 // if one is found AND the appropriate extensions are enabled, create a
1384 // VkImageCompressionControlEXT structure to pass on to
1385 // GetPhysicalDeviceImageFormatProperties2
1386 void* compression_control_pNext = nullptr;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001387 VkImageCompressionControlEXT image_compression = {};
Trevor David Black02926f52024-01-04 18:44:20 +00001388 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1389 while (create_infos->pNext) {
1390 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(create_infos->pNext);
1391 switch (create_infos->sType) {
1392 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1393 const VkImageCompressionControlEXT* compression_infos =
1394 reinterpret_cast<const VkImageCompressionControlEXT*>(create_infos);
1395 image_compression = *compression_infos;
1396 image_compression.pNext = nullptr;
1397 compression_control_pNext = &image_compression;
1398 } break;
1399 default:
1400 // Ignore all other info structs
1401 break;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001402 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001403 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001404
Trevor David Black02926f52024-01-04 18:44:20 +00001405 // call GetPhysicalDeviceImageFormatProperties2KHR
1406 VkPhysicalDeviceExternalImageFormatInfo external_image_format_info = {
1407 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1408 .pNext = compression_control_pNext,
1409 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID,
1410 };
1411
1412 // AHB does not have an sRGB format so we can't pass it to GPDIFP
1413 // We need to convert the format to unorm if it is srgb
1414 VkFormat format = create_info->imageFormat;
1415 if (format == VK_FORMAT_R8G8B8A8_SRGB) {
1416 format = VK_FORMAT_R8G8B8A8_UNORM;
1417 }
1418
1419 VkPhysicalDeviceImageFormatInfo2 image_format_info = {
1420 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1421 .pNext = &external_image_format_info,
1422 .format = format,
1423 .type = VK_IMAGE_TYPE_2D,
1424 .tiling = VK_IMAGE_TILING_OPTIMAL,
1425 .usage = create_info->imageUsage,
1426 .flags = create_protected_swapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
1427 };
1428
1429 VkAndroidHardwareBufferUsageANDROID ahb_usage;
1430 ahb_usage.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_USAGE_ANDROID;
1431 ahb_usage.pNext = nullptr;
1432
1433 VkImageFormatProperties2 image_format_properties;
1434 image_format_properties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
1435 image_format_properties.pNext = &ahb_usage;
1436
1437 if (instance_dispatch.GetPhysicalDeviceImageFormatProperties2) {
1438 VkResult result = instance_dispatch.GetPhysicalDeviceImageFormatProperties2(
1439 pdev, &image_format_info, &image_format_properties);
1440 if (result != VK_SUCCESS) {
1441 ALOGE("VkGetPhysicalDeviceImageFormatProperties2 for AHB usage failed: %d", result);
1442 return VK_ERROR_SURFACE_LOST_KHR;
1443 }
1444 }
1445 else {
1446 VkResult result = instance_dispatch.GetPhysicalDeviceImageFormatProperties2KHR(
1447 pdev, &image_format_info,
1448 &image_format_properties);
1449 if (result != VK_SUCCESS) {
1450 ALOGE("VkGetPhysicalDeviceImageFormatProperties2KHR for AHB usage failed: %d",
1451 result);
1452 return VK_ERROR_SURFACE_LOST_KHR;
1453 }
1454 }
1455
1456 // Determine if USAGE_FRONT_BUFFER is needed.
1457 // GPDIFP2 has no means of using VkSwapchainImageUsageFlagsANDROID when
1458 // querying for producer_usage. So androidHardwareBufferUsage will not
1459 // contain USAGE_FRONT_BUFFER. We need to manually check for usage here.
1460 if (!(swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID)) {
1461 *producer_usage = ahb_usage.androidHardwareBufferUsage;
1462 return VK_SUCCESS;
1463 }
1464
1465 // Check if USAGE_FRONT_BUFFER is supported for this swapchain
1466 AHardwareBuffer_Desc ahb_desc = {
1467 .width = create_info->imageExtent.width,
1468 .height = create_info->imageExtent.height,
1469 .layers = create_info->imageArrayLayers,
1470 .format = create_info->imageFormat,
1471 .usage = ahb_usage.androidHardwareBufferUsage | AHARDWAREBUFFER_USAGE_FRONT_BUFFER,
1472 .stride = 0, // stride is always ignored when calling isSupported()
1473 };
1474
1475 // If FRONT_BUFFER is not supported,
1476 // then we need to call GetSwapchainGrallocUsageXAndroid below
1477 if (AHardwareBuffer_isSupported(&ahb_desc)) {
1478 *producer_usage = ahb_usage.androidHardwareBufferUsage;
1479 *producer_usage |= AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
1480 return VK_SUCCESS;
1481 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001482 }
1483
Trevor David Black02926f52024-01-04 18:44:20 +00001484 uint64_t native_usage = 0;
1485 void* usage_info_pNext = nullptr;
1486 VkResult result;
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001487 VkImageCompressionControlEXT image_compression = {};
Trevor David Black02926f52024-01-04 18:44:20 +00001488 const auto& dispatch = GetData(device).driver;
1489 if (dispatch.GetSwapchainGrallocUsage4ANDROID) {
1490 ATRACE_BEGIN("GetSwapchainGrallocUsage4ANDROID");
1491 VkGrallocUsageInfo2ANDROID gralloc_usage_info = {};
1492 gralloc_usage_info.sType =
1493 VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_2_ANDROID;
1494 gralloc_usage_info.format = create_info->imageFormat;
1495 gralloc_usage_info.imageUsage = create_info->imageUsage;
1496 gralloc_usage_info.swapchainImageUsage = swapchain_image_usage;
1497
1498 // Look through the pNext chain for an image compression control struct
1499 // if one is found AND the appropriate extensions are enabled,
1500 // append it to be the gralloc usage pNext chain
1501 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1502 while (create_infos->pNext) {
1503 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1504 create_infos->pNext);
1505 switch (create_infos->sType) {
1506 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1507 const VkImageCompressionControlEXT* compression_infos =
1508 reinterpret_cast<const VkImageCompressionControlEXT*>(
1509 create_infos);
1510 image_compression = *compression_infos;
1511 image_compression.pNext = nullptr;
1512 usage_info_pNext = &image_compression;
1513 } break;
1514
1515 default:
1516 // Ignore all other info structs
1517 break;
1518 }
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001519 }
Trevor David Black02926f52024-01-04 18:44:20 +00001520 gralloc_usage_info.pNext = usage_info_pNext;
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001521
Trevor David Black02926f52024-01-04 18:44:20 +00001522 result = dispatch.GetSwapchainGrallocUsage4ANDROID(
1523 device, &gralloc_usage_info, &native_usage);
1524 ATRACE_END();
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001525 if (result != VK_SUCCESS) {
Trevor David Black02926f52024-01-04 18:44:20 +00001526 ALOGE("vkGetSwapchainGrallocUsage4ANDROID failed: %d", result);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001527 return VK_ERROR_SURFACE_LOST_KHR;
1528 }
Trevor David Black02926f52024-01-04 18:44:20 +00001529 } else if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
1530 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1531 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1532 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1533 gralloc_usage_info.format = create_info->imageFormat;
1534 gralloc_usage_info.imageUsage = create_info->imageUsage;
1535
1536 // Look through the pNext chain for an image compression control struct
1537 // if one is found AND the appropriate extensions are enabled,
1538 // append it to be the gralloc usage pNext chain
1539 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1540 while (create_infos->pNext) {
1541 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1542 create_infos->pNext);
1543 switch (create_infos->sType) {
1544 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1545 const VkImageCompressionControlEXT* compression_infos =
1546 reinterpret_cast<const VkImageCompressionControlEXT*>(
1547 create_infos);
1548 image_compression = *compression_infos;
1549 image_compression.pNext = nullptr;
1550 usage_info_pNext = &image_compression;
1551 } break;
1552
1553 default:
1554 // Ignore all other info structs
1555 break;
1556 }
1557 }
1558 gralloc_usage_info.pNext = usage_info_pNext;
1559
1560 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1561 device, &gralloc_usage_info, &native_usage);
1562 ATRACE_END();
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001563 if (result != VK_SUCCESS) {
Trevor David Black02926f52024-01-04 18:44:20 +00001564 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001565 return VK_ERROR_SURFACE_LOST_KHR;
1566 }
Trevor David Black02926f52024-01-04 18:44:20 +00001567 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
1568 uint64_t consumer_usage, producer_usage;
1569 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
1570 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1571 device, create_info->imageFormat, create_info->imageUsage,
1572 swapchain_image_usage, &consumer_usage, &producer_usage);
1573 ATRACE_END();
1574 if (result != VK_SUCCESS) {
1575 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
1576 return VK_ERROR_SURFACE_LOST_KHR;
1577 }
1578 native_usage =
1579 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
1580 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
1581 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
1582 int32_t legacy_usage = 0;
1583 result = dispatch.GetSwapchainGrallocUsageANDROID(
1584 device, create_info->imageFormat, create_info->imageUsage,
1585 &legacy_usage);
1586 ATRACE_END();
1587 if (result != VK_SUCCESS) {
1588 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
1589 return VK_ERROR_SURFACE_LOST_KHR;
1590 }
1591 native_usage = static_cast<uint64_t>(legacy_usage);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001592 }
Trevor David Black02926f52024-01-04 18:44:20 +00001593 *producer_usage = native_usage;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001594
1595 return VK_SUCCESS;
1596}
1597
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001598VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001599VkResult CreateSwapchainKHR(VkDevice device,
1600 const VkSwapchainCreateInfoKHR* create_info,
1601 const VkAllocationCallbacks* allocator,
1602 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001603 ATRACE_CALL();
1604
Jesse Halld7b994a2015-09-07 14:17:37 -07001605 int err;
1606 VkResult result = VK_SUCCESS;
1607
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001608 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1609 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1610 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1611 " oldSwapchain=0x%" PRIx64,
1612 reinterpret_cast<uint64_t>(create_info->surface),
1613 create_info->minImageCount, create_info->imageFormat,
1614 create_info->imageColorSpace, create_info->imageExtent.width,
1615 create_info->imageExtent.height, create_info->imageUsage,
1616 create_info->preTransform, create_info->presentMode,
1617 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1618
Jesse Hall1f91d392015-12-11 16:28:44 -08001619 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001620 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001621
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001622 PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001623 GetNativePixelFormat(create_info->imageFormat);
sergiuferentz47989332023-09-26 10:24:36 +00001624 DataSpace native_dataspace =
Sally Qiaa238972023-07-17 12:52:05 +08001625 GetNativeDataspace(create_info->imageColorSpace, native_pixel_format);
sergiuferentz47989332023-09-26 10:24:36 +00001626 if (native_dataspace == DataSpace::UNKNOWN) {
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001627 ALOGE(
1628 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1629 "failed: Unsupported color space",
1630 create_info->imageColorSpace);
1631 return VK_ERROR_INITIALIZATION_FAILED;
1632 }
1633
Jesse Hall42a9eec2016-06-03 12:39:49 -07001634 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001635 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001636 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001637 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001638 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001639 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001640 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001641 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001642 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1643 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001644 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001645 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001646
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001647 Surface& surface = *SurfaceFromHandle(create_info->surface);
1648
Jesse Halldc225072016-05-30 22:40:14 -07001649 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001650 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001651 " because it already has active swapchain 0x%" PRIx64
1652 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1653 reinterpret_cast<uint64_t>(create_info->surface),
1654 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1655 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1656 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1657 }
1658 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1659 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1660
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001661 // -- Reset the native window --
1662 // The native window might have been used previously, and had its properties
1663 // changed from defaults. That will affect the answer we get for queries
1664 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1665 // attempt such queries.
1666
Jesse Halldc225072016-05-30 22:40:14 -07001667 // The native window only allows dequeueing all buffers before any have
1668 // been queued, since after that point at least one is assumed to be in
1669 // non-FREE state at any given time. Disconnecting and re-connecting
1670 // orphans the previous buffers, getting us back to the state where we can
1671 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001672 //
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001673 // This is not necessary if the surface was never used previously.
1674 //
Yiwei Zhang70a21962019-05-31 17:26:52 -07001675 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001676 ANativeWindow* window = surface.window.get();
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001677 if (surface.used_by_swapchain) {
1678 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1679 ALOGW_IF(err != android::OK,
1680 "native_window_api_disconnect failed: %s (%d)", strerror(-err),
1681 err);
1682 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1683 ALOGW_IF(err != android::OK,
1684 "native_window_api_connect failed: %s (%d)", strerror(-err),
1685 err);
1686 }
Jesse Halldc225072016-05-30 22:40:14 -07001687
Nicolas Capens147b7da2021-04-09 14:53:06 -04001688 err =
1689 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001690 if (err != android::OK) {
1691 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1692 strerror(-err), err);
1693 return VK_ERROR_SURFACE_LOST_KHR;
1694 }
1695
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301696 int swap_interval =
1697 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001698 err = window->setSwapInterval(window, swap_interval);
1699 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001700 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1701 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001702 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001703 }
1704
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001705 err = native_window_set_shared_buffer_mode(window, false);
1706 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001707 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1708 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001709 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001710 }
1711
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001712 err = native_window_set_auto_refresh(window, false);
1713 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001714 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1715 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001716 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001717 }
1718
Jesse Halld7b994a2015-09-07 14:17:37 -07001719 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001720
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001721 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001722
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001723 err = native_window_set_buffers_format(
1724 window, static_cast<int>(native_pixel_format));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001725 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001726 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001727 toString(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001728 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001729 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001730
1731 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
sergiuferentz47989332023-09-26 10:24:36 +00001732 if (native_dataspace != DataSpace::ARBITRARY) {
1733 err = native_window_set_buffers_data_space(
1734 window, static_cast<android_dataspace_t>(native_dataspace));
Yiwei Zhang51572c22022-07-22 23:08:30 +00001735 if (err != android::OK) {
1736 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1737 native_dataspace, strerror(-err), err);
1738 return VK_ERROR_SURFACE_LOST_KHR;
1739 }
Jesse Hall517274a2016-02-10 00:07:18 -08001740 }
1741
Jesse Hall3dd678a2016-01-08 21:52:01 -08001742 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001743 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001744 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001745 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001746 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1747 create_info->imageExtent.width, create_info->imageExtent.height,
1748 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001749 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001750 }
1751
Jesse Hall178b6962016-02-24 15:39:50 -08001752 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1753 // applied during rendering. native_window_set_transform() expects the
1754 // inverse: the transform the app is requesting that the compositor perform
1755 // during composition. With native windows, pre-transform works by rendering
1756 // with the same transform the compositor is applying (as in Vulkan), but
1757 // then requesting the inverse transform, so that when the compositor does
1758 // it's job the two transforms cancel each other out and the compositor ends
1759 // up applying an identity transform to the app's buffer.
1760 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001761 window, InvertTransformToNative(create_info->preTransform));
1762 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001763 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1764 InvertTransformToNative(create_info->preTransform),
1765 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001766 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001767 }
1768
Jesse Hallf64ca122015-11-03 16:11:10 -08001769 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001770 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1771 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001772 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1773 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001774 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001775 }
1776
Chris Forbes97ef4612017-03-30 19:37:50 +13001777 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001778 if (IsSharedPresentMode(create_info->presentMode)) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001779 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001780 err = native_window_set_shared_buffer_mode(window, true);
1781 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001782 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1783 return VK_ERROR_SURFACE_LOST_KHR;
1784 }
1785 }
1786
1787 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001788 err = native_window_set_auto_refresh(window, true);
1789 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001790 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1791 return VK_ERROR_SURFACE_LOST_KHR;
1792 }
1793 }
1794
Ian Elliott16c443c2021-11-30 17:10:32 -07001795 int query_value;
Trevor David Blackabab5a02023-12-19 20:27:07 +00001796 // TODO: Now that we are calling into GPDSC2 directly, this query may be redundant
1797 // the call to std::max(min_buffer_count, num_images) may be redundant as well
Ian Elliott16c443c2021-11-30 17:10:32 -07001798 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1799 &query_value);
1800 if (err != android::OK || query_value < 0) {
1801 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1802 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001803 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001804 }
Trevor David Black8c0122e2023-09-07 20:33:54 +00001805 const uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
Chris Forbes2c8fc752017-03-17 11:28:32 +13001806
Ian Elliott5396b702021-12-13 19:32:34 -07001807 // Lower layer insists that we have at least min_undequeued_buffers + 1
1808 // buffers. This is wasteful and we'd like to relax it in the shared case,
1809 // but not all the pieces are in place for that to work yet. Note we only
1810 // lie to the lower layer--we don't want to give the app back a swapchain
1811 // with extra images (which they can't actually use!).
Trevor David Black8c0122e2023-09-07 20:33:54 +00001812 const uint32_t min_buffer_count = min_undequeued_buffers + 1;
1813
Trevor David Blackabab5a02023-12-19 20:27:07 +00001814 // Call into GPDSC2 to get the minimum and maximum allowable buffer count for the surface of
1815 // interest. This step is only necessary if the app requests a number of images
1816 // (create_info->minImageCount) that is less or more than the surface capabilities.
1817 // An app should be calling GPDSC2 and using those values to set create_info, but in the
1818 // event that the app has hard-coded image counts an error can occur
1819 VkSurfacePresentModeEXT present_mode = {
1820 VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT,
1821 nullptr,
1822 create_info->presentMode
1823 };
1824 VkPhysicalDeviceSurfaceInfo2KHR surface_info2 = {
1825 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
1826 &present_mode,
1827 create_info->surface
1828 };
1829 VkSurfaceCapabilities2KHR surface_capabilities2 = {
1830 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
1831 nullptr,
1832 {},
1833 };
1834 result = GetPhysicalDeviceSurfaceCapabilities2KHR(GetData(device).driver_physical_device,
1835 &surface_info2, &surface_capabilities2);
1836
1837 uint32_t num_images = create_info->minImageCount;
1838 num_images = std::clamp(num_images,
1839 surface_capabilities2.surfaceCapabilities.minImageCount,
1840 surface_capabilities2.surfaceCapabilities.maxImageCount);
Trevor David Black8c0122e2023-09-07 20:33:54 +00001841
1842 const uint32_t buffer_count = std::max(min_buffer_count, num_images);
1843 err = native_window_set_buffer_count(window, buffer_count);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001844 if (err != android::OK) {
Trevor David Black8c0122e2023-09-07 20:33:54 +00001845 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", buffer_count,
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001846 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001847 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001848 }
1849
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001850 // In shared mode the num_images must be one regardless of how many
1851 // buffers were allocated for the buffer queue.
1852 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1853 num_images = 1;
1854 }
1855
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001856 // Look through the create_info pNext chain passed to createSwapchainKHR
1857 // for an image compression control struct.
1858 // if one is found AND the appropriate extensions are enabled, create a
1859 // VkImageCompressionControlEXT structure to pass on to VkImageCreateInfo
1860 // TODO check for imageCompressionControlSwapchain feature is enabled
Trevor David Black2cc44682022-03-09 00:31:38 +00001861 void* usage_info_pNext = nullptr;
1862 VkImageCompressionControlEXT image_compression = {};
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001863 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1864 while (create_infos->pNext) {
1865 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(create_infos->pNext);
1866 switch (create_infos->sType) {
1867 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1868 const VkImageCompressionControlEXT* compression_infos =
1869 reinterpret_cast<const VkImageCompressionControlEXT*>(create_infos);
1870 image_compression = *compression_infos;
1871 image_compression.pNext = nullptr;
1872 usage_info_pNext = &image_compression;
1873 } break;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001874
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001875 default:
1876 // Ignore all other info structs
1877 break;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001878 }
Jesse Hall70f93352015-11-04 09:41:31 -08001879 }
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001880
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001881 // Get the appropriate native_usage for the images
1882 // Get the consumer usage
1883 uint64_t native_usage = surface.consumer_usage;
1884 // Determine if the swapchain is protected
1885 bool create_protected_swapchain = false;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001886 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001887 create_protected_swapchain = true;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001888 native_usage |= BufferUsage::PROTECTED;
1889 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001890 // Get the producer usage
1891 uint64_t producer_usage;
1892 result = getProducerUsage(device, create_info, swapchain_image_usage, create_protected_swapchain, &producer_usage);
1893 if (result != VK_SUCCESS) {
1894 return result;
1895 }
1896 native_usage |= producer_usage;
1897
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001898 err = native_window_set_usage(window, native_usage);
1899 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001900 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001901 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001902 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001903
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001904 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001905 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1906 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001907 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1908 strerror(-err), err);
1909 return VK_ERROR_SURFACE_LOST_KHR;
1910 }
1911
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001912 int64_t refresh_duration;
1913 err = native_window_get_refresh_cycle_duration(window, &refresh_duration);
1914 if (err != android::OK) {
1915 ALOGE("native_window_get_refresh_cycle_duration query failed: %s (%d)",
1916 strerror(-err), err);
1917 return VK_ERROR_SURFACE_LOST_KHR;
1918 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001919 // -- Allocate our Swapchain object --
1920 // After this point, we must deallocate the swapchain on error.
1921
Jesse Hall1f91d392015-12-11 16:28:44 -08001922 void* mem = allocator->pfnAllocation(allocator->pUserData,
1923 sizeof(Swapchain), alignof(Swapchain),
1924 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001925
Jesse Hall1356b0d2015-11-23 17:24:58 -08001926 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001927 return VK_ERROR_OUT_OF_HOST_MEMORY;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001928
silence_dogood73597592019-05-23 16:57:37 -07001929 Swapchain* swapchain = new (mem)
1930 Swapchain(surface, num_images, create_info->presentMode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001931 TranslateVulkanToNativeTransform(create_info->preTransform),
1932 refresh_duration);
Chris Forbesb56287a2017-01-12 14:28:58 +13001933 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1934#pragma clang diagnostic push
1935#pragma clang diagnostic ignored "-Wold-style-cast"
1936 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1937#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00001938 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13001939 .usage = swapchain_image_usage,
1940 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001941 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001942#pragma clang diagnostic push
1943#pragma clang diagnostic ignored "-Wold-style-cast"
1944 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1945#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001946 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001947 };
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001948
Jesse Halld7b994a2015-09-07 14:17:37 -07001949 VkImageCreateInfo image_create = {
1950 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001951 .pNext = nullptr,
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001952 .flags = create_protected_swapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07001953 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08001954 .format = create_info->imageFormat,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001955 .extent = {
1956 create_info->imageExtent.width,
1957 create_info->imageExtent.height,
1958 1
1959 },
Jesse Halld7b994a2015-09-07 14:17:37 -07001960 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08001961 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08001962 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07001963 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001964 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001965 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08001966 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07001967 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1968 };
1969
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001970 // Note: don't do deferred allocation for shared present modes. There's only one buffer
1971 // involved so very little benefit.
1972 if ((create_info->flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT) &&
1973 !IsSharedPresentMode(create_info->presentMode)) {
1974 // Don't want to touch the underlying gralloc buffers yet;
1975 // instead just create unbound VkImages which will later be bound to memory inside
1976 // AcquireNextImage.
1977 VkImageSwapchainCreateInfoKHR image_swapchain_create = {
1978 .sType = VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR,
1979 .pNext = nullptr,
1980 .swapchain = HandleFromSwapchain(swapchain),
1981 };
1982 image_create.pNext = &image_swapchain_create;
Jesse Halld7b994a2015-09-07 14:17:37 -07001983
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001984 for (uint32_t i = 0; i < num_images; i++) {
1985 Swapchain::Image& img = swapchain->images[i];
1986 img.buffer = nullptr;
1987 img.dequeued = false;
1988
1989 result = dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1990 if (result != VK_SUCCESS) {
1991 ALOGD("vkCreateImage w/ for deferred swapchain image failed: %u", result);
1992 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08001993 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001994 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001995 } else {
1996 // -- Dequeue all buffers and create a VkImage for each --
1997 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07001998
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001999 for (uint32_t i = 0; i < num_images; i++) {
2000 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07002001
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002002 ANativeWindowBuffer* buffer;
2003 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
2004 if (err != android::OK) {
2005 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
2006 switch (-err) {
2007 case ENOMEM:
2008 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
2009 break;
2010 default:
2011 result = VK_ERROR_SURFACE_LOST_KHR;
2012 break;
2013 }
2014 break;
2015 }
2016 img.buffer = buffer;
2017 img.dequeued = true;
2018
2019 image_native_buffer.handle = img.buffer->handle;
2020 image_native_buffer.stride = img.buffer->stride;
2021 image_native_buffer.format = img.buffer->format;
2022 image_native_buffer.usage = int(img.buffer->usage);
2023 android_convertGralloc0To1Usage(int(img.buffer->usage),
2024 &image_native_buffer.usage2.producer,
2025 &image_native_buffer.usage2.consumer);
2026 image_native_buffer.usage3 = img.buffer->usage;
Trevor David Black0db7a092023-12-11 23:46:36 +00002027 image_native_buffer.ahb =
2028 ANativeWindowBuffer_getHardwareBuffer(img.buffer.get());
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002029 image_create.pNext = &image_native_buffer;
2030
2031 ATRACE_BEGIN("CreateImage");
2032 result =
2033 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
2034 ATRACE_END();
2035 if (result != VK_SUCCESS) {
2036 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
2037 break;
2038 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002039 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002040
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002041 // -- Cancel all buffers, returning them to the queue --
2042 // If an error occurred before, also destroy the VkImage and release the
2043 // buffer reference. Otherwise, we retain a strong reference to the buffer.
2044 for (uint32_t i = 0; i < num_images; i++) {
2045 Swapchain::Image& img = swapchain->images[i];
2046 if (img.dequeued) {
2047 if (!swapchain->shared) {
2048 window->cancelBuffer(window, img.buffer.get(),
2049 img.dequeue_fence);
2050 img.dequeue_fence = -1;
2051 img.dequeued = false;
2052 }
Chris Forbese0ced032017-03-30 19:44:15 +13002053 }
Chris Forbes31b85c22018-05-29 15:03:28 -07002054 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002055 }
2056
2057 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07002058 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
2059 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07002060 return result;
2061 }
2062
Yiwei Zhang69395cd2019-07-03 16:55:39 -07002063 if (transform_hint != swapchain->pre_transform) {
2064 // Log that the app is not doing pre-rotation.
2065 android::GraphicsEnv::getInstance().setTargetStats(
2066 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
2067 }
2068
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00002069 // Set stats for creating a Vulkan swapchain
2070 android::GraphicsEnv::getInstance().setTargetStats(
2071 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
2072
Yiwei Zhang3b88f312023-04-18 23:11:35 +00002073 surface.used_by_swapchain = true;
Jesse Halldc225072016-05-30 22:40:14 -07002074 surface.swapchain_handle = HandleFromSwapchain(swapchain);
2075 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002076 return VK_SUCCESS;
2077}
2078
Jesse Halle1b12782015-11-30 11:27:32 -08002079VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002080void DestroySwapchainKHR(VkDevice device,
2081 VkSwapchainKHR swapchain_handle,
2082 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002083 ATRACE_CALL();
2084
Yiwei Zhang533cea92019-06-03 18:43:24 -07002085 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07002086}
2087
Jesse Halle1b12782015-11-30 11:27:32 -08002088VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002089VkResult GetSwapchainImagesKHR(VkDevice,
2090 VkSwapchainKHR swapchain_handle,
2091 uint32_t* count,
2092 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002093 ATRACE_CALL();
2094
Jesse Halld7b994a2015-09-07 14:17:37 -07002095 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07002096 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
2097 "getting images for non-active swapchain 0x%" PRIx64
2098 "; only dequeued image handles are valid",
2099 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07002100 VkResult result = VK_SUCCESS;
2101 if (images) {
2102 uint32_t n = swapchain.num_images;
2103 if (*count < swapchain.num_images) {
2104 n = *count;
2105 result = VK_INCOMPLETE;
2106 }
2107 for (uint32_t i = 0; i < n; i++)
2108 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07002109 *count = n;
2110 } else {
2111 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07002112 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002113 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002114}
2115
Jesse Halle1b12782015-11-30 11:27:32 -08002116VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002117VkResult AcquireNextImageKHR(VkDevice device,
2118 VkSwapchainKHR swapchain_handle,
2119 uint64_t timeout,
2120 VkSemaphore semaphore,
2121 VkFence vk_fence,
2122 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002123 ATRACE_CALL();
2124
Jesse Halld7b994a2015-09-07 14:17:37 -07002125 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08002126 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07002127 VkResult result;
2128 int err;
2129
Jesse Halldc225072016-05-30 22:40:14 -07002130 if (swapchain.surface.swapchain_handle != swapchain_handle)
2131 return VK_ERROR_OUT_OF_DATE_KHR;
2132
Chris Forbesc88409c2017-03-30 19:47:37 +13002133 if (swapchain.shared) {
2134 // In shared mode, we keep the buffer dequeued all the time, so we don't
2135 // want to dequeue a buffer here. Instead, just ask the driver to ensure
2136 // the semaphore and fence passed to us will be signalled.
2137 *image_index = 0;
2138 result = GetData(device).driver.AcquireImageANDROID(
2139 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
2140 return result;
2141 }
2142
Yiwei Zhang705c2e62019-12-18 23:12:43 -08002143 const nsecs_t acquire_next_image_timeout =
2144 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
2145 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
2146 // Cache the timeout to avoid the duplicate binder cost.
2147 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
2148 acquire_next_image_timeout);
2149 if (err != android::OK) {
2150 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
2151 strerror(-err), err);
2152 return VK_ERROR_SURFACE_LOST_KHR;
2153 }
2154 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
2155 }
2156
Jesse Halld7b994a2015-09-07 14:17:37 -07002157 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08002158 int fence_fd;
2159 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07002160 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08002161 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
2162 return timeout ? VK_TIMEOUT : VK_NOT_READY;
2163 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07002164 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07002165 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002166 }
2167
2168 uint32_t idx;
2169 for (idx = 0; idx < swapchain.num_images; idx++) {
2170 if (swapchain.images[idx].buffer.get() == buffer) {
2171 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08002172 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07002173 break;
2174 }
2175 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002176
2177 // If this is a deferred alloc swapchain, this may be the first time we've
2178 // seen a particular buffer. If so, there should be an empty slot. Find it,
2179 // and bind the gralloc buffer to the VkImage for that slot. If there is no
2180 // empty slot, then we dequeued an unexpected buffer. Non-deferred swapchains
2181 // will also take this path, but will never have an empty slot since we
2182 // populated them all upfront.
2183 if (idx == swapchain.num_images) {
2184 for (idx = 0; idx < swapchain.num_images; idx++) {
2185 if (!swapchain.images[idx].buffer) {
2186 // Note: this structure is technically required for
2187 // Vulkan correctness, even though the driver is probably going
2188 // to use everything from the VkNativeBufferANDROID below.
2189 // This is kindof silly, but it's how we did the ANB
2190 // side of VK_KHR_swapchain v69, so we're stuck with it unless
2191 // we want to go tinkering with the ANB spec some more.
2192 VkBindImageMemorySwapchainInfoKHR bimsi = {
2193 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR,
2194 .pNext = nullptr,
2195 .swapchain = swapchain_handle,
2196 .imageIndex = idx,
2197 };
2198 VkNativeBufferANDROID nb = {
2199 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2200 .pNext = &bimsi,
2201 .handle = buffer->handle,
2202 .stride = buffer->stride,
2203 .format = buffer->format,
2204 .usage = int(buffer->usage),
Trevor David Black0db7a092023-12-11 23:46:36 +00002205 .usage3 = buffer->usage,
2206 .ahb = ANativeWindowBuffer_getHardwareBuffer(buffer),
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002207 };
Trevor David Black0db7a092023-12-11 23:46:36 +00002208 android_convertGralloc0To1Usage(int(buffer->usage),
2209 &nb.usage2.producer,
2210 &nb.usage2.consumer);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002211 VkBindImageMemoryInfo bimi = {
2212 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO,
2213 .pNext = &nb,
2214 .image = swapchain.images[idx].image,
2215 .memory = VK_NULL_HANDLE,
2216 .memoryOffset = 0,
2217 };
2218 result = GetData(device).driver.BindImageMemory2(device, 1, &bimi);
2219 if (result != VK_SUCCESS) {
2220 // This shouldn't really happen. If it does, something is probably
2221 // unrecoverably wrong with the swapchain and its images. Cancel
2222 // the buffer and declare the swapchain broken.
2223 ALOGE("failed to do deferred gralloc buffer bind");
2224 window->cancelBuffer(window, buffer, fence_fd);
2225 return VK_ERROR_OUT_OF_DATE_KHR;
2226 }
2227
2228 swapchain.images[idx].dequeued = true;
2229 swapchain.images[idx].dequeue_fence = fence_fd;
2230 swapchain.images[idx].buffer = buffer;
2231 break;
2232 }
2233 }
2234 }
2235
2236 // The buffer doesn't match any slot. This shouldn't normally happen, but is
2237 // possible if the bufferqueue is reconfigured behind libvulkan's back. If this
2238 // happens, just declare the swapchain to be broken and the app will recreate it.
Jesse Halld7b994a2015-09-07 14:17:37 -07002239 if (idx == swapchain.num_images) {
2240 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08002241 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002242 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002243 }
2244
2245 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08002246 if (fence_fd != -1) {
2247 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002248 if (fence_clone == -1) {
2249 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
2250 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08002251 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07002252 }
2253 }
2254
Chia-I Wu4a6a9162016-03-26 07:17:34 +08002255 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08002256 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07002257 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08002258 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
2259 // even if the call fails. We could close it ourselves on failure, but
2260 // that would create a race condition if the driver closes it on a
2261 // failure path: some other thread might create an fd with the same
2262 // number between the time the driver closes it and the time we close
2263 // it. We must assume one of: the driver *always* closes it even on
2264 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08002265 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002266 swapchain.images[idx].dequeued = false;
2267 swapchain.images[idx].dequeue_fence = -1;
2268 return result;
2269 }
2270
2271 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002272 return VK_SUCCESS;
2273}
2274
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002275VKAPI_ATTR
2276VkResult AcquireNextImage2KHR(VkDevice device,
2277 const VkAcquireNextImageInfoKHR* pAcquireInfo,
2278 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002279 ATRACE_CALL();
2280
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002281 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
2282 pAcquireInfo->timeout, pAcquireInfo->semaphore,
2283 pAcquireInfo->fence, pImageIndex);
2284}
2285
Jesse Halldc225072016-05-30 22:40:14 -07002286static VkResult WorstPresentResult(VkResult a, VkResult b) {
2287 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
2288 // (in spec version 1.0.14).
2289 static const VkResult kWorstToBest[] = {
2290 VK_ERROR_DEVICE_LOST,
2291 VK_ERROR_SURFACE_LOST_KHR,
2292 VK_ERROR_OUT_OF_DATE_KHR,
2293 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2294 VK_ERROR_OUT_OF_HOST_MEMORY,
2295 VK_SUBOPTIMAL_KHR,
2296 };
2297 for (auto result : kWorstToBest) {
2298 if (a == result || b == result)
2299 return result;
2300 }
2301 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
2302 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
2303 return a != VK_SUCCESS ? a : b;
2304}
2305
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002306// KHR_incremental_present aspect of QueuePresentKHR
2307static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
2308 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
2309 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
2310 auto const& rect = pRegion->pRectangles[i];
2311 if (rect.layer > 0) {
2312 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
2313 rect.layer);
2314 }
2315
2316 rects[i].left = rect.offset.x;
2317 rects[i].bottom = rect.offset.y;
2318 rects[i].right = rect.offset.x + rect.extent.width;
2319 rects[i].top = rect.offset.y + rect.extent.height;
2320 }
2321 native_window_set_surface_damage(window, rects.data(), rects.size());
2322}
2323
2324// GOOGLE_display_timing aspect of QueuePresentKHR
2325static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
2326 ANativeWindow *window = swapchain.surface.window.get();
2327
2328 // We don't know whether the app will actually use GOOGLE_display_timing
2329 // with a particular swapchain until QueuePresent; enable it on the BQ
2330 // now if needed
2331 if (!swapchain.frame_timestamps_enabled) {
2332 ALOGV("Calling native_window_enable_frame_timestamps(true)");
2333 native_window_enable_frame_timestamps(window, true);
2334 swapchain.frame_timestamps_enabled = true;
2335 }
2336
2337 // Record the nativeFrameId so it can be later correlated to
2338 // this present.
2339 uint64_t nativeFrameId = 0;
2340 int err = native_window_get_next_frame_id(
2341 window, &nativeFrameId);
2342 if (err != android::OK) {
2343 ALOGE("Failed to get next native frame ID.");
2344 }
2345
2346 // Add a new timing record with the user's presentID and
2347 // the nativeFrameId.
2348 swapchain.timing.emplace_back(pTime, nativeFrameId);
2349 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
2350 swapchain.timing.erase(
2351 swapchain.timing.begin(),
2352 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
2353 }
2354 if (pTime->desiredPresentTime) {
2355 ALOGV(
2356 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
2357 pTime->desiredPresentTime);
2358 native_window_set_buffers_timestamp(
2359 window,
2360 static_cast<int64_t>(pTime->desiredPresentTime));
2361 }
2362}
2363
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002364// EXT_swapchain_maintenance1 present mode change
2365static bool SetSwapchainPresentMode(ANativeWindow *window, VkPresentModeKHR mode) {
2366 // There is no dynamic switching between non-shared present modes.
2367 // All we support is switching between demand and continuous refresh.
2368 if (!IsSharedPresentMode(mode))
2369 return true;
2370
2371 int err = native_window_set_auto_refresh(window,
2372 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
2373 if (err != android::OK) {
2374 ALOGE("native_window_set_auto_refresh() failed: %s (%d)",
2375 strerror(-err), err);
2376 return false;
2377 }
2378
2379 return true;
2380}
2381
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002382static VkResult PresentOneSwapchain(
2383 VkQueue queue,
2384 Swapchain& swapchain,
2385 uint32_t imageIndex,
2386 const VkPresentRegionKHR *pRegion,
2387 const VkPresentTimeGOOGLE *pTime,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002388 VkFence presentFence,
2389 const VkPresentModeKHR *pPresentMode,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002390 uint32_t waitSemaphoreCount,
2391 const VkSemaphore *pWaitSemaphores) {
2392
2393 VkDevice device = GetData(queue).driver_device;
2394 const auto& dispatch = GetData(queue).driver;
2395
2396 Swapchain::Image& img = swapchain.images[imageIndex];
2397 VkResult swapchain_result = VK_SUCCESS;
2398 VkResult result;
2399 int err;
2400
2401 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
2402 // wait semaphores, so this doesn't actually work for the multiple swapchain
2403 // case.
2404 int fence = -1;
2405 result = dispatch.QueueSignalReleaseImageANDROID(
2406 queue, waitSemaphoreCount,
2407 pWaitSemaphores, img.image, &fence);
2408 if (result != VK_SUCCESS) {
2409 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
2410 swapchain_result = result;
2411 }
2412 if (img.release_fence >= 0)
2413 close(img.release_fence);
2414 img.release_fence = fence < 0 ? -1 : dup(fence);
2415
2416 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
2417 ANativeWindow* window = swapchain.surface.window.get();
2418 if (swapchain_result == VK_SUCCESS) {
2419
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002420 if (presentFence != VK_NULL_HANDLE) {
2421 int fence_copy = fence < 0 ? -1 : dup(fence);
2422 VkImportFenceFdInfoKHR iffi = {
2423 VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,
2424 nullptr,
2425 presentFence,
2426 VK_FENCE_IMPORT_TEMPORARY_BIT,
2427 VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,
2428 fence_copy,
2429 };
2430 if (VK_SUCCESS != dispatch.ImportFenceFdKHR(device, &iffi) && fence_copy >= 0) {
2431 // ImportFenceFdKHR takes ownership only if it succeeds
2432 close(fence_copy);
2433 }
2434 }
2435
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002436 if (pRegion) {
2437 SetSwapchainSurfaceDamage(window, pRegion);
2438 }
2439 if (pTime) {
2440 SetSwapchainFrameTimestamp(swapchain, pTime);
2441 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002442 if (pPresentMode) {
2443 if (!SetSwapchainPresentMode(window, *pPresentMode))
2444 swapchain_result = WorstPresentResult(swapchain_result,
2445 VK_ERROR_SURFACE_LOST_KHR);
2446 }
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002447
2448 err = window->queueBuffer(window, img.buffer.get(), fence);
2449 // queueBuffer always closes fence, even on error
2450 if (err != android::OK) {
2451 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
2452 swapchain_result = WorstPresentResult(
2453 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2454 } else {
2455 if (img.dequeue_fence >= 0) {
2456 close(img.dequeue_fence);
2457 img.dequeue_fence = -1;
2458 }
2459 img.dequeued = false;
2460 }
2461
2462 // If the swapchain is in shared mode, immediately dequeue the
2463 // buffer so it can be presented again without an intervening
2464 // call to AcquireNextImageKHR. We expect to get the same buffer
2465 // back from every call to dequeueBuffer in this mode.
2466 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
2467 ANativeWindowBuffer* buffer;
2468 int fence_fd;
2469 err = window->dequeueBuffer(window, &buffer, &fence_fd);
2470 if (err != android::OK) {
2471 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
2472 swapchain_result = WorstPresentResult(swapchain_result,
2473 VK_ERROR_SURFACE_LOST_KHR);
2474 } else if (img.buffer != buffer) {
2475 ALOGE("got wrong image back for shared swapchain");
2476 swapchain_result = WorstPresentResult(swapchain_result,
2477 VK_ERROR_SURFACE_LOST_KHR);
2478 } else {
2479 img.dequeue_fence = fence_fd;
2480 img.dequeued = true;
2481 }
2482 }
2483 }
2484 if (swapchain_result != VK_SUCCESS) {
2485 OrphanSwapchain(device, &swapchain);
2486 }
2487 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
2488 // and only when the window's transform/rotation changes. Extent
2489 // changes will not cause VK_SUBOPTIMAL_KHR because of the
2490 // application issues that were caused when the following transform
2491 // change was added.
2492 int window_transform_hint;
2493 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
2494 &window_transform_hint);
2495 if (err != android::OK) {
2496 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
2497 strerror(-err), err);
2498 swapchain_result = WorstPresentResult(
2499 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2500 }
2501 if (swapchain.pre_transform != window_transform_hint) {
2502 swapchain_result =
2503 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
2504 }
2505 } else {
2506 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
2507 img, true);
2508 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
2509 }
2510
2511 return swapchain_result;
2512}
2513
Jesse Halle1b12782015-11-30 11:27:32 -08002514VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002515VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002516 ATRACE_CALL();
2517
Jesse Halld7b994a2015-09-07 14:17:37 -07002518 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
2519 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
2520 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07002521
Jesse Halld7b994a2015-09-07 14:17:37 -07002522 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07002523
Ian Elliottcb351132016-12-13 10:30:40 -07002524 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002525 const VkPresentRegionsKHR* present_regions = nullptr;
2526 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002527 const VkSwapchainPresentFenceInfoEXT* present_fences = nullptr;
2528 const VkSwapchainPresentModeInfoEXT* present_modes = nullptr;
2529
Ian Elliottcb351132016-12-13 10:30:40 -07002530 const VkPresentRegionsKHR* next =
2531 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
2532 while (next) {
2533 switch (next->sType) {
2534 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
2535 present_regions = next;
2536 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07002537 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002538 present_times =
2539 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
2540 break;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002541 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT:
2542 present_fences =
2543 reinterpret_cast<const VkSwapchainPresentFenceInfoEXT*>(next);
2544 break;
2545 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT:
2546 present_modes =
2547 reinterpret_cast<const VkSwapchainPresentModeInfoEXT*>(next);
2548 break;
Ian Elliottcb351132016-12-13 10:30:40 -07002549 default:
2550 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
2551 next->sType);
2552 break;
2553 }
2554 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2555 }
2556 ALOGV_IF(
2557 present_regions &&
2558 present_regions->swapchainCount != present_info->swapchainCount,
2559 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002560 ALOGV_IF(present_times &&
2561 present_times->swapchainCount != present_info->swapchainCount,
2562 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2563 "VkPresentInfo::swapchainCount");
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002564 ALOGV_IF(present_fences &&
2565 present_fences->swapchainCount != present_info->swapchainCount,
2566 "VkSwapchainPresentFenceInfoEXT::swapchainCount != "
2567 "VkPresentInfo::swapchainCount");
2568 ALOGV_IF(present_modes &&
2569 present_modes->swapchainCount != present_info->swapchainCount,
2570 "VkSwapchainPresentModeInfoEXT::swapchainCount != "
2571 "VkPresentInfo::swapchainCount");
2572
Ian Elliottcb351132016-12-13 10:30:40 -07002573 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002574 (present_regions) ? present_regions->pRegions : nullptr;
2575 const VkPresentTimeGOOGLE* times =
2576 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002577
Jesse Halld7b994a2015-09-07 14:17:37 -07002578 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2579 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002580 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002581
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002582 VkResult swapchain_result = PresentOneSwapchain(
2583 queue,
2584 swapchain,
2585 present_info->pImageIndices[sc],
2586 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2587 times ? &times[sc] : nullptr,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002588 present_fences ? present_fences->pFences[sc] : VK_NULL_HANDLE,
2589 present_modes ? &present_modes->pPresentModes[sc] : nullptr,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002590 present_info->waitSemaphoreCount,
2591 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002592
Jesse Halla9e57032015-11-30 01:03:10 -08002593 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002594 present_info->pResults[sc] = swapchain_result;
2595
2596 if (swapchain_result != final_result)
2597 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002598 }
2599
2600 return final_result;
2601}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002602
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002603VKAPI_ATTR
2604VkResult GetRefreshCycleDurationGOOGLE(
2605 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002606 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002607 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002608 ATRACE_CALL();
2609
Ian Elliott62c48c92017-01-20 13:13:20 -07002610 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00002611 VkResult result = swapchain.get_refresh_duration(pDisplayTimingProperties->refreshDuration);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002612
2613 return result;
2614}
2615
2616VKAPI_ATTR
2617VkResult GetPastPresentationTimingGOOGLE(
2618 VkDevice,
2619 VkSwapchainKHR swapchain_handle,
2620 uint32_t* count,
2621 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002622 ATRACE_CALL();
2623
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002624 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002625 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2626 return VK_ERROR_OUT_OF_DATE_KHR;
2627 }
2628
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002629 ANativeWindow* window = swapchain.surface.window.get();
2630 VkResult result = VK_SUCCESS;
2631
2632 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002633 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002634 native_window_enable_frame_timestamps(window, true);
2635 swapchain.frame_timestamps_enabled = true;
2636 }
2637
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002638 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002639 // Get the latest ready timing count before copying, since the copied
2640 // timing info will be erased in copy_ready_timings function.
2641 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002642 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002643 // Check the *count here against the recorded ready timing count, since
2644 // *count can be overwritten per spec describes.
2645 if (*count < n) {
2646 result = VK_INCOMPLETE;
2647 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002648 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002649 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002650 }
2651
2652 return result;
2653}
2654
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002655VKAPI_ATTR
2656VkResult GetSwapchainStatusKHR(
2657 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002658 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002659 ATRACE_CALL();
2660
Chris Forbes4e18ba82017-01-20 12:50:17 +13002661 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002662 VkResult result = VK_SUCCESS;
2663
Chris Forbes4e18ba82017-01-20 12:50:17 +13002664 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2665 return VK_ERROR_OUT_OF_DATE_KHR;
2666 }
2667
Yiwei Zhanga885c062019-10-24 12:07:57 -07002668 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002669
2670 return result;
2671}
2672
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002673VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002674 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002675 uint32_t swapchainCount,
2676 const VkSwapchainKHR* pSwapchains,
2677 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002678 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002679
2680 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2681 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2682 if (!swapchain)
2683 continue;
2684
2685 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2686
2687 ANativeWindow* window = swapchain->surface.window.get();
2688
2689 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2690 const android_smpte2086_metadata smpteMetdata = {
2691 {vulkanMetadata.displayPrimaryRed.x,
2692 vulkanMetadata.displayPrimaryRed.y},
2693 {vulkanMetadata.displayPrimaryGreen.x,
2694 vulkanMetadata.displayPrimaryGreen.y},
2695 {vulkanMetadata.displayPrimaryBlue.x,
2696 vulkanMetadata.displayPrimaryBlue.y},
2697 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2698 vulkanMetadata.maxLuminance,
2699 vulkanMetadata.minLuminance};
2700 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2701
2702 const android_cta861_3_metadata cta8613Metadata = {
2703 vulkanMetadata.maxContentLightLevel,
2704 vulkanMetadata.maxFrameAverageLightLevel};
2705 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2706 }
2707
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002708 return;
2709}
2710
Yiwei Zhang0f475222019-04-11 19:38:00 -07002711static void InterceptBindImageMemory2(
2712 uint32_t bind_info_count,
2713 const VkBindImageMemoryInfo* bind_infos,
2714 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2715 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2716 out_native_buffers->clear();
2717 out_bind_infos->clear();
2718
2719 if (!bind_info_count)
2720 return;
2721
2722 std::unordered_set<uint32_t> intercepted_indexes;
2723
2724 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2725 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2726 bind_infos[idx].pNext);
2727 while (info &&
2728 info->sType !=
2729 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2730 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2731 info->pNext);
2732 }
2733
2734 if (!info)
2735 continue;
2736
2737 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2738 "swapchain handle must not be NULL");
2739 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2740 ALOG_ASSERT(
2741 info->imageIndex < swapchain->num_images,
2742 "imageIndex must be less than the number of images in swapchain");
2743
2744 ANativeWindowBuffer* buffer =
2745 swapchain->images[info->imageIndex].buffer.get();
2746 VkNativeBufferANDROID native_buffer = {
2747#pragma clang diagnostic push
2748#pragma clang diagnostic ignored "-Wold-style-cast"
2749 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2750#pragma clang diagnostic pop
2751 .pNext = bind_infos[idx].pNext,
2752 .handle = buffer->handle,
2753 .stride = buffer->stride,
2754 .format = buffer->format,
2755 .usage = int(buffer->usage),
Trevor David Black0db7a092023-12-11 23:46:36 +00002756 .usage3 = buffer->usage,
2757 .ahb = ANativeWindowBuffer_getHardwareBuffer(buffer),
Yiwei Zhang0f475222019-04-11 19:38:00 -07002758 };
Trevor David Black0db7a092023-12-11 23:46:36 +00002759 android_convertGralloc0To1Usage(int(buffer->usage),
2760 &native_buffer.usage2.producer,
2761 &native_buffer.usage2.consumer);
Yiwei Zhang0f475222019-04-11 19:38:00 -07002762 // Reserve enough space to avoid letting re-allocation invalidate the
2763 // addresses of the elements inside.
2764 out_native_buffers->reserve(bind_info_count);
2765 out_native_buffers->emplace_back(native_buffer);
2766
2767 // Reserve the space now since we know how much is needed now.
2768 out_bind_infos->reserve(bind_info_count);
2769 out_bind_infos->emplace_back(bind_infos[idx]);
2770 out_bind_infos->back().pNext = &out_native_buffers->back();
2771
2772 intercepted_indexes.insert(idx);
2773 }
2774
2775 if (intercepted_indexes.empty())
2776 return;
2777
2778 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2779 if (intercepted_indexes.count(idx))
2780 continue;
2781 out_bind_infos->emplace_back(bind_infos[idx]);
2782 }
2783}
2784
Yiwei Zhang23143102019-04-10 18:24:05 -07002785VKAPI_ATTR
2786VkResult BindImageMemory2(VkDevice device,
2787 uint32_t bindInfoCount,
2788 const VkBindImageMemoryInfo* pBindInfos) {
2789 ATRACE_CALL();
2790
Yiwei Zhang0f475222019-04-11 19:38:00 -07002791 // out_native_buffers is for maintaining the lifecycle of the constructed
2792 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2793 std::vector<VkNativeBufferANDROID> out_native_buffers;
2794 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2795 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2796 &out_bind_infos);
2797 return GetData(device).driver.BindImageMemory2(
2798 device, bindInfoCount,
2799 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002800}
2801
2802VKAPI_ATTR
2803VkResult BindImageMemory2KHR(VkDevice device,
2804 uint32_t bindInfoCount,
2805 const VkBindImageMemoryInfo* pBindInfos) {
2806 ATRACE_CALL();
2807
Yiwei Zhang0f475222019-04-11 19:38:00 -07002808 std::vector<VkNativeBufferANDROID> out_native_buffers;
2809 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2810 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2811 &out_bind_infos);
2812 return GetData(device).driver.BindImageMemory2KHR(
2813 device, bindInfoCount,
2814 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002815}
2816
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002817VKAPI_ATTR
2818VkResult ReleaseSwapchainImagesEXT(VkDevice /*device*/,
2819 const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
2820 ATRACE_CALL();
2821
2822 Swapchain& swapchain = *SwapchainFromHandle(pReleaseInfo->swapchain);
2823 ANativeWindow* window = swapchain.surface.window.get();
2824
2825 // If in shared present mode, don't actually release the image back to the BQ.
2826 // Both sides share it forever.
2827 if (swapchain.shared)
2828 return VK_SUCCESS;
2829
2830 for (uint32_t i = 0; i < pReleaseInfo->imageIndexCount; i++) {
2831 Swapchain::Image& img = swapchain.images[pReleaseInfo->pImageIndices[i]];
2832 window->cancelBuffer(window, img.buffer.get(), img.dequeue_fence);
2833
2834 // cancelBuffer has taken ownership of the dequeue fence
2835 img.dequeue_fence = -1;
2836 // if we're still holding a release fence, get rid of it now
2837 if (img.release_fence >= 0) {
2838 close(img.release_fence);
2839 img.release_fence = -1;
2840 }
2841 img.dequeued = false;
2842 }
2843
2844 return VK_SUCCESS;
2845}
2846
Chia-I Wu62262232016-03-26 07:06:44 +08002847} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002848} // namespace vulkan