blob: 867fc45516cb2c8407847a04dc8bf169cf7d1550 [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});
789 }
790 }
791
792 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
793 if (AHardwareBuffer_isSupported(&desc)) {
794 all_formats.emplace_back(
795 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
796 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800797 if (colorspace_ext) {
798 all_formats.emplace_back(
799 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
800 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800801 all_formats.emplace_back(
802 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
803 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
804 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700805 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700806
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500807 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
808 if (AHardwareBuffer_isSupported(&desc)) {
Jason Macnakca506332022-11-09 11:00:36 -0800809 if (colorspace_ext) {
810 all_formats.emplace_back(VkSurfaceFormatKHR{
811 VK_FORMAT_R8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
812 }
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500813 }
814
Trevor David Black67e9b102023-03-07 05:28:15 +0000815 bool rgba10x6_formats_ext = false;
816 uint32_t exts_count;
817 const auto& driver = GetData(pdev).driver;
818 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
819 nullptr);
820 std::vector<VkExtensionProperties> props(exts_count);
821 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
822 props.data());
823 for (uint32_t i = 0; i < exts_count; i++) {
824 VkExtensionProperties prop = props[i];
825 if (strcmp(prop.extensionName,
826 VK_EXT_RGBA10X6_FORMATS_EXTENSION_NAME) == 0) {
827 rgba10x6_formats_ext = true;
828 }
829 }
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000830 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM;
Trevor David Black67e9b102023-03-07 05:28:15 +0000831 if (AHardwareBuffer_isSupported(&desc) && rgba10x6_formats_ext) {
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000832 all_formats.emplace_back(
833 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
834 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
835 if (colorspace_ext) {
836 all_formats.emplace_back(
837 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
838 VK_COLOR_SPACE_PASS_THROUGH_EXT});
839 all_formats.emplace_back(
840 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
841 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
842 }
843 }
844
Ian Elliott6ba85d92022-02-18 16:44:58 -0700845 // NOTE: Any new formats that are added must be coordinated across different
846 // Android users. This includes the ANGLE team (a layered implementation of
847 // OpenGL-ES).
848
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000849 return CopyWithIncomplete(all_formats, formats, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700850}
851
Jesse Halle1b12782015-11-30 11:27:32 -0800852VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300853VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
854 VkPhysicalDevice physicalDevice,
855 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
856 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800857 ATRACE_CALL();
858
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000859 auto surface = pSurfaceInfo->surface;
860 auto capabilities = &pSurfaceCapabilities->surfaceCapabilities;
Chris Forbes2452cf72017-03-16 16:30:17 +1300861
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000862 VkSurfacePresentModeEXT const *pPresentMode = nullptr;
863 for (auto pNext = reinterpret_cast<VkBaseInStructure const *>(pSurfaceInfo->pNext);
864 pNext; pNext = reinterpret_cast<VkBaseInStructure const *>(pNext->pNext)) {
865 switch (pNext->sType) {
866 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT:
867 pPresentMode = reinterpret_cast<VkSurfacePresentModeEXT const *>(pNext);
868 break;
Chris Forbes06bc0092017-03-16 16:46:05 +1300869
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000870 default:
871 break;
872 }
873 }
874
875 int err;
876 int width, height;
877 int transform_hint;
878 int max_buffer_count;
Trevor David Black1d3509e2023-06-08 00:17:40 +0000879 int min_undequeued_buffers;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000880 if (surface == VK_NULL_HANDLE) {
881 const InstanceData& instance_data = GetData(physicalDevice);
882 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
883 bool surfaceless_enabled =
884 instance_data.hook_extensions.test(surfaceless);
885 if (!surfaceless_enabled) {
886 // It is an error to pass a surface==VK_NULL_HANDLE unless the
887 // VK_GOOGLE_surfaceless_query extension is enabled
888 return VK_ERROR_SURFACE_LOST_KHR;
889 }
890 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
891 // extension for this function is for
892 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
893 // four values cannot be known without a surface. Default values will
894 // be supplied anyway, but cannot be relied upon.
895 width = 0xFFFFFFFF;
896 height = 0xFFFFFFFF;
897 transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
898 capabilities->minImageCount = 0xFFFFFFFF;
899 capabilities->maxImageCount = 0xFFFFFFFF;
900 } else {
901 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
902
903 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
904 if (err != android::OK) {
905 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
906 strerror(-err), err);
907 return VK_ERROR_SURFACE_LOST_KHR;
908 }
909 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
910 if (err != android::OK) {
911 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
912 strerror(-err), err);
913 return VK_ERROR_SURFACE_LOST_KHR;
914 }
915
916 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
917 &transform_hint);
918 if (err != android::OK) {
919 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
920 strerror(-err), err);
921 return VK_ERROR_SURFACE_LOST_KHR;
922 }
923
924 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
925 &max_buffer_count);
926 if (err != android::OK) {
927 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
928 strerror(-err), err);
929 return VK_ERROR_SURFACE_LOST_KHR;
930 }
931
Trevor David Black1d3509e2023-06-08 00:17:40 +0000932 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
933 &min_undequeued_buffers);
934 if (err != android::OK) {
935 ALOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d)",
936 strerror(-err), err);
937 return VK_ERROR_SURFACE_LOST_KHR;
938 }
939
Trevor David Blacke4d23b92023-09-26 20:30:42 +0000940 // Additional buffer count over min_undequeued_buffers in vulkan came from 2 total
941 // being technically enough for fifo (although a poor experience) vs 3 being the
942 // absolute minimum for mailbox to be useful. So min_undequeued_buffers + 2 is sensible
943 static constexpr int default_additional_buffers = 2;
944
Trevor David Blacka93e21f2023-08-30 23:42:20 +0000945 if(pPresentMode != nullptr) {
946 switch (pPresentMode->presentMode) {
947 case VK_PRESENT_MODE_IMMEDIATE_KHR:
948 ALOGE("Swapchain present mode VK_PRESENT_MODE_IMMEDIATE_KHR is not supported");
949 break;
950 case VK_PRESENT_MODE_MAILBOX_KHR:
951 case VK_PRESENT_MODE_FIFO_KHR:
Trevor David Blacke4d23b92023-09-26 20:30:42 +0000952 capabilities->minImageCount = std::min(max_buffer_count,
953 min_undequeued_buffers + default_additional_buffers);
Trevor David Blacka93e21f2023-08-30 23:42:20 +0000954 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
955 break;
956 case VK_PRESENT_MODE_FIFO_RELAXED_KHR:
957 ALOGE("Swapchain present mode VK_PRESENT_MODE_FIFO_RELEAXED_KHR "
958 "is not supported");
959 break;
960 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
961 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
962 capabilities->minImageCount = 1;
963 capabilities->maxImageCount = 1;
964 break;
965
966 default:
967 ALOGE("Unrecognized swapchain present mode %u is not supported",
968 pPresentMode->presentMode);
969 break;
970 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000971 } else {
Trevor David Blacke4d23b92023-09-26 20:30:42 +0000972 capabilities->minImageCount = std::min(max_buffer_count,
973 min_undequeued_buffers + default_additional_buffers);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000974 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
975 }
976 }
977
978 capabilities->currentExtent =
979 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
980
981 // TODO(http://b/134182502): Figure out what the max extent should be.
982 capabilities->minImageExtent = VkExtent2D{1, 1};
983 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
984
985 if (capabilities->maxImageExtent.height <
986 capabilities->currentExtent.height) {
987 capabilities->maxImageExtent.height =
988 capabilities->currentExtent.height;
989 }
990
991 if (capabilities->maxImageExtent.width <
992 capabilities->currentExtent.width) {
993 capabilities->maxImageExtent.width = capabilities->currentExtent.width;
994 }
995
996 capabilities->maxImageArrayLayers = 1;
997
998 capabilities->supportedTransforms = kSupportedTransforms;
999 capabilities->currentTransform =
1000 TranslateNativeToVulkanTransform(transform_hint);
1001
1002 // On Android, window composition is a WindowManager property, not something
1003 // associated with the bufferqueue. It can't be changed from here.
1004 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
1005
1006 capabilities->supportedUsageFlags =
1007 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
1008 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
1009 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
1010 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
1011
1012 for (auto pNext = reinterpret_cast<VkBaseOutStructure*>(pSurfaceCapabilities->pNext);
1013 pNext; pNext = reinterpret_cast<VkBaseOutStructure*>(pNext->pNext)) {
1014
1015 switch (pNext->sType) {
Chris Forbes06bc0092017-03-16 16:46:05 +13001016 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
1017 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001018 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(pNext);
Chris Forbes06bc0092017-03-16 16:46:05 +13001019 // Claim same set of usage flags are supported for
1020 // shared present modes as for other modes.
1021 shared_caps->sharedPresentSupportedUsageFlags =
1022 pSurfaceCapabilities->surfaceCapabilities
1023 .supportedUsageFlags;
1024 } break;
1025
Ian Elliottbb67b242022-03-16 09:52:28 -06001026 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
1027 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001028 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(pNext);
Ian Elliottbb67b242022-03-16 09:52:28 -06001029 protected_caps->supportsProtected = VK_TRUE;
1030 } break;
1031
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001032 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_SCALING_CAPABILITIES_EXT: {
1033 VkSurfacePresentScalingCapabilitiesEXT* scaling_caps =
1034 reinterpret_cast<VkSurfacePresentScalingCapabilitiesEXT*>(pNext);
1035 // By default, Android stretches the buffer to fit the window,
1036 // without preserving aspect ratio. Other modes are technically possible
1037 // but consult with CoGS team before exposing them here!
1038 scaling_caps->supportedPresentScaling = VK_PRESENT_SCALING_STRETCH_BIT_EXT;
1039
1040 // Since we always scale, we don't support any gravity.
1041 scaling_caps->supportedPresentGravityX = 0;
1042 scaling_caps->supportedPresentGravityY = 0;
1043
1044 // Scaled image limits are just the basic image limits
1045 scaling_caps->minScaledImageExtent = capabilities->minImageExtent;
1046 scaling_caps->maxScaledImageExtent = capabilities->maxImageExtent;
1047 } break;
1048
1049 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT: {
1050 VkSurfacePresentModeCompatibilityEXT* mode_caps =
1051 reinterpret_cast<VkSurfacePresentModeCompatibilityEXT*>(pNext);
1052
1053 ALOG_ASSERT(pPresentMode,
1054 "querying VkSurfacePresentModeCompatibilityEXT "
1055 "requires VkSurfacePresentModeEXT to be provided");
1056 std::vector<VkPresentModeKHR> compatibleModes;
1057 compatibleModes.push_back(pPresentMode->presentMode);
1058
1059 switch (pPresentMode->presentMode) {
1060 // Shared modes are both compatible with each other.
1061 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
1062 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
1063 break;
1064 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
1065 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1066 break;
1067 default:
1068 // Other modes are only compatible with themselves.
1069 // TODO: consider whether switching between FIFO and MAILBOX is reasonable
1070 break;
1071 }
1072
1073 // Note: this does not generate VK_INCOMPLETE since we're nested inside
1074 // a larger query and there would be no way to determine exactly where it came from.
1075 CopyWithIncomplete(compatibleModes, mode_caps->pPresentModes,
1076 &mode_caps->presentModeCount);
1077 } break;
1078
Chris Forbes06bc0092017-03-16 16:46:05 +13001079 default:
1080 // Ignore all other extension structs
1081 break;
1082 }
1083 }
1084
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001085 return VK_SUCCESS;
Chris Forbes2452cf72017-03-16 16:30:17 +13001086}
1087
1088VKAPI_ATTR
1089VkResult GetPhysicalDeviceSurfaceFormats2KHR(
1090 VkPhysicalDevice physicalDevice,
1091 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
1092 uint32_t* pSurfaceFormatCount,
1093 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001094 ATRACE_CALL();
1095
Chris Forbes2452cf72017-03-16 16:30:17 +13001096 if (!pSurfaceFormats) {
1097 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
1098 pSurfaceInfo->surface,
1099 pSurfaceFormatCount, nullptr);
Trevor David Black929e9cd2022-11-22 04:12:19 +00001100 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001101
Trevor David Black929e9cd2022-11-22 04:12:19 +00001102 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
1103 // after the call.
1104 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
1105 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
1106 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
1107 surface_formats.data());
Trevor David Black2cc44682022-03-09 00:31:38 +00001108
Trevor David Black929e9cd2022-11-22 04:12:19 +00001109 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
1110 return result;
1111 }
Trevor David Black2cc44682022-03-09 00:31:38 +00001112
Trevor David Black929e9cd2022-11-22 04:12:19 +00001113 const auto& driver = GetData(physicalDevice).driver;
1114
1115 // marshal results individually due to stride difference.
1116 uint32_t formats_to_marshal = *pSurfaceFormatCount;
1117 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
1118 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
1119
1120 // Query the compression properties for the surface format
1121 VkSurfaceFormat2KHR* pSurfaceFormat = &pSurfaceFormats[i];
1122 while (pSurfaceFormat->pNext) {
1123 pSurfaceFormat =
1124 reinterpret_cast<VkSurfaceFormat2KHR*>(pSurfaceFormat->pNext);
1125 switch (pSurfaceFormat->sType) {
1126 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT: {
Trevor David Black2cc44682022-03-09 00:31:38 +00001127 VkImageCompressionPropertiesEXT* surfaceCompressionProps =
1128 reinterpret_cast<VkImageCompressionPropertiesEXT*>(
Trevor David Black929e9cd2022-11-22 04:12:19 +00001129 pSurfaceFormat);
Trevor David Black2cc44682022-03-09 00:31:38 +00001130
1131 if (surfaceCompressionProps &&
1132 driver.GetPhysicalDeviceImageFormatProperties2KHR) {
1133 VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = {};
1134 imageFormatInfo.sType =
1135 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
1136 imageFormatInfo.format =
1137 pSurfaceFormats[i].surfaceFormat.format;
Trevor David Blacka4298c92023-06-20 17:11:58 +00001138 imageFormatInfo.type = VK_IMAGE_TYPE_2D;
1139 imageFormatInfo.usage =
1140 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
Trevor David Black2cc44682022-03-09 00:31:38 +00001141 imageFormatInfo.pNext = nullptr;
1142
1143 VkImageCompressionControlEXT compressionControl = {};
1144 compressionControl.sType =
1145 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT;
1146 compressionControl.pNext = imageFormatInfo.pNext;
Trevor David Blacka4298c92023-06-20 17:11:58 +00001147 compressionControl.flags =
1148 VK_IMAGE_COMPRESSION_FIXED_RATE_DEFAULT_EXT;
Trevor David Black2cc44682022-03-09 00:31:38 +00001149
1150 imageFormatInfo.pNext = &compressionControl;
1151
1152 VkImageCompressionPropertiesEXT compressionProps = {};
1153 compressionProps.sType =
1154 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT;
1155 compressionProps.pNext = nullptr;
1156
1157 VkImageFormatProperties2KHR imageFormatProps = {};
1158 imageFormatProps.sType =
1159 VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
1160 imageFormatProps.pNext = &compressionProps;
1161
1162 VkResult compressionRes =
1163 driver.GetPhysicalDeviceImageFormatProperties2KHR(
1164 physicalDevice, &imageFormatInfo,
1165 &imageFormatProps);
1166 if (compressionRes == VK_SUCCESS) {
1167 surfaceCompressionProps->imageCompressionFlags =
1168 compressionProps.imageCompressionFlags;
1169 surfaceCompressionProps
1170 ->imageCompressionFixedRateFlags =
1171 compressionProps.imageCompressionFixedRateFlags;
1172 } else {
1173 return compressionRes;
1174 }
1175 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001176 } break;
1177
1178 default:
1179 // Ignore all other extension structs
1180 break;
Chris Forbes2452cf72017-03-16 16:30:17 +13001181 }
1182 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001183 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001184
1185 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +13001186}
1187
1188VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +13001189VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001190 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +08001191 uint32_t* count,
1192 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001193 ATRACE_CALL();
1194
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001195 int err;
1196 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -06001197 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -06001198 if (surface == VK_NULL_HANDLE) {
1199 const InstanceData& instance_data = GetData(pdev);
1200 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
1201 bool surfaceless_enabled =
1202 instance_data.hook_extensions.test(surfaceless);
1203 if (!surfaceless_enabled) {
1204 return VK_ERROR_SURFACE_LOST_KHR;
1205 }
1206 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
1207 // extension for this function is for
1208 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
1209 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
1210 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
Ian Elliott7e361142022-06-02 10:45:17 -06001211 // surface, and that cannot be relied upon. Therefore, don't return it.
Ian Elliott1ce053f2022-03-16 09:49:53 -06001212 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1213 } else {
1214 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1215
1216 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1217 &query_value);
1218 if (err != android::OK || query_value < 0) {
1219 ALOGE(
1220 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
1221 "value=%d",
1222 strerror(-err), err, query_value);
1223 return VK_ERROR_SURFACE_LOST_KHR;
1224 }
1225 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1226
1227 err =
1228 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
1229 if (err != android::OK || query_value < 0) {
1230 ALOGE(
1231 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
1232 strerror(-err), err, query_value);
1233 return VK_ERROR_SURFACE_LOST_KHR;
1234 }
1235 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
1236
1237 if (min_undequeued_buffers + 1 < max_buffer_count)
1238 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
1239 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1240 }
Chris Forbese8d79a62017-02-22 12:49:18 +13001241
1242 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -07001243 QueryPresentationProperties(pdev, &present_properties);
1244 if (present_properties.sharedImage) {
1245 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1246 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +13001247 }
1248
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001249 return CopyWithIncomplete(present_modes, modes, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001250}
1251
Jesse Halle1b12782015-11-30 11:27:32 -08001252VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001253VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001254 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001255 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001256 ATRACE_CALL();
1257
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001258 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
1259 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1260 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1261 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1262 pDeviceGroupPresentCapabilities->sType);
1263
1264 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1265 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1266
1267 // assume device group of size 1
1268 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1269 pDeviceGroupPresentCapabilities->modes =
1270 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1271
1272 return VK_SUCCESS;
1273}
1274
1275VKAPI_ATTR
1276VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001277 VkDevice,
1278 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001279 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001280 ATRACE_CALL();
1281
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001282 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1283 return VK_SUCCESS;
1284}
1285
1286VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001287VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001288 VkSurfaceKHR surface,
1289 uint32_t* pRectCount,
1290 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001291 ATRACE_CALL();
1292
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001293 if (!pRects) {
1294 *pRectCount = 1;
1295 } else {
1296 uint32_t count = std::min(*pRectCount, 1u);
1297 bool incomplete = *pRectCount < 1;
1298
1299 *pRectCount = count;
1300
1301 if (incomplete) {
1302 return VK_INCOMPLETE;
1303 }
1304
1305 int err;
1306 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1307
1308 int width = 0, height = 0;
1309 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001310 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001311 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1312 strerror(-err), err);
1313 }
1314 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001315 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001316 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1317 strerror(-err), err);
1318 }
1319
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001320 pRects[0].offset.x = 0;
1321 pRects[0].offset.y = 0;
1322 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1323 static_cast<uint32_t>(height)};
1324 }
1325 return VK_SUCCESS;
1326}
1327
Yiwei Zhang533cea92019-06-03 18:43:24 -07001328static void DestroySwapchainInternal(VkDevice device,
1329 VkSwapchainKHR swapchain_handle,
1330 const VkAllocationCallbacks* allocator) {
1331 ATRACE_CALL();
1332
1333 const auto& dispatch = GetData(device).driver;
1334 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1335 if (!swapchain) {
1336 return;
1337 }
1338
1339 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1340 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1341
1342 if (window && swapchain->frame_timestamps_enabled) {
1343 native_window_enable_frame_timestamps(window, false);
1344 }
1345
1346 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +00001347 ReleaseSwapchainImage(device, swapchain->shared, window, -1,
1348 swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001349 }
1350
1351 if (active) {
1352 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1353 }
1354
1355 if (!allocator) {
1356 allocator = &GetData(device).allocator;
1357 }
1358
1359 swapchain->~Swapchain();
1360 allocator->pfnFree(allocator->pUserData, swapchain);
1361}
1362
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001363static VkResult getProducerUsage(const VkDevice& device,
1364 const VkSwapchainCreateInfoKHR* create_info,
1365 const VkSwapchainImageUsageFlagsANDROID swapchain_image_usage,
1366 bool create_protected_swapchain,
1367 uint64_t* producer_usage) {
1368 // Get the physical device to query the appropriate producer usage
1369 const VkPhysicalDevice& pdev = GetData(device).driver_physical_device;
1370 const InstanceData& instance_data = GetData(pdev);
1371 const InstanceDriverTable& instance_dispatch = instance_data.driver;
Trevor David Black02926f52024-01-04 18:44:20 +00001372 if (instance_dispatch.GetPhysicalDeviceImageFormatProperties2 ||
1373 instance_dispatch.GetPhysicalDeviceImageFormatProperties2KHR) {
1374 // Look through the create_info pNext chain passed to createSwapchainKHR
1375 // for an image compression control struct.
1376 // if one is found AND the appropriate extensions are enabled, create a
1377 // VkImageCompressionControlEXT structure to pass on to
1378 // GetPhysicalDeviceImageFormatProperties2
1379 void* compression_control_pNext = nullptr;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001380 VkImageCompressionControlEXT image_compression = {};
Trevor David Black02926f52024-01-04 18:44:20 +00001381 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1382 while (create_infos->pNext) {
1383 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(create_infos->pNext);
1384 switch (create_infos->sType) {
1385 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1386 const VkImageCompressionControlEXT* compression_infos =
1387 reinterpret_cast<const VkImageCompressionControlEXT*>(create_infos);
1388 image_compression = *compression_infos;
1389 image_compression.pNext = nullptr;
1390 compression_control_pNext = &image_compression;
1391 } break;
1392 default:
1393 // Ignore all other info structs
1394 break;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001395 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001396 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001397
Trevor David Black02926f52024-01-04 18:44:20 +00001398 // call GetPhysicalDeviceImageFormatProperties2KHR
1399 VkPhysicalDeviceExternalImageFormatInfo external_image_format_info = {
1400 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1401 .pNext = compression_control_pNext,
1402 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID,
1403 };
1404
1405 // AHB does not have an sRGB format so we can't pass it to GPDIFP
1406 // We need to convert the format to unorm if it is srgb
1407 VkFormat format = create_info->imageFormat;
1408 if (format == VK_FORMAT_R8G8B8A8_SRGB) {
1409 format = VK_FORMAT_R8G8B8A8_UNORM;
1410 }
1411
1412 VkPhysicalDeviceImageFormatInfo2 image_format_info = {
1413 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1414 .pNext = &external_image_format_info,
1415 .format = format,
1416 .type = VK_IMAGE_TYPE_2D,
1417 .tiling = VK_IMAGE_TILING_OPTIMAL,
1418 .usage = create_info->imageUsage,
1419 .flags = create_protected_swapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
1420 };
1421
1422 VkAndroidHardwareBufferUsageANDROID ahb_usage;
1423 ahb_usage.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_USAGE_ANDROID;
1424 ahb_usage.pNext = nullptr;
1425
1426 VkImageFormatProperties2 image_format_properties;
1427 image_format_properties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
1428 image_format_properties.pNext = &ahb_usage;
1429
1430 if (instance_dispatch.GetPhysicalDeviceImageFormatProperties2) {
1431 VkResult result = instance_dispatch.GetPhysicalDeviceImageFormatProperties2(
1432 pdev, &image_format_info, &image_format_properties);
1433 if (result != VK_SUCCESS) {
1434 ALOGE("VkGetPhysicalDeviceImageFormatProperties2 for AHB usage failed: %d", result);
1435 return VK_ERROR_SURFACE_LOST_KHR;
1436 }
1437 }
1438 else {
1439 VkResult result = instance_dispatch.GetPhysicalDeviceImageFormatProperties2KHR(
1440 pdev, &image_format_info,
1441 &image_format_properties);
1442 if (result != VK_SUCCESS) {
1443 ALOGE("VkGetPhysicalDeviceImageFormatProperties2KHR for AHB usage failed: %d",
1444 result);
1445 return VK_ERROR_SURFACE_LOST_KHR;
1446 }
1447 }
1448
1449 // Determine if USAGE_FRONT_BUFFER is needed.
1450 // GPDIFP2 has no means of using VkSwapchainImageUsageFlagsANDROID when
1451 // querying for producer_usage. So androidHardwareBufferUsage will not
1452 // contain USAGE_FRONT_BUFFER. We need to manually check for usage here.
1453 if (!(swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID)) {
1454 *producer_usage = ahb_usage.androidHardwareBufferUsage;
1455 return VK_SUCCESS;
1456 }
1457
1458 // Check if USAGE_FRONT_BUFFER is supported for this swapchain
1459 AHardwareBuffer_Desc ahb_desc = {
1460 .width = create_info->imageExtent.width,
1461 .height = create_info->imageExtent.height,
1462 .layers = create_info->imageArrayLayers,
1463 .format = create_info->imageFormat,
1464 .usage = ahb_usage.androidHardwareBufferUsage | AHARDWAREBUFFER_USAGE_FRONT_BUFFER,
1465 .stride = 0, // stride is always ignored when calling isSupported()
1466 };
1467
1468 // If FRONT_BUFFER is not supported,
1469 // then we need to call GetSwapchainGrallocUsageXAndroid below
1470 if (AHardwareBuffer_isSupported(&ahb_desc)) {
1471 *producer_usage = ahb_usage.androidHardwareBufferUsage;
1472 *producer_usage |= AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
1473 return VK_SUCCESS;
1474 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001475 }
1476
Trevor David Black02926f52024-01-04 18:44:20 +00001477 uint64_t native_usage = 0;
1478 void* usage_info_pNext = nullptr;
1479 VkResult result;
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001480 VkImageCompressionControlEXT image_compression = {};
Trevor David Black02926f52024-01-04 18:44:20 +00001481 const auto& dispatch = GetData(device).driver;
1482 if (dispatch.GetSwapchainGrallocUsage4ANDROID) {
1483 ATRACE_BEGIN("GetSwapchainGrallocUsage4ANDROID");
1484 VkGrallocUsageInfo2ANDROID gralloc_usage_info = {};
1485 gralloc_usage_info.sType =
1486 VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_2_ANDROID;
1487 gralloc_usage_info.format = create_info->imageFormat;
1488 gralloc_usage_info.imageUsage = create_info->imageUsage;
1489 gralloc_usage_info.swapchainImageUsage = swapchain_image_usage;
1490
1491 // Look through the pNext chain for an image compression control struct
1492 // if one is found AND the appropriate extensions are enabled,
1493 // append it to be the gralloc usage pNext chain
1494 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1495 while (create_infos->pNext) {
1496 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1497 create_infos->pNext);
1498 switch (create_infos->sType) {
1499 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1500 const VkImageCompressionControlEXT* compression_infos =
1501 reinterpret_cast<const VkImageCompressionControlEXT*>(
1502 create_infos);
1503 image_compression = *compression_infos;
1504 image_compression.pNext = nullptr;
1505 usage_info_pNext = &image_compression;
1506 } break;
1507
1508 default:
1509 // Ignore all other info structs
1510 break;
1511 }
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001512 }
Trevor David Black02926f52024-01-04 18:44:20 +00001513 gralloc_usage_info.pNext = usage_info_pNext;
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001514
Trevor David Black02926f52024-01-04 18:44:20 +00001515 result = dispatch.GetSwapchainGrallocUsage4ANDROID(
1516 device, &gralloc_usage_info, &native_usage);
1517 ATRACE_END();
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001518 if (result != VK_SUCCESS) {
Trevor David Black02926f52024-01-04 18:44:20 +00001519 ALOGE("vkGetSwapchainGrallocUsage4ANDROID failed: %d", result);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001520 return VK_ERROR_SURFACE_LOST_KHR;
1521 }
Trevor David Black02926f52024-01-04 18:44:20 +00001522 } else if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
1523 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1524 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1525 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1526 gralloc_usage_info.format = create_info->imageFormat;
1527 gralloc_usage_info.imageUsage = create_info->imageUsage;
1528
1529 // Look through the pNext chain for an image compression control struct
1530 // if one is found AND the appropriate extensions are enabled,
1531 // append it to be the gralloc usage pNext chain
1532 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1533 while (create_infos->pNext) {
1534 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1535 create_infos->pNext);
1536 switch (create_infos->sType) {
1537 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1538 const VkImageCompressionControlEXT* compression_infos =
1539 reinterpret_cast<const VkImageCompressionControlEXT*>(
1540 create_infos);
1541 image_compression = *compression_infos;
1542 image_compression.pNext = nullptr;
1543 usage_info_pNext = &image_compression;
1544 } break;
1545
1546 default:
1547 // Ignore all other info structs
1548 break;
1549 }
1550 }
1551 gralloc_usage_info.pNext = usage_info_pNext;
1552
1553 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1554 device, &gralloc_usage_info, &native_usage);
1555 ATRACE_END();
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001556 if (result != VK_SUCCESS) {
Trevor David Black02926f52024-01-04 18:44:20 +00001557 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001558 return VK_ERROR_SURFACE_LOST_KHR;
1559 }
Trevor David Black02926f52024-01-04 18:44:20 +00001560 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
1561 uint64_t consumer_usage, producer_usage;
1562 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
1563 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1564 device, create_info->imageFormat, create_info->imageUsage,
1565 swapchain_image_usage, &consumer_usage, &producer_usage);
1566 ATRACE_END();
1567 if (result != VK_SUCCESS) {
1568 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
1569 return VK_ERROR_SURFACE_LOST_KHR;
1570 }
1571 native_usage =
1572 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
1573 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
1574 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
1575 int32_t legacy_usage = 0;
1576 result = dispatch.GetSwapchainGrallocUsageANDROID(
1577 device, create_info->imageFormat, create_info->imageUsage,
1578 &legacy_usage);
1579 ATRACE_END();
1580 if (result != VK_SUCCESS) {
1581 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
1582 return VK_ERROR_SURFACE_LOST_KHR;
1583 }
1584 native_usage = static_cast<uint64_t>(legacy_usage);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001585 }
Trevor David Black02926f52024-01-04 18:44:20 +00001586 *producer_usage = native_usage;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001587
1588 return VK_SUCCESS;
1589}
1590
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001591VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001592VkResult CreateSwapchainKHR(VkDevice device,
1593 const VkSwapchainCreateInfoKHR* create_info,
1594 const VkAllocationCallbacks* allocator,
1595 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001596 ATRACE_CALL();
1597
Jesse Halld7b994a2015-09-07 14:17:37 -07001598 int err;
1599 VkResult result = VK_SUCCESS;
1600
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001601 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1602 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1603 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1604 " oldSwapchain=0x%" PRIx64,
1605 reinterpret_cast<uint64_t>(create_info->surface),
1606 create_info->minImageCount, create_info->imageFormat,
1607 create_info->imageColorSpace, create_info->imageExtent.width,
1608 create_info->imageExtent.height, create_info->imageUsage,
1609 create_info->preTransform, create_info->presentMode,
1610 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1611
Jesse Hall1f91d392015-12-11 16:28:44 -08001612 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001613 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001614
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001615 PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001616 GetNativePixelFormat(create_info->imageFormat);
sergiuferentz47989332023-09-26 10:24:36 +00001617 DataSpace native_dataspace =
Sally Qiaa238972023-07-17 12:52:05 +08001618 GetNativeDataspace(create_info->imageColorSpace, native_pixel_format);
sergiuferentz47989332023-09-26 10:24:36 +00001619 if (native_dataspace == DataSpace::UNKNOWN) {
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001620 ALOGE(
1621 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1622 "failed: Unsupported color space",
1623 create_info->imageColorSpace);
1624 return VK_ERROR_INITIALIZATION_FAILED;
1625 }
1626
Jesse Hall42a9eec2016-06-03 12:39:49 -07001627 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001628 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001629 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001630 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001631 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001632 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001633 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001634 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001635 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1636 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001637 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001638 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001639
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001640 Surface& surface = *SurfaceFromHandle(create_info->surface);
1641
Jesse Halldc225072016-05-30 22:40:14 -07001642 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001643 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001644 " because it already has active swapchain 0x%" PRIx64
1645 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1646 reinterpret_cast<uint64_t>(create_info->surface),
1647 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1648 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1649 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1650 }
1651 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1652 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1653
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001654 // -- Reset the native window --
1655 // The native window might have been used previously, and had its properties
1656 // changed from defaults. That will affect the answer we get for queries
1657 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1658 // attempt such queries.
1659
Jesse Halldc225072016-05-30 22:40:14 -07001660 // The native window only allows dequeueing all buffers before any have
1661 // been queued, since after that point at least one is assumed to be in
1662 // non-FREE state at any given time. Disconnecting and re-connecting
1663 // orphans the previous buffers, getting us back to the state where we can
1664 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001665 //
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001666 // This is not necessary if the surface was never used previously.
1667 //
Yiwei Zhang70a21962019-05-31 17:26:52 -07001668 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001669 ANativeWindow* window = surface.window.get();
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001670 if (surface.used_by_swapchain) {
1671 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1672 ALOGW_IF(err != android::OK,
1673 "native_window_api_disconnect failed: %s (%d)", strerror(-err),
1674 err);
1675 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1676 ALOGW_IF(err != android::OK,
1677 "native_window_api_connect failed: %s (%d)", strerror(-err),
1678 err);
1679 }
Jesse Halldc225072016-05-30 22:40:14 -07001680
Nicolas Capens147b7da2021-04-09 14:53:06 -04001681 err =
1682 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001683 if (err != android::OK) {
1684 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1685 strerror(-err), err);
1686 return VK_ERROR_SURFACE_LOST_KHR;
1687 }
1688
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301689 int swap_interval =
1690 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001691 err = window->setSwapInterval(window, swap_interval);
1692 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001693 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1694 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001695 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001696 }
1697
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001698 err = native_window_set_shared_buffer_mode(window, false);
1699 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001700 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1701 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001702 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001703 }
1704
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001705 err = native_window_set_auto_refresh(window, false);
1706 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001707 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1708 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001709 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001710 }
1711
Jesse Halld7b994a2015-09-07 14:17:37 -07001712 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001713
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001714 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001715
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001716 err = native_window_set_buffers_format(
1717 window, static_cast<int>(native_pixel_format));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001718 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001719 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001720 toString(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001721 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001722 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001723
1724 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
sergiuferentz47989332023-09-26 10:24:36 +00001725 if (native_dataspace != DataSpace::ARBITRARY) {
1726 err = native_window_set_buffers_data_space(
1727 window, static_cast<android_dataspace_t>(native_dataspace));
Yiwei Zhang51572c22022-07-22 23:08:30 +00001728 if (err != android::OK) {
1729 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1730 native_dataspace, strerror(-err), err);
1731 return VK_ERROR_SURFACE_LOST_KHR;
1732 }
Jesse Hall517274a2016-02-10 00:07:18 -08001733 }
1734
Jesse Hall3dd678a2016-01-08 21:52:01 -08001735 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001736 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001737 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001738 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001739 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1740 create_info->imageExtent.width, create_info->imageExtent.height,
1741 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001742 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001743 }
1744
Jesse Hall178b6962016-02-24 15:39:50 -08001745 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1746 // applied during rendering. native_window_set_transform() expects the
1747 // inverse: the transform the app is requesting that the compositor perform
1748 // during composition. With native windows, pre-transform works by rendering
1749 // with the same transform the compositor is applying (as in Vulkan), but
1750 // then requesting the inverse transform, so that when the compositor does
1751 // it's job the two transforms cancel each other out and the compositor ends
1752 // up applying an identity transform to the app's buffer.
1753 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001754 window, InvertTransformToNative(create_info->preTransform));
1755 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001756 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1757 InvertTransformToNative(create_info->preTransform),
1758 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001759 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001760 }
1761
Jesse Hallf64ca122015-11-03 16:11:10 -08001762 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001763 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1764 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001765 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1766 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001767 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001768 }
1769
Chris Forbes97ef4612017-03-30 19:37:50 +13001770 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001771 if (IsSharedPresentMode(create_info->presentMode)) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001772 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001773 err = native_window_set_shared_buffer_mode(window, true);
1774 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001775 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1776 return VK_ERROR_SURFACE_LOST_KHR;
1777 }
1778 }
1779
1780 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001781 err = native_window_set_auto_refresh(window, true);
1782 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001783 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1784 return VK_ERROR_SURFACE_LOST_KHR;
1785 }
1786 }
1787
Ian Elliott16c443c2021-11-30 17:10:32 -07001788 int query_value;
Trevor David Blackabab5a02023-12-19 20:27:07 +00001789 // TODO: Now that we are calling into GPDSC2 directly, this query may be redundant
1790 // the call to std::max(min_buffer_count, num_images) may be redundant as well
Ian Elliott16c443c2021-11-30 17:10:32 -07001791 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1792 &query_value);
1793 if (err != android::OK || query_value < 0) {
1794 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1795 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001796 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001797 }
Trevor David Black8c0122e2023-09-07 20:33:54 +00001798 const uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
Chris Forbes2c8fc752017-03-17 11:28:32 +13001799
Ian Elliott5396b702021-12-13 19:32:34 -07001800 // Lower layer insists that we have at least min_undequeued_buffers + 1
1801 // buffers. This is wasteful and we'd like to relax it in the shared case,
1802 // but not all the pieces are in place for that to work yet. Note we only
1803 // lie to the lower layer--we don't want to give the app back a swapchain
1804 // with extra images (which they can't actually use!).
Trevor David Black8c0122e2023-09-07 20:33:54 +00001805 const uint32_t min_buffer_count = min_undequeued_buffers + 1;
1806
Trevor David Blackabab5a02023-12-19 20:27:07 +00001807 // Call into GPDSC2 to get the minimum and maximum allowable buffer count for the surface of
1808 // interest. This step is only necessary if the app requests a number of images
1809 // (create_info->minImageCount) that is less or more than the surface capabilities.
1810 // An app should be calling GPDSC2 and using those values to set create_info, but in the
1811 // event that the app has hard-coded image counts an error can occur
1812 VkSurfacePresentModeEXT present_mode = {
1813 VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT,
1814 nullptr,
1815 create_info->presentMode
1816 };
1817 VkPhysicalDeviceSurfaceInfo2KHR surface_info2 = {
1818 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
1819 &present_mode,
1820 create_info->surface
1821 };
1822 VkSurfaceCapabilities2KHR surface_capabilities2 = {
1823 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
1824 nullptr,
1825 {},
1826 };
1827 result = GetPhysicalDeviceSurfaceCapabilities2KHR(GetData(device).driver_physical_device,
1828 &surface_info2, &surface_capabilities2);
1829
1830 uint32_t num_images = create_info->minImageCount;
1831 num_images = std::clamp(num_images,
1832 surface_capabilities2.surfaceCapabilities.minImageCount,
1833 surface_capabilities2.surfaceCapabilities.maxImageCount);
Trevor David Black8c0122e2023-09-07 20:33:54 +00001834
1835 const uint32_t buffer_count = std::max(min_buffer_count, num_images);
1836 err = native_window_set_buffer_count(window, buffer_count);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001837 if (err != android::OK) {
Trevor David Black8c0122e2023-09-07 20:33:54 +00001838 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", buffer_count,
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001839 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001840 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001841 }
1842
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001843 // In shared mode the num_images must be one regardless of how many
1844 // buffers were allocated for the buffer queue.
1845 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1846 num_images = 1;
1847 }
1848
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001849 // Look through the create_info pNext chain passed to createSwapchainKHR
1850 // for an image compression control struct.
1851 // if one is found AND the appropriate extensions are enabled, create a
1852 // VkImageCompressionControlEXT structure to pass on to VkImageCreateInfo
1853 // TODO check for imageCompressionControlSwapchain feature is enabled
Trevor David Black2cc44682022-03-09 00:31:38 +00001854 void* usage_info_pNext = nullptr;
1855 VkImageCompressionControlEXT image_compression = {};
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001856 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1857 while (create_infos->pNext) {
1858 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(create_infos->pNext);
1859 switch (create_infos->sType) {
1860 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1861 const VkImageCompressionControlEXT* compression_infos =
1862 reinterpret_cast<const VkImageCompressionControlEXT*>(create_infos);
1863 image_compression = *compression_infos;
1864 image_compression.pNext = nullptr;
1865 usage_info_pNext = &image_compression;
1866 } break;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001867
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001868 default:
1869 // Ignore all other info structs
1870 break;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001871 }
Jesse Hall70f93352015-11-04 09:41:31 -08001872 }
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001873
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001874 // Get the appropriate native_usage for the images
1875 // Get the consumer usage
1876 uint64_t native_usage = surface.consumer_usage;
1877 // Determine if the swapchain is protected
1878 bool create_protected_swapchain = false;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001879 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001880 create_protected_swapchain = true;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001881 native_usage |= BufferUsage::PROTECTED;
1882 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001883 // Get the producer usage
1884 uint64_t producer_usage;
1885 result = getProducerUsage(device, create_info, swapchain_image_usage, create_protected_swapchain, &producer_usage);
1886 if (result != VK_SUCCESS) {
1887 return result;
1888 }
1889 native_usage |= producer_usage;
1890
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001891 err = native_window_set_usage(window, native_usage);
1892 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001893 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001894 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001895 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001896
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001897 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001898 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1899 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001900 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1901 strerror(-err), err);
1902 return VK_ERROR_SURFACE_LOST_KHR;
1903 }
1904
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001905 int64_t refresh_duration;
1906 err = native_window_get_refresh_cycle_duration(window, &refresh_duration);
1907 if (err != android::OK) {
1908 ALOGE("native_window_get_refresh_cycle_duration query failed: %s (%d)",
1909 strerror(-err), err);
1910 return VK_ERROR_SURFACE_LOST_KHR;
1911 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001912 // -- Allocate our Swapchain object --
1913 // After this point, we must deallocate the swapchain on error.
1914
Jesse Hall1f91d392015-12-11 16:28:44 -08001915 void* mem = allocator->pfnAllocation(allocator->pUserData,
1916 sizeof(Swapchain), alignof(Swapchain),
1917 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001918
Jesse Hall1356b0d2015-11-23 17:24:58 -08001919 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001920 return VK_ERROR_OUT_OF_HOST_MEMORY;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001921
silence_dogood73597592019-05-23 16:57:37 -07001922 Swapchain* swapchain = new (mem)
1923 Swapchain(surface, num_images, create_info->presentMode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001924 TranslateVulkanToNativeTransform(create_info->preTransform),
1925 refresh_duration);
Chris Forbesb56287a2017-01-12 14:28:58 +13001926 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1927#pragma clang diagnostic push
1928#pragma clang diagnostic ignored "-Wold-style-cast"
1929 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1930#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00001931 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13001932 .usage = swapchain_image_usage,
1933 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001934 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001935#pragma clang diagnostic push
1936#pragma clang diagnostic ignored "-Wold-style-cast"
1937 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1938#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001939 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001940 };
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001941
Jesse Halld7b994a2015-09-07 14:17:37 -07001942 VkImageCreateInfo image_create = {
1943 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001944 .pNext = nullptr,
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001945 .flags = create_protected_swapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07001946 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08001947 .format = create_info->imageFormat,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001948 .extent = {
1949 create_info->imageExtent.width,
1950 create_info->imageExtent.height,
1951 1
1952 },
Jesse Halld7b994a2015-09-07 14:17:37 -07001953 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08001954 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08001955 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07001956 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001957 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001958 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08001959 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07001960 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1961 };
1962
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001963 // Note: don't do deferred allocation for shared present modes. There's only one buffer
1964 // involved so very little benefit.
1965 if ((create_info->flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT) &&
1966 !IsSharedPresentMode(create_info->presentMode)) {
1967 // Don't want to touch the underlying gralloc buffers yet;
1968 // instead just create unbound VkImages which will later be bound to memory inside
1969 // AcquireNextImage.
1970 VkImageSwapchainCreateInfoKHR image_swapchain_create = {
1971 .sType = VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR,
1972 .pNext = nullptr,
1973 .swapchain = HandleFromSwapchain(swapchain),
1974 };
1975 image_create.pNext = &image_swapchain_create;
Jesse Halld7b994a2015-09-07 14:17:37 -07001976
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001977 for (uint32_t i = 0; i < num_images; i++) {
1978 Swapchain::Image& img = swapchain->images[i];
1979 img.buffer = nullptr;
1980 img.dequeued = false;
1981
1982 result = dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1983 if (result != VK_SUCCESS) {
1984 ALOGD("vkCreateImage w/ for deferred swapchain image failed: %u", result);
1985 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08001986 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001987 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001988 } else {
1989 // -- Dequeue all buffers and create a VkImage for each --
1990 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07001991
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001992 for (uint32_t i = 0; i < num_images; i++) {
1993 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07001994
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001995 ANativeWindowBuffer* buffer;
1996 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
1997 if (err != android::OK) {
1998 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
1999 switch (-err) {
2000 case ENOMEM:
2001 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
2002 break;
2003 default:
2004 result = VK_ERROR_SURFACE_LOST_KHR;
2005 break;
2006 }
2007 break;
2008 }
2009 img.buffer = buffer;
2010 img.dequeued = true;
2011
2012 image_native_buffer.handle = img.buffer->handle;
2013 image_native_buffer.stride = img.buffer->stride;
2014 image_native_buffer.format = img.buffer->format;
2015 image_native_buffer.usage = int(img.buffer->usage);
2016 android_convertGralloc0To1Usage(int(img.buffer->usage),
2017 &image_native_buffer.usage2.producer,
2018 &image_native_buffer.usage2.consumer);
2019 image_native_buffer.usage3 = img.buffer->usage;
Trevor David Black0db7a092023-12-11 23:46:36 +00002020 image_native_buffer.ahb =
2021 ANativeWindowBuffer_getHardwareBuffer(img.buffer.get());
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002022 image_create.pNext = &image_native_buffer;
2023
2024 ATRACE_BEGIN("CreateImage");
2025 result =
2026 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
2027 ATRACE_END();
2028 if (result != VK_SUCCESS) {
2029 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
2030 break;
2031 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002032 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002033
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002034 // -- Cancel all buffers, returning them to the queue --
2035 // If an error occurred before, also destroy the VkImage and release the
2036 // buffer reference. Otherwise, we retain a strong reference to the buffer.
2037 for (uint32_t i = 0; i < num_images; i++) {
2038 Swapchain::Image& img = swapchain->images[i];
2039 if (img.dequeued) {
2040 if (!swapchain->shared) {
2041 window->cancelBuffer(window, img.buffer.get(),
2042 img.dequeue_fence);
2043 img.dequeue_fence = -1;
2044 img.dequeued = false;
2045 }
Chris Forbese0ced032017-03-30 19:44:15 +13002046 }
Chris Forbes31b85c22018-05-29 15:03:28 -07002047 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002048 }
2049
2050 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07002051 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
2052 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07002053 return result;
2054 }
2055
Yiwei Zhang69395cd2019-07-03 16:55:39 -07002056 if (transform_hint != swapchain->pre_transform) {
2057 // Log that the app is not doing pre-rotation.
2058 android::GraphicsEnv::getInstance().setTargetStats(
2059 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
2060 }
2061
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00002062 // Set stats for creating a Vulkan swapchain
2063 android::GraphicsEnv::getInstance().setTargetStats(
2064 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
2065
Yiwei Zhang3b88f312023-04-18 23:11:35 +00002066 surface.used_by_swapchain = true;
Jesse Halldc225072016-05-30 22:40:14 -07002067 surface.swapchain_handle = HandleFromSwapchain(swapchain);
2068 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002069 return VK_SUCCESS;
2070}
2071
Jesse Halle1b12782015-11-30 11:27:32 -08002072VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002073void DestroySwapchainKHR(VkDevice device,
2074 VkSwapchainKHR swapchain_handle,
2075 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002076 ATRACE_CALL();
2077
Yiwei Zhang533cea92019-06-03 18:43:24 -07002078 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07002079}
2080
Jesse Halle1b12782015-11-30 11:27:32 -08002081VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002082VkResult GetSwapchainImagesKHR(VkDevice,
2083 VkSwapchainKHR swapchain_handle,
2084 uint32_t* count,
2085 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002086 ATRACE_CALL();
2087
Jesse Halld7b994a2015-09-07 14:17:37 -07002088 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07002089 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
2090 "getting images for non-active swapchain 0x%" PRIx64
2091 "; only dequeued image handles are valid",
2092 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07002093 VkResult result = VK_SUCCESS;
2094 if (images) {
2095 uint32_t n = swapchain.num_images;
2096 if (*count < swapchain.num_images) {
2097 n = *count;
2098 result = VK_INCOMPLETE;
2099 }
2100 for (uint32_t i = 0; i < n; i++)
2101 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07002102 *count = n;
2103 } else {
2104 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07002105 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002106 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002107}
2108
Jesse Halle1b12782015-11-30 11:27:32 -08002109VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002110VkResult AcquireNextImageKHR(VkDevice device,
2111 VkSwapchainKHR swapchain_handle,
2112 uint64_t timeout,
2113 VkSemaphore semaphore,
2114 VkFence vk_fence,
2115 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002116 ATRACE_CALL();
2117
Jesse Halld7b994a2015-09-07 14:17:37 -07002118 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08002119 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07002120 VkResult result;
2121 int err;
2122
Jesse Halldc225072016-05-30 22:40:14 -07002123 if (swapchain.surface.swapchain_handle != swapchain_handle)
2124 return VK_ERROR_OUT_OF_DATE_KHR;
2125
Chris Forbesc88409c2017-03-30 19:47:37 +13002126 if (swapchain.shared) {
2127 // In shared mode, we keep the buffer dequeued all the time, so we don't
2128 // want to dequeue a buffer here. Instead, just ask the driver to ensure
2129 // the semaphore and fence passed to us will be signalled.
2130 *image_index = 0;
2131 result = GetData(device).driver.AcquireImageANDROID(
2132 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
2133 return result;
2134 }
2135
Yiwei Zhang705c2e62019-12-18 23:12:43 -08002136 const nsecs_t acquire_next_image_timeout =
2137 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
2138 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
2139 // Cache the timeout to avoid the duplicate binder cost.
2140 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
2141 acquire_next_image_timeout);
2142 if (err != android::OK) {
2143 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
2144 strerror(-err), err);
2145 return VK_ERROR_SURFACE_LOST_KHR;
2146 }
2147 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
2148 }
2149
Jesse Halld7b994a2015-09-07 14:17:37 -07002150 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08002151 int fence_fd;
2152 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07002153 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08002154 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
2155 return timeout ? VK_TIMEOUT : VK_NOT_READY;
2156 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07002157 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07002158 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002159 }
2160
2161 uint32_t idx;
2162 for (idx = 0; idx < swapchain.num_images; idx++) {
2163 if (swapchain.images[idx].buffer.get() == buffer) {
2164 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08002165 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07002166 break;
2167 }
2168 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002169
2170 // If this is a deferred alloc swapchain, this may be the first time we've
2171 // seen a particular buffer. If so, there should be an empty slot. Find it,
2172 // and bind the gralloc buffer to the VkImage for that slot. If there is no
2173 // empty slot, then we dequeued an unexpected buffer. Non-deferred swapchains
2174 // will also take this path, but will never have an empty slot since we
2175 // populated them all upfront.
2176 if (idx == swapchain.num_images) {
2177 for (idx = 0; idx < swapchain.num_images; idx++) {
2178 if (!swapchain.images[idx].buffer) {
2179 // Note: this structure is technically required for
2180 // Vulkan correctness, even though the driver is probably going
2181 // to use everything from the VkNativeBufferANDROID below.
2182 // This is kindof silly, but it's how we did the ANB
2183 // side of VK_KHR_swapchain v69, so we're stuck with it unless
2184 // we want to go tinkering with the ANB spec some more.
2185 VkBindImageMemorySwapchainInfoKHR bimsi = {
2186 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR,
2187 .pNext = nullptr,
2188 .swapchain = swapchain_handle,
2189 .imageIndex = idx,
2190 };
2191 VkNativeBufferANDROID nb = {
2192 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2193 .pNext = &bimsi,
2194 .handle = buffer->handle,
2195 .stride = buffer->stride,
2196 .format = buffer->format,
2197 .usage = int(buffer->usage),
Trevor David Black0db7a092023-12-11 23:46:36 +00002198 .usage3 = buffer->usage,
2199 .ahb = ANativeWindowBuffer_getHardwareBuffer(buffer),
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002200 };
Trevor David Black0db7a092023-12-11 23:46:36 +00002201 android_convertGralloc0To1Usage(int(buffer->usage),
2202 &nb.usage2.producer,
2203 &nb.usage2.consumer);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002204 VkBindImageMemoryInfo bimi = {
2205 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO,
2206 .pNext = &nb,
2207 .image = swapchain.images[idx].image,
2208 .memory = VK_NULL_HANDLE,
2209 .memoryOffset = 0,
2210 };
2211 result = GetData(device).driver.BindImageMemory2(device, 1, &bimi);
2212 if (result != VK_SUCCESS) {
2213 // This shouldn't really happen. If it does, something is probably
2214 // unrecoverably wrong with the swapchain and its images. Cancel
2215 // the buffer and declare the swapchain broken.
2216 ALOGE("failed to do deferred gralloc buffer bind");
2217 window->cancelBuffer(window, buffer, fence_fd);
2218 return VK_ERROR_OUT_OF_DATE_KHR;
2219 }
2220
2221 swapchain.images[idx].dequeued = true;
2222 swapchain.images[idx].dequeue_fence = fence_fd;
2223 swapchain.images[idx].buffer = buffer;
2224 break;
2225 }
2226 }
2227 }
2228
2229 // The buffer doesn't match any slot. This shouldn't normally happen, but is
2230 // possible if the bufferqueue is reconfigured behind libvulkan's back. If this
2231 // happens, just declare the swapchain to be broken and the app will recreate it.
Jesse Halld7b994a2015-09-07 14:17:37 -07002232 if (idx == swapchain.num_images) {
2233 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08002234 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002235 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002236 }
2237
2238 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08002239 if (fence_fd != -1) {
2240 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002241 if (fence_clone == -1) {
2242 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
2243 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08002244 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07002245 }
2246 }
2247
Chia-I Wu4a6a9162016-03-26 07:17:34 +08002248 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08002249 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07002250 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08002251 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
2252 // even if the call fails. We could close it ourselves on failure, but
2253 // that would create a race condition if the driver closes it on a
2254 // failure path: some other thread might create an fd with the same
2255 // number between the time the driver closes it and the time we close
2256 // it. We must assume one of: the driver *always* closes it even on
2257 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08002258 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002259 swapchain.images[idx].dequeued = false;
2260 swapchain.images[idx].dequeue_fence = -1;
2261 return result;
2262 }
2263
2264 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002265 return VK_SUCCESS;
2266}
2267
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002268VKAPI_ATTR
2269VkResult AcquireNextImage2KHR(VkDevice device,
2270 const VkAcquireNextImageInfoKHR* pAcquireInfo,
2271 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002272 ATRACE_CALL();
2273
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002274 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
2275 pAcquireInfo->timeout, pAcquireInfo->semaphore,
2276 pAcquireInfo->fence, pImageIndex);
2277}
2278
Jesse Halldc225072016-05-30 22:40:14 -07002279static VkResult WorstPresentResult(VkResult a, VkResult b) {
2280 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
2281 // (in spec version 1.0.14).
2282 static const VkResult kWorstToBest[] = {
2283 VK_ERROR_DEVICE_LOST,
2284 VK_ERROR_SURFACE_LOST_KHR,
2285 VK_ERROR_OUT_OF_DATE_KHR,
2286 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2287 VK_ERROR_OUT_OF_HOST_MEMORY,
2288 VK_SUBOPTIMAL_KHR,
2289 };
2290 for (auto result : kWorstToBest) {
2291 if (a == result || b == result)
2292 return result;
2293 }
2294 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
2295 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
2296 return a != VK_SUCCESS ? a : b;
2297}
2298
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002299// KHR_incremental_present aspect of QueuePresentKHR
2300static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
2301 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
2302 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
2303 auto const& rect = pRegion->pRectangles[i];
2304 if (rect.layer > 0) {
2305 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
2306 rect.layer);
2307 }
2308
2309 rects[i].left = rect.offset.x;
2310 rects[i].bottom = rect.offset.y;
2311 rects[i].right = rect.offset.x + rect.extent.width;
2312 rects[i].top = rect.offset.y + rect.extent.height;
2313 }
2314 native_window_set_surface_damage(window, rects.data(), rects.size());
2315}
2316
2317// GOOGLE_display_timing aspect of QueuePresentKHR
2318static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
2319 ANativeWindow *window = swapchain.surface.window.get();
2320
2321 // We don't know whether the app will actually use GOOGLE_display_timing
2322 // with a particular swapchain until QueuePresent; enable it on the BQ
2323 // now if needed
2324 if (!swapchain.frame_timestamps_enabled) {
2325 ALOGV("Calling native_window_enable_frame_timestamps(true)");
2326 native_window_enable_frame_timestamps(window, true);
2327 swapchain.frame_timestamps_enabled = true;
2328 }
2329
2330 // Record the nativeFrameId so it can be later correlated to
2331 // this present.
2332 uint64_t nativeFrameId = 0;
2333 int err = native_window_get_next_frame_id(
2334 window, &nativeFrameId);
2335 if (err != android::OK) {
2336 ALOGE("Failed to get next native frame ID.");
2337 }
2338
2339 // Add a new timing record with the user's presentID and
2340 // the nativeFrameId.
2341 swapchain.timing.emplace_back(pTime, nativeFrameId);
2342 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
2343 swapchain.timing.erase(
2344 swapchain.timing.begin(),
2345 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
2346 }
2347 if (pTime->desiredPresentTime) {
2348 ALOGV(
2349 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
2350 pTime->desiredPresentTime);
2351 native_window_set_buffers_timestamp(
2352 window,
2353 static_cast<int64_t>(pTime->desiredPresentTime));
2354 }
2355}
2356
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002357// EXT_swapchain_maintenance1 present mode change
2358static bool SetSwapchainPresentMode(ANativeWindow *window, VkPresentModeKHR mode) {
2359 // There is no dynamic switching between non-shared present modes.
2360 // All we support is switching between demand and continuous refresh.
2361 if (!IsSharedPresentMode(mode))
2362 return true;
2363
2364 int err = native_window_set_auto_refresh(window,
2365 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
2366 if (err != android::OK) {
2367 ALOGE("native_window_set_auto_refresh() failed: %s (%d)",
2368 strerror(-err), err);
2369 return false;
2370 }
2371
2372 return true;
2373}
2374
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002375static VkResult PresentOneSwapchain(
2376 VkQueue queue,
2377 Swapchain& swapchain,
2378 uint32_t imageIndex,
2379 const VkPresentRegionKHR *pRegion,
2380 const VkPresentTimeGOOGLE *pTime,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002381 VkFence presentFence,
2382 const VkPresentModeKHR *pPresentMode,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002383 uint32_t waitSemaphoreCount,
2384 const VkSemaphore *pWaitSemaphores) {
2385
2386 VkDevice device = GetData(queue).driver_device;
2387 const auto& dispatch = GetData(queue).driver;
2388
2389 Swapchain::Image& img = swapchain.images[imageIndex];
2390 VkResult swapchain_result = VK_SUCCESS;
2391 VkResult result;
2392 int err;
2393
2394 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
2395 // wait semaphores, so this doesn't actually work for the multiple swapchain
2396 // case.
2397 int fence = -1;
2398 result = dispatch.QueueSignalReleaseImageANDROID(
2399 queue, waitSemaphoreCount,
2400 pWaitSemaphores, img.image, &fence);
2401 if (result != VK_SUCCESS) {
2402 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
2403 swapchain_result = result;
2404 }
2405 if (img.release_fence >= 0)
2406 close(img.release_fence);
2407 img.release_fence = fence < 0 ? -1 : dup(fence);
2408
2409 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
2410 ANativeWindow* window = swapchain.surface.window.get();
2411 if (swapchain_result == VK_SUCCESS) {
2412
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002413 if (presentFence != VK_NULL_HANDLE) {
2414 int fence_copy = fence < 0 ? -1 : dup(fence);
2415 VkImportFenceFdInfoKHR iffi = {
2416 VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,
2417 nullptr,
2418 presentFence,
2419 VK_FENCE_IMPORT_TEMPORARY_BIT,
2420 VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,
2421 fence_copy,
2422 };
2423 if (VK_SUCCESS != dispatch.ImportFenceFdKHR(device, &iffi) && fence_copy >= 0) {
2424 // ImportFenceFdKHR takes ownership only if it succeeds
2425 close(fence_copy);
2426 }
2427 }
2428
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002429 if (pRegion) {
2430 SetSwapchainSurfaceDamage(window, pRegion);
2431 }
2432 if (pTime) {
2433 SetSwapchainFrameTimestamp(swapchain, pTime);
2434 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002435 if (pPresentMode) {
2436 if (!SetSwapchainPresentMode(window, *pPresentMode))
2437 swapchain_result = WorstPresentResult(swapchain_result,
2438 VK_ERROR_SURFACE_LOST_KHR);
2439 }
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002440
2441 err = window->queueBuffer(window, img.buffer.get(), fence);
2442 // queueBuffer always closes fence, even on error
2443 if (err != android::OK) {
2444 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
2445 swapchain_result = WorstPresentResult(
2446 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2447 } else {
2448 if (img.dequeue_fence >= 0) {
2449 close(img.dequeue_fence);
2450 img.dequeue_fence = -1;
2451 }
2452 img.dequeued = false;
2453 }
2454
2455 // If the swapchain is in shared mode, immediately dequeue the
2456 // buffer so it can be presented again without an intervening
2457 // call to AcquireNextImageKHR. We expect to get the same buffer
2458 // back from every call to dequeueBuffer in this mode.
2459 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
2460 ANativeWindowBuffer* buffer;
2461 int fence_fd;
2462 err = window->dequeueBuffer(window, &buffer, &fence_fd);
2463 if (err != android::OK) {
2464 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
2465 swapchain_result = WorstPresentResult(swapchain_result,
2466 VK_ERROR_SURFACE_LOST_KHR);
2467 } else if (img.buffer != buffer) {
2468 ALOGE("got wrong image back for shared swapchain");
2469 swapchain_result = WorstPresentResult(swapchain_result,
2470 VK_ERROR_SURFACE_LOST_KHR);
2471 } else {
2472 img.dequeue_fence = fence_fd;
2473 img.dequeued = true;
2474 }
2475 }
2476 }
2477 if (swapchain_result != VK_SUCCESS) {
2478 OrphanSwapchain(device, &swapchain);
2479 }
2480 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
2481 // and only when the window's transform/rotation changes. Extent
2482 // changes will not cause VK_SUBOPTIMAL_KHR because of the
2483 // application issues that were caused when the following transform
2484 // change was added.
2485 int window_transform_hint;
2486 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
2487 &window_transform_hint);
2488 if (err != android::OK) {
2489 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
2490 strerror(-err), err);
2491 swapchain_result = WorstPresentResult(
2492 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2493 }
2494 if (swapchain.pre_transform != window_transform_hint) {
2495 swapchain_result =
2496 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
2497 }
2498 } else {
2499 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
2500 img, true);
2501 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
2502 }
2503
2504 return swapchain_result;
2505}
2506
Jesse Halle1b12782015-11-30 11:27:32 -08002507VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002508VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002509 ATRACE_CALL();
2510
Jesse Halld7b994a2015-09-07 14:17:37 -07002511 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
2512 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
2513 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07002514
Jesse Halld7b994a2015-09-07 14:17:37 -07002515 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07002516
Ian Elliottcb351132016-12-13 10:30:40 -07002517 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002518 const VkPresentRegionsKHR* present_regions = nullptr;
2519 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002520 const VkSwapchainPresentFenceInfoEXT* present_fences = nullptr;
2521 const VkSwapchainPresentModeInfoEXT* present_modes = nullptr;
2522
Ian Elliottcb351132016-12-13 10:30:40 -07002523 const VkPresentRegionsKHR* next =
2524 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
2525 while (next) {
2526 switch (next->sType) {
2527 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
2528 present_regions = next;
2529 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07002530 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002531 present_times =
2532 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
2533 break;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002534 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT:
2535 present_fences =
2536 reinterpret_cast<const VkSwapchainPresentFenceInfoEXT*>(next);
2537 break;
2538 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT:
2539 present_modes =
2540 reinterpret_cast<const VkSwapchainPresentModeInfoEXT*>(next);
2541 break;
Ian Elliottcb351132016-12-13 10:30:40 -07002542 default:
2543 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
2544 next->sType);
2545 break;
2546 }
2547 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2548 }
2549 ALOGV_IF(
2550 present_regions &&
2551 present_regions->swapchainCount != present_info->swapchainCount,
2552 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002553 ALOGV_IF(present_times &&
2554 present_times->swapchainCount != present_info->swapchainCount,
2555 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2556 "VkPresentInfo::swapchainCount");
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002557 ALOGV_IF(present_fences &&
2558 present_fences->swapchainCount != present_info->swapchainCount,
2559 "VkSwapchainPresentFenceInfoEXT::swapchainCount != "
2560 "VkPresentInfo::swapchainCount");
2561 ALOGV_IF(present_modes &&
2562 present_modes->swapchainCount != present_info->swapchainCount,
2563 "VkSwapchainPresentModeInfoEXT::swapchainCount != "
2564 "VkPresentInfo::swapchainCount");
2565
Ian Elliottcb351132016-12-13 10:30:40 -07002566 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002567 (present_regions) ? present_regions->pRegions : nullptr;
2568 const VkPresentTimeGOOGLE* times =
2569 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002570
Jesse Halld7b994a2015-09-07 14:17:37 -07002571 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2572 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002573 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002574
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002575 VkResult swapchain_result = PresentOneSwapchain(
2576 queue,
2577 swapchain,
2578 present_info->pImageIndices[sc],
2579 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2580 times ? &times[sc] : nullptr,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002581 present_fences ? present_fences->pFences[sc] : VK_NULL_HANDLE,
2582 present_modes ? &present_modes->pPresentModes[sc] : nullptr,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002583 present_info->waitSemaphoreCount,
2584 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002585
Jesse Halla9e57032015-11-30 01:03:10 -08002586 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002587 present_info->pResults[sc] = swapchain_result;
2588
2589 if (swapchain_result != final_result)
2590 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002591 }
2592
2593 return final_result;
2594}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002595
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002596VKAPI_ATTR
2597VkResult GetRefreshCycleDurationGOOGLE(
2598 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002599 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002600 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002601 ATRACE_CALL();
2602
Ian Elliott62c48c92017-01-20 13:13:20 -07002603 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00002604 VkResult result = swapchain.get_refresh_duration(pDisplayTimingProperties->refreshDuration);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002605
2606 return result;
2607}
2608
2609VKAPI_ATTR
2610VkResult GetPastPresentationTimingGOOGLE(
2611 VkDevice,
2612 VkSwapchainKHR swapchain_handle,
2613 uint32_t* count,
2614 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002615 ATRACE_CALL();
2616
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002617 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002618 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2619 return VK_ERROR_OUT_OF_DATE_KHR;
2620 }
2621
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002622 ANativeWindow* window = swapchain.surface.window.get();
2623 VkResult result = VK_SUCCESS;
2624
2625 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002626 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002627 native_window_enable_frame_timestamps(window, true);
2628 swapchain.frame_timestamps_enabled = true;
2629 }
2630
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002631 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002632 // Get the latest ready timing count before copying, since the copied
2633 // timing info will be erased in copy_ready_timings function.
2634 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002635 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002636 // Check the *count here against the recorded ready timing count, since
2637 // *count can be overwritten per spec describes.
2638 if (*count < n) {
2639 result = VK_INCOMPLETE;
2640 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002641 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002642 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002643 }
2644
2645 return result;
2646}
2647
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002648VKAPI_ATTR
2649VkResult GetSwapchainStatusKHR(
2650 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002651 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002652 ATRACE_CALL();
2653
Chris Forbes4e18ba82017-01-20 12:50:17 +13002654 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002655 VkResult result = VK_SUCCESS;
2656
Chris Forbes4e18ba82017-01-20 12:50:17 +13002657 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2658 return VK_ERROR_OUT_OF_DATE_KHR;
2659 }
2660
Yiwei Zhanga885c062019-10-24 12:07:57 -07002661 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002662
2663 return result;
2664}
2665
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002666VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002667 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002668 uint32_t swapchainCount,
2669 const VkSwapchainKHR* pSwapchains,
2670 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002671 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002672
2673 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2674 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2675 if (!swapchain)
2676 continue;
2677
2678 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2679
2680 ANativeWindow* window = swapchain->surface.window.get();
2681
2682 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2683 const android_smpte2086_metadata smpteMetdata = {
2684 {vulkanMetadata.displayPrimaryRed.x,
2685 vulkanMetadata.displayPrimaryRed.y},
2686 {vulkanMetadata.displayPrimaryGreen.x,
2687 vulkanMetadata.displayPrimaryGreen.y},
2688 {vulkanMetadata.displayPrimaryBlue.x,
2689 vulkanMetadata.displayPrimaryBlue.y},
2690 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2691 vulkanMetadata.maxLuminance,
2692 vulkanMetadata.minLuminance};
2693 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2694
2695 const android_cta861_3_metadata cta8613Metadata = {
2696 vulkanMetadata.maxContentLightLevel,
2697 vulkanMetadata.maxFrameAverageLightLevel};
2698 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2699 }
2700
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002701 return;
2702}
2703
Yiwei Zhang0f475222019-04-11 19:38:00 -07002704static void InterceptBindImageMemory2(
2705 uint32_t bind_info_count,
2706 const VkBindImageMemoryInfo* bind_infos,
2707 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2708 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2709 out_native_buffers->clear();
2710 out_bind_infos->clear();
2711
2712 if (!bind_info_count)
2713 return;
2714
2715 std::unordered_set<uint32_t> intercepted_indexes;
2716
2717 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2718 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2719 bind_infos[idx].pNext);
2720 while (info &&
2721 info->sType !=
2722 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2723 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2724 info->pNext);
2725 }
2726
2727 if (!info)
2728 continue;
2729
2730 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2731 "swapchain handle must not be NULL");
2732 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2733 ALOG_ASSERT(
2734 info->imageIndex < swapchain->num_images,
2735 "imageIndex must be less than the number of images in swapchain");
2736
2737 ANativeWindowBuffer* buffer =
2738 swapchain->images[info->imageIndex].buffer.get();
2739 VkNativeBufferANDROID native_buffer = {
2740#pragma clang diagnostic push
2741#pragma clang diagnostic ignored "-Wold-style-cast"
2742 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2743#pragma clang diagnostic pop
2744 .pNext = bind_infos[idx].pNext,
2745 .handle = buffer->handle,
2746 .stride = buffer->stride,
2747 .format = buffer->format,
2748 .usage = int(buffer->usage),
Trevor David Black0db7a092023-12-11 23:46:36 +00002749 .usage3 = buffer->usage,
2750 .ahb = ANativeWindowBuffer_getHardwareBuffer(buffer),
Yiwei Zhang0f475222019-04-11 19:38:00 -07002751 };
Trevor David Black0db7a092023-12-11 23:46:36 +00002752 android_convertGralloc0To1Usage(int(buffer->usage),
2753 &native_buffer.usage2.producer,
2754 &native_buffer.usage2.consumer);
Yiwei Zhang0f475222019-04-11 19:38:00 -07002755 // Reserve enough space to avoid letting re-allocation invalidate the
2756 // addresses of the elements inside.
2757 out_native_buffers->reserve(bind_info_count);
2758 out_native_buffers->emplace_back(native_buffer);
2759
2760 // Reserve the space now since we know how much is needed now.
2761 out_bind_infos->reserve(bind_info_count);
2762 out_bind_infos->emplace_back(bind_infos[idx]);
2763 out_bind_infos->back().pNext = &out_native_buffers->back();
2764
2765 intercepted_indexes.insert(idx);
2766 }
2767
2768 if (intercepted_indexes.empty())
2769 return;
2770
2771 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2772 if (intercepted_indexes.count(idx))
2773 continue;
2774 out_bind_infos->emplace_back(bind_infos[idx]);
2775 }
2776}
2777
Yiwei Zhang23143102019-04-10 18:24:05 -07002778VKAPI_ATTR
2779VkResult BindImageMemory2(VkDevice device,
2780 uint32_t bindInfoCount,
2781 const VkBindImageMemoryInfo* pBindInfos) {
2782 ATRACE_CALL();
2783
Yiwei Zhang0f475222019-04-11 19:38:00 -07002784 // out_native_buffers is for maintaining the lifecycle of the constructed
2785 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2786 std::vector<VkNativeBufferANDROID> out_native_buffers;
2787 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2788 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2789 &out_bind_infos);
2790 return GetData(device).driver.BindImageMemory2(
2791 device, bindInfoCount,
2792 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002793}
2794
2795VKAPI_ATTR
2796VkResult BindImageMemory2KHR(VkDevice device,
2797 uint32_t bindInfoCount,
2798 const VkBindImageMemoryInfo* pBindInfos) {
2799 ATRACE_CALL();
2800
Yiwei Zhang0f475222019-04-11 19:38:00 -07002801 std::vector<VkNativeBufferANDROID> out_native_buffers;
2802 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2803 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2804 &out_bind_infos);
2805 return GetData(device).driver.BindImageMemory2KHR(
2806 device, bindInfoCount,
2807 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002808}
2809
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002810VKAPI_ATTR
2811VkResult ReleaseSwapchainImagesEXT(VkDevice /*device*/,
2812 const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
2813 ATRACE_CALL();
2814
2815 Swapchain& swapchain = *SwapchainFromHandle(pReleaseInfo->swapchain);
2816 ANativeWindow* window = swapchain.surface.window.get();
2817
2818 // If in shared present mode, don't actually release the image back to the BQ.
2819 // Both sides share it forever.
2820 if (swapchain.shared)
2821 return VK_SUCCESS;
2822
2823 for (uint32_t i = 0; i < pReleaseInfo->imageIndexCount; i++) {
2824 Swapchain::Image& img = swapchain.images[pReleaseInfo->pImageIndices[i]];
2825 window->cancelBuffer(window, img.buffer.get(), img.dequeue_fence);
2826
2827 // cancelBuffer has taken ownership of the dequeue fence
2828 img.dequeue_fence = -1;
2829 // if we're still holding a release fence, get rid of it now
2830 if (img.release_fence >= 0) {
2831 close(img.release_fence);
2832 img.release_fence = -1;
2833 }
2834 img.dequeued = false;
2835 }
2836
2837 return VK_SUCCESS;
2838}
2839
Chia-I Wu62262232016-03-26 07:06:44 +08002840} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002841} // namespace vulkan