blob: 892cd19f2f2b6a4f3ed0e8cb0238950e1ed8decb [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
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080017#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
sergiuferentz47989332023-09-26 10:24:36 +000019#include <aidl/android/hardware/graphics/common/Dataspace.h>
Trevor David Blackf499b5a2023-07-14 17:30:41 +000020#include <aidl/android/hardware/graphics/common/PixelFormat.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070021#include <android/hardware/graphics/common/1.0/types.h>
Trevor David Blackd7320ef2023-08-23 21:21:51 +000022#include <android/hardware_buffer.h>
Jesse Hall79927812017-03-23 11:03:23 -070023#include <grallocusage/GrallocUsageConversion.h>
Yiwei Zhang69395cd2019-07-03 16:55:39 -070024#include <graphicsenv/GraphicsEnv.h>
John Reck97678d42022-08-23 11:24:51 -040025#include <hardware/gralloc.h>
26#include <hardware/gralloc1.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070027#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070028#include <sync/sync.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070029#include <system/window.h>
30#include <ui/BufferQueueDefs.h>
Chia-I Wue8e689f2016-04-18 08:21:31 +080031#include <utils/StrongPointer.h>
Yiwei Zhang705c2e62019-12-18 23:12:43 -080032#include <utils/Timers.h>
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080033#include <utils/Trace.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070034
35#include <algorithm>
36#include <unordered_set>
37#include <vector>
Jesse Halld7b994a2015-09-07 14:17:37 -070038
Chia-I Wu4a6a9162016-03-26 07:17:34 +080039#include "driver.h"
Jesse Halld7b994a2015-09-07 14:17:37 -070040
Trevor David Blackf499b5a2023-07-14 17:30:41 +000041using PixelFormat = aidl::android::hardware::graphics::common::PixelFormat;
sergiuferentz47989332023-09-26 10:24:36 +000042using DataSpace = aidl::android::hardware::graphics::common::Dataspace;
Daniel Kochf25f5bb2017-10-05 00:26:58 -040043using android::hardware::graphics::common::V1_0::BufferUsage;
44
Chia-I Wu62262232016-03-26 07:06:44 +080045namespace vulkan {
46namespace driver {
Jesse Hall5ae3abb2015-10-08 14:00:22 -070047
Jesse Halld7b994a2015-09-07 14:17:37 -070048namespace {
49
John Reck97678d42022-08-23 11:24:51 -040050static uint64_t convertGralloc1ToBufferUsage(uint64_t producerUsage,
51 uint64_t consumerUsage) {
52 static_assert(uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) ==
53 uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN),
54 "expected ConsumerUsage and ProducerUsage CPU_READ_OFTEN "
55 "bits to match");
56 uint64_t merged = producerUsage | consumerUsage;
57 if ((merged & (GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN)) ==
58 GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) {
59 merged &= ~uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN);
60 merged |= BufferUsage::CPU_READ_OFTEN;
61 }
62 if ((merged & (GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN)) ==
63 GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) {
64 merged &= ~uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN);
65 merged |= BufferUsage::CPU_WRITE_OFTEN;
66 }
67 return merged;
68}
69
Jesse Hall55bc0972016-02-23 16:43:29 -080070const VkSurfaceTransformFlagsKHR kSupportedTransforms =
71 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
72 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
73 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
74 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
Yiwei Zhang70a21962019-05-31 17:26:52 -070075 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
76 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
77 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
78 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
Jesse Hall55bc0972016-02-23 16:43:29 -080079 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
80
81VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
82 // Native and Vulkan transforms are isomorphic, but are represented
83 // differently. Vulkan transforms are built up of an optional horizontal
84 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
85 // transforms are built up from a horizontal flip, vertical flip, and
86 // 90-degree rotation, all optional but always in that order.
87
Jesse Hall55bc0972016-02-23 16:43:29 -080088 switch (native) {
Yiwei Zhang70a21962019-05-31 17:26:52 -070089 case 0:
Jesse Hall55bc0972016-02-23 16:43:29 -080090 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070091 case NATIVE_WINDOW_TRANSFORM_FLIP_H:
92 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
93 case NATIVE_WINDOW_TRANSFORM_FLIP_V:
94 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
95 case NATIVE_WINDOW_TRANSFORM_ROT_180:
Jesse Hall55bc0972016-02-23 16:43:29 -080096 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070097 case NATIVE_WINDOW_TRANSFORM_ROT_90:
Jesse Hall55bc0972016-02-23 16:43:29 -080098 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070099 case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
100 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
101 case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
102 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
103 case NATIVE_WINDOW_TRANSFORM_ROT_270:
Jesse Hall55bc0972016-02-23 16:43:29 -0800104 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
105 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
106 default:
107 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
108 }
109}
110
Yiwei Zhang70a21962019-05-31 17:26:52 -0700111int TranslateVulkanToNativeTransform(VkSurfaceTransformFlagBitsKHR transform) {
112 switch (transform) {
113 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
114 return NATIVE_WINDOW_TRANSFORM_ROT_90;
115 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
116 return NATIVE_WINDOW_TRANSFORM_ROT_180;
117 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
118 return NATIVE_WINDOW_TRANSFORM_ROT_270;
119 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
120 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
121 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
122 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
123 NATIVE_WINDOW_TRANSFORM_ROT_90;
124 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
125 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
126 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
127 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
128 NATIVE_WINDOW_TRANSFORM_ROT_90;
129 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
130 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
131 default:
132 return 0;
133 }
134}
135
Jesse Hall178b6962016-02-24 15:39:50 -0800136int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
137 switch (transform) {
138 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
139 return NATIVE_WINDOW_TRANSFORM_ROT_270;
140 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
141 return NATIVE_WINDOW_TRANSFORM_ROT_180;
142 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
143 return NATIVE_WINDOW_TRANSFORM_ROT_90;
Yiwei Zhang70a21962019-05-31 17:26:52 -0700144 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
145 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
146 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
147 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
148 NATIVE_WINDOW_TRANSFORM_ROT_90;
149 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
150 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
151 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
152 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
153 NATIVE_WINDOW_TRANSFORM_ROT_90;
Jesse Hall178b6962016-02-24 15:39:50 -0800154 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
155 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
156 default:
157 return 0;
158 }
159}
160
Ian Elliott8a977262017-01-19 09:05:58 -0700161class TimingInfo {
162 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800163 TimingInfo(const VkPresentTimeGOOGLE* qp, uint64_t nativeFrameId)
Ian Elliott2c6355d2017-01-19 11:02:13 -0700164 : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
Brian Anderson1049d1d2016-12-16 17:25:57 -0800165 native_frame_id_(nativeFrameId) {}
166 bool ready() const {
Brian Andersondc96fdf2017-03-20 16:54:25 -0700167 return (timestamp_desired_present_time_ !=
168 NATIVE_WINDOW_TIMESTAMP_PENDING &&
169 timestamp_actual_present_time_ !=
170 NATIVE_WINDOW_TIMESTAMP_PENDING &&
171 timestamp_render_complete_time_ !=
172 NATIVE_WINDOW_TIMESTAMP_PENDING &&
173 timestamp_composition_latch_time_ !=
174 NATIVE_WINDOW_TIMESTAMP_PENDING);
Ian Elliott8a977262017-01-19 09:05:58 -0700175 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700176 void calculate(int64_t rdur) {
177 bool anyTimestampInvalid =
178 (timestamp_actual_present_time_ ==
179 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
180 (timestamp_render_complete_time_ ==
181 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
182 (timestamp_composition_latch_time_ ==
183 NATIVE_WINDOW_TIMESTAMP_INVALID);
184 if (anyTimestampInvalid) {
185 ALOGE("Unexpectedly received invalid timestamp.");
186 vals_.actualPresentTime = 0;
187 vals_.earliestPresentTime = 0;
188 vals_.presentMargin = 0;
189 return;
190 }
191
192 vals_.actualPresentTime =
193 static_cast<uint64_t>(timestamp_actual_present_time_);
194 int64_t margin = (timestamp_composition_latch_time_ -
Ian Elliott8a977262017-01-19 09:05:58 -0700195 timestamp_render_complete_time_);
196 // Calculate vals_.earliestPresentTime, and potentially adjust
197 // vals_.presentMargin. The initial value of vals_.earliestPresentTime
198 // is vals_.actualPresentTime. If we can subtract rdur (the duration
199 // of a refresh cycle) from vals_.earliestPresentTime (and also from
200 // vals_.presentMargin) and still leave a positive margin, then we can
201 // report to the application that it could have presented earlier than
202 // it did (per the extension specification). If for some reason, we
203 // can do this subtraction repeatedly, we do, since
204 // vals_.earliestPresentTime really is supposed to be the "earliest".
Brian Andersondc96fdf2017-03-20 16:54:25 -0700205 int64_t early_time = timestamp_actual_present_time_;
Ian Elliott8a977262017-01-19 09:05:58 -0700206 while ((margin > rdur) &&
207 ((early_time - rdur) > timestamp_composition_latch_time_)) {
208 early_time -= rdur;
209 margin -= rdur;
210 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700211 vals_.earliestPresentTime = static_cast<uint64_t>(early_time);
212 vals_.presentMargin = static_cast<uint64_t>(margin);
Ian Elliott8a977262017-01-19 09:05:58 -0700213 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800214 void get_values(VkPastPresentationTimingGOOGLE* values) const {
215 *values = vals_;
216 }
Ian Elliott8a977262017-01-19 09:05:58 -0700217
218 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800219 VkPastPresentationTimingGOOGLE vals_ { 0, 0, 0, 0, 0 };
Ian Elliott8a977262017-01-19 09:05:58 -0700220
Brian Anderson1049d1d2016-12-16 17:25:57 -0800221 uint64_t native_frame_id_ { 0 };
Brian Andersondc96fdf2017-03-20 16:54:25 -0700222 int64_t timestamp_desired_present_time_{ NATIVE_WINDOW_TIMESTAMP_PENDING };
223 int64_t timestamp_actual_present_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
224 int64_t timestamp_render_complete_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
225 int64_t timestamp_composition_latch_time_
226 { NATIVE_WINDOW_TIMESTAMP_PENDING };
Ian Elliott8a977262017-01-19 09:05:58 -0700227};
228
Jesse Hall1356b0d2015-11-23 17:24:58 -0800229struct Surface {
Chia-I Wue8e689f2016-04-18 08:21:31 +0800230 android::sp<ANativeWindow> window;
Jesse Halldc225072016-05-30 22:40:14 -0700231 VkSwapchainKHR swapchain_handle;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700232 uint64_t consumer_usage;
Yiwei Zhang3b88f312023-04-18 23:11:35 +0000233
234 // Indicate whether this surface has been used by a swapchain, no matter the
235 // swapchain is still current or has been destroyed.
236 bool used_by_swapchain;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800237};
238
239VkSurfaceKHR HandleFromSurface(Surface* surface) {
240 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
241}
242
243Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800244 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800245}
246
Ian Elliott8a977262017-01-19 09:05:58 -0700247// Maximum number of TimingInfo structs to keep per swapchain:
248enum { MAX_TIMING_INFOS = 10 };
249// Minimum number of frames to look for in the past (so we don't cause
250// syncronous requests to Surface Flinger):
251enum { MIN_NUM_FRAMES_AGO = 5 };
252
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300253bool IsSharedPresentMode(VkPresentModeKHR mode) {
254 return mode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
255 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR;
256}
257
Jesse Hall1356b0d2015-11-23 17:24:58 -0800258struct Swapchain {
Ian Elliottffedb652017-02-14 10:58:30 -0700259 Swapchain(Surface& surface_,
260 uint32_t num_images_,
silence_dogood73597592019-05-23 16:57:37 -0700261 VkPresentModeKHR present_mode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000262 int pre_transform_,
263 int64_t refresh_duration_)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700264 : surface(surface_),
265 num_images(num_images_),
Ian Elliottffedb652017-02-14 10:58:30 -0700266 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
silence_dogood73597592019-05-23 16:57:37 -0700267 pre_transform(pre_transform_),
Chris Forbesf8835642017-03-30 19:31:40 +1300268 frame_timestamps_enabled(false),
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000269 refresh_duration(refresh_duration_),
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800270 acquire_next_image_timeout(-1),
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300271 shared(IsSharedPresentMode(present_mode)) {
Ian Elliott8a977262017-01-19 09:05:58 -0700272 }
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000273
274 VkResult get_refresh_duration(uint64_t& outRefreshDuration)
Ian Elliott3568bfe2019-05-03 15:54:46 -0600275 {
276 ANativeWindow* window = surface.window.get();
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000277 int err = native_window_get_refresh_cycle_duration(
Ian Elliott3568bfe2019-05-03 15:54:46 -0600278 window,
279 &refresh_duration);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000280 if (err != android::OK) {
281 ALOGE("%s:native_window_get_refresh_cycle_duration failed: %s (%d)",
282 __func__, strerror(-err), err );
283 return VK_ERROR_SURFACE_LOST_KHR;
284 }
285 outRefreshDuration = refresh_duration;
286 return VK_SUCCESS;
Ian Elliott3568bfe2019-05-03 15:54:46 -0600287 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800288
289 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700290 uint32_t num_images;
Ian Elliottffedb652017-02-14 10:58:30 -0700291 bool mailbox_mode;
silence_dogood73597592019-05-23 16:57:37 -0700292 int pre_transform;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700293 bool frame_timestamps_enabled;
Brian Andersondc96fdf2017-03-20 16:54:25 -0700294 int64_t refresh_duration;
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800295 nsecs_t acquire_next_image_timeout;
Chris Forbesf8835642017-03-30 19:31:40 +1300296 bool shared;
Jesse Halld7b994a2015-09-07 14:17:37 -0700297
298 struct Image {
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700299 Image()
300 : image(VK_NULL_HANDLE),
301 dequeue_fence(-1),
302 release_fence(-1),
303 dequeued(false) {}
Jesse Halld7b994a2015-09-07 14:17:37 -0700304 VkImage image;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000305 // If the image is bound to memory, an sp to the underlying gralloc buffer.
306 // Otherwise, nullptr; the image will be bound to memory as part of
307 // AcquireNextImage.
Chia-I Wue8e689f2016-04-18 08:21:31 +0800308 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700309 // The fence is only valid when the buffer is dequeued, and should be
310 // -1 any other time. When valid, we own the fd, and must ensure it is
311 // closed: either by closing it explicitly when queueing the buffer,
312 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
313 int dequeue_fence;
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700314 // This fence is a dup of the sync fd returned from the driver via
315 // vkQueueSignalReleaseImageANDROID upon vkQueuePresentKHR. We must
316 // ensure it is closed upon re-presenting or releasing the image.
317 int release_fence;
Jesse Halld7b994a2015-09-07 14:17:37 -0700318 bool dequeued;
Pawin Vongmasa6e1193a2017-03-07 13:08:40 -0800319 } images[android::BufferQueueDefs::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700320
Yiwei Zhang5e862202019-06-21 14:59:16 -0700321 std::vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700322};
323
324VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
325 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
326}
327
328Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800329 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700330}
331
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700332static bool IsFencePending(int fd) {
333 if (fd < 0)
334 return false;
335
336 errno = 0;
337 return sync_wait(fd, 0 /* timeout */) == -1 && errno == ETIME;
338}
339
Jesse Halldc225072016-05-30 22:40:14 -0700340void ReleaseSwapchainImage(VkDevice device,
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000341 bool shared_present,
Jesse Halldc225072016-05-30 22:40:14 -0700342 ANativeWindow* window,
343 int release_fence,
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700344 Swapchain::Image& image,
345 bool defer_if_pending) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700346 ATRACE_CALL();
347
Jesse Halldc225072016-05-30 22:40:14 -0700348 ALOG_ASSERT(release_fence == -1 || image.dequeued,
349 "ReleaseSwapchainImage: can't provide a release fence for "
350 "non-dequeued images");
351
352 if (image.dequeued) {
353 if (release_fence >= 0) {
354 // We get here from vkQueuePresentKHR. The application is
355 // responsible for creating an execution dependency chain from
356 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
357 // (release_fence), so we can drop the dequeue_fence here.
358 if (image.dequeue_fence >= 0)
359 close(image.dequeue_fence);
360 } else {
361 // We get here during swapchain destruction, or various serious
362 // error cases e.g. when we can't create the release_fence during
363 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
364 // have already signalled, since the swapchain images are supposed
365 // to be idle before the swapchain is destroyed. In error cases,
366 // there may be rendering in flight to the image, but since we
367 // weren't able to create a release_fence, waiting for the
368 // dequeue_fence is about the best we can do.
369 release_fence = image.dequeue_fence;
370 }
371 image.dequeue_fence = -1;
372
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000373 // It's invalid to call cancelBuffer on a shared buffer
374 if (window && !shared_present) {
Jesse Halldc225072016-05-30 22:40:14 -0700375 window->cancelBuffer(window, image.buffer.get(), release_fence);
376 } else {
377 if (release_fence >= 0) {
378 sync_wait(release_fence, -1 /* forever */);
379 close(release_fence);
380 }
381 }
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700382 release_fence = -1;
Jesse Halldc225072016-05-30 22:40:14 -0700383 image.dequeued = false;
384 }
385
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700386 if (defer_if_pending && IsFencePending(image.release_fence))
387 return;
388
389 if (image.release_fence >= 0) {
390 close(image.release_fence);
391 image.release_fence = -1;
392 }
393
Jesse Halldc225072016-05-30 22:40:14 -0700394 if (image.image) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700395 ATRACE_BEGIN("DestroyImage");
Jesse Halldc225072016-05-30 22:40:14 -0700396 GetData(device).driver.DestroyImage(device, image.image, nullptr);
Yiwei Zhang533cea92019-06-03 18:43:24 -0700397 ATRACE_END();
Jesse Halldc225072016-05-30 22:40:14 -0700398 image.image = VK_NULL_HANDLE;
399 }
400
401 image.buffer.clear();
402}
403
404void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
405 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
406 return;
Jesse Halldc225072016-05-30 22:40:14 -0700407 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000408 if (!swapchain->images[i].dequeued) {
409 ReleaseSwapchainImage(device, swapchain->shared, nullptr, -1,
410 swapchain->images[i], true);
411 }
Jesse Halldc225072016-05-30 22:40:14 -0700412 }
413 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700414 swapchain->timing.clear();
415}
416
417uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800418 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
419 return 0;
420 }
Ian Elliott8a977262017-01-19 09:05:58 -0700421
Brian Anderson1049d1d2016-12-16 17:25:57 -0800422 uint32_t num_ready = 0;
423 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
424 for (uint32_t i = 0; i < num_timings; i++) {
Yiwei Zhang5e862202019-06-21 14:59:16 -0700425 TimingInfo& ti = swapchain.timing[i];
Brian Anderson1049d1d2016-12-16 17:25:57 -0800426 if (ti.ready()) {
427 // This TimingInfo is ready to be reported to the user. Add it
428 // to the num_ready.
429 num_ready++;
430 continue;
431 }
432 // This TimingInfo is not yet ready to be reported to the user,
433 // and so we should look for any available timestamps that
434 // might make it ready.
435 int64_t desired_present_time = 0;
436 int64_t render_complete_time = 0;
437 int64_t composition_latch_time = 0;
438 int64_t actual_present_time = 0;
439 // Obtain timestamps:
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800440 int err = native_window_get_frame_timestamps(
Brian Anderson1049d1d2016-12-16 17:25:57 -0800441 swapchain.surface.window.get(), ti.native_frame_id_,
442 &desired_present_time, &render_complete_time,
443 &composition_latch_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700444 nullptr, //&first_composition_start_time,
445 nullptr, //&last_composition_start_time,
446 nullptr, //&composition_finish_time,
Brian Anderson1049d1d2016-12-16 17:25:57 -0800447 &actual_present_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700448 nullptr, //&dequeue_ready_time,
449 nullptr /*&reads_done_time*/);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800450
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800451 if (err != android::OK) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800452 continue;
453 }
454
455 // Record the timestamp(s) we received, and then see if this TimingInfo
456 // is ready to be reported to the user:
Brian Andersondc96fdf2017-03-20 16:54:25 -0700457 ti.timestamp_desired_present_time_ = desired_present_time;
458 ti.timestamp_actual_present_time_ = actual_present_time;
459 ti.timestamp_render_complete_time_ = render_complete_time;
460 ti.timestamp_composition_latch_time_ = composition_latch_time;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800461
462 if (ti.ready()) {
463 // The TimingInfo has received enough timestamps, and should now
464 // use those timestamps to calculate the info that should be
465 // reported to the user:
466 ti.calculate(swapchain.refresh_duration);
467 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700468 }
469 }
470 return num_ready;
471}
472
Ian Elliott8a977262017-01-19 09:05:58 -0700473void copy_ready_timings(Swapchain& swapchain,
474 uint32_t* count,
475 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800476 if (swapchain.timing.empty()) {
477 *count = 0;
478 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700479 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800480
481 size_t last_ready = swapchain.timing.size() - 1;
482 while (!swapchain.timing[last_ready].ready()) {
483 if (last_ready == 0) {
484 *count = 0;
485 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700486 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800487 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700488 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800489
490 uint32_t num_copied = 0;
Yiwei Zhang5e862202019-06-21 14:59:16 -0700491 int32_t num_to_remove = 0;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800492 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
493 const TimingInfo& ti = swapchain.timing[i];
494 if (ti.ready()) {
495 ti.get_values(&timings[num_copied]);
496 num_copied++;
497 }
498 num_to_remove++;
499 }
500
501 // Discard old frames that aren't ready if newer frames are ready.
502 // We don't expect to get the timing info for those old frames.
Yiwei Zhang5e862202019-06-21 14:59:16 -0700503 swapchain.timing.erase(swapchain.timing.begin(),
504 swapchain.timing.begin() + num_to_remove);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800505
Ian Elliott8a977262017-01-19 09:05:58 -0700506 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700507}
508
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000509PixelFormat GetNativePixelFormat(VkFormat format) {
510 PixelFormat native_format = PixelFormat::RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700511 switch (format) {
512 case VK_FORMAT_R8G8B8A8_UNORM:
513 case VK_FORMAT_R8G8B8A8_SRGB:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000514 native_format = PixelFormat::RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700515 break;
516 case VK_FORMAT_R5G6B5_UNORM_PACK16:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000517 native_format = PixelFormat::RGB_565;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700518 break;
519 case VK_FORMAT_R16G16B16A16_SFLOAT:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000520 native_format = PixelFormat::RGBA_FP16;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700521 break;
Yiwei Zhangc1ea8152019-02-05 15:11:32 -0800522 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000523 native_format = PixelFormat::RGBA_1010102;
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500524 break;
525 case VK_FORMAT_R8_UNORM:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000526 native_format = PixelFormat::R_8;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700527 break;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000528 case VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000529 native_format = PixelFormat::RGBA_10101010;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000530 break;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700531 default:
532 ALOGV("unsupported swapchain format %d", format);
533 break;
534 }
535 return native_format;
536}
537
sergiuferentz47989332023-09-26 10:24:36 +0000538DataSpace GetNativeDataspace(VkColorSpaceKHR colorspace,
539 PixelFormat pixelFormat) {
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700540 switch (colorspace) {
541 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
sergiuferentz47989332023-09-26 10:24:36 +0000542 return DataSpace::SRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700543 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000544 return DataSpace::DISPLAY_P3;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700545 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000546 return DataSpace::SCRGB_LINEAR;
Courtney Goeltzenleuchterb52abee2017-08-07 17:13:04 -0600547 case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000548 return DataSpace::SCRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700549 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000550 return DataSpace::DCI_P3_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700551 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000552 return DataSpace::DCI_P3;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700553 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000554 return DataSpace::SRGB_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700555 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000556 return DataSpace::SRGB;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600557 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
Sally Qiaa238972023-07-17 12:52:05 +0800558 if (pixelFormat == PixelFormat::RGBA_FP16) {
sergiuferentz47989332023-09-26 10:24:36 +0000559 return DataSpace::BT2020_LINEAR_EXTENDED;
Sally Qiaa238972023-07-17 12:52:05 +0800560 } else {
sergiuferentz47989332023-09-26 10:24:36 +0000561 return DataSpace::BT2020_LINEAR;
Sally Qiaa238972023-07-17 12:52:05 +0800562 }
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600563 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000564 return DataSpace::BT2020_PQ;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600565 case VK_COLOR_SPACE_DOLBYVISION_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000566 return DataSpace::BT2020_PQ;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600567 case VK_COLOR_SPACE_HDR10_HLG_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000568 return DataSpace::BT2020_HLG;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700569 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000570 return DataSpace::ADOBE_RGB_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700571 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000572 return DataSpace::ADOBE_RGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700573 // Pass through is intended to allow app to provide data that is passed
574 // to the display system without modification.
575 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000576 return DataSpace::ARBITRARY;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700577
578 default:
579 // This indicates that we don't know about the
580 // dataspace specified and we should indicate that
581 // it's unsupported
sergiuferentz47989332023-09-26 10:24:36 +0000582 return DataSpace::UNKNOWN;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700583 }
584}
585
Jesse Halld7b994a2015-09-07 14:17:37 -0700586} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700587
Jesse Halle1b12782015-11-30 11:27:32 -0800588VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800589VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800590 VkInstance instance,
591 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
592 const VkAllocationCallbacks* allocator,
593 VkSurfaceKHR* out_surface) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800594 ATRACE_CALL();
595
Jesse Hall1f91d392015-12-11 16:28:44 -0800596 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800597 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800598 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
599 alignof(Surface),
600 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800601 if (!mem)
602 return VK_ERROR_OUT_OF_HOST_MEMORY;
603 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700604
Chia-I Wue8e689f2016-04-18 08:21:31 +0800605 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700606 surface->swapchain_handle = VK_NULL_HANDLE;
Yiwei Zhang3b88f312023-04-18 23:11:35 +0000607 surface->used_by_swapchain = false;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700608 int err = native_window_get_consumer_usage(surface->window.get(),
609 &surface->consumer_usage);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800610 if (err != android::OK) {
Yiwei Zhang6435b322018-05-08 11:12:17 -0700611 ALOGE("native_window_get_consumer_usage() failed: %s (%d)",
612 strerror(-err), err);
613 surface->~Surface();
614 allocator->pfnFree(allocator->pUserData, surface);
Yiwei Zhang70a21962019-05-31 17:26:52 -0700615 return VK_ERROR_SURFACE_LOST_KHR;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700616 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700617
Yiwei Zhang6435b322018-05-08 11:12:17 -0700618 err =
Jesse Hall1356b0d2015-11-23 17:24:58 -0800619 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800620 if (err != android::OK) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800621 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
622 err);
623 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800624 allocator->pfnFree(allocator->pUserData, surface);
Mike Stroyan762c8132017-02-22 11:43:09 -0700625 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800626 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700627
Jesse Hall1356b0d2015-11-23 17:24:58 -0800628 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700629 return VK_SUCCESS;
630}
631
Jesse Halle1b12782015-11-30 11:27:32 -0800632VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800633void DestroySurfaceKHR(VkInstance instance,
634 VkSurfaceKHR surface_handle,
635 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800636 ATRACE_CALL();
637
Jesse Hall1356b0d2015-11-23 17:24:58 -0800638 Surface* surface = SurfaceFromHandle(surface_handle);
639 if (!surface)
640 return;
641 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700642 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700643 "destroyed VkSurfaceKHR 0x%" PRIx64
644 " has active VkSwapchainKHR 0x%" PRIx64,
645 reinterpret_cast<uint64_t>(surface_handle),
646 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800647 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800648 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800649 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800650 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800651}
652
Jesse Halle1b12782015-11-30 11:27:32 -0800653VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800654VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
655 uint32_t /*queue_family*/,
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000656 VkSurfaceKHR /*surface_handle*/,
Chia-I Wu62262232016-03-26 07:06:44 +0800657 VkBool32* supported) {
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000658 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800659 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800660}
661
Jesse Halle1b12782015-11-30 11:27:32 -0800662VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800663VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Ian Elliott1ce053f2022-03-16 09:49:53 -0600664 VkPhysicalDevice pdev,
Jesse Hallb00daad2015-11-29 19:46:20 -0800665 VkSurfaceKHR surface,
666 VkSurfaceCapabilitiesKHR* capabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800667 ATRACE_CALL();
668
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000669 // Implement in terms of GetPhysicalDeviceSurfaceCapabilities2KHR
670
671 VkPhysicalDeviceSurfaceInfo2KHR info2 = {
672 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
673 nullptr,
674 surface
675 };
676
677 VkSurfaceCapabilities2KHR caps2 = {
678 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
679 nullptr,
680 {},
681 };
682
683 VkResult result = GetPhysicalDeviceSurfaceCapabilities2KHR(pdev, &info2, &caps2);
684 *capabilities = caps2.surfaceCapabilities;
685 return result;
686}
687
688// Does the call-twice and VK_INCOMPLETE handling for querying lists
689// of things, where we already have the full set built in a vector.
690template <typename T>
691VkResult CopyWithIncomplete(std::vector<T> const& things,
692 T* callerPtr, uint32_t* callerCount) {
693 VkResult result = VK_SUCCESS;
694 if (callerPtr) {
695 if (things.size() > *callerCount)
696 result = VK_INCOMPLETE;
697 *callerCount = std::min(uint32_t(things.size()), *callerCount);
698 std::copy(things.begin(), things.begin() + *callerCount, callerPtr);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600699 } else {
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000700 *callerCount = things.size();
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800701 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000702 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700703}
704
Jesse Halle1b12782015-11-30 11:27:32 -0800705VKAPI_ATTR
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700706VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
707 VkSurfaceKHR surface_handle,
Chia-I Wu62262232016-03-26 07:06:44 +0800708 uint32_t* count,
709 VkSurfaceFormatKHR* formats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800710 ATRACE_CALL();
711
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700712 const InstanceData& instance_data = GetData(pdev);
713
Ian Elliott1ce053f2022-03-16 09:49:53 -0600714 uint64_t consumer_usage = 0;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000715 bool colorspace_ext =
Ian Elliottf6df08e2022-03-16 21:27:49 -0600716 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600717 if (surface_handle == VK_NULL_HANDLE) {
718 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
719 bool surfaceless_enabled =
720 instance_data.hook_extensions.test(surfaceless);
721 if (!surfaceless_enabled) {
722 return VK_ERROR_SURFACE_LOST_KHR;
723 }
Chris Forbesb1de3b12022-10-20 09:05:48 +1300724 // Support for VK_GOOGLE_surfaceless_query.
Ian Elliott1ce053f2022-03-16 09:49:53 -0600725
726 // TODO(b/203826952): research proper value; temporarily use the
727 // values seen on Pixel
728 consumer_usage = AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
729 } else {
730 Surface& surface = *SurfaceFromHandle(surface_handle);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600731 consumer_usage = surface.consumer_usage;
Ian Elliott6ba85d92022-02-18 16:44:58 -0700732 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700733
Charlie Lao324191f2019-12-13 11:03:16 -0800734 AHardwareBuffer_Desc desc = {};
735 desc.width = 1;
736 desc.height = 1;
737 desc.layers = 1;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600738 desc.usage = consumer_usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
Charlie Lao324191f2019-12-13 11:03:16 -0800739 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
740
741 // We must support R8G8B8A8
742 std::vector<VkSurfaceFormatKHR> all_formats = {
743 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000744 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000745 };
Charlie Lao324191f2019-12-13 11:03:16 -0800746
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000747 if (colorspace_ext) {
748 all_formats.emplace_back(VkSurfaceFormatKHR{
Jason Macnakca506332022-11-09 11:00:36 -0800749 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
750 all_formats.emplace_back(VkSurfaceFormatKHR{
751 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_PASS_THROUGH_EXT});
752 all_formats.emplace_back(VkSurfaceFormatKHR{
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000753 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_BT709_LINEAR_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800754 all_formats.emplace_back(VkSurfaceFormatKHR{
755 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
756 all_formats.emplace_back(VkSurfaceFormatKHR{
757 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
758 }
759
Ian Elliott1ce053f2022-03-16 09:49:53 -0600760 // NOTE: Any new formats that are added must be coordinated across different
761 // Android users. This includes the ANGLE team (a layered implementation of
762 // OpenGL-ES).
763
Charlie Lao324191f2019-12-13 11:03:16 -0800764 desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
765 if (AHardwareBuffer_isSupported(&desc)) {
766 all_formats.emplace_back(VkSurfaceFormatKHR{
767 VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800768 if (colorspace_ext) {
769 all_formats.emplace_back(
770 VkSurfaceFormatKHR{VK_FORMAT_R5G6B5_UNORM_PACK16,
771 VK_COLOR_SPACE_PASS_THROUGH_EXT});
772 }
Charlie Lao324191f2019-12-13 11:03:16 -0800773 }
774
775 desc.format = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
776 if (AHardwareBuffer_isSupported(&desc)) {
777 all_formats.emplace_back(VkSurfaceFormatKHR{
778 VK_FORMAT_R16G16B16A16_SFLOAT, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800779 if (colorspace_ext) {
780 all_formats.emplace_back(
781 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
782 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800783 all_formats.emplace_back(
784 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
785 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT});
786 all_formats.emplace_back(
787 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
788 VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT});
Yuxin Hud3ff5212024-02-06 02:39:19 +0000789 all_formats.emplace_back(
790 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
791 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800792 }
793 }
794
795 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
796 if (AHardwareBuffer_isSupported(&desc)) {
797 all_formats.emplace_back(
798 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
799 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800800 if (colorspace_ext) {
801 all_formats.emplace_back(
802 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
803 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800804 all_formats.emplace_back(
805 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
806 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
807 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700808 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700809
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500810 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
811 if (AHardwareBuffer_isSupported(&desc)) {
Jason Macnakca506332022-11-09 11:00:36 -0800812 if (colorspace_ext) {
813 all_formats.emplace_back(VkSurfaceFormatKHR{
814 VK_FORMAT_R8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
815 }
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500816 }
817
Trevor David Black67e9b102023-03-07 05:28:15 +0000818 bool rgba10x6_formats_ext = false;
819 uint32_t exts_count;
820 const auto& driver = GetData(pdev).driver;
821 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
822 nullptr);
823 std::vector<VkExtensionProperties> props(exts_count);
824 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
825 props.data());
826 for (uint32_t i = 0; i < exts_count; i++) {
827 VkExtensionProperties prop = props[i];
828 if (strcmp(prop.extensionName,
829 VK_EXT_RGBA10X6_FORMATS_EXTENSION_NAME) == 0) {
830 rgba10x6_formats_ext = true;
831 }
832 }
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000833 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM;
Trevor David Black67e9b102023-03-07 05:28:15 +0000834 if (AHardwareBuffer_isSupported(&desc) && rgba10x6_formats_ext) {
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000835 all_formats.emplace_back(
836 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
837 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
838 if (colorspace_ext) {
839 all_formats.emplace_back(
840 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
841 VK_COLOR_SPACE_PASS_THROUGH_EXT});
842 all_formats.emplace_back(
843 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
844 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
845 }
846 }
847
Ian Elliott6ba85d92022-02-18 16:44:58 -0700848 // NOTE: Any new formats that are added must be coordinated across different
849 // Android users. This includes the ANGLE team (a layered implementation of
850 // OpenGL-ES).
851
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000852 return CopyWithIncomplete(all_formats, formats, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700853}
854
Jesse Halle1b12782015-11-30 11:27:32 -0800855VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300856VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
857 VkPhysicalDevice physicalDevice,
858 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
859 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800860 ATRACE_CALL();
861
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000862 auto surface = pSurfaceInfo->surface;
863 auto capabilities = &pSurfaceCapabilities->surfaceCapabilities;
Chris Forbes2452cf72017-03-16 16:30:17 +1300864
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000865 VkSurfacePresentModeEXT const *pPresentMode = nullptr;
866 for (auto pNext = reinterpret_cast<VkBaseInStructure const *>(pSurfaceInfo->pNext);
867 pNext; pNext = reinterpret_cast<VkBaseInStructure const *>(pNext->pNext)) {
868 switch (pNext->sType) {
869 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT:
870 pPresentMode = reinterpret_cast<VkSurfacePresentModeEXT const *>(pNext);
871 break;
Chris Forbes06bc0092017-03-16 16:46:05 +1300872
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000873 default:
874 break;
875 }
876 }
877
878 int err;
879 int width, height;
880 int transform_hint;
881 int max_buffer_count;
Trevor David Black1d3509e2023-06-08 00:17:40 +0000882 int min_undequeued_buffers;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000883 if (surface == VK_NULL_HANDLE) {
884 const InstanceData& instance_data = GetData(physicalDevice);
885 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
886 bool surfaceless_enabled =
887 instance_data.hook_extensions.test(surfaceless);
888 if (!surfaceless_enabled) {
889 // It is an error to pass a surface==VK_NULL_HANDLE unless the
890 // VK_GOOGLE_surfaceless_query extension is enabled
891 return VK_ERROR_SURFACE_LOST_KHR;
892 }
893 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
894 // extension for this function is for
895 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
896 // four values cannot be known without a surface. Default values will
897 // be supplied anyway, but cannot be relied upon.
898 width = 0xFFFFFFFF;
899 height = 0xFFFFFFFF;
900 transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
901 capabilities->minImageCount = 0xFFFFFFFF;
902 capabilities->maxImageCount = 0xFFFFFFFF;
903 } else {
904 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
905
906 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
907 if (err != android::OK) {
908 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
909 strerror(-err), err);
910 return VK_ERROR_SURFACE_LOST_KHR;
911 }
912 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
913 if (err != android::OK) {
914 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
915 strerror(-err), err);
916 return VK_ERROR_SURFACE_LOST_KHR;
917 }
918
919 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
920 &transform_hint);
921 if (err != android::OK) {
922 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
923 strerror(-err), err);
924 return VK_ERROR_SURFACE_LOST_KHR;
925 }
926
927 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
928 &max_buffer_count);
929 if (err != android::OK) {
930 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
931 strerror(-err), err);
932 return VK_ERROR_SURFACE_LOST_KHR;
933 }
934
Trevor David Black1d3509e2023-06-08 00:17:40 +0000935 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
936 &min_undequeued_buffers);
937 if (err != android::OK) {
938 ALOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d)",
939 strerror(-err), err);
940 return VK_ERROR_SURFACE_LOST_KHR;
941 }
942
Trevor David Blacke4d23b92023-09-26 20:30:42 +0000943 // Additional buffer count over min_undequeued_buffers in vulkan came from 2 total
944 // being technically enough for fifo (although a poor experience) vs 3 being the
945 // absolute minimum for mailbox to be useful. So min_undequeued_buffers + 2 is sensible
946 static constexpr int default_additional_buffers = 2;
947
Trevor David Blacka93e21f2023-08-30 23:42:20 +0000948 if(pPresentMode != nullptr) {
949 switch (pPresentMode->presentMode) {
950 case VK_PRESENT_MODE_IMMEDIATE_KHR:
951 ALOGE("Swapchain present mode VK_PRESENT_MODE_IMMEDIATE_KHR is not supported");
952 break;
953 case VK_PRESENT_MODE_MAILBOX_KHR:
954 case VK_PRESENT_MODE_FIFO_KHR:
Trevor David Blacke4d23b92023-09-26 20:30:42 +0000955 capabilities->minImageCount = std::min(max_buffer_count,
956 min_undequeued_buffers + default_additional_buffers);
Trevor David Blacka93e21f2023-08-30 23:42:20 +0000957 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
958 break;
959 case VK_PRESENT_MODE_FIFO_RELAXED_KHR:
960 ALOGE("Swapchain present mode VK_PRESENT_MODE_FIFO_RELEAXED_KHR "
961 "is not supported");
962 break;
963 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
964 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
965 capabilities->minImageCount = 1;
966 capabilities->maxImageCount = 1;
967 break;
968
969 default:
970 ALOGE("Unrecognized swapchain present mode %u is not supported",
971 pPresentMode->presentMode);
972 break;
973 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000974 } else {
Trevor David Blacke4d23b92023-09-26 20:30:42 +0000975 capabilities->minImageCount = std::min(max_buffer_count,
976 min_undequeued_buffers + default_additional_buffers);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000977 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
978 }
979 }
980
981 capabilities->currentExtent =
982 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
983
984 // TODO(http://b/134182502): Figure out what the max extent should be.
985 capabilities->minImageExtent = VkExtent2D{1, 1};
986 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
987
988 if (capabilities->maxImageExtent.height <
989 capabilities->currentExtent.height) {
990 capabilities->maxImageExtent.height =
991 capabilities->currentExtent.height;
992 }
993
994 if (capabilities->maxImageExtent.width <
995 capabilities->currentExtent.width) {
996 capabilities->maxImageExtent.width = capabilities->currentExtent.width;
997 }
998
999 capabilities->maxImageArrayLayers = 1;
1000
1001 capabilities->supportedTransforms = kSupportedTransforms;
1002 capabilities->currentTransform =
1003 TranslateNativeToVulkanTransform(transform_hint);
1004
1005 // On Android, window composition is a WindowManager property, not something
1006 // associated with the bufferqueue. It can't be changed from here.
1007 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
1008
1009 capabilities->supportedUsageFlags =
1010 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
1011 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
1012 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
1013 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
1014
1015 for (auto pNext = reinterpret_cast<VkBaseOutStructure*>(pSurfaceCapabilities->pNext);
1016 pNext; pNext = reinterpret_cast<VkBaseOutStructure*>(pNext->pNext)) {
1017
1018 switch (pNext->sType) {
Chris Forbes06bc0092017-03-16 16:46:05 +13001019 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
1020 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001021 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(pNext);
Chris Forbes06bc0092017-03-16 16:46:05 +13001022 // Claim same set of usage flags are supported for
1023 // shared present modes as for other modes.
1024 shared_caps->sharedPresentSupportedUsageFlags =
1025 pSurfaceCapabilities->surfaceCapabilities
1026 .supportedUsageFlags;
1027 } break;
1028
Ian Elliottbb67b242022-03-16 09:52:28 -06001029 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
1030 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001031 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(pNext);
Ian Elliottbb67b242022-03-16 09:52:28 -06001032 protected_caps->supportsProtected = VK_TRUE;
1033 } break;
1034
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001035 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_SCALING_CAPABILITIES_EXT: {
1036 VkSurfacePresentScalingCapabilitiesEXT* scaling_caps =
1037 reinterpret_cast<VkSurfacePresentScalingCapabilitiesEXT*>(pNext);
1038 // By default, Android stretches the buffer to fit the window,
1039 // without preserving aspect ratio. Other modes are technically possible
1040 // but consult with CoGS team before exposing them here!
1041 scaling_caps->supportedPresentScaling = VK_PRESENT_SCALING_STRETCH_BIT_EXT;
1042
1043 // Since we always scale, we don't support any gravity.
1044 scaling_caps->supportedPresentGravityX = 0;
1045 scaling_caps->supportedPresentGravityY = 0;
1046
1047 // Scaled image limits are just the basic image limits
1048 scaling_caps->minScaledImageExtent = capabilities->minImageExtent;
1049 scaling_caps->maxScaledImageExtent = capabilities->maxImageExtent;
1050 } break;
1051
1052 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT: {
1053 VkSurfacePresentModeCompatibilityEXT* mode_caps =
1054 reinterpret_cast<VkSurfacePresentModeCompatibilityEXT*>(pNext);
1055
1056 ALOG_ASSERT(pPresentMode,
1057 "querying VkSurfacePresentModeCompatibilityEXT "
1058 "requires VkSurfacePresentModeEXT to be provided");
1059 std::vector<VkPresentModeKHR> compatibleModes;
1060 compatibleModes.push_back(pPresentMode->presentMode);
1061
1062 switch (pPresentMode->presentMode) {
1063 // Shared modes are both compatible with each other.
1064 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
1065 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
1066 break;
1067 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
1068 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1069 break;
1070 default:
1071 // Other modes are only compatible with themselves.
1072 // TODO: consider whether switching between FIFO and MAILBOX is reasonable
1073 break;
1074 }
1075
1076 // Note: this does not generate VK_INCOMPLETE since we're nested inside
1077 // a larger query and there would be no way to determine exactly where it came from.
1078 CopyWithIncomplete(compatibleModes, mode_caps->pPresentModes,
1079 &mode_caps->presentModeCount);
1080 } break;
1081
Chris Forbes06bc0092017-03-16 16:46:05 +13001082 default:
1083 // Ignore all other extension structs
1084 break;
1085 }
1086 }
1087
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001088 return VK_SUCCESS;
Chris Forbes2452cf72017-03-16 16:30:17 +13001089}
1090
1091VKAPI_ATTR
1092VkResult GetPhysicalDeviceSurfaceFormats2KHR(
1093 VkPhysicalDevice physicalDevice,
1094 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
1095 uint32_t* pSurfaceFormatCount,
1096 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001097 ATRACE_CALL();
1098
Chris Forbes2452cf72017-03-16 16:30:17 +13001099 if (!pSurfaceFormats) {
1100 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
1101 pSurfaceInfo->surface,
1102 pSurfaceFormatCount, nullptr);
Trevor David Black929e9cd2022-11-22 04:12:19 +00001103 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001104
Trevor David Black929e9cd2022-11-22 04:12:19 +00001105 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
1106 // after the call.
1107 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
1108 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
1109 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
1110 surface_formats.data());
Trevor David Black2cc44682022-03-09 00:31:38 +00001111
Trevor David Black929e9cd2022-11-22 04:12:19 +00001112 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
1113 return result;
1114 }
Trevor David Black2cc44682022-03-09 00:31:38 +00001115
Trevor David Black929e9cd2022-11-22 04:12:19 +00001116 const auto& driver = GetData(physicalDevice).driver;
1117
1118 // marshal results individually due to stride difference.
1119 uint32_t formats_to_marshal = *pSurfaceFormatCount;
1120 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
1121 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
1122
1123 // Query the compression properties for the surface format
1124 VkSurfaceFormat2KHR* pSurfaceFormat = &pSurfaceFormats[i];
1125 while (pSurfaceFormat->pNext) {
1126 pSurfaceFormat =
1127 reinterpret_cast<VkSurfaceFormat2KHR*>(pSurfaceFormat->pNext);
1128 switch (pSurfaceFormat->sType) {
1129 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT: {
Trevor David Black2cc44682022-03-09 00:31:38 +00001130 VkImageCompressionPropertiesEXT* surfaceCompressionProps =
1131 reinterpret_cast<VkImageCompressionPropertiesEXT*>(
Trevor David Black929e9cd2022-11-22 04:12:19 +00001132 pSurfaceFormat);
Trevor David Black2cc44682022-03-09 00:31:38 +00001133
1134 if (surfaceCompressionProps &&
1135 driver.GetPhysicalDeviceImageFormatProperties2KHR) {
1136 VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = {};
1137 imageFormatInfo.sType =
1138 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
1139 imageFormatInfo.format =
1140 pSurfaceFormats[i].surfaceFormat.format;
Trevor David Blacka4298c92023-06-20 17:11:58 +00001141 imageFormatInfo.type = VK_IMAGE_TYPE_2D;
1142 imageFormatInfo.usage =
1143 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
Trevor David Black2cc44682022-03-09 00:31:38 +00001144 imageFormatInfo.pNext = nullptr;
1145
1146 VkImageCompressionControlEXT compressionControl = {};
1147 compressionControl.sType =
1148 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT;
1149 compressionControl.pNext = imageFormatInfo.pNext;
Trevor David Blacka4298c92023-06-20 17:11:58 +00001150 compressionControl.flags =
1151 VK_IMAGE_COMPRESSION_FIXED_RATE_DEFAULT_EXT;
Trevor David Black2cc44682022-03-09 00:31:38 +00001152
1153 imageFormatInfo.pNext = &compressionControl;
1154
1155 VkImageCompressionPropertiesEXT compressionProps = {};
1156 compressionProps.sType =
1157 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT;
1158 compressionProps.pNext = nullptr;
1159
1160 VkImageFormatProperties2KHR imageFormatProps = {};
1161 imageFormatProps.sType =
1162 VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
1163 imageFormatProps.pNext = &compressionProps;
1164
1165 VkResult compressionRes =
1166 driver.GetPhysicalDeviceImageFormatProperties2KHR(
1167 physicalDevice, &imageFormatInfo,
1168 &imageFormatProps);
1169 if (compressionRes == VK_SUCCESS) {
1170 surfaceCompressionProps->imageCompressionFlags =
1171 compressionProps.imageCompressionFlags;
1172 surfaceCompressionProps
1173 ->imageCompressionFixedRateFlags =
1174 compressionProps.imageCompressionFixedRateFlags;
1175 } else {
1176 return compressionRes;
1177 }
1178 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001179 } break;
1180
1181 default:
1182 // Ignore all other extension structs
1183 break;
Chris Forbes2452cf72017-03-16 16:30:17 +13001184 }
1185 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001186 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001187
1188 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +13001189}
1190
1191VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +13001192VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001193 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +08001194 uint32_t* count,
1195 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001196 ATRACE_CALL();
1197
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001198 int err;
1199 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -06001200 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -06001201 if (surface == VK_NULL_HANDLE) {
1202 const InstanceData& instance_data = GetData(pdev);
1203 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
1204 bool surfaceless_enabled =
1205 instance_data.hook_extensions.test(surfaceless);
1206 if (!surfaceless_enabled) {
1207 return VK_ERROR_SURFACE_LOST_KHR;
1208 }
1209 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
1210 // extension for this function is for
1211 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
1212 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
1213 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
Ian Elliott7e361142022-06-02 10:45:17 -06001214 // surface, and that cannot be relied upon. Therefore, don't return it.
Ian Elliott1ce053f2022-03-16 09:49:53 -06001215 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1216 } else {
1217 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1218
1219 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1220 &query_value);
1221 if (err != android::OK || query_value < 0) {
1222 ALOGE(
1223 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
1224 "value=%d",
1225 strerror(-err), err, query_value);
1226 return VK_ERROR_SURFACE_LOST_KHR;
1227 }
1228 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1229
1230 err =
1231 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
1232 if (err != android::OK || query_value < 0) {
1233 ALOGE(
1234 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
1235 strerror(-err), err, query_value);
1236 return VK_ERROR_SURFACE_LOST_KHR;
1237 }
1238 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
1239
1240 if (min_undequeued_buffers + 1 < max_buffer_count)
1241 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
1242 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1243 }
Chris Forbese8d79a62017-02-22 12:49:18 +13001244
1245 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -07001246 QueryPresentationProperties(pdev, &present_properties);
1247 if (present_properties.sharedImage) {
1248 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1249 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +13001250 }
1251
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001252 return CopyWithIncomplete(present_modes, modes, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001253}
1254
Jesse Halle1b12782015-11-30 11:27:32 -08001255VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001256VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001257 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001258 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001259 ATRACE_CALL();
1260
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001261 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
1262 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1263 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1264 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1265 pDeviceGroupPresentCapabilities->sType);
1266
1267 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1268 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1269
1270 // assume device group of size 1
1271 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1272 pDeviceGroupPresentCapabilities->modes =
1273 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1274
1275 return VK_SUCCESS;
1276}
1277
1278VKAPI_ATTR
1279VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001280 VkDevice,
1281 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001282 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001283 ATRACE_CALL();
1284
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001285 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1286 return VK_SUCCESS;
1287}
1288
1289VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001290VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001291 VkSurfaceKHR surface,
1292 uint32_t* pRectCount,
1293 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001294 ATRACE_CALL();
1295
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001296 if (!pRects) {
1297 *pRectCount = 1;
1298 } else {
1299 uint32_t count = std::min(*pRectCount, 1u);
1300 bool incomplete = *pRectCount < 1;
1301
1302 *pRectCount = count;
1303
1304 if (incomplete) {
1305 return VK_INCOMPLETE;
1306 }
1307
1308 int err;
1309 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1310
1311 int width = 0, height = 0;
1312 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001313 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001314 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1315 strerror(-err), err);
1316 }
1317 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001318 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001319 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1320 strerror(-err), err);
1321 }
1322
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001323 pRects[0].offset.x = 0;
1324 pRects[0].offset.y = 0;
1325 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1326 static_cast<uint32_t>(height)};
1327 }
1328 return VK_SUCCESS;
1329}
1330
Yiwei Zhang533cea92019-06-03 18:43:24 -07001331static void DestroySwapchainInternal(VkDevice device,
1332 VkSwapchainKHR swapchain_handle,
1333 const VkAllocationCallbacks* allocator) {
1334 ATRACE_CALL();
1335
1336 const auto& dispatch = GetData(device).driver;
1337 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1338 if (!swapchain) {
1339 return;
1340 }
1341
1342 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1343 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1344
1345 if (window && swapchain->frame_timestamps_enabled) {
1346 native_window_enable_frame_timestamps(window, false);
1347 }
1348
1349 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +00001350 ReleaseSwapchainImage(device, swapchain->shared, window, -1,
1351 swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001352 }
1353
1354 if (active) {
1355 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1356 }
1357
1358 if (!allocator) {
1359 allocator = &GetData(device).allocator;
1360 }
1361
1362 swapchain->~Swapchain();
1363 allocator->pfnFree(allocator->pUserData, swapchain);
1364}
1365
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001366static VkResult getProducerUsage(const VkDevice& device,
1367 const VkSwapchainCreateInfoKHR* create_info,
1368 const VkSwapchainImageUsageFlagsANDROID swapchain_image_usage,
1369 bool create_protected_swapchain,
1370 uint64_t* producer_usage) {
1371 // Get the physical device to query the appropriate producer usage
1372 const VkPhysicalDevice& pdev = GetData(device).driver_physical_device;
1373 const InstanceData& instance_data = GetData(pdev);
1374 const InstanceDriverTable& instance_dispatch = instance_data.driver;
Trevor David Black02926f52024-01-04 18:44:20 +00001375 if (instance_dispatch.GetPhysicalDeviceImageFormatProperties2 ||
1376 instance_dispatch.GetPhysicalDeviceImageFormatProperties2KHR) {
1377 // Look through the create_info pNext chain passed to createSwapchainKHR
1378 // for an image compression control struct.
1379 // if one is found AND the appropriate extensions are enabled, create a
1380 // VkImageCompressionControlEXT structure to pass on to
1381 // GetPhysicalDeviceImageFormatProperties2
1382 void* compression_control_pNext = nullptr;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001383 VkImageCompressionControlEXT image_compression = {};
Trevor David Black02926f52024-01-04 18:44:20 +00001384 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1385 while (create_infos->pNext) {
1386 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(create_infos->pNext);
1387 switch (create_infos->sType) {
1388 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1389 const VkImageCompressionControlEXT* compression_infos =
1390 reinterpret_cast<const VkImageCompressionControlEXT*>(create_infos);
1391 image_compression = *compression_infos;
1392 image_compression.pNext = nullptr;
1393 compression_control_pNext = &image_compression;
1394 } break;
1395 default:
1396 // Ignore all other info structs
1397 break;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001398 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001399 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001400
Trevor David Black02926f52024-01-04 18:44:20 +00001401 // call GetPhysicalDeviceImageFormatProperties2KHR
1402 VkPhysicalDeviceExternalImageFormatInfo external_image_format_info = {
1403 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1404 .pNext = compression_control_pNext,
1405 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID,
1406 };
1407
1408 // AHB does not have an sRGB format so we can't pass it to GPDIFP
1409 // We need to convert the format to unorm if it is srgb
1410 VkFormat format = create_info->imageFormat;
1411 if (format == VK_FORMAT_R8G8B8A8_SRGB) {
1412 format = VK_FORMAT_R8G8B8A8_UNORM;
1413 }
1414
1415 VkPhysicalDeviceImageFormatInfo2 image_format_info = {
1416 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1417 .pNext = &external_image_format_info,
1418 .format = format,
1419 .type = VK_IMAGE_TYPE_2D,
1420 .tiling = VK_IMAGE_TILING_OPTIMAL,
1421 .usage = create_info->imageUsage,
1422 .flags = create_protected_swapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
1423 };
1424
1425 VkAndroidHardwareBufferUsageANDROID ahb_usage;
1426 ahb_usage.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_USAGE_ANDROID;
1427 ahb_usage.pNext = nullptr;
1428
1429 VkImageFormatProperties2 image_format_properties;
1430 image_format_properties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
1431 image_format_properties.pNext = &ahb_usage;
1432
1433 if (instance_dispatch.GetPhysicalDeviceImageFormatProperties2) {
1434 VkResult result = instance_dispatch.GetPhysicalDeviceImageFormatProperties2(
1435 pdev, &image_format_info, &image_format_properties);
1436 if (result != VK_SUCCESS) {
1437 ALOGE("VkGetPhysicalDeviceImageFormatProperties2 for AHB usage failed: %d", result);
1438 return VK_ERROR_SURFACE_LOST_KHR;
1439 }
1440 }
1441 else {
1442 VkResult result = instance_dispatch.GetPhysicalDeviceImageFormatProperties2KHR(
1443 pdev, &image_format_info,
1444 &image_format_properties);
1445 if (result != VK_SUCCESS) {
1446 ALOGE("VkGetPhysicalDeviceImageFormatProperties2KHR for AHB usage failed: %d",
1447 result);
1448 return VK_ERROR_SURFACE_LOST_KHR;
1449 }
1450 }
1451
1452 // Determine if USAGE_FRONT_BUFFER is needed.
1453 // GPDIFP2 has no means of using VkSwapchainImageUsageFlagsANDROID when
1454 // querying for producer_usage. So androidHardwareBufferUsage will not
1455 // contain USAGE_FRONT_BUFFER. We need to manually check for usage here.
1456 if (!(swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID)) {
1457 *producer_usage = ahb_usage.androidHardwareBufferUsage;
1458 return VK_SUCCESS;
1459 }
1460
1461 // Check if USAGE_FRONT_BUFFER is supported for this swapchain
1462 AHardwareBuffer_Desc ahb_desc = {
1463 .width = create_info->imageExtent.width,
1464 .height = create_info->imageExtent.height,
1465 .layers = create_info->imageArrayLayers,
1466 .format = create_info->imageFormat,
1467 .usage = ahb_usage.androidHardwareBufferUsage | AHARDWAREBUFFER_USAGE_FRONT_BUFFER,
1468 .stride = 0, // stride is always ignored when calling isSupported()
1469 };
1470
1471 // If FRONT_BUFFER is not supported,
1472 // then we need to call GetSwapchainGrallocUsageXAndroid below
1473 if (AHardwareBuffer_isSupported(&ahb_desc)) {
1474 *producer_usage = ahb_usage.androidHardwareBufferUsage;
1475 *producer_usage |= AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
1476 return VK_SUCCESS;
1477 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001478 }
1479
Trevor David Black02926f52024-01-04 18:44:20 +00001480 uint64_t native_usage = 0;
1481 void* usage_info_pNext = nullptr;
1482 VkResult result;
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001483 VkImageCompressionControlEXT image_compression = {};
Trevor David Black02926f52024-01-04 18:44:20 +00001484 const auto& dispatch = GetData(device).driver;
1485 if (dispatch.GetSwapchainGrallocUsage4ANDROID) {
1486 ATRACE_BEGIN("GetSwapchainGrallocUsage4ANDROID");
1487 VkGrallocUsageInfo2ANDROID gralloc_usage_info = {};
1488 gralloc_usage_info.sType =
1489 VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_2_ANDROID;
1490 gralloc_usage_info.format = create_info->imageFormat;
1491 gralloc_usage_info.imageUsage = create_info->imageUsage;
1492 gralloc_usage_info.swapchainImageUsage = swapchain_image_usage;
1493
1494 // Look through the pNext chain for an image compression control struct
1495 // if one is found AND the appropriate extensions are enabled,
1496 // append it to be the gralloc usage pNext chain
1497 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1498 while (create_infos->pNext) {
1499 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1500 create_infos->pNext);
1501 switch (create_infos->sType) {
1502 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1503 const VkImageCompressionControlEXT* compression_infos =
1504 reinterpret_cast<const VkImageCompressionControlEXT*>(
1505 create_infos);
1506 image_compression = *compression_infos;
1507 image_compression.pNext = nullptr;
1508 usage_info_pNext = &image_compression;
1509 } break;
1510
1511 default:
1512 // Ignore all other info structs
1513 break;
1514 }
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001515 }
Trevor David Black02926f52024-01-04 18:44:20 +00001516 gralloc_usage_info.pNext = usage_info_pNext;
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001517
Trevor David Black02926f52024-01-04 18:44:20 +00001518 result = dispatch.GetSwapchainGrallocUsage4ANDROID(
1519 device, &gralloc_usage_info, &native_usage);
1520 ATRACE_END();
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001521 if (result != VK_SUCCESS) {
Trevor David Black02926f52024-01-04 18:44:20 +00001522 ALOGE("vkGetSwapchainGrallocUsage4ANDROID failed: %d", result);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001523 return VK_ERROR_SURFACE_LOST_KHR;
1524 }
Trevor David Black02926f52024-01-04 18:44:20 +00001525 } else if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
1526 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1527 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1528 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1529 gralloc_usage_info.format = create_info->imageFormat;
1530 gralloc_usage_info.imageUsage = create_info->imageUsage;
1531
1532 // Look through the pNext chain for an image compression control struct
1533 // if one is found AND the appropriate extensions are enabled,
1534 // append it to be the gralloc usage pNext chain
1535 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1536 while (create_infos->pNext) {
1537 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1538 create_infos->pNext);
1539 switch (create_infos->sType) {
1540 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1541 const VkImageCompressionControlEXT* compression_infos =
1542 reinterpret_cast<const VkImageCompressionControlEXT*>(
1543 create_infos);
1544 image_compression = *compression_infos;
1545 image_compression.pNext = nullptr;
1546 usage_info_pNext = &image_compression;
1547 } break;
1548
1549 default:
1550 // Ignore all other info structs
1551 break;
1552 }
1553 }
1554 gralloc_usage_info.pNext = usage_info_pNext;
1555
1556 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1557 device, &gralloc_usage_info, &native_usage);
1558 ATRACE_END();
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001559 if (result != VK_SUCCESS) {
Trevor David Black02926f52024-01-04 18:44:20 +00001560 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001561 return VK_ERROR_SURFACE_LOST_KHR;
1562 }
Trevor David Black02926f52024-01-04 18:44:20 +00001563 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
1564 uint64_t consumer_usage, producer_usage;
1565 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
1566 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1567 device, create_info->imageFormat, create_info->imageUsage,
1568 swapchain_image_usage, &consumer_usage, &producer_usage);
1569 ATRACE_END();
1570 if (result != VK_SUCCESS) {
1571 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
1572 return VK_ERROR_SURFACE_LOST_KHR;
1573 }
1574 native_usage =
1575 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
1576 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
1577 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
1578 int32_t legacy_usage = 0;
1579 result = dispatch.GetSwapchainGrallocUsageANDROID(
1580 device, create_info->imageFormat, create_info->imageUsage,
1581 &legacy_usage);
1582 ATRACE_END();
1583 if (result != VK_SUCCESS) {
1584 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
1585 return VK_ERROR_SURFACE_LOST_KHR;
1586 }
1587 native_usage = static_cast<uint64_t>(legacy_usage);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001588 }
Trevor David Black02926f52024-01-04 18:44:20 +00001589 *producer_usage = native_usage;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001590
1591 return VK_SUCCESS;
1592}
1593
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001594VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001595VkResult CreateSwapchainKHR(VkDevice device,
1596 const VkSwapchainCreateInfoKHR* create_info,
1597 const VkAllocationCallbacks* allocator,
1598 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001599 ATRACE_CALL();
1600
Jesse Halld7b994a2015-09-07 14:17:37 -07001601 int err;
1602 VkResult result = VK_SUCCESS;
1603
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001604 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1605 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1606 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1607 " oldSwapchain=0x%" PRIx64,
1608 reinterpret_cast<uint64_t>(create_info->surface),
1609 create_info->minImageCount, create_info->imageFormat,
1610 create_info->imageColorSpace, create_info->imageExtent.width,
1611 create_info->imageExtent.height, create_info->imageUsage,
1612 create_info->preTransform, create_info->presentMode,
1613 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1614
Jesse Hall1f91d392015-12-11 16:28:44 -08001615 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001616 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001617
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001618 PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001619 GetNativePixelFormat(create_info->imageFormat);
sergiuferentz47989332023-09-26 10:24:36 +00001620 DataSpace native_dataspace =
Sally Qiaa238972023-07-17 12:52:05 +08001621 GetNativeDataspace(create_info->imageColorSpace, native_pixel_format);
sergiuferentz47989332023-09-26 10:24:36 +00001622 if (native_dataspace == DataSpace::UNKNOWN) {
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001623 ALOGE(
1624 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1625 "failed: Unsupported color space",
1626 create_info->imageColorSpace);
1627 return VK_ERROR_INITIALIZATION_FAILED;
1628 }
1629
Jesse Hall42a9eec2016-06-03 12:39:49 -07001630 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001631 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001632 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001633 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001634 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001635 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001636 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001637 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001638 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1639 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001640 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001641 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001642
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001643 Surface& surface = *SurfaceFromHandle(create_info->surface);
1644
Jesse Halldc225072016-05-30 22:40:14 -07001645 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001646 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001647 " because it already has active swapchain 0x%" PRIx64
1648 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1649 reinterpret_cast<uint64_t>(create_info->surface),
1650 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1651 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1652 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1653 }
1654 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1655 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1656
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001657 // -- Reset the native window --
1658 // The native window might have been used previously, and had its properties
1659 // changed from defaults. That will affect the answer we get for queries
1660 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1661 // attempt such queries.
1662
Jesse Halldc225072016-05-30 22:40:14 -07001663 // The native window only allows dequeueing all buffers before any have
1664 // been queued, since after that point at least one is assumed to be in
1665 // non-FREE state at any given time. Disconnecting and re-connecting
1666 // orphans the previous buffers, getting us back to the state where we can
1667 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001668 //
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001669 // This is not necessary if the surface was never used previously.
1670 //
Yiwei Zhang70a21962019-05-31 17:26:52 -07001671 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001672 ANativeWindow* window = surface.window.get();
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001673 if (surface.used_by_swapchain) {
1674 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1675 ALOGW_IF(err != android::OK,
1676 "native_window_api_disconnect failed: %s (%d)", strerror(-err),
1677 err);
1678 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1679 ALOGW_IF(err != android::OK,
1680 "native_window_api_connect failed: %s (%d)", strerror(-err),
1681 err);
1682 }
Jesse Halldc225072016-05-30 22:40:14 -07001683
Nicolas Capens147b7da2021-04-09 14:53:06 -04001684 err =
1685 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001686 if (err != android::OK) {
1687 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1688 strerror(-err), err);
1689 return VK_ERROR_SURFACE_LOST_KHR;
1690 }
1691
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301692 int swap_interval =
1693 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001694 err = window->setSwapInterval(window, swap_interval);
1695 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001696 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1697 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001698 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001699 }
1700
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001701 err = native_window_set_shared_buffer_mode(window, false);
1702 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001703 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1704 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001705 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001706 }
1707
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001708 err = native_window_set_auto_refresh(window, false);
1709 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001710 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1711 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001712 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001713 }
1714
Jesse Halld7b994a2015-09-07 14:17:37 -07001715 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001716
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001717 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001718
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001719 err = native_window_set_buffers_format(
1720 window, static_cast<int>(native_pixel_format));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001721 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001722 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001723 toString(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001724 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001725 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001726
1727 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
sergiuferentz47989332023-09-26 10:24:36 +00001728 if (native_dataspace != DataSpace::ARBITRARY) {
1729 err = native_window_set_buffers_data_space(
1730 window, static_cast<android_dataspace_t>(native_dataspace));
Yiwei Zhang51572c22022-07-22 23:08:30 +00001731 if (err != android::OK) {
1732 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1733 native_dataspace, strerror(-err), err);
1734 return VK_ERROR_SURFACE_LOST_KHR;
1735 }
Jesse Hall517274a2016-02-10 00:07:18 -08001736 }
1737
Jesse Hall3dd678a2016-01-08 21:52:01 -08001738 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001739 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001740 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001741 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001742 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1743 create_info->imageExtent.width, create_info->imageExtent.height,
1744 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001745 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001746 }
1747
Jesse Hall178b6962016-02-24 15:39:50 -08001748 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1749 // applied during rendering. native_window_set_transform() expects the
1750 // inverse: the transform the app is requesting that the compositor perform
1751 // during composition. With native windows, pre-transform works by rendering
1752 // with the same transform the compositor is applying (as in Vulkan), but
1753 // then requesting the inverse transform, so that when the compositor does
1754 // it's job the two transforms cancel each other out and the compositor ends
1755 // up applying an identity transform to the app's buffer.
1756 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001757 window, InvertTransformToNative(create_info->preTransform));
1758 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001759 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1760 InvertTransformToNative(create_info->preTransform),
1761 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001762 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001763 }
1764
Jesse Hallf64ca122015-11-03 16:11:10 -08001765 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001766 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1767 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001768 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1769 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001770 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001771 }
1772
Chris Forbes97ef4612017-03-30 19:37:50 +13001773 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001774 if (IsSharedPresentMode(create_info->presentMode)) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001775 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001776 err = native_window_set_shared_buffer_mode(window, true);
1777 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001778 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1779 return VK_ERROR_SURFACE_LOST_KHR;
1780 }
1781 }
1782
1783 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001784 err = native_window_set_auto_refresh(window, true);
1785 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001786 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1787 return VK_ERROR_SURFACE_LOST_KHR;
1788 }
1789 }
1790
Ian Elliott16c443c2021-11-30 17:10:32 -07001791 int query_value;
Trevor David Blackabab5a02023-12-19 20:27:07 +00001792 // TODO: Now that we are calling into GPDSC2 directly, this query may be redundant
1793 // the call to std::max(min_buffer_count, num_images) may be redundant as well
Ian Elliott16c443c2021-11-30 17:10:32 -07001794 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1795 &query_value);
1796 if (err != android::OK || query_value < 0) {
1797 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1798 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001799 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001800 }
Trevor David Black8c0122e2023-09-07 20:33:54 +00001801 const uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
Chris Forbes2c8fc752017-03-17 11:28:32 +13001802
Ian Elliott5396b702021-12-13 19:32:34 -07001803 // Lower layer insists that we have at least min_undequeued_buffers + 1
1804 // buffers. This is wasteful and we'd like to relax it in the shared case,
1805 // but not all the pieces are in place for that to work yet. Note we only
1806 // lie to the lower layer--we don't want to give the app back a swapchain
1807 // with extra images (which they can't actually use!).
Trevor David Black8c0122e2023-09-07 20:33:54 +00001808 const uint32_t min_buffer_count = min_undequeued_buffers + 1;
1809
Trevor David Blackabab5a02023-12-19 20:27:07 +00001810 // Call into GPDSC2 to get the minimum and maximum allowable buffer count for the surface of
1811 // interest. This step is only necessary if the app requests a number of images
1812 // (create_info->minImageCount) that is less or more than the surface capabilities.
1813 // An app should be calling GPDSC2 and using those values to set create_info, but in the
1814 // event that the app has hard-coded image counts an error can occur
1815 VkSurfacePresentModeEXT present_mode = {
1816 VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT,
1817 nullptr,
1818 create_info->presentMode
1819 };
1820 VkPhysicalDeviceSurfaceInfo2KHR surface_info2 = {
1821 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
1822 &present_mode,
1823 create_info->surface
1824 };
1825 VkSurfaceCapabilities2KHR surface_capabilities2 = {
1826 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
1827 nullptr,
1828 {},
1829 };
1830 result = GetPhysicalDeviceSurfaceCapabilities2KHR(GetData(device).driver_physical_device,
1831 &surface_info2, &surface_capabilities2);
1832
1833 uint32_t num_images = create_info->minImageCount;
1834 num_images = std::clamp(num_images,
1835 surface_capabilities2.surfaceCapabilities.minImageCount,
1836 surface_capabilities2.surfaceCapabilities.maxImageCount);
Trevor David Black8c0122e2023-09-07 20:33:54 +00001837
1838 const uint32_t buffer_count = std::max(min_buffer_count, num_images);
1839 err = native_window_set_buffer_count(window, buffer_count);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001840 if (err != android::OK) {
Trevor David Black8c0122e2023-09-07 20:33:54 +00001841 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", buffer_count,
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001842 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001843 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001844 }
1845
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001846 // In shared mode the num_images must be one regardless of how many
1847 // buffers were allocated for the buffer queue.
1848 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1849 num_images = 1;
1850 }
1851
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001852 // Look through the create_info pNext chain passed to createSwapchainKHR
1853 // for an image compression control struct.
1854 // if one is found AND the appropriate extensions are enabled, create a
1855 // VkImageCompressionControlEXT structure to pass on to VkImageCreateInfo
1856 // TODO check for imageCompressionControlSwapchain feature is enabled
Trevor David Black2cc44682022-03-09 00:31:38 +00001857 void* usage_info_pNext = nullptr;
1858 VkImageCompressionControlEXT image_compression = {};
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001859 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1860 while (create_infos->pNext) {
1861 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(create_infos->pNext);
1862 switch (create_infos->sType) {
1863 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1864 const VkImageCompressionControlEXT* compression_infos =
1865 reinterpret_cast<const VkImageCompressionControlEXT*>(create_infos);
1866 image_compression = *compression_infos;
1867 image_compression.pNext = nullptr;
1868 usage_info_pNext = &image_compression;
1869 } break;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001870
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001871 default:
1872 // Ignore all other info structs
1873 break;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001874 }
Jesse Hall70f93352015-11-04 09:41:31 -08001875 }
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001876
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001877 // Get the appropriate native_usage for the images
1878 // Get the consumer usage
1879 uint64_t native_usage = surface.consumer_usage;
1880 // Determine if the swapchain is protected
1881 bool create_protected_swapchain = false;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001882 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001883 create_protected_swapchain = true;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001884 native_usage |= BufferUsage::PROTECTED;
1885 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001886 // Get the producer usage
1887 uint64_t producer_usage;
1888 result = getProducerUsage(device, create_info, swapchain_image_usage, create_protected_swapchain, &producer_usage);
1889 if (result != VK_SUCCESS) {
1890 return result;
1891 }
1892 native_usage |= producer_usage;
1893
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001894 err = native_window_set_usage(window, native_usage);
1895 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001896 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001897 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001898 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001899
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001900 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001901 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1902 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001903 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1904 strerror(-err), err);
1905 return VK_ERROR_SURFACE_LOST_KHR;
1906 }
1907
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001908 int64_t refresh_duration;
1909 err = native_window_get_refresh_cycle_duration(window, &refresh_duration);
1910 if (err != android::OK) {
1911 ALOGE("native_window_get_refresh_cycle_duration query failed: %s (%d)",
1912 strerror(-err), err);
1913 return VK_ERROR_SURFACE_LOST_KHR;
1914 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001915 // -- Allocate our Swapchain object --
1916 // After this point, we must deallocate the swapchain on error.
1917
Jesse Hall1f91d392015-12-11 16:28:44 -08001918 void* mem = allocator->pfnAllocation(allocator->pUserData,
1919 sizeof(Swapchain), alignof(Swapchain),
1920 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001921
Jesse Hall1356b0d2015-11-23 17:24:58 -08001922 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001923 return VK_ERROR_OUT_OF_HOST_MEMORY;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001924
silence_dogood73597592019-05-23 16:57:37 -07001925 Swapchain* swapchain = new (mem)
1926 Swapchain(surface, num_images, create_info->presentMode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001927 TranslateVulkanToNativeTransform(create_info->preTransform),
1928 refresh_duration);
Chris Forbesb56287a2017-01-12 14:28:58 +13001929 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1930#pragma clang diagnostic push
1931#pragma clang diagnostic ignored "-Wold-style-cast"
1932 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1933#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00001934 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13001935 .usage = swapchain_image_usage,
1936 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001937 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001938#pragma clang diagnostic push
1939#pragma clang diagnostic ignored "-Wold-style-cast"
1940 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1941#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001942 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001943 };
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001944
Jesse Halld7b994a2015-09-07 14:17:37 -07001945 VkImageCreateInfo image_create = {
1946 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001947 .pNext = nullptr,
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001948 .flags = create_protected_swapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07001949 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08001950 .format = create_info->imageFormat,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001951 .extent = {
1952 create_info->imageExtent.width,
1953 create_info->imageExtent.height,
1954 1
1955 },
Jesse Halld7b994a2015-09-07 14:17:37 -07001956 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08001957 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08001958 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07001959 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001960 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001961 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08001962 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07001963 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1964 };
1965
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001966 // Note: don't do deferred allocation for shared present modes. There's only one buffer
1967 // involved so very little benefit.
1968 if ((create_info->flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT) &&
1969 !IsSharedPresentMode(create_info->presentMode)) {
1970 // Don't want to touch the underlying gralloc buffers yet;
1971 // instead just create unbound VkImages which will later be bound to memory inside
1972 // AcquireNextImage.
1973 VkImageSwapchainCreateInfoKHR image_swapchain_create = {
1974 .sType = VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR,
1975 .pNext = nullptr,
1976 .swapchain = HandleFromSwapchain(swapchain),
1977 };
1978 image_create.pNext = &image_swapchain_create;
Jesse Halld7b994a2015-09-07 14:17:37 -07001979
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001980 for (uint32_t i = 0; i < num_images; i++) {
1981 Swapchain::Image& img = swapchain->images[i];
1982 img.buffer = nullptr;
1983 img.dequeued = false;
1984
1985 result = dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1986 if (result != VK_SUCCESS) {
1987 ALOGD("vkCreateImage w/ for deferred swapchain image failed: %u", result);
1988 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08001989 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001990 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001991 } else {
1992 // -- Dequeue all buffers and create a VkImage for each --
1993 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07001994
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001995 for (uint32_t i = 0; i < num_images; i++) {
1996 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07001997
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001998 ANativeWindowBuffer* buffer;
1999 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
2000 if (err != android::OK) {
2001 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
2002 switch (-err) {
2003 case ENOMEM:
2004 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
2005 break;
2006 default:
2007 result = VK_ERROR_SURFACE_LOST_KHR;
2008 break;
2009 }
2010 break;
2011 }
2012 img.buffer = buffer;
2013 img.dequeued = true;
2014
2015 image_native_buffer.handle = img.buffer->handle;
2016 image_native_buffer.stride = img.buffer->stride;
2017 image_native_buffer.format = img.buffer->format;
2018 image_native_buffer.usage = int(img.buffer->usage);
2019 android_convertGralloc0To1Usage(int(img.buffer->usage),
2020 &image_native_buffer.usage2.producer,
2021 &image_native_buffer.usage2.consumer);
2022 image_native_buffer.usage3 = img.buffer->usage;
Trevor David Black0db7a092023-12-11 23:46:36 +00002023 image_native_buffer.ahb =
2024 ANativeWindowBuffer_getHardwareBuffer(img.buffer.get());
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002025 image_create.pNext = &image_native_buffer;
2026
2027 ATRACE_BEGIN("CreateImage");
2028 result =
2029 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
2030 ATRACE_END();
2031 if (result != VK_SUCCESS) {
2032 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
2033 break;
2034 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002035 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002036
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002037 // -- Cancel all buffers, returning them to the queue --
2038 // If an error occurred before, also destroy the VkImage and release the
2039 // buffer reference. Otherwise, we retain a strong reference to the buffer.
2040 for (uint32_t i = 0; i < num_images; i++) {
2041 Swapchain::Image& img = swapchain->images[i];
2042 if (img.dequeued) {
2043 if (!swapchain->shared) {
2044 window->cancelBuffer(window, img.buffer.get(),
2045 img.dequeue_fence);
2046 img.dequeue_fence = -1;
2047 img.dequeued = false;
2048 }
Chris Forbese0ced032017-03-30 19:44:15 +13002049 }
Chris Forbes31b85c22018-05-29 15:03:28 -07002050 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002051 }
2052
2053 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07002054 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
2055 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07002056 return result;
2057 }
2058
Yiwei Zhang69395cd2019-07-03 16:55:39 -07002059 if (transform_hint != swapchain->pre_transform) {
2060 // Log that the app is not doing pre-rotation.
2061 android::GraphicsEnv::getInstance().setTargetStats(
2062 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
2063 }
2064
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00002065 // Set stats for creating a Vulkan swapchain
2066 android::GraphicsEnv::getInstance().setTargetStats(
2067 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
2068
Yiwei Zhang3b88f312023-04-18 23:11:35 +00002069 surface.used_by_swapchain = true;
Jesse Halldc225072016-05-30 22:40:14 -07002070 surface.swapchain_handle = HandleFromSwapchain(swapchain);
2071 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002072 return VK_SUCCESS;
2073}
2074
Jesse Halle1b12782015-11-30 11:27:32 -08002075VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002076void DestroySwapchainKHR(VkDevice device,
2077 VkSwapchainKHR swapchain_handle,
2078 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002079 ATRACE_CALL();
2080
Yiwei Zhang533cea92019-06-03 18:43:24 -07002081 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07002082}
2083
Jesse Halle1b12782015-11-30 11:27:32 -08002084VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002085VkResult GetSwapchainImagesKHR(VkDevice,
2086 VkSwapchainKHR swapchain_handle,
2087 uint32_t* count,
2088 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002089 ATRACE_CALL();
2090
Jesse Halld7b994a2015-09-07 14:17:37 -07002091 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07002092 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
2093 "getting images for non-active swapchain 0x%" PRIx64
2094 "; only dequeued image handles are valid",
2095 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07002096 VkResult result = VK_SUCCESS;
2097 if (images) {
2098 uint32_t n = swapchain.num_images;
2099 if (*count < swapchain.num_images) {
2100 n = *count;
2101 result = VK_INCOMPLETE;
2102 }
2103 for (uint32_t i = 0; i < n; i++)
2104 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07002105 *count = n;
2106 } else {
2107 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07002108 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002109 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002110}
2111
Jesse Halle1b12782015-11-30 11:27:32 -08002112VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002113VkResult AcquireNextImageKHR(VkDevice device,
2114 VkSwapchainKHR swapchain_handle,
2115 uint64_t timeout,
2116 VkSemaphore semaphore,
2117 VkFence vk_fence,
2118 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002119 ATRACE_CALL();
2120
Jesse Halld7b994a2015-09-07 14:17:37 -07002121 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08002122 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07002123 VkResult result;
2124 int err;
2125
Jesse Halldc225072016-05-30 22:40:14 -07002126 if (swapchain.surface.swapchain_handle != swapchain_handle)
2127 return VK_ERROR_OUT_OF_DATE_KHR;
2128
Chris Forbesc88409c2017-03-30 19:47:37 +13002129 if (swapchain.shared) {
2130 // In shared mode, we keep the buffer dequeued all the time, so we don't
2131 // want to dequeue a buffer here. Instead, just ask the driver to ensure
2132 // the semaphore and fence passed to us will be signalled.
2133 *image_index = 0;
2134 result = GetData(device).driver.AcquireImageANDROID(
2135 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
2136 return result;
2137 }
2138
Yiwei Zhang705c2e62019-12-18 23:12:43 -08002139 const nsecs_t acquire_next_image_timeout =
2140 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
2141 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
2142 // Cache the timeout to avoid the duplicate binder cost.
2143 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
2144 acquire_next_image_timeout);
2145 if (err != android::OK) {
2146 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
2147 strerror(-err), err);
2148 return VK_ERROR_SURFACE_LOST_KHR;
2149 }
2150 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
2151 }
2152
Jesse Halld7b994a2015-09-07 14:17:37 -07002153 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08002154 int fence_fd;
2155 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07002156 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08002157 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
2158 return timeout ? VK_TIMEOUT : VK_NOT_READY;
2159 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07002160 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07002161 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002162 }
2163
2164 uint32_t idx;
2165 for (idx = 0; idx < swapchain.num_images; idx++) {
2166 if (swapchain.images[idx].buffer.get() == buffer) {
2167 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08002168 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07002169 break;
2170 }
2171 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002172
2173 // If this is a deferred alloc swapchain, this may be the first time we've
2174 // seen a particular buffer. If so, there should be an empty slot. Find it,
2175 // and bind the gralloc buffer to the VkImage for that slot. If there is no
2176 // empty slot, then we dequeued an unexpected buffer. Non-deferred swapchains
2177 // will also take this path, but will never have an empty slot since we
2178 // populated them all upfront.
2179 if (idx == swapchain.num_images) {
2180 for (idx = 0; idx < swapchain.num_images; idx++) {
2181 if (!swapchain.images[idx].buffer) {
2182 // Note: this structure is technically required for
2183 // Vulkan correctness, even though the driver is probably going
2184 // to use everything from the VkNativeBufferANDROID below.
2185 // This is kindof silly, but it's how we did the ANB
2186 // side of VK_KHR_swapchain v69, so we're stuck with it unless
2187 // we want to go tinkering with the ANB spec some more.
2188 VkBindImageMemorySwapchainInfoKHR bimsi = {
2189 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR,
2190 .pNext = nullptr,
2191 .swapchain = swapchain_handle,
2192 .imageIndex = idx,
2193 };
2194 VkNativeBufferANDROID nb = {
2195 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2196 .pNext = &bimsi,
2197 .handle = buffer->handle,
2198 .stride = buffer->stride,
2199 .format = buffer->format,
2200 .usage = int(buffer->usage),
Trevor David Black0db7a092023-12-11 23:46:36 +00002201 .usage3 = buffer->usage,
2202 .ahb = ANativeWindowBuffer_getHardwareBuffer(buffer),
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002203 };
Trevor David Black0db7a092023-12-11 23:46:36 +00002204 android_convertGralloc0To1Usage(int(buffer->usage),
2205 &nb.usage2.producer,
2206 &nb.usage2.consumer);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002207 VkBindImageMemoryInfo bimi = {
2208 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO,
2209 .pNext = &nb,
2210 .image = swapchain.images[idx].image,
2211 .memory = VK_NULL_HANDLE,
2212 .memoryOffset = 0,
2213 };
2214 result = GetData(device).driver.BindImageMemory2(device, 1, &bimi);
2215 if (result != VK_SUCCESS) {
2216 // This shouldn't really happen. If it does, something is probably
2217 // unrecoverably wrong with the swapchain and its images. Cancel
2218 // the buffer and declare the swapchain broken.
2219 ALOGE("failed to do deferred gralloc buffer bind");
2220 window->cancelBuffer(window, buffer, fence_fd);
2221 return VK_ERROR_OUT_OF_DATE_KHR;
2222 }
2223
2224 swapchain.images[idx].dequeued = true;
2225 swapchain.images[idx].dequeue_fence = fence_fd;
2226 swapchain.images[idx].buffer = buffer;
2227 break;
2228 }
2229 }
2230 }
2231
2232 // The buffer doesn't match any slot. This shouldn't normally happen, but is
2233 // possible if the bufferqueue is reconfigured behind libvulkan's back. If this
2234 // happens, just declare the swapchain to be broken and the app will recreate it.
Jesse Halld7b994a2015-09-07 14:17:37 -07002235 if (idx == swapchain.num_images) {
2236 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08002237 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002238 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002239 }
2240
2241 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08002242 if (fence_fd != -1) {
2243 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002244 if (fence_clone == -1) {
2245 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
2246 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08002247 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07002248 }
2249 }
2250
Chia-I Wu4a6a9162016-03-26 07:17:34 +08002251 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08002252 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07002253 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08002254 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
2255 // even if the call fails. We could close it ourselves on failure, but
2256 // that would create a race condition if the driver closes it on a
2257 // failure path: some other thread might create an fd with the same
2258 // number between the time the driver closes it and the time we close
2259 // it. We must assume one of: the driver *always* closes it even on
2260 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08002261 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002262 swapchain.images[idx].dequeued = false;
2263 swapchain.images[idx].dequeue_fence = -1;
2264 return result;
2265 }
2266
2267 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002268 return VK_SUCCESS;
2269}
2270
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002271VKAPI_ATTR
2272VkResult AcquireNextImage2KHR(VkDevice device,
2273 const VkAcquireNextImageInfoKHR* pAcquireInfo,
2274 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002275 ATRACE_CALL();
2276
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002277 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
2278 pAcquireInfo->timeout, pAcquireInfo->semaphore,
2279 pAcquireInfo->fence, pImageIndex);
2280}
2281
Jesse Halldc225072016-05-30 22:40:14 -07002282static VkResult WorstPresentResult(VkResult a, VkResult b) {
2283 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
2284 // (in spec version 1.0.14).
2285 static const VkResult kWorstToBest[] = {
2286 VK_ERROR_DEVICE_LOST,
2287 VK_ERROR_SURFACE_LOST_KHR,
2288 VK_ERROR_OUT_OF_DATE_KHR,
2289 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2290 VK_ERROR_OUT_OF_HOST_MEMORY,
2291 VK_SUBOPTIMAL_KHR,
2292 };
2293 for (auto result : kWorstToBest) {
2294 if (a == result || b == result)
2295 return result;
2296 }
2297 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
2298 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
2299 return a != VK_SUCCESS ? a : b;
2300}
2301
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002302// KHR_incremental_present aspect of QueuePresentKHR
2303static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
2304 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
2305 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
2306 auto const& rect = pRegion->pRectangles[i];
2307 if (rect.layer > 0) {
2308 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
2309 rect.layer);
2310 }
2311
2312 rects[i].left = rect.offset.x;
2313 rects[i].bottom = rect.offset.y;
2314 rects[i].right = rect.offset.x + rect.extent.width;
2315 rects[i].top = rect.offset.y + rect.extent.height;
2316 }
2317 native_window_set_surface_damage(window, rects.data(), rects.size());
2318}
2319
2320// GOOGLE_display_timing aspect of QueuePresentKHR
2321static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
2322 ANativeWindow *window = swapchain.surface.window.get();
2323
2324 // We don't know whether the app will actually use GOOGLE_display_timing
2325 // with a particular swapchain until QueuePresent; enable it on the BQ
2326 // now if needed
2327 if (!swapchain.frame_timestamps_enabled) {
2328 ALOGV("Calling native_window_enable_frame_timestamps(true)");
2329 native_window_enable_frame_timestamps(window, true);
2330 swapchain.frame_timestamps_enabled = true;
2331 }
2332
2333 // Record the nativeFrameId so it can be later correlated to
2334 // this present.
2335 uint64_t nativeFrameId = 0;
2336 int err = native_window_get_next_frame_id(
2337 window, &nativeFrameId);
2338 if (err != android::OK) {
2339 ALOGE("Failed to get next native frame ID.");
2340 }
2341
2342 // Add a new timing record with the user's presentID and
2343 // the nativeFrameId.
2344 swapchain.timing.emplace_back(pTime, nativeFrameId);
2345 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
2346 swapchain.timing.erase(
2347 swapchain.timing.begin(),
2348 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
2349 }
2350 if (pTime->desiredPresentTime) {
2351 ALOGV(
2352 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
2353 pTime->desiredPresentTime);
2354 native_window_set_buffers_timestamp(
2355 window,
2356 static_cast<int64_t>(pTime->desiredPresentTime));
2357 }
2358}
2359
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002360// EXT_swapchain_maintenance1 present mode change
2361static bool SetSwapchainPresentMode(ANativeWindow *window, VkPresentModeKHR mode) {
2362 // There is no dynamic switching between non-shared present modes.
2363 // All we support is switching between demand and continuous refresh.
2364 if (!IsSharedPresentMode(mode))
2365 return true;
2366
2367 int err = native_window_set_auto_refresh(window,
2368 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
2369 if (err != android::OK) {
2370 ALOGE("native_window_set_auto_refresh() failed: %s (%d)",
2371 strerror(-err), err);
2372 return false;
2373 }
2374
2375 return true;
2376}
2377
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002378static VkResult PresentOneSwapchain(
2379 VkQueue queue,
2380 Swapchain& swapchain,
2381 uint32_t imageIndex,
2382 const VkPresentRegionKHR *pRegion,
2383 const VkPresentTimeGOOGLE *pTime,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002384 VkFence presentFence,
2385 const VkPresentModeKHR *pPresentMode,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002386 uint32_t waitSemaphoreCount,
2387 const VkSemaphore *pWaitSemaphores) {
2388
2389 VkDevice device = GetData(queue).driver_device;
2390 const auto& dispatch = GetData(queue).driver;
2391
2392 Swapchain::Image& img = swapchain.images[imageIndex];
2393 VkResult swapchain_result = VK_SUCCESS;
2394 VkResult result;
2395 int err;
2396
2397 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
2398 // wait semaphores, so this doesn't actually work for the multiple swapchain
2399 // case.
2400 int fence = -1;
2401 result = dispatch.QueueSignalReleaseImageANDROID(
2402 queue, waitSemaphoreCount,
2403 pWaitSemaphores, img.image, &fence);
2404 if (result != VK_SUCCESS) {
2405 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
2406 swapchain_result = result;
2407 }
2408 if (img.release_fence >= 0)
2409 close(img.release_fence);
2410 img.release_fence = fence < 0 ? -1 : dup(fence);
2411
2412 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
2413 ANativeWindow* window = swapchain.surface.window.get();
2414 if (swapchain_result == VK_SUCCESS) {
2415
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002416 if (presentFence != VK_NULL_HANDLE) {
2417 int fence_copy = fence < 0 ? -1 : dup(fence);
2418 VkImportFenceFdInfoKHR iffi = {
2419 VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,
2420 nullptr,
2421 presentFence,
2422 VK_FENCE_IMPORT_TEMPORARY_BIT,
2423 VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,
2424 fence_copy,
2425 };
2426 if (VK_SUCCESS != dispatch.ImportFenceFdKHR(device, &iffi) && fence_copy >= 0) {
2427 // ImportFenceFdKHR takes ownership only if it succeeds
2428 close(fence_copy);
2429 }
2430 }
2431
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002432 if (pRegion) {
2433 SetSwapchainSurfaceDamage(window, pRegion);
2434 }
2435 if (pTime) {
2436 SetSwapchainFrameTimestamp(swapchain, pTime);
2437 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002438 if (pPresentMode) {
2439 if (!SetSwapchainPresentMode(window, *pPresentMode))
2440 swapchain_result = WorstPresentResult(swapchain_result,
2441 VK_ERROR_SURFACE_LOST_KHR);
2442 }
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002443
2444 err = window->queueBuffer(window, img.buffer.get(), fence);
2445 // queueBuffer always closes fence, even on error
2446 if (err != android::OK) {
2447 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
2448 swapchain_result = WorstPresentResult(
2449 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2450 } else {
2451 if (img.dequeue_fence >= 0) {
2452 close(img.dequeue_fence);
2453 img.dequeue_fence = -1;
2454 }
2455 img.dequeued = false;
2456 }
2457
2458 // If the swapchain is in shared mode, immediately dequeue the
2459 // buffer so it can be presented again without an intervening
2460 // call to AcquireNextImageKHR. We expect to get the same buffer
2461 // back from every call to dequeueBuffer in this mode.
2462 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
2463 ANativeWindowBuffer* buffer;
2464 int fence_fd;
2465 err = window->dequeueBuffer(window, &buffer, &fence_fd);
2466 if (err != android::OK) {
2467 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
2468 swapchain_result = WorstPresentResult(swapchain_result,
2469 VK_ERROR_SURFACE_LOST_KHR);
2470 } else if (img.buffer != buffer) {
2471 ALOGE("got wrong image back for shared swapchain");
2472 swapchain_result = WorstPresentResult(swapchain_result,
2473 VK_ERROR_SURFACE_LOST_KHR);
2474 } else {
2475 img.dequeue_fence = fence_fd;
2476 img.dequeued = true;
2477 }
2478 }
2479 }
2480 if (swapchain_result != VK_SUCCESS) {
2481 OrphanSwapchain(device, &swapchain);
2482 }
2483 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
2484 // and only when the window's transform/rotation changes. Extent
2485 // changes will not cause VK_SUBOPTIMAL_KHR because of the
2486 // application issues that were caused when the following transform
2487 // change was added.
2488 int window_transform_hint;
2489 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
2490 &window_transform_hint);
2491 if (err != android::OK) {
2492 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
2493 strerror(-err), err);
2494 swapchain_result = WorstPresentResult(
2495 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2496 }
2497 if (swapchain.pre_transform != window_transform_hint) {
2498 swapchain_result =
2499 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
2500 }
2501 } else {
2502 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
2503 img, true);
2504 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
2505 }
2506
2507 return swapchain_result;
2508}
2509
Jesse Halle1b12782015-11-30 11:27:32 -08002510VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002511VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002512 ATRACE_CALL();
2513
Jesse Halld7b994a2015-09-07 14:17:37 -07002514 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
2515 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
2516 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07002517
Jesse Halld7b994a2015-09-07 14:17:37 -07002518 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07002519
Ian Elliottcb351132016-12-13 10:30:40 -07002520 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002521 const VkPresentRegionsKHR* present_regions = nullptr;
2522 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002523 const VkSwapchainPresentFenceInfoEXT* present_fences = nullptr;
2524 const VkSwapchainPresentModeInfoEXT* present_modes = nullptr;
2525
Ian Elliottcb351132016-12-13 10:30:40 -07002526 const VkPresentRegionsKHR* next =
2527 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
2528 while (next) {
2529 switch (next->sType) {
2530 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
2531 present_regions = next;
2532 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07002533 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002534 present_times =
2535 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
2536 break;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002537 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT:
2538 present_fences =
2539 reinterpret_cast<const VkSwapchainPresentFenceInfoEXT*>(next);
2540 break;
2541 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT:
2542 present_modes =
2543 reinterpret_cast<const VkSwapchainPresentModeInfoEXT*>(next);
2544 break;
Ian Elliottcb351132016-12-13 10:30:40 -07002545 default:
2546 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
2547 next->sType);
2548 break;
2549 }
2550 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2551 }
2552 ALOGV_IF(
2553 present_regions &&
2554 present_regions->swapchainCount != present_info->swapchainCount,
2555 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002556 ALOGV_IF(present_times &&
2557 present_times->swapchainCount != present_info->swapchainCount,
2558 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2559 "VkPresentInfo::swapchainCount");
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002560 ALOGV_IF(present_fences &&
2561 present_fences->swapchainCount != present_info->swapchainCount,
2562 "VkSwapchainPresentFenceInfoEXT::swapchainCount != "
2563 "VkPresentInfo::swapchainCount");
2564 ALOGV_IF(present_modes &&
2565 present_modes->swapchainCount != present_info->swapchainCount,
2566 "VkSwapchainPresentModeInfoEXT::swapchainCount != "
2567 "VkPresentInfo::swapchainCount");
2568
Ian Elliottcb351132016-12-13 10:30:40 -07002569 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002570 (present_regions) ? present_regions->pRegions : nullptr;
2571 const VkPresentTimeGOOGLE* times =
2572 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002573
Jesse Halld7b994a2015-09-07 14:17:37 -07002574 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2575 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002576 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002577
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002578 VkResult swapchain_result = PresentOneSwapchain(
2579 queue,
2580 swapchain,
2581 present_info->pImageIndices[sc],
2582 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2583 times ? &times[sc] : nullptr,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002584 present_fences ? present_fences->pFences[sc] : VK_NULL_HANDLE,
2585 present_modes ? &present_modes->pPresentModes[sc] : nullptr,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002586 present_info->waitSemaphoreCount,
2587 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002588
Jesse Halla9e57032015-11-30 01:03:10 -08002589 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002590 present_info->pResults[sc] = swapchain_result;
2591
2592 if (swapchain_result != final_result)
2593 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002594 }
2595
2596 return final_result;
2597}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002598
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002599VKAPI_ATTR
2600VkResult GetRefreshCycleDurationGOOGLE(
2601 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002602 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002603 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002604 ATRACE_CALL();
2605
Ian Elliott62c48c92017-01-20 13:13:20 -07002606 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00002607 VkResult result = swapchain.get_refresh_duration(pDisplayTimingProperties->refreshDuration);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002608
2609 return result;
2610}
2611
2612VKAPI_ATTR
2613VkResult GetPastPresentationTimingGOOGLE(
2614 VkDevice,
2615 VkSwapchainKHR swapchain_handle,
2616 uint32_t* count,
2617 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002618 ATRACE_CALL();
2619
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002620 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002621 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2622 return VK_ERROR_OUT_OF_DATE_KHR;
2623 }
2624
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002625 ANativeWindow* window = swapchain.surface.window.get();
2626 VkResult result = VK_SUCCESS;
2627
2628 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002629 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002630 native_window_enable_frame_timestamps(window, true);
2631 swapchain.frame_timestamps_enabled = true;
2632 }
2633
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002634 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002635 // Get the latest ready timing count before copying, since the copied
2636 // timing info will be erased in copy_ready_timings function.
2637 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002638 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002639 // Check the *count here against the recorded ready timing count, since
2640 // *count can be overwritten per spec describes.
2641 if (*count < n) {
2642 result = VK_INCOMPLETE;
2643 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002644 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002645 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002646 }
2647
2648 return result;
2649}
2650
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002651VKAPI_ATTR
2652VkResult GetSwapchainStatusKHR(
2653 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002654 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002655 ATRACE_CALL();
2656
Chris Forbes4e18ba82017-01-20 12:50:17 +13002657 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002658 VkResult result = VK_SUCCESS;
2659
Chris Forbes4e18ba82017-01-20 12:50:17 +13002660 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2661 return VK_ERROR_OUT_OF_DATE_KHR;
2662 }
2663
Yiwei Zhanga885c062019-10-24 12:07:57 -07002664 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002665
2666 return result;
2667}
2668
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002669VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002670 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002671 uint32_t swapchainCount,
2672 const VkSwapchainKHR* pSwapchains,
2673 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002674 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002675
2676 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2677 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2678 if (!swapchain)
2679 continue;
2680
2681 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2682
2683 ANativeWindow* window = swapchain->surface.window.get();
2684
2685 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2686 const android_smpte2086_metadata smpteMetdata = {
2687 {vulkanMetadata.displayPrimaryRed.x,
2688 vulkanMetadata.displayPrimaryRed.y},
2689 {vulkanMetadata.displayPrimaryGreen.x,
2690 vulkanMetadata.displayPrimaryGreen.y},
2691 {vulkanMetadata.displayPrimaryBlue.x,
2692 vulkanMetadata.displayPrimaryBlue.y},
2693 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2694 vulkanMetadata.maxLuminance,
2695 vulkanMetadata.minLuminance};
2696 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2697
2698 const android_cta861_3_metadata cta8613Metadata = {
2699 vulkanMetadata.maxContentLightLevel,
2700 vulkanMetadata.maxFrameAverageLightLevel};
2701 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2702 }
2703
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002704 return;
2705}
2706
Yiwei Zhang0f475222019-04-11 19:38:00 -07002707static void InterceptBindImageMemory2(
2708 uint32_t bind_info_count,
2709 const VkBindImageMemoryInfo* bind_infos,
2710 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2711 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2712 out_native_buffers->clear();
2713 out_bind_infos->clear();
2714
2715 if (!bind_info_count)
2716 return;
2717
2718 std::unordered_set<uint32_t> intercepted_indexes;
2719
2720 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2721 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2722 bind_infos[idx].pNext);
2723 while (info &&
2724 info->sType !=
2725 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2726 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2727 info->pNext);
2728 }
2729
2730 if (!info)
2731 continue;
2732
2733 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2734 "swapchain handle must not be NULL");
2735 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2736 ALOG_ASSERT(
2737 info->imageIndex < swapchain->num_images,
2738 "imageIndex must be less than the number of images in swapchain");
2739
2740 ANativeWindowBuffer* buffer =
2741 swapchain->images[info->imageIndex].buffer.get();
2742 VkNativeBufferANDROID native_buffer = {
2743#pragma clang diagnostic push
2744#pragma clang diagnostic ignored "-Wold-style-cast"
2745 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2746#pragma clang diagnostic pop
2747 .pNext = bind_infos[idx].pNext,
2748 .handle = buffer->handle,
2749 .stride = buffer->stride,
2750 .format = buffer->format,
2751 .usage = int(buffer->usage),
Trevor David Black0db7a092023-12-11 23:46:36 +00002752 .usage3 = buffer->usage,
2753 .ahb = ANativeWindowBuffer_getHardwareBuffer(buffer),
Yiwei Zhang0f475222019-04-11 19:38:00 -07002754 };
Trevor David Black0db7a092023-12-11 23:46:36 +00002755 android_convertGralloc0To1Usage(int(buffer->usage),
2756 &native_buffer.usage2.producer,
2757 &native_buffer.usage2.consumer);
Yiwei Zhang0f475222019-04-11 19:38:00 -07002758 // Reserve enough space to avoid letting re-allocation invalidate the
2759 // addresses of the elements inside.
2760 out_native_buffers->reserve(bind_info_count);
2761 out_native_buffers->emplace_back(native_buffer);
2762
2763 // Reserve the space now since we know how much is needed now.
2764 out_bind_infos->reserve(bind_info_count);
2765 out_bind_infos->emplace_back(bind_infos[idx]);
2766 out_bind_infos->back().pNext = &out_native_buffers->back();
2767
2768 intercepted_indexes.insert(idx);
2769 }
2770
2771 if (intercepted_indexes.empty())
2772 return;
2773
2774 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2775 if (intercepted_indexes.count(idx))
2776 continue;
2777 out_bind_infos->emplace_back(bind_infos[idx]);
2778 }
2779}
2780
Yiwei Zhang23143102019-04-10 18:24:05 -07002781VKAPI_ATTR
2782VkResult BindImageMemory2(VkDevice device,
2783 uint32_t bindInfoCount,
2784 const VkBindImageMemoryInfo* pBindInfos) {
2785 ATRACE_CALL();
2786
Yiwei Zhang0f475222019-04-11 19:38:00 -07002787 // out_native_buffers is for maintaining the lifecycle of the constructed
2788 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2789 std::vector<VkNativeBufferANDROID> out_native_buffers;
2790 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2791 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2792 &out_bind_infos);
2793 return GetData(device).driver.BindImageMemory2(
2794 device, bindInfoCount,
2795 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002796}
2797
2798VKAPI_ATTR
2799VkResult BindImageMemory2KHR(VkDevice device,
2800 uint32_t bindInfoCount,
2801 const VkBindImageMemoryInfo* pBindInfos) {
2802 ATRACE_CALL();
2803
Yiwei Zhang0f475222019-04-11 19:38:00 -07002804 std::vector<VkNativeBufferANDROID> out_native_buffers;
2805 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2806 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2807 &out_bind_infos);
2808 return GetData(device).driver.BindImageMemory2KHR(
2809 device, bindInfoCount,
2810 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002811}
2812
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002813VKAPI_ATTR
2814VkResult ReleaseSwapchainImagesEXT(VkDevice /*device*/,
2815 const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
2816 ATRACE_CALL();
2817
2818 Swapchain& swapchain = *SwapchainFromHandle(pReleaseInfo->swapchain);
2819 ANativeWindow* window = swapchain.surface.window.get();
2820
2821 // If in shared present mode, don't actually release the image back to the BQ.
2822 // Both sides share it forever.
2823 if (swapchain.shared)
2824 return VK_SUCCESS;
2825
2826 for (uint32_t i = 0; i < pReleaseInfo->imageIndexCount; i++) {
2827 Swapchain::Image& img = swapchain.images[pReleaseInfo->pImageIndices[i]];
2828 window->cancelBuffer(window, img.buffer.get(), img.dequeue_fence);
2829
2830 // cancelBuffer has taken ownership of the dequeue fence
2831 img.dequeue_fence = -1;
2832 // if we're still holding a release fence, get rid of it now
2833 if (img.release_fence >= 0) {
2834 close(img.release_fence);
2835 img.release_fence = -1;
2836 }
2837 img.dequeued = false;
2838 }
2839
2840 return VK_SUCCESS;
2841}
2842
Chia-I Wu62262232016-03-26 07:06:44 +08002843} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002844} // namespace vulkan