blob: 7159d83e610b69b6eafe9e9eafbdb47fdf5c78cb [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
Trevor David Blackf499b5a2023-07-14 17:30:41 +000019#include <aidl/android/hardware/graphics/common/PixelFormat.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070020#include <android/hardware/graphics/common/1.0/types.h>
Jesse Hall79927812017-03-23 11:03:23 -070021#include <grallocusage/GrallocUsageConversion.h>
Yiwei Zhang69395cd2019-07-03 16:55:39 -070022#include <graphicsenv/GraphicsEnv.h>
John Reck97678d42022-08-23 11:24:51 -040023#include <hardware/gralloc.h>
24#include <hardware/gralloc1.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070025#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070026#include <sync/sync.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070027#include <system/window.h>
28#include <ui/BufferQueueDefs.h>
Chia-I Wue8e689f2016-04-18 08:21:31 +080029#include <utils/StrongPointer.h>
Yiwei Zhang705c2e62019-12-18 23:12:43 -080030#include <utils/Timers.h>
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080031#include <utils/Trace.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070032
33#include <algorithm>
34#include <unordered_set>
35#include <vector>
Jesse Halld7b994a2015-09-07 14:17:37 -070036
Chia-I Wu4a6a9162016-03-26 07:17:34 +080037#include "driver.h"
Jesse Halld7b994a2015-09-07 14:17:37 -070038
Trevor David Blackf499b5a2023-07-14 17:30:41 +000039using PixelFormat = aidl::android::hardware::graphics::common::PixelFormat;
Daniel Kochf25f5bb2017-10-05 00:26:58 -040040using android::hardware::graphics::common::V1_0::BufferUsage;
41
Chia-I Wu62262232016-03-26 07:06:44 +080042namespace vulkan {
43namespace driver {
Jesse Hall5ae3abb2015-10-08 14:00:22 -070044
Jesse Halld7b994a2015-09-07 14:17:37 -070045namespace {
46
John Reck97678d42022-08-23 11:24:51 -040047static uint64_t convertGralloc1ToBufferUsage(uint64_t producerUsage,
48 uint64_t consumerUsage) {
49 static_assert(uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) ==
50 uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN),
51 "expected ConsumerUsage and ProducerUsage CPU_READ_OFTEN "
52 "bits to match");
53 uint64_t merged = producerUsage | consumerUsage;
54 if ((merged & (GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN)) ==
55 GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) {
56 merged &= ~uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN);
57 merged |= BufferUsage::CPU_READ_OFTEN;
58 }
59 if ((merged & (GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN)) ==
60 GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) {
61 merged &= ~uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN);
62 merged |= BufferUsage::CPU_WRITE_OFTEN;
63 }
64 return merged;
65}
66
Jesse Hall55bc0972016-02-23 16:43:29 -080067const VkSurfaceTransformFlagsKHR kSupportedTransforms =
68 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
69 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
70 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
71 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
Yiwei Zhang70a21962019-05-31 17:26:52 -070072 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
73 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
74 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
75 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
Jesse Hall55bc0972016-02-23 16:43:29 -080076 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
77
78VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
79 // Native and Vulkan transforms are isomorphic, but are represented
80 // differently. Vulkan transforms are built up of an optional horizontal
81 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
82 // transforms are built up from a horizontal flip, vertical flip, and
83 // 90-degree rotation, all optional but always in that order.
84
Jesse Hall55bc0972016-02-23 16:43:29 -080085 switch (native) {
Yiwei Zhang70a21962019-05-31 17:26:52 -070086 case 0:
Jesse Hall55bc0972016-02-23 16:43:29 -080087 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070088 case NATIVE_WINDOW_TRANSFORM_FLIP_H:
89 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
90 case NATIVE_WINDOW_TRANSFORM_FLIP_V:
91 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
92 case NATIVE_WINDOW_TRANSFORM_ROT_180:
Jesse Hall55bc0972016-02-23 16:43:29 -080093 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070094 case NATIVE_WINDOW_TRANSFORM_ROT_90:
Jesse Hall55bc0972016-02-23 16:43:29 -080095 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070096 case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
97 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
98 case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
99 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
100 case NATIVE_WINDOW_TRANSFORM_ROT_270:
Jesse Hall55bc0972016-02-23 16:43:29 -0800101 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
102 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
103 default:
104 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
105 }
106}
107
Yiwei Zhang70a21962019-05-31 17:26:52 -0700108int TranslateVulkanToNativeTransform(VkSurfaceTransformFlagBitsKHR transform) {
109 switch (transform) {
110 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
111 return NATIVE_WINDOW_TRANSFORM_ROT_90;
112 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
113 return NATIVE_WINDOW_TRANSFORM_ROT_180;
114 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
115 return NATIVE_WINDOW_TRANSFORM_ROT_270;
116 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
117 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
118 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
119 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
120 NATIVE_WINDOW_TRANSFORM_ROT_90;
121 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
122 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
123 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
124 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
125 NATIVE_WINDOW_TRANSFORM_ROT_90;
126 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
127 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
128 default:
129 return 0;
130 }
131}
132
Jesse Hall178b6962016-02-24 15:39:50 -0800133int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
134 switch (transform) {
135 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
136 return NATIVE_WINDOW_TRANSFORM_ROT_270;
137 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
138 return NATIVE_WINDOW_TRANSFORM_ROT_180;
139 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
140 return NATIVE_WINDOW_TRANSFORM_ROT_90;
Yiwei Zhang70a21962019-05-31 17:26:52 -0700141 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
142 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
143 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
144 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
145 NATIVE_WINDOW_TRANSFORM_ROT_90;
146 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
147 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
148 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
149 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
150 NATIVE_WINDOW_TRANSFORM_ROT_90;
Jesse Hall178b6962016-02-24 15:39:50 -0800151 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
152 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
153 default:
154 return 0;
155 }
156}
157
Ian Elliott8a977262017-01-19 09:05:58 -0700158class TimingInfo {
159 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800160 TimingInfo(const VkPresentTimeGOOGLE* qp, uint64_t nativeFrameId)
Ian Elliott2c6355d2017-01-19 11:02:13 -0700161 : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
Brian Anderson1049d1d2016-12-16 17:25:57 -0800162 native_frame_id_(nativeFrameId) {}
163 bool ready() const {
Brian Andersondc96fdf2017-03-20 16:54:25 -0700164 return (timestamp_desired_present_time_ !=
165 NATIVE_WINDOW_TIMESTAMP_PENDING &&
166 timestamp_actual_present_time_ !=
167 NATIVE_WINDOW_TIMESTAMP_PENDING &&
168 timestamp_render_complete_time_ !=
169 NATIVE_WINDOW_TIMESTAMP_PENDING &&
170 timestamp_composition_latch_time_ !=
171 NATIVE_WINDOW_TIMESTAMP_PENDING);
Ian Elliott8a977262017-01-19 09:05:58 -0700172 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700173 void calculate(int64_t rdur) {
174 bool anyTimestampInvalid =
175 (timestamp_actual_present_time_ ==
176 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
177 (timestamp_render_complete_time_ ==
178 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
179 (timestamp_composition_latch_time_ ==
180 NATIVE_WINDOW_TIMESTAMP_INVALID);
181 if (anyTimestampInvalid) {
182 ALOGE("Unexpectedly received invalid timestamp.");
183 vals_.actualPresentTime = 0;
184 vals_.earliestPresentTime = 0;
185 vals_.presentMargin = 0;
186 return;
187 }
188
189 vals_.actualPresentTime =
190 static_cast<uint64_t>(timestamp_actual_present_time_);
191 int64_t margin = (timestamp_composition_latch_time_ -
Ian Elliott8a977262017-01-19 09:05:58 -0700192 timestamp_render_complete_time_);
193 // Calculate vals_.earliestPresentTime, and potentially adjust
194 // vals_.presentMargin. The initial value of vals_.earliestPresentTime
195 // is vals_.actualPresentTime. If we can subtract rdur (the duration
196 // of a refresh cycle) from vals_.earliestPresentTime (and also from
197 // vals_.presentMargin) and still leave a positive margin, then we can
198 // report to the application that it could have presented earlier than
199 // it did (per the extension specification). If for some reason, we
200 // can do this subtraction repeatedly, we do, since
201 // vals_.earliestPresentTime really is supposed to be the "earliest".
Brian Andersondc96fdf2017-03-20 16:54:25 -0700202 int64_t early_time = timestamp_actual_present_time_;
Ian Elliott8a977262017-01-19 09:05:58 -0700203 while ((margin > rdur) &&
204 ((early_time - rdur) > timestamp_composition_latch_time_)) {
205 early_time -= rdur;
206 margin -= rdur;
207 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700208 vals_.earliestPresentTime = static_cast<uint64_t>(early_time);
209 vals_.presentMargin = static_cast<uint64_t>(margin);
Ian Elliott8a977262017-01-19 09:05:58 -0700210 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800211 void get_values(VkPastPresentationTimingGOOGLE* values) const {
212 *values = vals_;
213 }
Ian Elliott8a977262017-01-19 09:05:58 -0700214
215 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800216 VkPastPresentationTimingGOOGLE vals_ { 0, 0, 0, 0, 0 };
Ian Elliott8a977262017-01-19 09:05:58 -0700217
Brian Anderson1049d1d2016-12-16 17:25:57 -0800218 uint64_t native_frame_id_ { 0 };
Brian Andersondc96fdf2017-03-20 16:54:25 -0700219 int64_t timestamp_desired_present_time_{ NATIVE_WINDOW_TIMESTAMP_PENDING };
220 int64_t timestamp_actual_present_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
221 int64_t timestamp_render_complete_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
222 int64_t timestamp_composition_latch_time_
223 { NATIVE_WINDOW_TIMESTAMP_PENDING };
Ian Elliott8a977262017-01-19 09:05:58 -0700224};
225
Jesse Hall1356b0d2015-11-23 17:24:58 -0800226struct Surface {
Chia-I Wue8e689f2016-04-18 08:21:31 +0800227 android::sp<ANativeWindow> window;
Jesse Halldc225072016-05-30 22:40:14 -0700228 VkSwapchainKHR swapchain_handle;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700229 uint64_t consumer_usage;
Yiwei Zhang3b88f312023-04-18 23:11:35 +0000230
231 // Indicate whether this surface has been used by a swapchain, no matter the
232 // swapchain is still current or has been destroyed.
233 bool used_by_swapchain;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800234};
235
236VkSurfaceKHR HandleFromSurface(Surface* surface) {
237 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
238}
239
240Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800241 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800242}
243
Ian Elliott8a977262017-01-19 09:05:58 -0700244// Maximum number of TimingInfo structs to keep per swapchain:
245enum { MAX_TIMING_INFOS = 10 };
246// Minimum number of frames to look for in the past (so we don't cause
247// syncronous requests to Surface Flinger):
248enum { MIN_NUM_FRAMES_AGO = 5 };
249
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300250bool IsSharedPresentMode(VkPresentModeKHR mode) {
251 return mode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
252 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR;
253}
254
Jesse Hall1356b0d2015-11-23 17:24:58 -0800255struct Swapchain {
Ian Elliottffedb652017-02-14 10:58:30 -0700256 Swapchain(Surface& surface_,
257 uint32_t num_images_,
silence_dogood73597592019-05-23 16:57:37 -0700258 VkPresentModeKHR present_mode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000259 int pre_transform_,
260 int64_t refresh_duration_)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700261 : surface(surface_),
262 num_images(num_images_),
Ian Elliottffedb652017-02-14 10:58:30 -0700263 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
silence_dogood73597592019-05-23 16:57:37 -0700264 pre_transform(pre_transform_),
Chris Forbesf8835642017-03-30 19:31:40 +1300265 frame_timestamps_enabled(false),
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000266 refresh_duration(refresh_duration_),
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800267 acquire_next_image_timeout(-1),
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300268 shared(IsSharedPresentMode(present_mode)) {
Ian Elliott8a977262017-01-19 09:05:58 -0700269 }
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000270
271 VkResult get_refresh_duration(uint64_t& outRefreshDuration)
Ian Elliott3568bfe2019-05-03 15:54:46 -0600272 {
273 ANativeWindow* window = surface.window.get();
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000274 int err = native_window_get_refresh_cycle_duration(
Ian Elliott3568bfe2019-05-03 15:54:46 -0600275 window,
276 &refresh_duration);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000277 if (err != android::OK) {
278 ALOGE("%s:native_window_get_refresh_cycle_duration failed: %s (%d)",
279 __func__, strerror(-err), err );
280 return VK_ERROR_SURFACE_LOST_KHR;
281 }
282 outRefreshDuration = refresh_duration;
283 return VK_SUCCESS;
Ian Elliott3568bfe2019-05-03 15:54:46 -0600284 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800285
286 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700287 uint32_t num_images;
Ian Elliottffedb652017-02-14 10:58:30 -0700288 bool mailbox_mode;
silence_dogood73597592019-05-23 16:57:37 -0700289 int pre_transform;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700290 bool frame_timestamps_enabled;
Brian Andersondc96fdf2017-03-20 16:54:25 -0700291 int64_t refresh_duration;
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800292 nsecs_t acquire_next_image_timeout;
Chris Forbesf8835642017-03-30 19:31:40 +1300293 bool shared;
Jesse Halld7b994a2015-09-07 14:17:37 -0700294
295 struct Image {
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700296 Image()
297 : image(VK_NULL_HANDLE),
298 dequeue_fence(-1),
299 release_fence(-1),
300 dequeued(false) {}
Jesse Halld7b994a2015-09-07 14:17:37 -0700301 VkImage image;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000302 // If the image is bound to memory, an sp to the underlying gralloc buffer.
303 // Otherwise, nullptr; the image will be bound to memory as part of
304 // AcquireNextImage.
Chia-I Wue8e689f2016-04-18 08:21:31 +0800305 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700306 // The fence is only valid when the buffer is dequeued, and should be
307 // -1 any other time. When valid, we own the fd, and must ensure it is
308 // closed: either by closing it explicitly when queueing the buffer,
309 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
310 int dequeue_fence;
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700311 // This fence is a dup of the sync fd returned from the driver via
312 // vkQueueSignalReleaseImageANDROID upon vkQueuePresentKHR. We must
313 // ensure it is closed upon re-presenting or releasing the image.
314 int release_fence;
Jesse Halld7b994a2015-09-07 14:17:37 -0700315 bool dequeued;
Pawin Vongmasa6e1193a2017-03-07 13:08:40 -0800316 } images[android::BufferQueueDefs::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700317
Yiwei Zhang5e862202019-06-21 14:59:16 -0700318 std::vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700319};
320
321VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
322 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
323}
324
325Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800326 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700327}
328
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700329static bool IsFencePending(int fd) {
330 if (fd < 0)
331 return false;
332
333 errno = 0;
334 return sync_wait(fd, 0 /* timeout */) == -1 && errno == ETIME;
335}
336
Jesse Halldc225072016-05-30 22:40:14 -0700337void ReleaseSwapchainImage(VkDevice device,
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000338 bool shared_present,
Jesse Halldc225072016-05-30 22:40:14 -0700339 ANativeWindow* window,
340 int release_fence,
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700341 Swapchain::Image& image,
342 bool defer_if_pending) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700343 ATRACE_CALL();
344
Jesse Halldc225072016-05-30 22:40:14 -0700345 ALOG_ASSERT(release_fence == -1 || image.dequeued,
346 "ReleaseSwapchainImage: can't provide a release fence for "
347 "non-dequeued images");
348
349 if (image.dequeued) {
350 if (release_fence >= 0) {
351 // We get here from vkQueuePresentKHR. The application is
352 // responsible for creating an execution dependency chain from
353 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
354 // (release_fence), so we can drop the dequeue_fence here.
355 if (image.dequeue_fence >= 0)
356 close(image.dequeue_fence);
357 } else {
358 // We get here during swapchain destruction, or various serious
359 // error cases e.g. when we can't create the release_fence during
360 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
361 // have already signalled, since the swapchain images are supposed
362 // to be idle before the swapchain is destroyed. In error cases,
363 // there may be rendering in flight to the image, but since we
364 // weren't able to create a release_fence, waiting for the
365 // dequeue_fence is about the best we can do.
366 release_fence = image.dequeue_fence;
367 }
368 image.dequeue_fence = -1;
369
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000370 // It's invalid to call cancelBuffer on a shared buffer
371 if (window && !shared_present) {
Jesse Halldc225072016-05-30 22:40:14 -0700372 window->cancelBuffer(window, image.buffer.get(), release_fence);
373 } else {
374 if (release_fence >= 0) {
375 sync_wait(release_fence, -1 /* forever */);
376 close(release_fence);
377 }
378 }
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700379 release_fence = -1;
Jesse Halldc225072016-05-30 22:40:14 -0700380 image.dequeued = false;
381 }
382
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700383 if (defer_if_pending && IsFencePending(image.release_fence))
384 return;
385
386 if (image.release_fence >= 0) {
387 close(image.release_fence);
388 image.release_fence = -1;
389 }
390
Jesse Halldc225072016-05-30 22:40:14 -0700391 if (image.image) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700392 ATRACE_BEGIN("DestroyImage");
Jesse Halldc225072016-05-30 22:40:14 -0700393 GetData(device).driver.DestroyImage(device, image.image, nullptr);
Yiwei Zhang533cea92019-06-03 18:43:24 -0700394 ATRACE_END();
Jesse Halldc225072016-05-30 22:40:14 -0700395 image.image = VK_NULL_HANDLE;
396 }
397
398 image.buffer.clear();
399}
400
401void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
402 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
403 return;
Jesse Halldc225072016-05-30 22:40:14 -0700404 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000405 if (!swapchain->images[i].dequeued) {
406 ReleaseSwapchainImage(device, swapchain->shared, nullptr, -1,
407 swapchain->images[i], true);
408 }
Jesse Halldc225072016-05-30 22:40:14 -0700409 }
410 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700411 swapchain->timing.clear();
412}
413
414uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800415 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
416 return 0;
417 }
Ian Elliott8a977262017-01-19 09:05:58 -0700418
Brian Anderson1049d1d2016-12-16 17:25:57 -0800419 uint32_t num_ready = 0;
420 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
421 for (uint32_t i = 0; i < num_timings; i++) {
Yiwei Zhang5e862202019-06-21 14:59:16 -0700422 TimingInfo& ti = swapchain.timing[i];
Brian Anderson1049d1d2016-12-16 17:25:57 -0800423 if (ti.ready()) {
424 // This TimingInfo is ready to be reported to the user. Add it
425 // to the num_ready.
426 num_ready++;
427 continue;
428 }
429 // This TimingInfo is not yet ready to be reported to the user,
430 // and so we should look for any available timestamps that
431 // might make it ready.
432 int64_t desired_present_time = 0;
433 int64_t render_complete_time = 0;
434 int64_t composition_latch_time = 0;
435 int64_t actual_present_time = 0;
436 // Obtain timestamps:
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800437 int err = native_window_get_frame_timestamps(
Brian Anderson1049d1d2016-12-16 17:25:57 -0800438 swapchain.surface.window.get(), ti.native_frame_id_,
439 &desired_present_time, &render_complete_time,
440 &composition_latch_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700441 nullptr, //&first_composition_start_time,
442 nullptr, //&last_composition_start_time,
443 nullptr, //&composition_finish_time,
Brian Anderson1049d1d2016-12-16 17:25:57 -0800444 &actual_present_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700445 nullptr, //&dequeue_ready_time,
446 nullptr /*&reads_done_time*/);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800447
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800448 if (err != android::OK) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800449 continue;
450 }
451
452 // Record the timestamp(s) we received, and then see if this TimingInfo
453 // is ready to be reported to the user:
Brian Andersondc96fdf2017-03-20 16:54:25 -0700454 ti.timestamp_desired_present_time_ = desired_present_time;
455 ti.timestamp_actual_present_time_ = actual_present_time;
456 ti.timestamp_render_complete_time_ = render_complete_time;
457 ti.timestamp_composition_latch_time_ = composition_latch_time;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800458
459 if (ti.ready()) {
460 // The TimingInfo has received enough timestamps, and should now
461 // use those timestamps to calculate the info that should be
462 // reported to the user:
463 ti.calculate(swapchain.refresh_duration);
464 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700465 }
466 }
467 return num_ready;
468}
469
Ian Elliott8a977262017-01-19 09:05:58 -0700470void copy_ready_timings(Swapchain& swapchain,
471 uint32_t* count,
472 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800473 if (swapchain.timing.empty()) {
474 *count = 0;
475 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700476 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800477
478 size_t last_ready = swapchain.timing.size() - 1;
479 while (!swapchain.timing[last_ready].ready()) {
480 if (last_ready == 0) {
481 *count = 0;
482 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700483 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800484 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700485 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800486
487 uint32_t num_copied = 0;
Yiwei Zhang5e862202019-06-21 14:59:16 -0700488 int32_t num_to_remove = 0;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800489 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
490 const TimingInfo& ti = swapchain.timing[i];
491 if (ti.ready()) {
492 ti.get_values(&timings[num_copied]);
493 num_copied++;
494 }
495 num_to_remove++;
496 }
497
498 // Discard old frames that aren't ready if newer frames are ready.
499 // We don't expect to get the timing info for those old frames.
Yiwei Zhang5e862202019-06-21 14:59:16 -0700500 swapchain.timing.erase(swapchain.timing.begin(),
501 swapchain.timing.begin() + num_to_remove);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800502
Ian Elliott8a977262017-01-19 09:05:58 -0700503 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700504}
505
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000506PixelFormat GetNativePixelFormat(VkFormat format) {
507 PixelFormat native_format = PixelFormat::RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700508 switch (format) {
509 case VK_FORMAT_R8G8B8A8_UNORM:
510 case VK_FORMAT_R8G8B8A8_SRGB:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000511 native_format = PixelFormat::RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700512 break;
513 case VK_FORMAT_R5G6B5_UNORM_PACK16:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000514 native_format = PixelFormat::RGB_565;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700515 break;
516 case VK_FORMAT_R16G16B16A16_SFLOAT:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000517 native_format = PixelFormat::RGBA_FP16;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700518 break;
Yiwei Zhangc1ea8152019-02-05 15:11:32 -0800519 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000520 native_format = PixelFormat::RGBA_1010102;
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500521 break;
522 case VK_FORMAT_R8_UNORM:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000523 native_format = PixelFormat::R_8;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700524 break;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000525 case VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000526 native_format = PixelFormat::RGBA_10101010;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000527 break;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700528 default:
529 ALOGV("unsupported swapchain format %d", format);
530 break;
531 }
532 return native_format;
533}
534
Sally Qiaa238972023-07-17 12:52:05 +0800535android_dataspace GetNativeDataspace(VkColorSpaceKHR colorspace,
536 PixelFormat pixelFormat) {
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700537 switch (colorspace) {
538 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
539 return HAL_DATASPACE_V0_SRGB;
540 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
541 return HAL_DATASPACE_DISPLAY_P3;
542 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
543 return HAL_DATASPACE_V0_SCRGB_LINEAR;
Courtney Goeltzenleuchterb52abee2017-08-07 17:13:04 -0600544 case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT:
545 return HAL_DATASPACE_V0_SCRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700546 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
547 return HAL_DATASPACE_DCI_P3_LINEAR;
548 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
549 return HAL_DATASPACE_DCI_P3;
550 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
551 return HAL_DATASPACE_V0_SRGB_LINEAR;
552 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
553 return HAL_DATASPACE_V0_SRGB;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600554 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
Sally Qiaa238972023-07-17 12:52:05 +0800555 if (pixelFormat == PixelFormat::RGBA_FP16) {
556 return static_cast<android_dataspace>(
557 HAL_DATASPACE_STANDARD_BT2020 |
558 HAL_DATASPACE_TRANSFER_LINEAR |
559 HAL_DATASPACE_RANGE_EXTENDED);
560 } else {
561 return HAL_DATASPACE_BT2020_LINEAR;
562 }
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600563 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700564 return static_cast<android_dataspace>(
565 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
566 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600567 case VK_COLOR_SPACE_DOLBYVISION_EXT:
568 return static_cast<android_dataspace>(
569 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
570 HAL_DATASPACE_RANGE_FULL);
571 case VK_COLOR_SPACE_HDR10_HLG_EXT:
Sally Qiaa238972023-07-17 12:52:05 +0800572 return static_cast<android_dataspace>(HAL_DATASPACE_BT2020_HLG);
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700573 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
574 return static_cast<android_dataspace>(
575 HAL_DATASPACE_STANDARD_ADOBE_RGB |
576 HAL_DATASPACE_TRANSFER_LINEAR | HAL_DATASPACE_RANGE_FULL);
577 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
578 return HAL_DATASPACE_ADOBE_RGB;
579
580 // Pass through is intended to allow app to provide data that is passed
581 // to the display system without modification.
582 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
583 return HAL_DATASPACE_ARBITRARY;
584
585 default:
586 // This indicates that we don't know about the
587 // dataspace specified and we should indicate that
588 // it's unsupported
589 return HAL_DATASPACE_UNKNOWN;
590 }
591}
592
Jesse Halld7b994a2015-09-07 14:17:37 -0700593} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700594
Jesse Halle1b12782015-11-30 11:27:32 -0800595VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800596VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800597 VkInstance instance,
598 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
599 const VkAllocationCallbacks* allocator,
600 VkSurfaceKHR* out_surface) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800601 ATRACE_CALL();
602
Jesse Hall1f91d392015-12-11 16:28:44 -0800603 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800604 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800605 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
606 alignof(Surface),
607 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800608 if (!mem)
609 return VK_ERROR_OUT_OF_HOST_MEMORY;
610 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700611
Chia-I Wue8e689f2016-04-18 08:21:31 +0800612 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700613 surface->swapchain_handle = VK_NULL_HANDLE;
Yiwei Zhang3b88f312023-04-18 23:11:35 +0000614 surface->used_by_swapchain = false;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700615 int err = native_window_get_consumer_usage(surface->window.get(),
616 &surface->consumer_usage);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800617 if (err != android::OK) {
Yiwei Zhang6435b322018-05-08 11:12:17 -0700618 ALOGE("native_window_get_consumer_usage() failed: %s (%d)",
619 strerror(-err), err);
620 surface->~Surface();
621 allocator->pfnFree(allocator->pUserData, surface);
Yiwei Zhang70a21962019-05-31 17:26:52 -0700622 return VK_ERROR_SURFACE_LOST_KHR;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700623 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700624
Yiwei Zhang6435b322018-05-08 11:12:17 -0700625 err =
Jesse Hall1356b0d2015-11-23 17:24:58 -0800626 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800627 if (err != android::OK) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800628 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
629 err);
630 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800631 allocator->pfnFree(allocator->pUserData, surface);
Mike Stroyan762c8132017-02-22 11:43:09 -0700632 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800633 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700634
Jesse Hall1356b0d2015-11-23 17:24:58 -0800635 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700636 return VK_SUCCESS;
637}
638
Jesse Halle1b12782015-11-30 11:27:32 -0800639VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800640void DestroySurfaceKHR(VkInstance instance,
641 VkSurfaceKHR surface_handle,
642 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800643 ATRACE_CALL();
644
Jesse Hall1356b0d2015-11-23 17:24:58 -0800645 Surface* surface = SurfaceFromHandle(surface_handle);
646 if (!surface)
647 return;
648 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700649 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700650 "destroyed VkSurfaceKHR 0x%" PRIx64
651 " has active VkSwapchainKHR 0x%" PRIx64,
652 reinterpret_cast<uint64_t>(surface_handle),
653 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800654 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800655 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800656 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800657 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800658}
659
Jesse Halle1b12782015-11-30 11:27:32 -0800660VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800661VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
662 uint32_t /*queue_family*/,
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000663 VkSurfaceKHR /*surface_handle*/,
Chia-I Wu62262232016-03-26 07:06:44 +0800664 VkBool32* supported) {
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000665 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800666 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800667}
668
Jesse Halle1b12782015-11-30 11:27:32 -0800669VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800670VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Ian Elliott1ce053f2022-03-16 09:49:53 -0600671 VkPhysicalDevice pdev,
Jesse Hallb00daad2015-11-29 19:46:20 -0800672 VkSurfaceKHR surface,
673 VkSurfaceCapabilitiesKHR* capabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800674 ATRACE_CALL();
675
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000676 // Implement in terms of GetPhysicalDeviceSurfaceCapabilities2KHR
677
678 VkPhysicalDeviceSurfaceInfo2KHR info2 = {
679 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
680 nullptr,
681 surface
682 };
683
684 VkSurfaceCapabilities2KHR caps2 = {
685 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
686 nullptr,
687 {},
688 };
689
690 VkResult result = GetPhysicalDeviceSurfaceCapabilities2KHR(pdev, &info2, &caps2);
691 *capabilities = caps2.surfaceCapabilities;
692 return result;
693}
694
695// Does the call-twice and VK_INCOMPLETE handling for querying lists
696// of things, where we already have the full set built in a vector.
697template <typename T>
698VkResult CopyWithIncomplete(std::vector<T> const& things,
699 T* callerPtr, uint32_t* callerCount) {
700 VkResult result = VK_SUCCESS;
701 if (callerPtr) {
702 if (things.size() > *callerCount)
703 result = VK_INCOMPLETE;
704 *callerCount = std::min(uint32_t(things.size()), *callerCount);
705 std::copy(things.begin(), things.begin() + *callerCount, callerPtr);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600706 } else {
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000707 *callerCount = things.size();
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800708 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000709 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700710}
711
Jesse Halle1b12782015-11-30 11:27:32 -0800712VKAPI_ATTR
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700713VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
714 VkSurfaceKHR surface_handle,
Chia-I Wu62262232016-03-26 07:06:44 +0800715 uint32_t* count,
716 VkSurfaceFormatKHR* formats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800717 ATRACE_CALL();
718
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700719 const InstanceData& instance_data = GetData(pdev);
720
Ian Elliott1ce053f2022-03-16 09:49:53 -0600721 uint64_t consumer_usage = 0;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000722 bool colorspace_ext =
Ian Elliottf6df08e2022-03-16 21:27:49 -0600723 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600724 if (surface_handle == VK_NULL_HANDLE) {
725 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
726 bool surfaceless_enabled =
727 instance_data.hook_extensions.test(surfaceless);
728 if (!surfaceless_enabled) {
729 return VK_ERROR_SURFACE_LOST_KHR;
730 }
Chris Forbesb1de3b12022-10-20 09:05:48 +1300731 // Support for VK_GOOGLE_surfaceless_query.
Ian Elliott1ce053f2022-03-16 09:49:53 -0600732
733 // TODO(b/203826952): research proper value; temporarily use the
734 // values seen on Pixel
735 consumer_usage = AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
736 } else {
737 Surface& surface = *SurfaceFromHandle(surface_handle);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600738 consumer_usage = surface.consumer_usage;
Ian Elliott6ba85d92022-02-18 16:44:58 -0700739 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700740
Charlie Lao324191f2019-12-13 11:03:16 -0800741 AHardwareBuffer_Desc desc = {};
742 desc.width = 1;
743 desc.height = 1;
744 desc.layers = 1;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600745 desc.usage = consumer_usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
Charlie Lao324191f2019-12-13 11:03:16 -0800746 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
747
748 // We must support R8G8B8A8
749 std::vector<VkSurfaceFormatKHR> all_formats = {
750 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000751 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000752 };
Charlie Lao324191f2019-12-13 11:03:16 -0800753
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000754 if (colorspace_ext) {
755 all_formats.emplace_back(VkSurfaceFormatKHR{
Jason Macnakca506332022-11-09 11:00:36 -0800756 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
757 all_formats.emplace_back(VkSurfaceFormatKHR{
758 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_PASS_THROUGH_EXT});
759 all_formats.emplace_back(VkSurfaceFormatKHR{
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000760 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_BT709_LINEAR_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800761 all_formats.emplace_back(VkSurfaceFormatKHR{
762 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
763 all_formats.emplace_back(VkSurfaceFormatKHR{
764 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
765 }
766
Ian Elliott1ce053f2022-03-16 09:49:53 -0600767 // NOTE: Any new formats that are added must be coordinated across different
768 // Android users. This includes the ANGLE team (a layered implementation of
769 // OpenGL-ES).
770
Charlie Lao324191f2019-12-13 11:03:16 -0800771 desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
772 if (AHardwareBuffer_isSupported(&desc)) {
773 all_formats.emplace_back(VkSurfaceFormatKHR{
774 VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800775 if (colorspace_ext) {
776 all_formats.emplace_back(
777 VkSurfaceFormatKHR{VK_FORMAT_R5G6B5_UNORM_PACK16,
778 VK_COLOR_SPACE_PASS_THROUGH_EXT});
779 }
Charlie Lao324191f2019-12-13 11:03:16 -0800780 }
781
782 desc.format = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
783 if (AHardwareBuffer_isSupported(&desc)) {
784 all_formats.emplace_back(VkSurfaceFormatKHR{
785 VK_FORMAT_R16G16B16A16_SFLOAT, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800786 if (colorspace_ext) {
787 all_formats.emplace_back(
788 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
789 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800790 all_formats.emplace_back(
791 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
792 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT});
793 all_formats.emplace_back(
794 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
795 VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT});
796 }
797 }
798
799 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
800 if (AHardwareBuffer_isSupported(&desc)) {
801 all_formats.emplace_back(
802 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
803 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800804 if (colorspace_ext) {
805 all_formats.emplace_back(
806 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
807 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800808 all_formats.emplace_back(
809 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
810 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
811 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700812 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700813
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500814 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
815 if (AHardwareBuffer_isSupported(&desc)) {
Jason Macnakca506332022-11-09 11:00:36 -0800816 if (colorspace_ext) {
817 all_formats.emplace_back(VkSurfaceFormatKHR{
818 VK_FORMAT_R8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
819 }
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500820 }
821
Trevor David Black67e9b102023-03-07 05:28:15 +0000822 bool rgba10x6_formats_ext = false;
823 uint32_t exts_count;
824 const auto& driver = GetData(pdev).driver;
825 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
826 nullptr);
827 std::vector<VkExtensionProperties> props(exts_count);
828 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
829 props.data());
830 for (uint32_t i = 0; i < exts_count; i++) {
831 VkExtensionProperties prop = props[i];
832 if (strcmp(prop.extensionName,
833 VK_EXT_RGBA10X6_FORMATS_EXTENSION_NAME) == 0) {
834 rgba10x6_formats_ext = true;
835 }
836 }
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000837 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM;
Trevor David Black67e9b102023-03-07 05:28:15 +0000838 if (AHardwareBuffer_isSupported(&desc) && rgba10x6_formats_ext) {
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000839 all_formats.emplace_back(
840 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
841 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
842 if (colorspace_ext) {
843 all_formats.emplace_back(
844 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
845 VK_COLOR_SPACE_PASS_THROUGH_EXT});
846 all_formats.emplace_back(
847 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
848 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
849 }
850 }
851
Ian Elliott6ba85d92022-02-18 16:44:58 -0700852 // NOTE: Any new formats that are added must be coordinated across different
853 // Android users. This includes the ANGLE team (a layered implementation of
854 // OpenGL-ES).
855
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000856 return CopyWithIncomplete(all_formats, formats, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700857}
858
Jesse Halle1b12782015-11-30 11:27:32 -0800859VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300860VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
861 VkPhysicalDevice physicalDevice,
862 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
863 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800864 ATRACE_CALL();
865
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000866 auto surface = pSurfaceInfo->surface;
867 auto capabilities = &pSurfaceCapabilities->surfaceCapabilities;
Chris Forbes2452cf72017-03-16 16:30:17 +1300868
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000869 VkSurfacePresentModeEXT const *pPresentMode = nullptr;
870 for (auto pNext = reinterpret_cast<VkBaseInStructure const *>(pSurfaceInfo->pNext);
871 pNext; pNext = reinterpret_cast<VkBaseInStructure const *>(pNext->pNext)) {
872 switch (pNext->sType) {
873 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT:
874 pPresentMode = reinterpret_cast<VkSurfacePresentModeEXT const *>(pNext);
875 break;
Chris Forbes06bc0092017-03-16 16:46:05 +1300876
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000877 default:
878 break;
879 }
880 }
881
882 int err;
883 int width, height;
884 int transform_hint;
885 int max_buffer_count;
Trevor David Black1d3509e2023-06-08 00:17:40 +0000886 int min_undequeued_buffers;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000887 if (surface == VK_NULL_HANDLE) {
888 const InstanceData& instance_data = GetData(physicalDevice);
889 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
890 bool surfaceless_enabled =
891 instance_data.hook_extensions.test(surfaceless);
892 if (!surfaceless_enabled) {
893 // It is an error to pass a surface==VK_NULL_HANDLE unless the
894 // VK_GOOGLE_surfaceless_query extension is enabled
895 return VK_ERROR_SURFACE_LOST_KHR;
896 }
897 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
898 // extension for this function is for
899 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
900 // four values cannot be known without a surface. Default values will
901 // be supplied anyway, but cannot be relied upon.
902 width = 0xFFFFFFFF;
903 height = 0xFFFFFFFF;
904 transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
905 capabilities->minImageCount = 0xFFFFFFFF;
906 capabilities->maxImageCount = 0xFFFFFFFF;
907 } else {
908 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
909
910 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
911 if (err != android::OK) {
912 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
913 strerror(-err), err);
914 return VK_ERROR_SURFACE_LOST_KHR;
915 }
916 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
917 if (err != android::OK) {
918 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
919 strerror(-err), err);
920 return VK_ERROR_SURFACE_LOST_KHR;
921 }
922
923 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
924 &transform_hint);
925 if (err != android::OK) {
926 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
927 strerror(-err), err);
928 return VK_ERROR_SURFACE_LOST_KHR;
929 }
930
931 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
932 &max_buffer_count);
933 if (err != android::OK) {
934 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
935 strerror(-err), err);
936 return VK_ERROR_SURFACE_LOST_KHR;
937 }
938
Trevor David Black1d3509e2023-06-08 00:17:40 +0000939 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
940 &min_undequeued_buffers);
941 if (err != android::OK) {
942 ALOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d)",
943 strerror(-err), err);
944 return VK_ERROR_SURFACE_LOST_KHR;
945 }
946
Trevor David Blacka93e21f2023-08-30 23:42:20 +0000947 if(pPresentMode != nullptr) {
948 switch (pPresentMode->presentMode) {
949 case VK_PRESENT_MODE_IMMEDIATE_KHR:
950 ALOGE("Swapchain present mode VK_PRESENT_MODE_IMMEDIATE_KHR is not supported");
951 break;
952 case VK_PRESENT_MODE_MAILBOX_KHR:
953 case VK_PRESENT_MODE_FIFO_KHR:
954 capabilities->minImageCount =
955 std::min(max_buffer_count, min_undequeued_buffers + 2);
956 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
957 break;
958 case VK_PRESENT_MODE_FIFO_RELAXED_KHR:
959 ALOGE("Swapchain present mode VK_PRESENT_MODE_FIFO_RELEAXED_KHR "
960 "is not supported");
961 break;
962 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
963 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
964 capabilities->minImageCount = 1;
965 capabilities->maxImageCount = 1;
966 break;
967
968 default:
969 ALOGE("Unrecognized swapchain present mode %u is not supported",
970 pPresentMode->presentMode);
971 break;
972 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000973 } else {
Trevor David Blacka93e21f2023-08-30 23:42:20 +0000974 capabilities->minImageCount = std::min(max_buffer_count, min_undequeued_buffers + 2);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000975 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
976 }
977 }
978
979 capabilities->currentExtent =
980 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
981
982 // TODO(http://b/134182502): Figure out what the max extent should be.
983 capabilities->minImageExtent = VkExtent2D{1, 1};
984 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
985
986 if (capabilities->maxImageExtent.height <
987 capabilities->currentExtent.height) {
988 capabilities->maxImageExtent.height =
989 capabilities->currentExtent.height;
990 }
991
992 if (capabilities->maxImageExtent.width <
993 capabilities->currentExtent.width) {
994 capabilities->maxImageExtent.width = capabilities->currentExtent.width;
995 }
996
997 capabilities->maxImageArrayLayers = 1;
998
999 capabilities->supportedTransforms = kSupportedTransforms;
1000 capabilities->currentTransform =
1001 TranslateNativeToVulkanTransform(transform_hint);
1002
1003 // On Android, window composition is a WindowManager property, not something
1004 // associated with the bufferqueue. It can't be changed from here.
1005 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
1006
1007 capabilities->supportedUsageFlags =
1008 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
1009 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
1010 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
1011 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
1012
1013 for (auto pNext = reinterpret_cast<VkBaseOutStructure*>(pSurfaceCapabilities->pNext);
1014 pNext; pNext = reinterpret_cast<VkBaseOutStructure*>(pNext->pNext)) {
1015
1016 switch (pNext->sType) {
Chris Forbes06bc0092017-03-16 16:46:05 +13001017 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
1018 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001019 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(pNext);
Chris Forbes06bc0092017-03-16 16:46:05 +13001020 // Claim same set of usage flags are supported for
1021 // shared present modes as for other modes.
1022 shared_caps->sharedPresentSupportedUsageFlags =
1023 pSurfaceCapabilities->surfaceCapabilities
1024 .supportedUsageFlags;
1025 } break;
1026
Ian Elliottbb67b242022-03-16 09:52:28 -06001027 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
1028 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001029 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(pNext);
Ian Elliottbb67b242022-03-16 09:52:28 -06001030 protected_caps->supportsProtected = VK_TRUE;
1031 } break;
1032
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001033 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_SCALING_CAPABILITIES_EXT: {
1034 VkSurfacePresentScalingCapabilitiesEXT* scaling_caps =
1035 reinterpret_cast<VkSurfacePresentScalingCapabilitiesEXT*>(pNext);
1036 // By default, Android stretches the buffer to fit the window,
1037 // without preserving aspect ratio. Other modes are technically possible
1038 // but consult with CoGS team before exposing them here!
1039 scaling_caps->supportedPresentScaling = VK_PRESENT_SCALING_STRETCH_BIT_EXT;
1040
1041 // Since we always scale, we don't support any gravity.
1042 scaling_caps->supportedPresentGravityX = 0;
1043 scaling_caps->supportedPresentGravityY = 0;
1044
1045 // Scaled image limits are just the basic image limits
1046 scaling_caps->minScaledImageExtent = capabilities->minImageExtent;
1047 scaling_caps->maxScaledImageExtent = capabilities->maxImageExtent;
1048 } break;
1049
1050 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT: {
1051 VkSurfacePresentModeCompatibilityEXT* mode_caps =
1052 reinterpret_cast<VkSurfacePresentModeCompatibilityEXT*>(pNext);
1053
1054 ALOG_ASSERT(pPresentMode,
1055 "querying VkSurfacePresentModeCompatibilityEXT "
1056 "requires VkSurfacePresentModeEXT to be provided");
1057 std::vector<VkPresentModeKHR> compatibleModes;
1058 compatibleModes.push_back(pPresentMode->presentMode);
1059
1060 switch (pPresentMode->presentMode) {
1061 // Shared modes are both compatible with each other.
1062 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
1063 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
1064 break;
1065 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
1066 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1067 break;
1068 default:
1069 // Other modes are only compatible with themselves.
1070 // TODO: consider whether switching between FIFO and MAILBOX is reasonable
1071 break;
1072 }
1073
1074 // Note: this does not generate VK_INCOMPLETE since we're nested inside
1075 // a larger query and there would be no way to determine exactly where it came from.
1076 CopyWithIncomplete(compatibleModes, mode_caps->pPresentModes,
1077 &mode_caps->presentModeCount);
1078 } break;
1079
Chris Forbes06bc0092017-03-16 16:46:05 +13001080 default:
1081 // Ignore all other extension structs
1082 break;
1083 }
1084 }
1085
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001086 return VK_SUCCESS;
Chris Forbes2452cf72017-03-16 16:30:17 +13001087}
1088
1089VKAPI_ATTR
1090VkResult GetPhysicalDeviceSurfaceFormats2KHR(
1091 VkPhysicalDevice physicalDevice,
1092 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
1093 uint32_t* pSurfaceFormatCount,
1094 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001095 ATRACE_CALL();
1096
Chris Forbes2452cf72017-03-16 16:30:17 +13001097 if (!pSurfaceFormats) {
1098 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
1099 pSurfaceInfo->surface,
1100 pSurfaceFormatCount, nullptr);
Trevor David Black929e9cd2022-11-22 04:12:19 +00001101 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001102
Trevor David Black929e9cd2022-11-22 04:12:19 +00001103 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
1104 // after the call.
1105 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
1106 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
1107 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
1108 surface_formats.data());
Trevor David Black2cc44682022-03-09 00:31:38 +00001109
Trevor David Black929e9cd2022-11-22 04:12:19 +00001110 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
1111 return result;
1112 }
Trevor David Black2cc44682022-03-09 00:31:38 +00001113
Trevor David Black929e9cd2022-11-22 04:12:19 +00001114 const auto& driver = GetData(physicalDevice).driver;
1115
1116 // marshal results individually due to stride difference.
1117 uint32_t formats_to_marshal = *pSurfaceFormatCount;
1118 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
1119 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
1120
1121 // Query the compression properties for the surface format
1122 VkSurfaceFormat2KHR* pSurfaceFormat = &pSurfaceFormats[i];
1123 while (pSurfaceFormat->pNext) {
1124 pSurfaceFormat =
1125 reinterpret_cast<VkSurfaceFormat2KHR*>(pSurfaceFormat->pNext);
1126 switch (pSurfaceFormat->sType) {
1127 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT: {
Trevor David Black2cc44682022-03-09 00:31:38 +00001128 VkImageCompressionPropertiesEXT* surfaceCompressionProps =
1129 reinterpret_cast<VkImageCompressionPropertiesEXT*>(
Trevor David Black929e9cd2022-11-22 04:12:19 +00001130 pSurfaceFormat);
Trevor David Black2cc44682022-03-09 00:31:38 +00001131
1132 if (surfaceCompressionProps &&
1133 driver.GetPhysicalDeviceImageFormatProperties2KHR) {
1134 VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = {};
1135 imageFormatInfo.sType =
1136 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
1137 imageFormatInfo.format =
1138 pSurfaceFormats[i].surfaceFormat.format;
Trevor David Blacka4298c92023-06-20 17:11:58 +00001139 imageFormatInfo.type = VK_IMAGE_TYPE_2D;
1140 imageFormatInfo.usage =
1141 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
Trevor David Black2cc44682022-03-09 00:31:38 +00001142 imageFormatInfo.pNext = nullptr;
1143
1144 VkImageCompressionControlEXT compressionControl = {};
1145 compressionControl.sType =
1146 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT;
1147 compressionControl.pNext = imageFormatInfo.pNext;
Trevor David Blacka4298c92023-06-20 17:11:58 +00001148 compressionControl.flags =
1149 VK_IMAGE_COMPRESSION_FIXED_RATE_DEFAULT_EXT;
Trevor David Black2cc44682022-03-09 00:31:38 +00001150
1151 imageFormatInfo.pNext = &compressionControl;
1152
1153 VkImageCompressionPropertiesEXT compressionProps = {};
1154 compressionProps.sType =
1155 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT;
1156 compressionProps.pNext = nullptr;
1157
1158 VkImageFormatProperties2KHR imageFormatProps = {};
1159 imageFormatProps.sType =
1160 VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
1161 imageFormatProps.pNext = &compressionProps;
1162
1163 VkResult compressionRes =
1164 driver.GetPhysicalDeviceImageFormatProperties2KHR(
1165 physicalDevice, &imageFormatInfo,
1166 &imageFormatProps);
1167 if (compressionRes == VK_SUCCESS) {
1168 surfaceCompressionProps->imageCompressionFlags =
1169 compressionProps.imageCompressionFlags;
1170 surfaceCompressionProps
1171 ->imageCompressionFixedRateFlags =
1172 compressionProps.imageCompressionFixedRateFlags;
1173 } else {
1174 return compressionRes;
1175 }
1176 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001177 } break;
1178
1179 default:
1180 // Ignore all other extension structs
1181 break;
Chris Forbes2452cf72017-03-16 16:30:17 +13001182 }
1183 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001184 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001185
1186 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +13001187}
1188
1189VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +13001190VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001191 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +08001192 uint32_t* count,
1193 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001194 ATRACE_CALL();
1195
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001196 int err;
1197 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -06001198 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -06001199 if (surface == VK_NULL_HANDLE) {
1200 const InstanceData& instance_data = GetData(pdev);
1201 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
1202 bool surfaceless_enabled =
1203 instance_data.hook_extensions.test(surfaceless);
1204 if (!surfaceless_enabled) {
1205 return VK_ERROR_SURFACE_LOST_KHR;
1206 }
1207 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
1208 // extension for this function is for
1209 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
1210 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
1211 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
Ian Elliott7e361142022-06-02 10:45:17 -06001212 // surface, and that cannot be relied upon. Therefore, don't return it.
Ian Elliott1ce053f2022-03-16 09:49:53 -06001213 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1214 } else {
1215 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1216
1217 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1218 &query_value);
1219 if (err != android::OK || query_value < 0) {
1220 ALOGE(
1221 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
1222 "value=%d",
1223 strerror(-err), err, query_value);
1224 return VK_ERROR_SURFACE_LOST_KHR;
1225 }
1226 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1227
1228 err =
1229 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
1230 if (err != android::OK || query_value < 0) {
1231 ALOGE(
1232 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
1233 strerror(-err), err, query_value);
1234 return VK_ERROR_SURFACE_LOST_KHR;
1235 }
1236 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
1237
1238 if (min_undequeued_buffers + 1 < max_buffer_count)
1239 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
1240 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1241 }
Chris Forbese8d79a62017-02-22 12:49:18 +13001242
1243 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -07001244 QueryPresentationProperties(pdev, &present_properties);
1245 if (present_properties.sharedImage) {
1246 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1247 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +13001248 }
1249
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001250 return CopyWithIncomplete(present_modes, modes, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001251}
1252
Jesse Halle1b12782015-11-30 11:27:32 -08001253VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001254VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001255 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001256 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001257 ATRACE_CALL();
1258
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001259 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
1260 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1261 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1262 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1263 pDeviceGroupPresentCapabilities->sType);
1264
1265 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1266 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1267
1268 // assume device group of size 1
1269 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1270 pDeviceGroupPresentCapabilities->modes =
1271 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1272
1273 return VK_SUCCESS;
1274}
1275
1276VKAPI_ATTR
1277VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001278 VkDevice,
1279 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001280 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001281 ATRACE_CALL();
1282
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001283 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1284 return VK_SUCCESS;
1285}
1286
1287VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001288VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001289 VkSurfaceKHR surface,
1290 uint32_t* pRectCount,
1291 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001292 ATRACE_CALL();
1293
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001294 if (!pRects) {
1295 *pRectCount = 1;
1296 } else {
1297 uint32_t count = std::min(*pRectCount, 1u);
1298 bool incomplete = *pRectCount < 1;
1299
1300 *pRectCount = count;
1301
1302 if (incomplete) {
1303 return VK_INCOMPLETE;
1304 }
1305
1306 int err;
1307 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1308
1309 int width = 0, height = 0;
1310 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001311 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001312 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1313 strerror(-err), err);
1314 }
1315 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001316 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001317 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1318 strerror(-err), err);
1319 }
1320
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001321 pRects[0].offset.x = 0;
1322 pRects[0].offset.y = 0;
1323 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1324 static_cast<uint32_t>(height)};
1325 }
1326 return VK_SUCCESS;
1327}
1328
Yiwei Zhang533cea92019-06-03 18:43:24 -07001329static void DestroySwapchainInternal(VkDevice device,
1330 VkSwapchainKHR swapchain_handle,
1331 const VkAllocationCallbacks* allocator) {
1332 ATRACE_CALL();
1333
1334 const auto& dispatch = GetData(device).driver;
1335 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1336 if (!swapchain) {
1337 return;
1338 }
1339
1340 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1341 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1342
1343 if (window && swapchain->frame_timestamps_enabled) {
1344 native_window_enable_frame_timestamps(window, false);
1345 }
1346
1347 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +00001348 ReleaseSwapchainImage(device, swapchain->shared, window, -1,
1349 swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001350 }
1351
1352 if (active) {
1353 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1354 }
1355
1356 if (!allocator) {
1357 allocator = &GetData(device).allocator;
1358 }
1359
1360 swapchain->~Swapchain();
1361 allocator->pfnFree(allocator->pUserData, swapchain);
1362}
1363
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001364VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001365VkResult CreateSwapchainKHR(VkDevice device,
1366 const VkSwapchainCreateInfoKHR* create_info,
1367 const VkAllocationCallbacks* allocator,
1368 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001369 ATRACE_CALL();
1370
Jesse Halld7b994a2015-09-07 14:17:37 -07001371 int err;
1372 VkResult result = VK_SUCCESS;
1373
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001374 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1375 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1376 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1377 " oldSwapchain=0x%" PRIx64,
1378 reinterpret_cast<uint64_t>(create_info->surface),
1379 create_info->minImageCount, create_info->imageFormat,
1380 create_info->imageColorSpace, create_info->imageExtent.width,
1381 create_info->imageExtent.height, create_info->imageUsage,
1382 create_info->preTransform, create_info->presentMode,
1383 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1384
Jesse Hall1f91d392015-12-11 16:28:44 -08001385 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001386 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001387
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001388 PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001389 GetNativePixelFormat(create_info->imageFormat);
1390 android_dataspace native_dataspace =
Sally Qiaa238972023-07-17 12:52:05 +08001391 GetNativeDataspace(create_info->imageColorSpace, native_pixel_format);
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001392 if (native_dataspace == HAL_DATASPACE_UNKNOWN) {
1393 ALOGE(
1394 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1395 "failed: Unsupported color space",
1396 create_info->imageColorSpace);
1397 return VK_ERROR_INITIALIZATION_FAILED;
1398 }
1399
Jesse Hall42a9eec2016-06-03 12:39:49 -07001400 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001401 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001402 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001403 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001404 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001405 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001406 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001407 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001408 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1409 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001410 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001411 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001412
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001413 Surface& surface = *SurfaceFromHandle(create_info->surface);
1414
Jesse Halldc225072016-05-30 22:40:14 -07001415 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001416 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001417 " because it already has active swapchain 0x%" PRIx64
1418 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1419 reinterpret_cast<uint64_t>(create_info->surface),
1420 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1421 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1422 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1423 }
1424 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1425 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1426
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001427 // -- Reset the native window --
1428 // The native window might have been used previously, and had its properties
1429 // changed from defaults. That will affect the answer we get for queries
1430 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1431 // attempt such queries.
1432
Jesse Halldc225072016-05-30 22:40:14 -07001433 // The native window only allows dequeueing all buffers before any have
1434 // been queued, since after that point at least one is assumed to be in
1435 // non-FREE state at any given time. Disconnecting and re-connecting
1436 // orphans the previous buffers, getting us back to the state where we can
1437 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001438 //
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001439 // This is not necessary if the surface was never used previously.
1440 //
Yiwei Zhang70a21962019-05-31 17:26:52 -07001441 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001442 ANativeWindow* window = surface.window.get();
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001443 if (surface.used_by_swapchain) {
1444 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1445 ALOGW_IF(err != android::OK,
1446 "native_window_api_disconnect failed: %s (%d)", strerror(-err),
1447 err);
1448 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1449 ALOGW_IF(err != android::OK,
1450 "native_window_api_connect failed: %s (%d)", strerror(-err),
1451 err);
1452 }
Jesse Halldc225072016-05-30 22:40:14 -07001453
Nicolas Capens147b7da2021-04-09 14:53:06 -04001454 err =
1455 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001456 if (err != android::OK) {
1457 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1458 strerror(-err), err);
1459 return VK_ERROR_SURFACE_LOST_KHR;
1460 }
1461
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301462 int swap_interval =
1463 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001464 err = window->setSwapInterval(window, swap_interval);
1465 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001466 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1467 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001468 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001469 }
1470
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001471 err = native_window_set_shared_buffer_mode(window, false);
1472 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001473 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1474 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001475 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001476 }
1477
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001478 err = native_window_set_auto_refresh(window, false);
1479 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001480 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1481 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001482 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001483 }
1484
Jesse Halld7b994a2015-09-07 14:17:37 -07001485 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001486
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001487 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001488
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001489 err = native_window_set_buffers_format(
1490 window, static_cast<int>(native_pixel_format));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001491 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001492 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001493 toString(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001494 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001495 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001496
1497 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
1498 if (native_dataspace != HAL_DATASPACE_ARBITRARY) {
1499 err = native_window_set_buffers_data_space(window, native_dataspace);
1500 if (err != android::OK) {
1501 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1502 native_dataspace, strerror(-err), err);
1503 return VK_ERROR_SURFACE_LOST_KHR;
1504 }
Jesse Hall517274a2016-02-10 00:07:18 -08001505 }
1506
Jesse Hall3dd678a2016-01-08 21:52:01 -08001507 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001508 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001509 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001510 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001511 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1512 create_info->imageExtent.width, create_info->imageExtent.height,
1513 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001514 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001515 }
1516
Jesse Hall178b6962016-02-24 15:39:50 -08001517 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1518 // applied during rendering. native_window_set_transform() expects the
1519 // inverse: the transform the app is requesting that the compositor perform
1520 // during composition. With native windows, pre-transform works by rendering
1521 // with the same transform the compositor is applying (as in Vulkan), but
1522 // then requesting the inverse transform, so that when the compositor does
1523 // it's job the two transforms cancel each other out and the compositor ends
1524 // up applying an identity transform to the app's buffer.
1525 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001526 window, InvertTransformToNative(create_info->preTransform));
1527 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001528 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1529 InvertTransformToNative(create_info->preTransform),
1530 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001531 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001532 }
1533
Jesse Hallf64ca122015-11-03 16:11:10 -08001534 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001535 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1536 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001537 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1538 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001539 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001540 }
1541
Chris Forbes97ef4612017-03-30 19:37:50 +13001542 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001543 if (IsSharedPresentMode(create_info->presentMode)) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001544 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001545 err = native_window_set_shared_buffer_mode(window, true);
1546 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001547 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1548 return VK_ERROR_SURFACE_LOST_KHR;
1549 }
1550 }
1551
1552 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001553 err = native_window_set_auto_refresh(window, true);
1554 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001555 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1556 return VK_ERROR_SURFACE_LOST_KHR;
1557 }
1558 }
1559
Ian Elliott16c443c2021-11-30 17:10:32 -07001560 int query_value;
1561 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1562 &query_value);
1563 if (err != android::OK || query_value < 0) {
1564 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1565 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001566 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001567 }
Ian Elliott16c443c2021-11-30 17:10:32 -07001568 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1569 const auto mailbox_num_images = std::max(3u, create_info->minImageCount);
1570 const auto requested_images =
1571 swap_interval ? create_info->minImageCount : mailbox_num_images;
1572 uint32_t num_images = requested_images - 1 + min_undequeued_buffers;
Chris Forbes2c8fc752017-03-17 11:28:32 +13001573
Ian Elliott5396b702021-12-13 19:32:34 -07001574 // Lower layer insists that we have at least min_undequeued_buffers + 1
1575 // buffers. This is wasteful and we'd like to relax it in the shared case,
1576 // but not all the pieces are in place for that to work yet. Note we only
1577 // lie to the lower layer--we don't want to give the app back a swapchain
1578 // with extra images (which they can't actually use!).
1579 uint32_t min_buffer_count = min_undequeued_buffers + 1;
1580 err = native_window_set_buffer_count(
1581 window, std::max(min_buffer_count, num_images));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001582 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001583 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", num_images,
1584 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001585 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001586 }
1587
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001588 // In shared mode the num_images must be one regardless of how many
1589 // buffers were allocated for the buffer queue.
1590 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1591 num_images = 1;
1592 }
1593
Trevor David Black2cc44682022-03-09 00:31:38 +00001594 void* usage_info_pNext = nullptr;
1595 VkImageCompressionControlEXT image_compression = {};
John Reck97678d42022-08-23 11:24:51 -04001596 uint64_t native_usage = 0;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001597 if (dispatch.GetSwapchainGrallocUsage4ANDROID) {
1598 ATRACE_BEGIN("GetSwapchainGrallocUsage4ANDROID");
1599 VkGrallocUsageInfo2ANDROID gralloc_usage_info = {};
1600 gralloc_usage_info.sType =
1601 VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_2_ANDROID;
1602 gralloc_usage_info.format = create_info->imageFormat;
1603 gralloc_usage_info.imageUsage = create_info->imageUsage;
1604 gralloc_usage_info.swapchainImageUsage = swapchain_image_usage;
1605
1606 // Look through the pNext chain for an image compression control struct
1607 // if one is found AND the appropriate extensions are enabled,
1608 // append it to be the gralloc usage pNext chain
1609 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1610 while (create_infos->pNext) {
1611 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1612 create_infos->pNext);
1613 switch (create_infos->sType) {
1614 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1615 const VkImageCompressionControlEXT* compression_infos =
1616 reinterpret_cast<const VkImageCompressionControlEXT*>(
1617 create_infos);
1618 image_compression = *compression_infos;
1619 image_compression.pNext = nullptr;
1620 usage_info_pNext = &image_compression;
1621 } break;
1622
1623 default:
1624 // Ignore all other info structs
1625 break;
1626 }
1627 }
1628 gralloc_usage_info.pNext = usage_info_pNext;
1629
1630 result = dispatch.GetSwapchainGrallocUsage4ANDROID(
1631 device, &gralloc_usage_info, &native_usage);
1632 ATRACE_END();
1633 if (result != VK_SUCCESS) {
1634 ALOGE("vkGetSwapchainGrallocUsage4ANDROID failed: %d", result);
1635 return VK_ERROR_SURFACE_LOST_KHR;
1636 }
1637 } else if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
Trevor David Black2cc44682022-03-09 00:31:38 +00001638 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1639 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1640 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1641 gralloc_usage_info.format = create_info->imageFormat;
1642 gralloc_usage_info.imageUsage = create_info->imageUsage;
1643
1644 // Look through the pNext chain for an image compression control struct
1645 // if one is found AND the appropriate extensions are enabled,
1646 // append it to be the gralloc usage pNext chain
1647 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1648 while (create_infos->pNext) {
1649 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1650 create_infos->pNext);
1651 switch (create_infos->sType) {
1652 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1653 const VkImageCompressionControlEXT* compression_infos =
1654 reinterpret_cast<const VkImageCompressionControlEXT*>(
1655 create_infos);
1656 image_compression = *compression_infos;
1657 image_compression.pNext = nullptr;
1658 usage_info_pNext = &image_compression;
1659 } break;
1660
1661 default:
1662 // Ignore all other info structs
1663 break;
1664 }
1665 }
1666 gralloc_usage_info.pNext = usage_info_pNext;
1667
1668 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1669 device, &gralloc_usage_info, &native_usage);
1670 ATRACE_END();
1671 if (result != VK_SUCCESS) {
1672 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
1673 return VK_ERROR_SURFACE_LOST_KHR;
1674 }
1675 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
Jesse Halld1abd742017-02-09 21:45:51 -08001676 uint64_t consumer_usage, producer_usage;
Yiwei Zhang533cea92019-06-03 18:43:24 -07001677 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
Courtney Goeltzenleuchter894780b2017-04-03 16:11:30 -06001678 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1679 device, create_info->imageFormat, create_info->imageUsage,
1680 swapchain_image_usage, &consumer_usage, &producer_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001681 ATRACE_END();
Chris Forbes8c47dc92017-01-12 11:13:58 +13001682 if (result != VK_SUCCESS) {
1683 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001684 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbes8c47dc92017-01-12 11:13:58 +13001685 }
John Reck97678d42022-08-23 11:24:51 -04001686 native_usage =
Trevor David Black2cc44682022-03-09 00:31:38 +00001687 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
Chris Forbes8c47dc92017-01-12 11:13:58 +13001688 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001689 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
John Reck97678d42022-08-23 11:24:51 -04001690 int32_t legacy_usage = 0;
Jesse Hall1f91d392015-12-11 16:28:44 -08001691 result = dispatch.GetSwapchainGrallocUsageANDROID(
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001692 device, create_info->imageFormat, create_info->imageUsage,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001693 &legacy_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001694 ATRACE_END();
Jesse Hall70f93352015-11-04 09:41:31 -08001695 if (result != VK_SUCCESS) {
1696 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001697 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001698 }
John Reck97678d42022-08-23 11:24:51 -04001699 native_usage = static_cast<uint64_t>(legacy_usage);
Jesse Hall70f93352015-11-04 09:41:31 -08001700 }
John Reck97678d42022-08-23 11:24:51 -04001701 native_usage |= surface.consumer_usage;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001702
1703 bool createProtectedSwapchain = false;
1704 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
1705 createProtectedSwapchain = true;
1706 native_usage |= BufferUsage::PROTECTED;
1707 }
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001708 err = native_window_set_usage(window, native_usage);
1709 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001710 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001711 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001712 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001713
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001714 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001715 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1716 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001717 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1718 strerror(-err), err);
1719 return VK_ERROR_SURFACE_LOST_KHR;
1720 }
1721
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001722 int64_t refresh_duration;
1723 err = native_window_get_refresh_cycle_duration(window, &refresh_duration);
1724 if (err != android::OK) {
1725 ALOGE("native_window_get_refresh_cycle_duration query failed: %s (%d)",
1726 strerror(-err), err);
1727 return VK_ERROR_SURFACE_LOST_KHR;
1728 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001729 // -- Allocate our Swapchain object --
1730 // After this point, we must deallocate the swapchain on error.
1731
Jesse Hall1f91d392015-12-11 16:28:44 -08001732 void* mem = allocator->pfnAllocation(allocator->pUserData,
1733 sizeof(Swapchain), alignof(Swapchain),
1734 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001735 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001736 return VK_ERROR_OUT_OF_HOST_MEMORY;
silence_dogood73597592019-05-23 16:57:37 -07001737 Swapchain* swapchain = new (mem)
1738 Swapchain(surface, num_images, create_info->presentMode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001739 TranslateVulkanToNativeTransform(create_info->preTransform),
1740 refresh_duration);
Chris Forbesb56287a2017-01-12 14:28:58 +13001741 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1742#pragma clang diagnostic push
1743#pragma clang diagnostic ignored "-Wold-style-cast"
1744 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1745#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00001746 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13001747 .usage = swapchain_image_usage,
1748 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001749 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001750#pragma clang diagnostic push
1751#pragma clang diagnostic ignored "-Wold-style-cast"
1752 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1753#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001754 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001755 };
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001756
Jesse Halld7b994a2015-09-07 14:17:37 -07001757 VkImageCreateInfo image_create = {
1758 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001759 .pNext = nullptr,
Nick Desaulnierse745a3e2019-10-18 10:38:45 -07001760 .flags = createProtectedSwapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07001761 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08001762 .format = create_info->imageFormat,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001763 .extent = {
1764 create_info->imageExtent.width,
1765 create_info->imageExtent.height,
1766 1
1767 },
Jesse Halld7b994a2015-09-07 14:17:37 -07001768 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08001769 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08001770 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07001771 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001772 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001773 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08001774 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07001775 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1776 };
1777
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001778 // Note: don't do deferred allocation for shared present modes. There's only one buffer
1779 // involved so very little benefit.
1780 if ((create_info->flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT) &&
1781 !IsSharedPresentMode(create_info->presentMode)) {
1782 // Don't want to touch the underlying gralloc buffers yet;
1783 // instead just create unbound VkImages which will later be bound to memory inside
1784 // AcquireNextImage.
1785 VkImageSwapchainCreateInfoKHR image_swapchain_create = {
1786 .sType = VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR,
1787 .pNext = nullptr,
1788 .swapchain = HandleFromSwapchain(swapchain),
1789 };
1790 image_create.pNext = &image_swapchain_create;
Jesse Halld7b994a2015-09-07 14:17:37 -07001791
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001792 for (uint32_t i = 0; i < num_images; i++) {
1793 Swapchain::Image& img = swapchain->images[i];
1794 img.buffer = nullptr;
1795 img.dequeued = false;
1796
1797 result = dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1798 if (result != VK_SUCCESS) {
1799 ALOGD("vkCreateImage w/ for deferred swapchain image failed: %u", result);
1800 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08001801 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001802 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001803 } else {
1804 // -- Dequeue all buffers and create a VkImage for each --
1805 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07001806
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001807 for (uint32_t i = 0; i < num_images; i++) {
1808 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07001809
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001810 ANativeWindowBuffer* buffer;
1811 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
1812 if (err != android::OK) {
1813 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
1814 switch (-err) {
1815 case ENOMEM:
1816 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
1817 break;
1818 default:
1819 result = VK_ERROR_SURFACE_LOST_KHR;
1820 break;
1821 }
1822 break;
1823 }
1824 img.buffer = buffer;
1825 img.dequeued = true;
1826
1827 image_native_buffer.handle = img.buffer->handle;
1828 image_native_buffer.stride = img.buffer->stride;
1829 image_native_buffer.format = img.buffer->format;
1830 image_native_buffer.usage = int(img.buffer->usage);
1831 android_convertGralloc0To1Usage(int(img.buffer->usage),
1832 &image_native_buffer.usage2.producer,
1833 &image_native_buffer.usage2.consumer);
1834 image_native_buffer.usage3 = img.buffer->usage;
1835 image_create.pNext = &image_native_buffer;
1836
1837 ATRACE_BEGIN("CreateImage");
1838 result =
1839 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1840 ATRACE_END();
1841 if (result != VK_SUCCESS) {
1842 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
1843 break;
1844 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001845 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001846
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001847 // -- Cancel all buffers, returning them to the queue --
1848 // If an error occurred before, also destroy the VkImage and release the
1849 // buffer reference. Otherwise, we retain a strong reference to the buffer.
1850 for (uint32_t i = 0; i < num_images; i++) {
1851 Swapchain::Image& img = swapchain->images[i];
1852 if (img.dequeued) {
1853 if (!swapchain->shared) {
1854 window->cancelBuffer(window, img.buffer.get(),
1855 img.dequeue_fence);
1856 img.dequeue_fence = -1;
1857 img.dequeued = false;
1858 }
Chris Forbese0ced032017-03-30 19:44:15 +13001859 }
Chris Forbes31b85c22018-05-29 15:03:28 -07001860 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001861 }
1862
1863 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001864 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
1865 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07001866 return result;
1867 }
1868
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001869 if (transform_hint != swapchain->pre_transform) {
1870 // Log that the app is not doing pre-rotation.
1871 android::GraphicsEnv::getInstance().setTargetStats(
1872 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
1873 }
1874
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00001875 // Set stats for creating a Vulkan swapchain
1876 android::GraphicsEnv::getInstance().setTargetStats(
1877 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
1878
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001879 surface.used_by_swapchain = true;
Jesse Halldc225072016-05-30 22:40:14 -07001880 surface.swapchain_handle = HandleFromSwapchain(swapchain);
1881 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001882 return VK_SUCCESS;
1883}
1884
Jesse Halle1b12782015-11-30 11:27:32 -08001885VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001886void DestroySwapchainKHR(VkDevice device,
1887 VkSwapchainKHR swapchain_handle,
1888 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001889 ATRACE_CALL();
1890
Yiwei Zhang533cea92019-06-03 18:43:24 -07001891 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001892}
1893
Jesse Halle1b12782015-11-30 11:27:32 -08001894VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001895VkResult GetSwapchainImagesKHR(VkDevice,
1896 VkSwapchainKHR swapchain_handle,
1897 uint32_t* count,
1898 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001899 ATRACE_CALL();
1900
Jesse Halld7b994a2015-09-07 14:17:37 -07001901 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07001902 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
1903 "getting images for non-active swapchain 0x%" PRIx64
1904 "; only dequeued image handles are valid",
1905 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07001906 VkResult result = VK_SUCCESS;
1907 if (images) {
1908 uint32_t n = swapchain.num_images;
1909 if (*count < swapchain.num_images) {
1910 n = *count;
1911 result = VK_INCOMPLETE;
1912 }
1913 for (uint32_t i = 0; i < n; i++)
1914 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07001915 *count = n;
1916 } else {
1917 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07001918 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001919 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001920}
1921
Jesse Halle1b12782015-11-30 11:27:32 -08001922VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001923VkResult AcquireNextImageKHR(VkDevice device,
1924 VkSwapchainKHR swapchain_handle,
1925 uint64_t timeout,
1926 VkSemaphore semaphore,
1927 VkFence vk_fence,
1928 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001929 ATRACE_CALL();
1930
Jesse Halld7b994a2015-09-07 14:17:37 -07001931 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001932 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07001933 VkResult result;
1934 int err;
1935
Jesse Halldc225072016-05-30 22:40:14 -07001936 if (swapchain.surface.swapchain_handle != swapchain_handle)
1937 return VK_ERROR_OUT_OF_DATE_KHR;
1938
Chris Forbesc88409c2017-03-30 19:47:37 +13001939 if (swapchain.shared) {
1940 // In shared mode, we keep the buffer dequeued all the time, so we don't
1941 // want to dequeue a buffer here. Instead, just ask the driver to ensure
1942 // the semaphore and fence passed to us will be signalled.
1943 *image_index = 0;
1944 result = GetData(device).driver.AcquireImageANDROID(
1945 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
1946 return result;
1947 }
1948
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001949 const nsecs_t acquire_next_image_timeout =
1950 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
1951 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
1952 // Cache the timeout to avoid the duplicate binder cost.
1953 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
1954 acquire_next_image_timeout);
1955 if (err != android::OK) {
1956 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1957 strerror(-err), err);
1958 return VK_ERROR_SURFACE_LOST_KHR;
1959 }
1960 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
1961 }
1962
Jesse Halld7b994a2015-09-07 14:17:37 -07001963 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08001964 int fence_fd;
1965 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07001966 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001967 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
1968 return timeout ? VK_TIMEOUT : VK_NOT_READY;
1969 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001970 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001971 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001972 }
1973
1974 uint32_t idx;
1975 for (idx = 0; idx < swapchain.num_images; idx++) {
1976 if (swapchain.images[idx].buffer.get() == buffer) {
1977 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08001978 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07001979 break;
1980 }
1981 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001982
1983 // If this is a deferred alloc swapchain, this may be the first time we've
1984 // seen a particular buffer. If so, there should be an empty slot. Find it,
1985 // and bind the gralloc buffer to the VkImage for that slot. If there is no
1986 // empty slot, then we dequeued an unexpected buffer. Non-deferred swapchains
1987 // will also take this path, but will never have an empty slot since we
1988 // populated them all upfront.
1989 if (idx == swapchain.num_images) {
1990 for (idx = 0; idx < swapchain.num_images; idx++) {
1991 if (!swapchain.images[idx].buffer) {
1992 // Note: this structure is technically required for
1993 // Vulkan correctness, even though the driver is probably going
1994 // to use everything from the VkNativeBufferANDROID below.
1995 // This is kindof silly, but it's how we did the ANB
1996 // side of VK_KHR_swapchain v69, so we're stuck with it unless
1997 // we want to go tinkering with the ANB spec some more.
1998 VkBindImageMemorySwapchainInfoKHR bimsi = {
1999 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR,
2000 .pNext = nullptr,
2001 .swapchain = swapchain_handle,
2002 .imageIndex = idx,
2003 };
2004 VkNativeBufferANDROID nb = {
2005 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2006 .pNext = &bimsi,
2007 .handle = buffer->handle,
2008 .stride = buffer->stride,
2009 .format = buffer->format,
2010 .usage = int(buffer->usage),
2011 };
2012 VkBindImageMemoryInfo bimi = {
2013 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO,
2014 .pNext = &nb,
2015 .image = swapchain.images[idx].image,
2016 .memory = VK_NULL_HANDLE,
2017 .memoryOffset = 0,
2018 };
2019 result = GetData(device).driver.BindImageMemory2(device, 1, &bimi);
2020 if (result != VK_SUCCESS) {
2021 // This shouldn't really happen. If it does, something is probably
2022 // unrecoverably wrong with the swapchain and its images. Cancel
2023 // the buffer and declare the swapchain broken.
2024 ALOGE("failed to do deferred gralloc buffer bind");
2025 window->cancelBuffer(window, buffer, fence_fd);
2026 return VK_ERROR_OUT_OF_DATE_KHR;
2027 }
2028
2029 swapchain.images[idx].dequeued = true;
2030 swapchain.images[idx].dequeue_fence = fence_fd;
2031 swapchain.images[idx].buffer = buffer;
2032 break;
2033 }
2034 }
2035 }
2036
2037 // The buffer doesn't match any slot. This shouldn't normally happen, but is
2038 // possible if the bufferqueue is reconfigured behind libvulkan's back. If this
2039 // happens, just declare the swapchain to be broken and the app will recreate it.
Jesse Halld7b994a2015-09-07 14:17:37 -07002040 if (idx == swapchain.num_images) {
2041 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08002042 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002043 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002044 }
2045
2046 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08002047 if (fence_fd != -1) {
2048 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002049 if (fence_clone == -1) {
2050 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
2051 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08002052 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07002053 }
2054 }
2055
Chia-I Wu4a6a9162016-03-26 07:17:34 +08002056 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08002057 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07002058 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08002059 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
2060 // even if the call fails. We could close it ourselves on failure, but
2061 // that would create a race condition if the driver closes it on a
2062 // failure path: some other thread might create an fd with the same
2063 // number between the time the driver closes it and the time we close
2064 // it. We must assume one of: the driver *always* closes it even on
2065 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08002066 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002067 swapchain.images[idx].dequeued = false;
2068 swapchain.images[idx].dequeue_fence = -1;
2069 return result;
2070 }
2071
2072 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002073 return VK_SUCCESS;
2074}
2075
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002076VKAPI_ATTR
2077VkResult AcquireNextImage2KHR(VkDevice device,
2078 const VkAcquireNextImageInfoKHR* pAcquireInfo,
2079 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002080 ATRACE_CALL();
2081
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002082 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
2083 pAcquireInfo->timeout, pAcquireInfo->semaphore,
2084 pAcquireInfo->fence, pImageIndex);
2085}
2086
Jesse Halldc225072016-05-30 22:40:14 -07002087static VkResult WorstPresentResult(VkResult a, VkResult b) {
2088 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
2089 // (in spec version 1.0.14).
2090 static const VkResult kWorstToBest[] = {
2091 VK_ERROR_DEVICE_LOST,
2092 VK_ERROR_SURFACE_LOST_KHR,
2093 VK_ERROR_OUT_OF_DATE_KHR,
2094 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2095 VK_ERROR_OUT_OF_HOST_MEMORY,
2096 VK_SUBOPTIMAL_KHR,
2097 };
2098 for (auto result : kWorstToBest) {
2099 if (a == result || b == result)
2100 return result;
2101 }
2102 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
2103 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
2104 return a != VK_SUCCESS ? a : b;
2105}
2106
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002107// KHR_incremental_present aspect of QueuePresentKHR
2108static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
2109 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
2110 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
2111 auto const& rect = pRegion->pRectangles[i];
2112 if (rect.layer > 0) {
2113 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
2114 rect.layer);
2115 }
2116
2117 rects[i].left = rect.offset.x;
2118 rects[i].bottom = rect.offset.y;
2119 rects[i].right = rect.offset.x + rect.extent.width;
2120 rects[i].top = rect.offset.y + rect.extent.height;
2121 }
2122 native_window_set_surface_damage(window, rects.data(), rects.size());
2123}
2124
2125// GOOGLE_display_timing aspect of QueuePresentKHR
2126static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
2127 ANativeWindow *window = swapchain.surface.window.get();
2128
2129 // We don't know whether the app will actually use GOOGLE_display_timing
2130 // with a particular swapchain until QueuePresent; enable it on the BQ
2131 // now if needed
2132 if (!swapchain.frame_timestamps_enabled) {
2133 ALOGV("Calling native_window_enable_frame_timestamps(true)");
2134 native_window_enable_frame_timestamps(window, true);
2135 swapchain.frame_timestamps_enabled = true;
2136 }
2137
2138 // Record the nativeFrameId so it can be later correlated to
2139 // this present.
2140 uint64_t nativeFrameId = 0;
2141 int err = native_window_get_next_frame_id(
2142 window, &nativeFrameId);
2143 if (err != android::OK) {
2144 ALOGE("Failed to get next native frame ID.");
2145 }
2146
2147 // Add a new timing record with the user's presentID and
2148 // the nativeFrameId.
2149 swapchain.timing.emplace_back(pTime, nativeFrameId);
2150 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
2151 swapchain.timing.erase(
2152 swapchain.timing.begin(),
2153 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
2154 }
2155 if (pTime->desiredPresentTime) {
2156 ALOGV(
2157 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
2158 pTime->desiredPresentTime);
2159 native_window_set_buffers_timestamp(
2160 window,
2161 static_cast<int64_t>(pTime->desiredPresentTime));
2162 }
2163}
2164
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002165// EXT_swapchain_maintenance1 present mode change
2166static bool SetSwapchainPresentMode(ANativeWindow *window, VkPresentModeKHR mode) {
2167 // There is no dynamic switching between non-shared present modes.
2168 // All we support is switching between demand and continuous refresh.
2169 if (!IsSharedPresentMode(mode))
2170 return true;
2171
2172 int err = native_window_set_auto_refresh(window,
2173 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
2174 if (err != android::OK) {
2175 ALOGE("native_window_set_auto_refresh() failed: %s (%d)",
2176 strerror(-err), err);
2177 return false;
2178 }
2179
2180 return true;
2181}
2182
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002183static VkResult PresentOneSwapchain(
2184 VkQueue queue,
2185 Swapchain& swapchain,
2186 uint32_t imageIndex,
2187 const VkPresentRegionKHR *pRegion,
2188 const VkPresentTimeGOOGLE *pTime,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002189 VkFence presentFence,
2190 const VkPresentModeKHR *pPresentMode,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002191 uint32_t waitSemaphoreCount,
2192 const VkSemaphore *pWaitSemaphores) {
2193
2194 VkDevice device = GetData(queue).driver_device;
2195 const auto& dispatch = GetData(queue).driver;
2196
2197 Swapchain::Image& img = swapchain.images[imageIndex];
2198 VkResult swapchain_result = VK_SUCCESS;
2199 VkResult result;
2200 int err;
2201
2202 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
2203 // wait semaphores, so this doesn't actually work for the multiple swapchain
2204 // case.
2205 int fence = -1;
2206 result = dispatch.QueueSignalReleaseImageANDROID(
2207 queue, waitSemaphoreCount,
2208 pWaitSemaphores, img.image, &fence);
2209 if (result != VK_SUCCESS) {
2210 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
2211 swapchain_result = result;
2212 }
2213 if (img.release_fence >= 0)
2214 close(img.release_fence);
2215 img.release_fence = fence < 0 ? -1 : dup(fence);
2216
2217 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
2218 ANativeWindow* window = swapchain.surface.window.get();
2219 if (swapchain_result == VK_SUCCESS) {
2220
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002221 if (presentFence != VK_NULL_HANDLE) {
2222 int fence_copy = fence < 0 ? -1 : dup(fence);
2223 VkImportFenceFdInfoKHR iffi = {
2224 VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,
2225 nullptr,
2226 presentFence,
2227 VK_FENCE_IMPORT_TEMPORARY_BIT,
2228 VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,
2229 fence_copy,
2230 };
2231 if (VK_SUCCESS != dispatch.ImportFenceFdKHR(device, &iffi) && fence_copy >= 0) {
2232 // ImportFenceFdKHR takes ownership only if it succeeds
2233 close(fence_copy);
2234 }
2235 }
2236
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002237 if (pRegion) {
2238 SetSwapchainSurfaceDamage(window, pRegion);
2239 }
2240 if (pTime) {
2241 SetSwapchainFrameTimestamp(swapchain, pTime);
2242 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002243 if (pPresentMode) {
2244 if (!SetSwapchainPresentMode(window, *pPresentMode))
2245 swapchain_result = WorstPresentResult(swapchain_result,
2246 VK_ERROR_SURFACE_LOST_KHR);
2247 }
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002248
2249 err = window->queueBuffer(window, img.buffer.get(), fence);
2250 // queueBuffer always closes fence, even on error
2251 if (err != android::OK) {
2252 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
2253 swapchain_result = WorstPresentResult(
2254 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2255 } else {
2256 if (img.dequeue_fence >= 0) {
2257 close(img.dequeue_fence);
2258 img.dequeue_fence = -1;
2259 }
2260 img.dequeued = false;
2261 }
2262
2263 // If the swapchain is in shared mode, immediately dequeue the
2264 // buffer so it can be presented again without an intervening
2265 // call to AcquireNextImageKHR. We expect to get the same buffer
2266 // back from every call to dequeueBuffer in this mode.
2267 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
2268 ANativeWindowBuffer* buffer;
2269 int fence_fd;
2270 err = window->dequeueBuffer(window, &buffer, &fence_fd);
2271 if (err != android::OK) {
2272 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
2273 swapchain_result = WorstPresentResult(swapchain_result,
2274 VK_ERROR_SURFACE_LOST_KHR);
2275 } else if (img.buffer != buffer) {
2276 ALOGE("got wrong image back for shared swapchain");
2277 swapchain_result = WorstPresentResult(swapchain_result,
2278 VK_ERROR_SURFACE_LOST_KHR);
2279 } else {
2280 img.dequeue_fence = fence_fd;
2281 img.dequeued = true;
2282 }
2283 }
2284 }
2285 if (swapchain_result != VK_SUCCESS) {
2286 OrphanSwapchain(device, &swapchain);
2287 }
2288 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
2289 // and only when the window's transform/rotation changes. Extent
2290 // changes will not cause VK_SUBOPTIMAL_KHR because of the
2291 // application issues that were caused when the following transform
2292 // change was added.
2293 int window_transform_hint;
2294 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
2295 &window_transform_hint);
2296 if (err != android::OK) {
2297 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
2298 strerror(-err), err);
2299 swapchain_result = WorstPresentResult(
2300 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2301 }
2302 if (swapchain.pre_transform != window_transform_hint) {
2303 swapchain_result =
2304 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
2305 }
2306 } else {
2307 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
2308 img, true);
2309 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
2310 }
2311
2312 return swapchain_result;
2313}
2314
Jesse Halle1b12782015-11-30 11:27:32 -08002315VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002316VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002317 ATRACE_CALL();
2318
Jesse Halld7b994a2015-09-07 14:17:37 -07002319 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
2320 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
2321 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07002322
Jesse Halld7b994a2015-09-07 14:17:37 -07002323 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07002324
Ian Elliottcb351132016-12-13 10:30:40 -07002325 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002326 const VkPresentRegionsKHR* present_regions = nullptr;
2327 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002328 const VkSwapchainPresentFenceInfoEXT* present_fences = nullptr;
2329 const VkSwapchainPresentModeInfoEXT* present_modes = nullptr;
2330
Ian Elliottcb351132016-12-13 10:30:40 -07002331 const VkPresentRegionsKHR* next =
2332 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
2333 while (next) {
2334 switch (next->sType) {
2335 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
2336 present_regions = next;
2337 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07002338 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002339 present_times =
2340 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
2341 break;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002342 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT:
2343 present_fences =
2344 reinterpret_cast<const VkSwapchainPresentFenceInfoEXT*>(next);
2345 break;
2346 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT:
2347 present_modes =
2348 reinterpret_cast<const VkSwapchainPresentModeInfoEXT*>(next);
2349 break;
Ian Elliottcb351132016-12-13 10:30:40 -07002350 default:
2351 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
2352 next->sType);
2353 break;
2354 }
2355 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2356 }
2357 ALOGV_IF(
2358 present_regions &&
2359 present_regions->swapchainCount != present_info->swapchainCount,
2360 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002361 ALOGV_IF(present_times &&
2362 present_times->swapchainCount != present_info->swapchainCount,
2363 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2364 "VkPresentInfo::swapchainCount");
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002365 ALOGV_IF(present_fences &&
2366 present_fences->swapchainCount != present_info->swapchainCount,
2367 "VkSwapchainPresentFenceInfoEXT::swapchainCount != "
2368 "VkPresentInfo::swapchainCount");
2369 ALOGV_IF(present_modes &&
2370 present_modes->swapchainCount != present_info->swapchainCount,
2371 "VkSwapchainPresentModeInfoEXT::swapchainCount != "
2372 "VkPresentInfo::swapchainCount");
2373
Ian Elliottcb351132016-12-13 10:30:40 -07002374 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002375 (present_regions) ? present_regions->pRegions : nullptr;
2376 const VkPresentTimeGOOGLE* times =
2377 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002378
Jesse Halld7b994a2015-09-07 14:17:37 -07002379 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2380 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002381 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002382
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002383 VkResult swapchain_result = PresentOneSwapchain(
2384 queue,
2385 swapchain,
2386 present_info->pImageIndices[sc],
2387 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2388 times ? &times[sc] : nullptr,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002389 present_fences ? present_fences->pFences[sc] : VK_NULL_HANDLE,
2390 present_modes ? &present_modes->pPresentModes[sc] : nullptr,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002391 present_info->waitSemaphoreCount,
2392 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002393
Jesse Halla9e57032015-11-30 01:03:10 -08002394 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002395 present_info->pResults[sc] = swapchain_result;
2396
2397 if (swapchain_result != final_result)
2398 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002399 }
2400
2401 return final_result;
2402}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002403
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002404VKAPI_ATTR
2405VkResult GetRefreshCycleDurationGOOGLE(
2406 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002407 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002408 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002409 ATRACE_CALL();
2410
Ian Elliott62c48c92017-01-20 13:13:20 -07002411 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00002412 VkResult result = swapchain.get_refresh_duration(pDisplayTimingProperties->refreshDuration);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002413
2414 return result;
2415}
2416
2417VKAPI_ATTR
2418VkResult GetPastPresentationTimingGOOGLE(
2419 VkDevice,
2420 VkSwapchainKHR swapchain_handle,
2421 uint32_t* count,
2422 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002423 ATRACE_CALL();
2424
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002425 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002426 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2427 return VK_ERROR_OUT_OF_DATE_KHR;
2428 }
2429
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002430 ANativeWindow* window = swapchain.surface.window.get();
2431 VkResult result = VK_SUCCESS;
2432
2433 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002434 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002435 native_window_enable_frame_timestamps(window, true);
2436 swapchain.frame_timestamps_enabled = true;
2437 }
2438
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002439 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002440 // Get the latest ready timing count before copying, since the copied
2441 // timing info will be erased in copy_ready_timings function.
2442 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002443 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002444 // Check the *count here against the recorded ready timing count, since
2445 // *count can be overwritten per spec describes.
2446 if (*count < n) {
2447 result = VK_INCOMPLETE;
2448 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002449 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002450 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002451 }
2452
2453 return result;
2454}
2455
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002456VKAPI_ATTR
2457VkResult GetSwapchainStatusKHR(
2458 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002459 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002460 ATRACE_CALL();
2461
Chris Forbes4e18ba82017-01-20 12:50:17 +13002462 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002463 VkResult result = VK_SUCCESS;
2464
Chris Forbes4e18ba82017-01-20 12:50:17 +13002465 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2466 return VK_ERROR_OUT_OF_DATE_KHR;
2467 }
2468
Yiwei Zhanga885c062019-10-24 12:07:57 -07002469 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002470
2471 return result;
2472}
2473
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002474VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002475 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002476 uint32_t swapchainCount,
2477 const VkSwapchainKHR* pSwapchains,
2478 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002479 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002480
2481 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2482 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2483 if (!swapchain)
2484 continue;
2485
2486 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2487
2488 ANativeWindow* window = swapchain->surface.window.get();
2489
2490 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2491 const android_smpte2086_metadata smpteMetdata = {
2492 {vulkanMetadata.displayPrimaryRed.x,
2493 vulkanMetadata.displayPrimaryRed.y},
2494 {vulkanMetadata.displayPrimaryGreen.x,
2495 vulkanMetadata.displayPrimaryGreen.y},
2496 {vulkanMetadata.displayPrimaryBlue.x,
2497 vulkanMetadata.displayPrimaryBlue.y},
2498 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2499 vulkanMetadata.maxLuminance,
2500 vulkanMetadata.minLuminance};
2501 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2502
2503 const android_cta861_3_metadata cta8613Metadata = {
2504 vulkanMetadata.maxContentLightLevel,
2505 vulkanMetadata.maxFrameAverageLightLevel};
2506 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2507 }
2508
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002509 return;
2510}
2511
Yiwei Zhang0f475222019-04-11 19:38:00 -07002512static void InterceptBindImageMemory2(
2513 uint32_t bind_info_count,
2514 const VkBindImageMemoryInfo* bind_infos,
2515 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2516 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2517 out_native_buffers->clear();
2518 out_bind_infos->clear();
2519
2520 if (!bind_info_count)
2521 return;
2522
2523 std::unordered_set<uint32_t> intercepted_indexes;
2524
2525 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2526 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2527 bind_infos[idx].pNext);
2528 while (info &&
2529 info->sType !=
2530 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2531 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2532 info->pNext);
2533 }
2534
2535 if (!info)
2536 continue;
2537
2538 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2539 "swapchain handle must not be NULL");
2540 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2541 ALOG_ASSERT(
2542 info->imageIndex < swapchain->num_images,
2543 "imageIndex must be less than the number of images in swapchain");
2544
2545 ANativeWindowBuffer* buffer =
2546 swapchain->images[info->imageIndex].buffer.get();
2547 VkNativeBufferANDROID native_buffer = {
2548#pragma clang diagnostic push
2549#pragma clang diagnostic ignored "-Wold-style-cast"
2550 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2551#pragma clang diagnostic pop
2552 .pNext = bind_infos[idx].pNext,
2553 .handle = buffer->handle,
2554 .stride = buffer->stride,
2555 .format = buffer->format,
2556 .usage = int(buffer->usage),
2557 };
2558 // Reserve enough space to avoid letting re-allocation invalidate the
2559 // addresses of the elements inside.
2560 out_native_buffers->reserve(bind_info_count);
2561 out_native_buffers->emplace_back(native_buffer);
2562
2563 // Reserve the space now since we know how much is needed now.
2564 out_bind_infos->reserve(bind_info_count);
2565 out_bind_infos->emplace_back(bind_infos[idx]);
2566 out_bind_infos->back().pNext = &out_native_buffers->back();
2567
2568 intercepted_indexes.insert(idx);
2569 }
2570
2571 if (intercepted_indexes.empty())
2572 return;
2573
2574 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2575 if (intercepted_indexes.count(idx))
2576 continue;
2577 out_bind_infos->emplace_back(bind_infos[idx]);
2578 }
2579}
2580
Yiwei Zhang23143102019-04-10 18:24:05 -07002581VKAPI_ATTR
2582VkResult BindImageMemory2(VkDevice device,
2583 uint32_t bindInfoCount,
2584 const VkBindImageMemoryInfo* pBindInfos) {
2585 ATRACE_CALL();
2586
Yiwei Zhang0f475222019-04-11 19:38:00 -07002587 // out_native_buffers is for maintaining the lifecycle of the constructed
2588 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2589 std::vector<VkNativeBufferANDROID> out_native_buffers;
2590 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2591 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2592 &out_bind_infos);
2593 return GetData(device).driver.BindImageMemory2(
2594 device, bindInfoCount,
2595 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002596}
2597
2598VKAPI_ATTR
2599VkResult BindImageMemory2KHR(VkDevice device,
2600 uint32_t bindInfoCount,
2601 const VkBindImageMemoryInfo* pBindInfos) {
2602 ATRACE_CALL();
2603
Yiwei Zhang0f475222019-04-11 19:38:00 -07002604 std::vector<VkNativeBufferANDROID> out_native_buffers;
2605 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2606 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2607 &out_bind_infos);
2608 return GetData(device).driver.BindImageMemory2KHR(
2609 device, bindInfoCount,
2610 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002611}
2612
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002613VKAPI_ATTR
2614VkResult ReleaseSwapchainImagesEXT(VkDevice /*device*/,
2615 const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
2616 ATRACE_CALL();
2617
2618 Swapchain& swapchain = *SwapchainFromHandle(pReleaseInfo->swapchain);
2619 ANativeWindow* window = swapchain.surface.window.get();
2620
2621 // If in shared present mode, don't actually release the image back to the BQ.
2622 // Both sides share it forever.
2623 if (swapchain.shared)
2624 return VK_SUCCESS;
2625
2626 for (uint32_t i = 0; i < pReleaseInfo->imageIndexCount; i++) {
2627 Swapchain::Image& img = swapchain.images[pReleaseInfo->pImageIndices[i]];
2628 window->cancelBuffer(window, img.buffer.get(), img.dequeue_fence);
2629
2630 // cancelBuffer has taken ownership of the dequeue fence
2631 img.dequeue_fence = -1;
2632 // if we're still holding a release fence, get rid of it now
2633 if (img.release_fence >= 0) {
2634 close(img.release_fence);
2635 img.release_fence = -1;
2636 }
2637 img.dequeued = false;
2638 }
2639
2640 return VK_SUCCESS;
2641}
2642
Chia-I Wu62262232016-03-26 07:06:44 +08002643} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002644} // namespace vulkan