blob: 6b3c37932d49e04f44a85ace5592bb8d2fc5fb5e [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;
1372 if (!instance_dispatch.GetPhysicalDeviceImageFormatProperties2 &&
1373 !instance_dispatch.GetPhysicalDeviceImageFormatProperties2KHR) {
1374 uint64_t native_usage = 0;
1375 void* usage_info_pNext = nullptr;
1376 VkResult result;
1377 VkImageCompressionControlEXT image_compression = {};
1378 const auto& dispatch = GetData(device).driver;
1379 if (dispatch.GetSwapchainGrallocUsage4ANDROID) {
1380 ATRACE_BEGIN("GetSwapchainGrallocUsage4ANDROID");
1381 VkGrallocUsageInfo2ANDROID gralloc_usage_info = {};
1382 gralloc_usage_info.sType =
1383 VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_2_ANDROID;
1384 gralloc_usage_info.format = create_info->imageFormat;
1385 gralloc_usage_info.imageUsage = create_info->imageUsage;
1386 gralloc_usage_info.swapchainImageUsage = swapchain_image_usage;
1387
1388 // Look through the pNext chain for an image compression control struct
1389 // if one is found AND the appropriate extensions are enabled,
1390 // append it to be the gralloc usage pNext chain
1391 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1392 while (create_infos->pNext) {
1393 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1394 create_infos->pNext);
1395 switch (create_infos->sType) {
1396 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1397 const VkImageCompressionControlEXT* compression_infos =
1398 reinterpret_cast<const VkImageCompressionControlEXT*>(
1399 create_infos);
1400 image_compression = *compression_infos;
1401 image_compression.pNext = nullptr;
1402 usage_info_pNext = &image_compression;
1403 } break;
1404
1405 default:
1406 // Ignore all other info structs
1407 break;
1408 }
1409 }
1410 gralloc_usage_info.pNext = usage_info_pNext;
1411
1412 result = dispatch.GetSwapchainGrallocUsage4ANDROID(
1413 device, &gralloc_usage_info, &native_usage);
1414 ATRACE_END();
1415 if (result != VK_SUCCESS) {
1416 ALOGE("vkGetSwapchainGrallocUsage4ANDROID failed: %d", result);
1417 return VK_ERROR_SURFACE_LOST_KHR;
1418 }
1419 } else if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
1420 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1421 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1422 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1423 gralloc_usage_info.format = create_info->imageFormat;
1424 gralloc_usage_info.imageUsage = create_info->imageUsage;
1425
1426 // Look through the pNext chain for an image compression control struct
1427 // if one is found AND the appropriate extensions are enabled,
1428 // append it to be the gralloc usage pNext chain
1429 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1430 while (create_infos->pNext) {
1431 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1432 create_infos->pNext);
1433 switch (create_infos->sType) {
1434 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1435 const VkImageCompressionControlEXT* compression_infos =
1436 reinterpret_cast<const VkImageCompressionControlEXT*>(
1437 create_infos);
1438 image_compression = *compression_infos;
1439 image_compression.pNext = nullptr;
1440 usage_info_pNext = &image_compression;
1441 } break;
1442
1443 default:
1444 // Ignore all other info structs
1445 break;
1446 }
1447 }
1448 gralloc_usage_info.pNext = usage_info_pNext;
1449
1450 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1451 device, &gralloc_usage_info, &native_usage);
1452 ATRACE_END();
1453 if (result != VK_SUCCESS) {
1454 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
1455 return VK_ERROR_SURFACE_LOST_KHR;
1456 }
1457 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
1458 uint64_t consumer_usage, producer_usage;
1459 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
1460 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1461 device, create_info->imageFormat, create_info->imageUsage,
1462 swapchain_image_usage, &consumer_usage, &producer_usage);
1463 ATRACE_END();
1464 if (result != VK_SUCCESS) {
1465 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
1466 return VK_ERROR_SURFACE_LOST_KHR;
1467 }
1468 native_usage =
1469 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
1470 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
1471 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
1472 int32_t legacy_usage = 0;
1473 result = dispatch.GetSwapchainGrallocUsageANDROID(
1474 device, create_info->imageFormat, create_info->imageUsage,
1475 &legacy_usage);
1476 ATRACE_END();
1477 if (result != VK_SUCCESS) {
1478 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
1479 return VK_ERROR_SURFACE_LOST_KHR;
1480 }
1481 native_usage = static_cast<uint64_t>(legacy_usage);
1482 }
1483 *producer_usage = native_usage;
1484
1485 return VK_SUCCESS;
1486 }
1487
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001488 // Look through the create_info pNext chain passed to createSwapchainKHR
1489 // for an image compression control struct.
1490 // if one is found AND the appropriate extensions are enabled, create a
1491 // VkImageCompressionControlEXT structure to pass on to GetPhysicalDeviceImageFormatProperties2
1492 void* compression_control_pNext = nullptr;
1493 VkImageCompressionControlEXT image_compression = {};
1494 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1495 while (create_infos->pNext) {
1496 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(create_infos->pNext);
1497 switch (create_infos->sType) {
1498 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1499 const VkImageCompressionControlEXT* compression_infos =
1500 reinterpret_cast<const VkImageCompressionControlEXT*>(create_infos);
1501 image_compression = *compression_infos;
1502 image_compression.pNext = nullptr;
1503 compression_control_pNext = &image_compression;
1504 } break;
1505 default:
1506 // Ignore all other info structs
1507 break;
1508 }
1509 }
1510
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001511 // call GetPhysicalDeviceImageFormatProperties2KHR
1512 VkPhysicalDeviceExternalImageFormatInfo external_image_format_info = {
1513 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001514 .pNext = compression_control_pNext,
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001515 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID,
1516 };
1517
1518 // AHB does not have an sRGB format so we can't pass it to GPDIFP
1519 // We need to convert the format to unorm if it is srgb
1520 VkFormat format = create_info->imageFormat;
1521 if (format == VK_FORMAT_R8G8B8A8_SRGB) {
1522 format = VK_FORMAT_R8G8B8A8_UNORM;
1523 }
1524
1525 VkPhysicalDeviceImageFormatInfo2 image_format_info = {
1526 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1527 .pNext = &external_image_format_info,
1528 .format = format,
1529 .type = VK_IMAGE_TYPE_2D,
1530 .tiling = VK_IMAGE_TILING_OPTIMAL,
1531 .usage = create_info->imageUsage,
1532 .flags = create_protected_swapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
1533 };
1534
1535 VkAndroidHardwareBufferUsageANDROID ahb_usage;
1536 ahb_usage.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_USAGE_ANDROID;
1537 ahb_usage.pNext = nullptr;
1538
1539 VkImageFormatProperties2 image_format_properties;
1540 image_format_properties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
1541 image_format_properties.pNext = &ahb_usage;
1542
1543 if (instance_dispatch.GetPhysicalDeviceImageFormatProperties2) {
1544 VkResult result = instance_dispatch.GetPhysicalDeviceImageFormatProperties2(
1545 pdev, &image_format_info, &image_format_properties);
1546 if (result != VK_SUCCESS) {
1547 ALOGE("VkGetPhysicalDeviceImageFormatProperties2 for AHB usage failed: %d", result);
1548 return VK_ERROR_SURFACE_LOST_KHR;
1549 }
1550 }
1551 else {
1552 VkResult result = instance_dispatch.GetPhysicalDeviceImageFormatProperties2KHR(
1553 pdev, &image_format_info,
1554 &image_format_properties);
1555 if (result != VK_SUCCESS) {
1556 ALOGE("VkGetPhysicalDeviceImageFormatProperties2KHR for AHB usage failed: %d",
1557 result);
1558 return VK_ERROR_SURFACE_LOST_KHR;
1559 }
1560 }
1561
1562 *producer_usage = ahb_usage.androidHardwareBufferUsage;
1563
1564 return VK_SUCCESS;
1565}
1566
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001567VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001568VkResult CreateSwapchainKHR(VkDevice device,
1569 const VkSwapchainCreateInfoKHR* create_info,
1570 const VkAllocationCallbacks* allocator,
1571 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001572 ATRACE_CALL();
1573
Jesse Halld7b994a2015-09-07 14:17:37 -07001574 int err;
1575 VkResult result = VK_SUCCESS;
1576
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001577 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1578 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1579 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1580 " oldSwapchain=0x%" PRIx64,
1581 reinterpret_cast<uint64_t>(create_info->surface),
1582 create_info->minImageCount, create_info->imageFormat,
1583 create_info->imageColorSpace, create_info->imageExtent.width,
1584 create_info->imageExtent.height, create_info->imageUsage,
1585 create_info->preTransform, create_info->presentMode,
1586 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1587
Jesse Hall1f91d392015-12-11 16:28:44 -08001588 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001589 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001590
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001591 PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001592 GetNativePixelFormat(create_info->imageFormat);
sergiuferentz47989332023-09-26 10:24:36 +00001593 DataSpace native_dataspace =
Sally Qiaa238972023-07-17 12:52:05 +08001594 GetNativeDataspace(create_info->imageColorSpace, native_pixel_format);
sergiuferentz47989332023-09-26 10:24:36 +00001595 if (native_dataspace == DataSpace::UNKNOWN) {
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001596 ALOGE(
1597 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1598 "failed: Unsupported color space",
1599 create_info->imageColorSpace);
1600 return VK_ERROR_INITIALIZATION_FAILED;
1601 }
1602
Jesse Hall42a9eec2016-06-03 12:39:49 -07001603 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001604 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001605 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001606 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001607 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001608 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001609 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001610 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001611 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1612 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001613 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001614 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001615
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001616 Surface& surface = *SurfaceFromHandle(create_info->surface);
1617
Jesse Halldc225072016-05-30 22:40:14 -07001618 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001619 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001620 " because it already has active swapchain 0x%" PRIx64
1621 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1622 reinterpret_cast<uint64_t>(create_info->surface),
1623 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1624 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1625 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1626 }
1627 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1628 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1629
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001630 // -- Reset the native window --
1631 // The native window might have been used previously, and had its properties
1632 // changed from defaults. That will affect the answer we get for queries
1633 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1634 // attempt such queries.
1635
Jesse Halldc225072016-05-30 22:40:14 -07001636 // The native window only allows dequeueing all buffers before any have
1637 // been queued, since after that point at least one is assumed to be in
1638 // non-FREE state at any given time. Disconnecting and re-connecting
1639 // orphans the previous buffers, getting us back to the state where we can
1640 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001641 //
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001642 // This is not necessary if the surface was never used previously.
1643 //
Yiwei Zhang70a21962019-05-31 17:26:52 -07001644 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001645 ANativeWindow* window = surface.window.get();
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001646 if (surface.used_by_swapchain) {
1647 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1648 ALOGW_IF(err != android::OK,
1649 "native_window_api_disconnect failed: %s (%d)", strerror(-err),
1650 err);
1651 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1652 ALOGW_IF(err != android::OK,
1653 "native_window_api_connect failed: %s (%d)", strerror(-err),
1654 err);
1655 }
Jesse Halldc225072016-05-30 22:40:14 -07001656
Nicolas Capens147b7da2021-04-09 14:53:06 -04001657 err =
1658 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001659 if (err != android::OK) {
1660 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1661 strerror(-err), err);
1662 return VK_ERROR_SURFACE_LOST_KHR;
1663 }
1664
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301665 int swap_interval =
1666 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001667 err = window->setSwapInterval(window, swap_interval);
1668 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001669 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1670 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001671 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001672 }
1673
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001674 err = native_window_set_shared_buffer_mode(window, false);
1675 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001676 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1677 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001678 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001679 }
1680
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001681 err = native_window_set_auto_refresh(window, false);
1682 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001683 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1684 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001685 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001686 }
1687
Jesse Halld7b994a2015-09-07 14:17:37 -07001688 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001689
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001690 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001691
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001692 err = native_window_set_buffers_format(
1693 window, static_cast<int>(native_pixel_format));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001694 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001695 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001696 toString(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001697 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001698 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001699
1700 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
sergiuferentz47989332023-09-26 10:24:36 +00001701 if (native_dataspace != DataSpace::ARBITRARY) {
1702 err = native_window_set_buffers_data_space(
1703 window, static_cast<android_dataspace_t>(native_dataspace));
Yiwei Zhang51572c22022-07-22 23:08:30 +00001704 if (err != android::OK) {
1705 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1706 native_dataspace, strerror(-err), err);
1707 return VK_ERROR_SURFACE_LOST_KHR;
1708 }
Jesse Hall517274a2016-02-10 00:07:18 -08001709 }
1710
Jesse Hall3dd678a2016-01-08 21:52:01 -08001711 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001712 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001713 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001714 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001715 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1716 create_info->imageExtent.width, create_info->imageExtent.height,
1717 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001718 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001719 }
1720
Jesse Hall178b6962016-02-24 15:39:50 -08001721 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1722 // applied during rendering. native_window_set_transform() expects the
1723 // inverse: the transform the app is requesting that the compositor perform
1724 // during composition. With native windows, pre-transform works by rendering
1725 // with the same transform the compositor is applying (as in Vulkan), but
1726 // then requesting the inverse transform, so that when the compositor does
1727 // it's job the two transforms cancel each other out and the compositor ends
1728 // up applying an identity transform to the app's buffer.
1729 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001730 window, InvertTransformToNative(create_info->preTransform));
1731 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001732 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1733 InvertTransformToNative(create_info->preTransform),
1734 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001735 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001736 }
1737
Jesse Hallf64ca122015-11-03 16:11:10 -08001738 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001739 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1740 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001741 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1742 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001743 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001744 }
1745
Chris Forbes97ef4612017-03-30 19:37:50 +13001746 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001747 if (IsSharedPresentMode(create_info->presentMode)) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001748 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001749 err = native_window_set_shared_buffer_mode(window, true);
1750 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001751 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1752 return VK_ERROR_SURFACE_LOST_KHR;
1753 }
1754 }
1755
1756 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001757 err = native_window_set_auto_refresh(window, true);
1758 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001759 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1760 return VK_ERROR_SURFACE_LOST_KHR;
1761 }
1762 }
1763
Ian Elliott16c443c2021-11-30 17:10:32 -07001764 int query_value;
Trevor David Blackabab5a02023-12-19 20:27:07 +00001765 // TODO: Now that we are calling into GPDSC2 directly, this query may be redundant
1766 // the call to std::max(min_buffer_count, num_images) may be redundant as well
Ian Elliott16c443c2021-11-30 17:10:32 -07001767 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1768 &query_value);
1769 if (err != android::OK || query_value < 0) {
1770 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1771 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001772 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001773 }
Trevor David Black8c0122e2023-09-07 20:33:54 +00001774 const uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
Chris Forbes2c8fc752017-03-17 11:28:32 +13001775
Ian Elliott5396b702021-12-13 19:32:34 -07001776 // Lower layer insists that we have at least min_undequeued_buffers + 1
1777 // buffers. This is wasteful and we'd like to relax it in the shared case,
1778 // but not all the pieces are in place for that to work yet. Note we only
1779 // lie to the lower layer--we don't want to give the app back a swapchain
1780 // with extra images (which they can't actually use!).
Trevor David Black8c0122e2023-09-07 20:33:54 +00001781 const uint32_t min_buffer_count = min_undequeued_buffers + 1;
1782
Trevor David Blackabab5a02023-12-19 20:27:07 +00001783 // Call into GPDSC2 to get the minimum and maximum allowable buffer count for the surface of
1784 // interest. This step is only necessary if the app requests a number of images
1785 // (create_info->minImageCount) that is less or more than the surface capabilities.
1786 // An app should be calling GPDSC2 and using those values to set create_info, but in the
1787 // event that the app has hard-coded image counts an error can occur
1788 VkSurfacePresentModeEXT present_mode = {
1789 VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT,
1790 nullptr,
1791 create_info->presentMode
1792 };
1793 VkPhysicalDeviceSurfaceInfo2KHR surface_info2 = {
1794 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
1795 &present_mode,
1796 create_info->surface
1797 };
1798 VkSurfaceCapabilities2KHR surface_capabilities2 = {
1799 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
1800 nullptr,
1801 {},
1802 };
1803 result = GetPhysicalDeviceSurfaceCapabilities2KHR(GetData(device).driver_physical_device,
1804 &surface_info2, &surface_capabilities2);
1805
1806 uint32_t num_images = create_info->minImageCount;
1807 num_images = std::clamp(num_images,
1808 surface_capabilities2.surfaceCapabilities.minImageCount,
1809 surface_capabilities2.surfaceCapabilities.maxImageCount);
Trevor David Black8c0122e2023-09-07 20:33:54 +00001810
1811 const uint32_t buffer_count = std::max(min_buffer_count, num_images);
1812 err = native_window_set_buffer_count(window, buffer_count);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001813 if (err != android::OK) {
Trevor David Black8c0122e2023-09-07 20:33:54 +00001814 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", buffer_count,
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001815 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001816 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001817 }
1818
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001819 // In shared mode the num_images must be one regardless of how many
1820 // buffers were allocated for the buffer queue.
1821 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1822 num_images = 1;
1823 }
1824
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001825 // Look through the create_info pNext chain passed to createSwapchainKHR
1826 // for an image compression control struct.
1827 // if one is found AND the appropriate extensions are enabled, create a
1828 // VkImageCompressionControlEXT structure to pass on to VkImageCreateInfo
1829 // TODO check for imageCompressionControlSwapchain feature is enabled
Trevor David Black2cc44682022-03-09 00:31:38 +00001830 void* usage_info_pNext = nullptr;
1831 VkImageCompressionControlEXT image_compression = {};
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001832 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1833 while (create_infos->pNext) {
1834 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(create_infos->pNext);
1835 switch (create_infos->sType) {
1836 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1837 const VkImageCompressionControlEXT* compression_infos =
1838 reinterpret_cast<const VkImageCompressionControlEXT*>(create_infos);
1839 image_compression = *compression_infos;
1840 image_compression.pNext = nullptr;
1841 usage_info_pNext = &image_compression;
1842 } break;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001843
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001844 default:
1845 // Ignore all other info structs
1846 break;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001847 }
Jesse Hall70f93352015-11-04 09:41:31 -08001848 }
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001849
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001850 // Get the appropriate native_usage for the images
1851 // Get the consumer usage
1852 uint64_t native_usage = surface.consumer_usage;
1853 // Determine if the swapchain is protected
1854 bool create_protected_swapchain = false;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001855 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001856 create_protected_swapchain = true;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001857 native_usage |= BufferUsage::PROTECTED;
1858 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001859 // Get the producer usage
1860 uint64_t producer_usage;
1861 result = getProducerUsage(device, create_info, swapchain_image_usage, create_protected_swapchain, &producer_usage);
1862 if (result != VK_SUCCESS) {
1863 return result;
1864 }
1865 native_usage |= producer_usage;
1866
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001867 err = native_window_set_usage(window, native_usage);
1868 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001869 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001870 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001871 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001872
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001873 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001874 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1875 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001876 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1877 strerror(-err), err);
1878 return VK_ERROR_SURFACE_LOST_KHR;
1879 }
1880
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001881 int64_t refresh_duration;
1882 err = native_window_get_refresh_cycle_duration(window, &refresh_duration);
1883 if (err != android::OK) {
1884 ALOGE("native_window_get_refresh_cycle_duration query failed: %s (%d)",
1885 strerror(-err), err);
1886 return VK_ERROR_SURFACE_LOST_KHR;
1887 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001888 // -- Allocate our Swapchain object --
1889 // After this point, we must deallocate the swapchain on error.
1890
Jesse Hall1f91d392015-12-11 16:28:44 -08001891 void* mem = allocator->pfnAllocation(allocator->pUserData,
1892 sizeof(Swapchain), alignof(Swapchain),
1893 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001894
Jesse Hall1356b0d2015-11-23 17:24:58 -08001895 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001896 return VK_ERROR_OUT_OF_HOST_MEMORY;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001897
silence_dogood73597592019-05-23 16:57:37 -07001898 Swapchain* swapchain = new (mem)
1899 Swapchain(surface, num_images, create_info->presentMode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001900 TranslateVulkanToNativeTransform(create_info->preTransform),
1901 refresh_duration);
Chris Forbesb56287a2017-01-12 14:28:58 +13001902 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1903#pragma clang diagnostic push
1904#pragma clang diagnostic ignored "-Wold-style-cast"
1905 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1906#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00001907 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13001908 .usage = swapchain_image_usage,
1909 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001910 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001911#pragma clang diagnostic push
1912#pragma clang diagnostic ignored "-Wold-style-cast"
1913 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1914#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001915 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001916 };
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001917
Jesse Halld7b994a2015-09-07 14:17:37 -07001918 VkImageCreateInfo image_create = {
1919 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001920 .pNext = nullptr,
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001921 .flags = create_protected_swapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07001922 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08001923 .format = create_info->imageFormat,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001924 .extent = {
1925 create_info->imageExtent.width,
1926 create_info->imageExtent.height,
1927 1
1928 },
Jesse Halld7b994a2015-09-07 14:17:37 -07001929 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08001930 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08001931 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07001932 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001933 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001934 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08001935 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07001936 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1937 };
1938
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001939 // Note: don't do deferred allocation for shared present modes. There's only one buffer
1940 // involved so very little benefit.
1941 if ((create_info->flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT) &&
1942 !IsSharedPresentMode(create_info->presentMode)) {
1943 // Don't want to touch the underlying gralloc buffers yet;
1944 // instead just create unbound VkImages which will later be bound to memory inside
1945 // AcquireNextImage.
1946 VkImageSwapchainCreateInfoKHR image_swapchain_create = {
1947 .sType = VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR,
1948 .pNext = nullptr,
1949 .swapchain = HandleFromSwapchain(swapchain),
1950 };
1951 image_create.pNext = &image_swapchain_create;
Jesse Halld7b994a2015-09-07 14:17:37 -07001952
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001953 for (uint32_t i = 0; i < num_images; i++) {
1954 Swapchain::Image& img = swapchain->images[i];
1955 img.buffer = nullptr;
1956 img.dequeued = false;
1957
1958 result = dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1959 if (result != VK_SUCCESS) {
1960 ALOGD("vkCreateImage w/ for deferred swapchain image failed: %u", result);
1961 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08001962 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001963 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001964 } else {
1965 // -- Dequeue all buffers and create a VkImage for each --
1966 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07001967
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001968 for (uint32_t i = 0; i < num_images; i++) {
1969 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07001970
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001971 ANativeWindowBuffer* buffer;
1972 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
1973 if (err != android::OK) {
1974 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
1975 switch (-err) {
1976 case ENOMEM:
1977 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
1978 break;
1979 default:
1980 result = VK_ERROR_SURFACE_LOST_KHR;
1981 break;
1982 }
1983 break;
1984 }
1985 img.buffer = buffer;
1986 img.dequeued = true;
1987
1988 image_native_buffer.handle = img.buffer->handle;
1989 image_native_buffer.stride = img.buffer->stride;
1990 image_native_buffer.format = img.buffer->format;
1991 image_native_buffer.usage = int(img.buffer->usage);
1992 android_convertGralloc0To1Usage(int(img.buffer->usage),
1993 &image_native_buffer.usage2.producer,
1994 &image_native_buffer.usage2.consumer);
1995 image_native_buffer.usage3 = img.buffer->usage;
Trevor David Black0db7a092023-12-11 23:46:36 +00001996 image_native_buffer.ahb =
1997 ANativeWindowBuffer_getHardwareBuffer(img.buffer.get());
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001998 image_create.pNext = &image_native_buffer;
1999
2000 ATRACE_BEGIN("CreateImage");
2001 result =
2002 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
2003 ATRACE_END();
2004 if (result != VK_SUCCESS) {
2005 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
2006 break;
2007 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002008 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002009
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002010 // -- Cancel all buffers, returning them to the queue --
2011 // If an error occurred before, also destroy the VkImage and release the
2012 // buffer reference. Otherwise, we retain a strong reference to the buffer.
2013 for (uint32_t i = 0; i < num_images; i++) {
2014 Swapchain::Image& img = swapchain->images[i];
2015 if (img.dequeued) {
2016 if (!swapchain->shared) {
2017 window->cancelBuffer(window, img.buffer.get(),
2018 img.dequeue_fence);
2019 img.dequeue_fence = -1;
2020 img.dequeued = false;
2021 }
Chris Forbese0ced032017-03-30 19:44:15 +13002022 }
Chris Forbes31b85c22018-05-29 15:03:28 -07002023 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002024 }
2025
2026 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07002027 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
2028 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07002029 return result;
2030 }
2031
Yiwei Zhang69395cd2019-07-03 16:55:39 -07002032 if (transform_hint != swapchain->pre_transform) {
2033 // Log that the app is not doing pre-rotation.
2034 android::GraphicsEnv::getInstance().setTargetStats(
2035 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
2036 }
2037
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00002038 // Set stats for creating a Vulkan swapchain
2039 android::GraphicsEnv::getInstance().setTargetStats(
2040 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
2041
Yiwei Zhang3b88f312023-04-18 23:11:35 +00002042 surface.used_by_swapchain = true;
Jesse Halldc225072016-05-30 22:40:14 -07002043 surface.swapchain_handle = HandleFromSwapchain(swapchain);
2044 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002045 return VK_SUCCESS;
2046}
2047
Jesse Halle1b12782015-11-30 11:27:32 -08002048VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002049void DestroySwapchainKHR(VkDevice device,
2050 VkSwapchainKHR swapchain_handle,
2051 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002052 ATRACE_CALL();
2053
Yiwei Zhang533cea92019-06-03 18:43:24 -07002054 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07002055}
2056
Jesse Halle1b12782015-11-30 11:27:32 -08002057VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002058VkResult GetSwapchainImagesKHR(VkDevice,
2059 VkSwapchainKHR swapchain_handle,
2060 uint32_t* count,
2061 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002062 ATRACE_CALL();
2063
Jesse Halld7b994a2015-09-07 14:17:37 -07002064 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07002065 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
2066 "getting images for non-active swapchain 0x%" PRIx64
2067 "; only dequeued image handles are valid",
2068 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07002069 VkResult result = VK_SUCCESS;
2070 if (images) {
2071 uint32_t n = swapchain.num_images;
2072 if (*count < swapchain.num_images) {
2073 n = *count;
2074 result = VK_INCOMPLETE;
2075 }
2076 for (uint32_t i = 0; i < n; i++)
2077 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07002078 *count = n;
2079 } else {
2080 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07002081 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002082 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002083}
2084
Jesse Halle1b12782015-11-30 11:27:32 -08002085VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002086VkResult AcquireNextImageKHR(VkDevice device,
2087 VkSwapchainKHR swapchain_handle,
2088 uint64_t timeout,
2089 VkSemaphore semaphore,
2090 VkFence vk_fence,
2091 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002092 ATRACE_CALL();
2093
Jesse Halld7b994a2015-09-07 14:17:37 -07002094 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08002095 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07002096 VkResult result;
2097 int err;
2098
Jesse Halldc225072016-05-30 22:40:14 -07002099 if (swapchain.surface.swapchain_handle != swapchain_handle)
2100 return VK_ERROR_OUT_OF_DATE_KHR;
2101
Chris Forbesc88409c2017-03-30 19:47:37 +13002102 if (swapchain.shared) {
2103 // In shared mode, we keep the buffer dequeued all the time, so we don't
2104 // want to dequeue a buffer here. Instead, just ask the driver to ensure
2105 // the semaphore and fence passed to us will be signalled.
2106 *image_index = 0;
2107 result = GetData(device).driver.AcquireImageANDROID(
2108 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
2109 return result;
2110 }
2111
Yiwei Zhang705c2e62019-12-18 23:12:43 -08002112 const nsecs_t acquire_next_image_timeout =
2113 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
2114 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
2115 // Cache the timeout to avoid the duplicate binder cost.
2116 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
2117 acquire_next_image_timeout);
2118 if (err != android::OK) {
2119 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
2120 strerror(-err), err);
2121 return VK_ERROR_SURFACE_LOST_KHR;
2122 }
2123 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
2124 }
2125
Jesse Halld7b994a2015-09-07 14:17:37 -07002126 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08002127 int fence_fd;
2128 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07002129 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08002130 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
2131 return timeout ? VK_TIMEOUT : VK_NOT_READY;
2132 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07002133 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07002134 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002135 }
2136
2137 uint32_t idx;
2138 for (idx = 0; idx < swapchain.num_images; idx++) {
2139 if (swapchain.images[idx].buffer.get() == buffer) {
2140 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08002141 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07002142 break;
2143 }
2144 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002145
2146 // If this is a deferred alloc swapchain, this may be the first time we've
2147 // seen a particular buffer. If so, there should be an empty slot. Find it,
2148 // and bind the gralloc buffer to the VkImage for that slot. If there is no
2149 // empty slot, then we dequeued an unexpected buffer. Non-deferred swapchains
2150 // will also take this path, but will never have an empty slot since we
2151 // populated them all upfront.
2152 if (idx == swapchain.num_images) {
2153 for (idx = 0; idx < swapchain.num_images; idx++) {
2154 if (!swapchain.images[idx].buffer) {
2155 // Note: this structure is technically required for
2156 // Vulkan correctness, even though the driver is probably going
2157 // to use everything from the VkNativeBufferANDROID below.
2158 // This is kindof silly, but it's how we did the ANB
2159 // side of VK_KHR_swapchain v69, so we're stuck with it unless
2160 // we want to go tinkering with the ANB spec some more.
2161 VkBindImageMemorySwapchainInfoKHR bimsi = {
2162 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR,
2163 .pNext = nullptr,
2164 .swapchain = swapchain_handle,
2165 .imageIndex = idx,
2166 };
2167 VkNativeBufferANDROID nb = {
2168 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2169 .pNext = &bimsi,
2170 .handle = buffer->handle,
2171 .stride = buffer->stride,
2172 .format = buffer->format,
2173 .usage = int(buffer->usage),
Trevor David Black0db7a092023-12-11 23:46:36 +00002174 .usage3 = buffer->usage,
2175 .ahb = ANativeWindowBuffer_getHardwareBuffer(buffer),
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002176 };
Trevor David Black0db7a092023-12-11 23:46:36 +00002177 android_convertGralloc0To1Usage(int(buffer->usage),
2178 &nb.usage2.producer,
2179 &nb.usage2.consumer);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002180 VkBindImageMemoryInfo bimi = {
2181 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO,
2182 .pNext = &nb,
2183 .image = swapchain.images[idx].image,
2184 .memory = VK_NULL_HANDLE,
2185 .memoryOffset = 0,
2186 };
2187 result = GetData(device).driver.BindImageMemory2(device, 1, &bimi);
2188 if (result != VK_SUCCESS) {
2189 // This shouldn't really happen. If it does, something is probably
2190 // unrecoverably wrong with the swapchain and its images. Cancel
2191 // the buffer and declare the swapchain broken.
2192 ALOGE("failed to do deferred gralloc buffer bind");
2193 window->cancelBuffer(window, buffer, fence_fd);
2194 return VK_ERROR_OUT_OF_DATE_KHR;
2195 }
2196
2197 swapchain.images[idx].dequeued = true;
2198 swapchain.images[idx].dequeue_fence = fence_fd;
2199 swapchain.images[idx].buffer = buffer;
2200 break;
2201 }
2202 }
2203 }
2204
2205 // The buffer doesn't match any slot. This shouldn't normally happen, but is
2206 // possible if the bufferqueue is reconfigured behind libvulkan's back. If this
2207 // happens, just declare the swapchain to be broken and the app will recreate it.
Jesse Halld7b994a2015-09-07 14:17:37 -07002208 if (idx == swapchain.num_images) {
2209 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08002210 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002211 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002212 }
2213
2214 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08002215 if (fence_fd != -1) {
2216 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002217 if (fence_clone == -1) {
2218 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
2219 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08002220 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07002221 }
2222 }
2223
Chia-I Wu4a6a9162016-03-26 07:17:34 +08002224 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08002225 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07002226 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08002227 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
2228 // even if the call fails. We could close it ourselves on failure, but
2229 // that would create a race condition if the driver closes it on a
2230 // failure path: some other thread might create an fd with the same
2231 // number between the time the driver closes it and the time we close
2232 // it. We must assume one of: the driver *always* closes it even on
2233 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08002234 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002235 swapchain.images[idx].dequeued = false;
2236 swapchain.images[idx].dequeue_fence = -1;
2237 return result;
2238 }
2239
2240 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002241 return VK_SUCCESS;
2242}
2243
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002244VKAPI_ATTR
2245VkResult AcquireNextImage2KHR(VkDevice device,
2246 const VkAcquireNextImageInfoKHR* pAcquireInfo,
2247 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002248 ATRACE_CALL();
2249
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002250 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
2251 pAcquireInfo->timeout, pAcquireInfo->semaphore,
2252 pAcquireInfo->fence, pImageIndex);
2253}
2254
Jesse Halldc225072016-05-30 22:40:14 -07002255static VkResult WorstPresentResult(VkResult a, VkResult b) {
2256 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
2257 // (in spec version 1.0.14).
2258 static const VkResult kWorstToBest[] = {
2259 VK_ERROR_DEVICE_LOST,
2260 VK_ERROR_SURFACE_LOST_KHR,
2261 VK_ERROR_OUT_OF_DATE_KHR,
2262 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2263 VK_ERROR_OUT_OF_HOST_MEMORY,
2264 VK_SUBOPTIMAL_KHR,
2265 };
2266 for (auto result : kWorstToBest) {
2267 if (a == result || b == result)
2268 return result;
2269 }
2270 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
2271 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
2272 return a != VK_SUCCESS ? a : b;
2273}
2274
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002275// KHR_incremental_present aspect of QueuePresentKHR
2276static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
2277 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
2278 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
2279 auto const& rect = pRegion->pRectangles[i];
2280 if (rect.layer > 0) {
2281 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
2282 rect.layer);
2283 }
2284
2285 rects[i].left = rect.offset.x;
2286 rects[i].bottom = rect.offset.y;
2287 rects[i].right = rect.offset.x + rect.extent.width;
2288 rects[i].top = rect.offset.y + rect.extent.height;
2289 }
2290 native_window_set_surface_damage(window, rects.data(), rects.size());
2291}
2292
2293// GOOGLE_display_timing aspect of QueuePresentKHR
2294static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
2295 ANativeWindow *window = swapchain.surface.window.get();
2296
2297 // We don't know whether the app will actually use GOOGLE_display_timing
2298 // with a particular swapchain until QueuePresent; enable it on the BQ
2299 // now if needed
2300 if (!swapchain.frame_timestamps_enabled) {
2301 ALOGV("Calling native_window_enable_frame_timestamps(true)");
2302 native_window_enable_frame_timestamps(window, true);
2303 swapchain.frame_timestamps_enabled = true;
2304 }
2305
2306 // Record the nativeFrameId so it can be later correlated to
2307 // this present.
2308 uint64_t nativeFrameId = 0;
2309 int err = native_window_get_next_frame_id(
2310 window, &nativeFrameId);
2311 if (err != android::OK) {
2312 ALOGE("Failed to get next native frame ID.");
2313 }
2314
2315 // Add a new timing record with the user's presentID and
2316 // the nativeFrameId.
2317 swapchain.timing.emplace_back(pTime, nativeFrameId);
2318 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
2319 swapchain.timing.erase(
2320 swapchain.timing.begin(),
2321 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
2322 }
2323 if (pTime->desiredPresentTime) {
2324 ALOGV(
2325 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
2326 pTime->desiredPresentTime);
2327 native_window_set_buffers_timestamp(
2328 window,
2329 static_cast<int64_t>(pTime->desiredPresentTime));
2330 }
2331}
2332
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002333// EXT_swapchain_maintenance1 present mode change
2334static bool SetSwapchainPresentMode(ANativeWindow *window, VkPresentModeKHR mode) {
2335 // There is no dynamic switching between non-shared present modes.
2336 // All we support is switching between demand and continuous refresh.
2337 if (!IsSharedPresentMode(mode))
2338 return true;
2339
2340 int err = native_window_set_auto_refresh(window,
2341 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
2342 if (err != android::OK) {
2343 ALOGE("native_window_set_auto_refresh() failed: %s (%d)",
2344 strerror(-err), err);
2345 return false;
2346 }
2347
2348 return true;
2349}
2350
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002351static VkResult PresentOneSwapchain(
2352 VkQueue queue,
2353 Swapchain& swapchain,
2354 uint32_t imageIndex,
2355 const VkPresentRegionKHR *pRegion,
2356 const VkPresentTimeGOOGLE *pTime,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002357 VkFence presentFence,
2358 const VkPresentModeKHR *pPresentMode,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002359 uint32_t waitSemaphoreCount,
2360 const VkSemaphore *pWaitSemaphores) {
2361
2362 VkDevice device = GetData(queue).driver_device;
2363 const auto& dispatch = GetData(queue).driver;
2364
2365 Swapchain::Image& img = swapchain.images[imageIndex];
2366 VkResult swapchain_result = VK_SUCCESS;
2367 VkResult result;
2368 int err;
2369
2370 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
2371 // wait semaphores, so this doesn't actually work for the multiple swapchain
2372 // case.
2373 int fence = -1;
2374 result = dispatch.QueueSignalReleaseImageANDROID(
2375 queue, waitSemaphoreCount,
2376 pWaitSemaphores, img.image, &fence);
2377 if (result != VK_SUCCESS) {
2378 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
2379 swapchain_result = result;
2380 }
2381 if (img.release_fence >= 0)
2382 close(img.release_fence);
2383 img.release_fence = fence < 0 ? -1 : dup(fence);
2384
2385 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
2386 ANativeWindow* window = swapchain.surface.window.get();
2387 if (swapchain_result == VK_SUCCESS) {
2388
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002389 if (presentFence != VK_NULL_HANDLE) {
2390 int fence_copy = fence < 0 ? -1 : dup(fence);
2391 VkImportFenceFdInfoKHR iffi = {
2392 VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,
2393 nullptr,
2394 presentFence,
2395 VK_FENCE_IMPORT_TEMPORARY_BIT,
2396 VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,
2397 fence_copy,
2398 };
2399 if (VK_SUCCESS != dispatch.ImportFenceFdKHR(device, &iffi) && fence_copy >= 0) {
2400 // ImportFenceFdKHR takes ownership only if it succeeds
2401 close(fence_copy);
2402 }
2403 }
2404
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002405 if (pRegion) {
2406 SetSwapchainSurfaceDamage(window, pRegion);
2407 }
2408 if (pTime) {
2409 SetSwapchainFrameTimestamp(swapchain, pTime);
2410 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002411 if (pPresentMode) {
2412 if (!SetSwapchainPresentMode(window, *pPresentMode))
2413 swapchain_result = WorstPresentResult(swapchain_result,
2414 VK_ERROR_SURFACE_LOST_KHR);
2415 }
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002416
2417 err = window->queueBuffer(window, img.buffer.get(), fence);
2418 // queueBuffer always closes fence, even on error
2419 if (err != android::OK) {
2420 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
2421 swapchain_result = WorstPresentResult(
2422 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2423 } else {
2424 if (img.dequeue_fence >= 0) {
2425 close(img.dequeue_fence);
2426 img.dequeue_fence = -1;
2427 }
2428 img.dequeued = false;
2429 }
2430
2431 // If the swapchain is in shared mode, immediately dequeue the
2432 // buffer so it can be presented again without an intervening
2433 // call to AcquireNextImageKHR. We expect to get the same buffer
2434 // back from every call to dequeueBuffer in this mode.
2435 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
2436 ANativeWindowBuffer* buffer;
2437 int fence_fd;
2438 err = window->dequeueBuffer(window, &buffer, &fence_fd);
2439 if (err != android::OK) {
2440 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
2441 swapchain_result = WorstPresentResult(swapchain_result,
2442 VK_ERROR_SURFACE_LOST_KHR);
2443 } else if (img.buffer != buffer) {
2444 ALOGE("got wrong image back for shared swapchain");
2445 swapchain_result = WorstPresentResult(swapchain_result,
2446 VK_ERROR_SURFACE_LOST_KHR);
2447 } else {
2448 img.dequeue_fence = fence_fd;
2449 img.dequeued = true;
2450 }
2451 }
2452 }
2453 if (swapchain_result != VK_SUCCESS) {
2454 OrphanSwapchain(device, &swapchain);
2455 }
2456 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
2457 // and only when the window's transform/rotation changes. Extent
2458 // changes will not cause VK_SUBOPTIMAL_KHR because of the
2459 // application issues that were caused when the following transform
2460 // change was added.
2461 int window_transform_hint;
2462 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
2463 &window_transform_hint);
2464 if (err != android::OK) {
2465 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
2466 strerror(-err), err);
2467 swapchain_result = WorstPresentResult(
2468 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2469 }
2470 if (swapchain.pre_transform != window_transform_hint) {
2471 swapchain_result =
2472 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
2473 }
2474 } else {
2475 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
2476 img, true);
2477 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
2478 }
2479
2480 return swapchain_result;
2481}
2482
Jesse Halle1b12782015-11-30 11:27:32 -08002483VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002484VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002485 ATRACE_CALL();
2486
Jesse Halld7b994a2015-09-07 14:17:37 -07002487 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
2488 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
2489 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07002490
Jesse Halld7b994a2015-09-07 14:17:37 -07002491 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07002492
Ian Elliottcb351132016-12-13 10:30:40 -07002493 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002494 const VkPresentRegionsKHR* present_regions = nullptr;
2495 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002496 const VkSwapchainPresentFenceInfoEXT* present_fences = nullptr;
2497 const VkSwapchainPresentModeInfoEXT* present_modes = nullptr;
2498
Ian Elliottcb351132016-12-13 10:30:40 -07002499 const VkPresentRegionsKHR* next =
2500 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
2501 while (next) {
2502 switch (next->sType) {
2503 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
2504 present_regions = next;
2505 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07002506 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002507 present_times =
2508 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
2509 break;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002510 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT:
2511 present_fences =
2512 reinterpret_cast<const VkSwapchainPresentFenceInfoEXT*>(next);
2513 break;
2514 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT:
2515 present_modes =
2516 reinterpret_cast<const VkSwapchainPresentModeInfoEXT*>(next);
2517 break;
Ian Elliottcb351132016-12-13 10:30:40 -07002518 default:
2519 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
2520 next->sType);
2521 break;
2522 }
2523 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2524 }
2525 ALOGV_IF(
2526 present_regions &&
2527 present_regions->swapchainCount != present_info->swapchainCount,
2528 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002529 ALOGV_IF(present_times &&
2530 present_times->swapchainCount != present_info->swapchainCount,
2531 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2532 "VkPresentInfo::swapchainCount");
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002533 ALOGV_IF(present_fences &&
2534 present_fences->swapchainCount != present_info->swapchainCount,
2535 "VkSwapchainPresentFenceInfoEXT::swapchainCount != "
2536 "VkPresentInfo::swapchainCount");
2537 ALOGV_IF(present_modes &&
2538 present_modes->swapchainCount != present_info->swapchainCount,
2539 "VkSwapchainPresentModeInfoEXT::swapchainCount != "
2540 "VkPresentInfo::swapchainCount");
2541
Ian Elliottcb351132016-12-13 10:30:40 -07002542 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002543 (present_regions) ? present_regions->pRegions : nullptr;
2544 const VkPresentTimeGOOGLE* times =
2545 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002546
Jesse Halld7b994a2015-09-07 14:17:37 -07002547 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2548 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002549 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002550
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002551 VkResult swapchain_result = PresentOneSwapchain(
2552 queue,
2553 swapchain,
2554 present_info->pImageIndices[sc],
2555 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2556 times ? &times[sc] : nullptr,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002557 present_fences ? present_fences->pFences[sc] : VK_NULL_HANDLE,
2558 present_modes ? &present_modes->pPresentModes[sc] : nullptr,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002559 present_info->waitSemaphoreCount,
2560 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002561
Jesse Halla9e57032015-11-30 01:03:10 -08002562 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002563 present_info->pResults[sc] = swapchain_result;
2564
2565 if (swapchain_result != final_result)
2566 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002567 }
2568
2569 return final_result;
2570}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002571
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002572VKAPI_ATTR
2573VkResult GetRefreshCycleDurationGOOGLE(
2574 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002575 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002576 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002577 ATRACE_CALL();
2578
Ian Elliott62c48c92017-01-20 13:13:20 -07002579 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00002580 VkResult result = swapchain.get_refresh_duration(pDisplayTimingProperties->refreshDuration);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002581
2582 return result;
2583}
2584
2585VKAPI_ATTR
2586VkResult GetPastPresentationTimingGOOGLE(
2587 VkDevice,
2588 VkSwapchainKHR swapchain_handle,
2589 uint32_t* count,
2590 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002591 ATRACE_CALL();
2592
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002593 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002594 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2595 return VK_ERROR_OUT_OF_DATE_KHR;
2596 }
2597
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002598 ANativeWindow* window = swapchain.surface.window.get();
2599 VkResult result = VK_SUCCESS;
2600
2601 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002602 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002603 native_window_enable_frame_timestamps(window, true);
2604 swapchain.frame_timestamps_enabled = true;
2605 }
2606
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002607 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002608 // Get the latest ready timing count before copying, since the copied
2609 // timing info will be erased in copy_ready_timings function.
2610 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002611 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002612 // Check the *count here against the recorded ready timing count, since
2613 // *count can be overwritten per spec describes.
2614 if (*count < n) {
2615 result = VK_INCOMPLETE;
2616 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002617 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002618 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002619 }
2620
2621 return result;
2622}
2623
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002624VKAPI_ATTR
2625VkResult GetSwapchainStatusKHR(
2626 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002627 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002628 ATRACE_CALL();
2629
Chris Forbes4e18ba82017-01-20 12:50:17 +13002630 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002631 VkResult result = VK_SUCCESS;
2632
Chris Forbes4e18ba82017-01-20 12:50:17 +13002633 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2634 return VK_ERROR_OUT_OF_DATE_KHR;
2635 }
2636
Yiwei Zhanga885c062019-10-24 12:07:57 -07002637 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002638
2639 return result;
2640}
2641
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002642VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002643 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002644 uint32_t swapchainCount,
2645 const VkSwapchainKHR* pSwapchains,
2646 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002647 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002648
2649 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2650 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2651 if (!swapchain)
2652 continue;
2653
2654 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2655
2656 ANativeWindow* window = swapchain->surface.window.get();
2657
2658 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2659 const android_smpte2086_metadata smpteMetdata = {
2660 {vulkanMetadata.displayPrimaryRed.x,
2661 vulkanMetadata.displayPrimaryRed.y},
2662 {vulkanMetadata.displayPrimaryGreen.x,
2663 vulkanMetadata.displayPrimaryGreen.y},
2664 {vulkanMetadata.displayPrimaryBlue.x,
2665 vulkanMetadata.displayPrimaryBlue.y},
2666 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2667 vulkanMetadata.maxLuminance,
2668 vulkanMetadata.minLuminance};
2669 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2670
2671 const android_cta861_3_metadata cta8613Metadata = {
2672 vulkanMetadata.maxContentLightLevel,
2673 vulkanMetadata.maxFrameAverageLightLevel};
2674 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2675 }
2676
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002677 return;
2678}
2679
Yiwei Zhang0f475222019-04-11 19:38:00 -07002680static void InterceptBindImageMemory2(
2681 uint32_t bind_info_count,
2682 const VkBindImageMemoryInfo* bind_infos,
2683 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2684 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2685 out_native_buffers->clear();
2686 out_bind_infos->clear();
2687
2688 if (!bind_info_count)
2689 return;
2690
2691 std::unordered_set<uint32_t> intercepted_indexes;
2692
2693 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2694 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2695 bind_infos[idx].pNext);
2696 while (info &&
2697 info->sType !=
2698 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2699 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2700 info->pNext);
2701 }
2702
2703 if (!info)
2704 continue;
2705
2706 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2707 "swapchain handle must not be NULL");
2708 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2709 ALOG_ASSERT(
2710 info->imageIndex < swapchain->num_images,
2711 "imageIndex must be less than the number of images in swapchain");
2712
2713 ANativeWindowBuffer* buffer =
2714 swapchain->images[info->imageIndex].buffer.get();
2715 VkNativeBufferANDROID native_buffer = {
2716#pragma clang diagnostic push
2717#pragma clang diagnostic ignored "-Wold-style-cast"
2718 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2719#pragma clang diagnostic pop
2720 .pNext = bind_infos[idx].pNext,
2721 .handle = buffer->handle,
2722 .stride = buffer->stride,
2723 .format = buffer->format,
2724 .usage = int(buffer->usage),
Trevor David Black0db7a092023-12-11 23:46:36 +00002725 .usage3 = buffer->usage,
2726 .ahb = ANativeWindowBuffer_getHardwareBuffer(buffer),
Yiwei Zhang0f475222019-04-11 19:38:00 -07002727 };
Trevor David Black0db7a092023-12-11 23:46:36 +00002728 android_convertGralloc0To1Usage(int(buffer->usage),
2729 &native_buffer.usage2.producer,
2730 &native_buffer.usage2.consumer);
Yiwei Zhang0f475222019-04-11 19:38:00 -07002731 // Reserve enough space to avoid letting re-allocation invalidate the
2732 // addresses of the elements inside.
2733 out_native_buffers->reserve(bind_info_count);
2734 out_native_buffers->emplace_back(native_buffer);
2735
2736 // Reserve the space now since we know how much is needed now.
2737 out_bind_infos->reserve(bind_info_count);
2738 out_bind_infos->emplace_back(bind_infos[idx]);
2739 out_bind_infos->back().pNext = &out_native_buffers->back();
2740
2741 intercepted_indexes.insert(idx);
2742 }
2743
2744 if (intercepted_indexes.empty())
2745 return;
2746
2747 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2748 if (intercepted_indexes.count(idx))
2749 continue;
2750 out_bind_infos->emplace_back(bind_infos[idx]);
2751 }
2752}
2753
Yiwei Zhang23143102019-04-10 18:24:05 -07002754VKAPI_ATTR
2755VkResult BindImageMemory2(VkDevice device,
2756 uint32_t bindInfoCount,
2757 const VkBindImageMemoryInfo* pBindInfos) {
2758 ATRACE_CALL();
2759
Yiwei Zhang0f475222019-04-11 19:38:00 -07002760 // out_native_buffers is for maintaining the lifecycle of the constructed
2761 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2762 std::vector<VkNativeBufferANDROID> out_native_buffers;
2763 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2764 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2765 &out_bind_infos);
2766 return GetData(device).driver.BindImageMemory2(
2767 device, bindInfoCount,
2768 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002769}
2770
2771VKAPI_ATTR
2772VkResult BindImageMemory2KHR(VkDevice device,
2773 uint32_t bindInfoCount,
2774 const VkBindImageMemoryInfo* pBindInfos) {
2775 ATRACE_CALL();
2776
Yiwei Zhang0f475222019-04-11 19:38:00 -07002777 std::vector<VkNativeBufferANDROID> out_native_buffers;
2778 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2779 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2780 &out_bind_infos);
2781 return GetData(device).driver.BindImageMemory2KHR(
2782 device, bindInfoCount,
2783 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002784}
2785
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002786VKAPI_ATTR
2787VkResult ReleaseSwapchainImagesEXT(VkDevice /*device*/,
2788 const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
2789 ATRACE_CALL();
2790
2791 Swapchain& swapchain = *SwapchainFromHandle(pReleaseInfo->swapchain);
2792 ANativeWindow* window = swapchain.surface.window.get();
2793
2794 // If in shared present mode, don't actually release the image back to the BQ.
2795 // Both sides share it forever.
2796 if (swapchain.shared)
2797 return VK_SUCCESS;
2798
2799 for (uint32_t i = 0; i < pReleaseInfo->imageIndexCount; i++) {
2800 Swapchain::Image& img = swapchain.images[pReleaseInfo->pImageIndices[i]];
2801 window->cancelBuffer(window, img.buffer.get(), img.dequeue_fence);
2802
2803 // cancelBuffer has taken ownership of the dequeue fence
2804 img.dequeue_fence = -1;
2805 // if we're still holding a release fence, get rid of it now
2806 if (img.release_fence >= 0) {
2807 close(img.release_fence);
2808 img.release_fence = -1;
2809 }
2810 img.dequeued = false;
2811 }
2812
2813 return VK_SUCCESS;
2814}
2815
Chia-I Wu62262232016-03-26 07:06:44 +08002816} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002817} // namespace vulkan