blob: af873065ff651999b15da7aa25d739f70b6c0ff0 [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
Yiwei Zhang0f475222019-04-11 19:38:00 -070019#include <android/hardware/graphics/common/1.0/types.h>
Jesse Hall79927812017-03-23 11:03:23 -070020#include <grallocusage/GrallocUsageConversion.h>
Yiwei Zhang69395cd2019-07-03 16:55:39 -070021#include <graphicsenv/GraphicsEnv.h>
John Reck97678d42022-08-23 11:24:51 -040022#include <hardware/gralloc.h>
23#include <hardware/gralloc1.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070024#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070025#include <sync/sync.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070026#include <system/window.h>
27#include <ui/BufferQueueDefs.h>
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -050028#include <ui/DebugUtils.h>
29#include <ui/PixelFormat.h>
Chia-I Wue8e689f2016-04-18 08:21:31 +080030#include <utils/StrongPointer.h>
Yiwei Zhang705c2e62019-12-18 23:12:43 -080031#include <utils/Timers.h>
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080032#include <utils/Trace.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070033
34#include <algorithm>
35#include <unordered_set>
36#include <vector>
Jesse Halld7b994a2015-09-07 14:17:37 -070037
Chia-I Wu4a6a9162016-03-26 07:17:34 +080038#include "driver.h"
Jesse Halld7b994a2015-09-07 14:17:37 -070039
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
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500506android::PixelFormat GetNativePixelFormat(VkFormat format) {
507 android::PixelFormat native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700508 switch (format) {
509 case VK_FORMAT_R8G8B8A8_UNORM:
510 case VK_FORMAT_R8G8B8A8_SRGB:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500511 native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700512 break;
513 case VK_FORMAT_R5G6B5_UNORM_PACK16:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500514 native_format = android::PIXEL_FORMAT_RGB_565;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700515 break;
516 case VK_FORMAT_R16G16B16A16_SFLOAT:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500517 native_format = android::PIXEL_FORMAT_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:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500520 native_format = android::PIXEL_FORMAT_RGBA_1010102;
521 break;
522 case VK_FORMAT_R8_UNORM:
523 native_format = android::PIXEL_FORMAT_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:
526 native_format = android::PIXEL_FORMAT_RGBA_10101010;
527 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
535android_dataspace GetNativeDataspace(VkColorSpaceKHR colorspace) {
536 switch (colorspace) {
537 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
538 return HAL_DATASPACE_V0_SRGB;
539 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
540 return HAL_DATASPACE_DISPLAY_P3;
541 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
542 return HAL_DATASPACE_V0_SCRGB_LINEAR;
Courtney Goeltzenleuchterb52abee2017-08-07 17:13:04 -0600543 case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT:
544 return HAL_DATASPACE_V0_SCRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700545 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
546 return HAL_DATASPACE_DCI_P3_LINEAR;
547 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
548 return HAL_DATASPACE_DCI_P3;
549 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
550 return HAL_DATASPACE_V0_SRGB_LINEAR;
551 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
552 return HAL_DATASPACE_V0_SRGB;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600553 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
554 return HAL_DATASPACE_BT2020_LINEAR;
555 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700556 return static_cast<android_dataspace>(
557 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
558 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600559 case VK_COLOR_SPACE_DOLBYVISION_EXT:
560 return static_cast<android_dataspace>(
561 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
562 HAL_DATASPACE_RANGE_FULL);
563 case VK_COLOR_SPACE_HDR10_HLG_EXT:
564 return static_cast<android_dataspace>(
565 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_HLG |
566 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700567 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
568 return static_cast<android_dataspace>(
569 HAL_DATASPACE_STANDARD_ADOBE_RGB |
570 HAL_DATASPACE_TRANSFER_LINEAR | HAL_DATASPACE_RANGE_FULL);
571 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
572 return HAL_DATASPACE_ADOBE_RGB;
573
574 // Pass through is intended to allow app to provide data that is passed
575 // to the display system without modification.
576 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
577 return HAL_DATASPACE_ARBITRARY;
578
579 default:
580 // This indicates that we don't know about the
581 // dataspace specified and we should indicate that
582 // it's unsupported
583 return HAL_DATASPACE_UNKNOWN;
584 }
585}
586
Jesse Halld7b994a2015-09-07 14:17:37 -0700587} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700588
Jesse Halle1b12782015-11-30 11:27:32 -0800589VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800590VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800591 VkInstance instance,
592 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
593 const VkAllocationCallbacks* allocator,
594 VkSurfaceKHR* out_surface) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800595 ATRACE_CALL();
596
Jesse Hall1f91d392015-12-11 16:28:44 -0800597 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800598 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800599 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
600 alignof(Surface),
601 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800602 if (!mem)
603 return VK_ERROR_OUT_OF_HOST_MEMORY;
604 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700605
Chia-I Wue8e689f2016-04-18 08:21:31 +0800606 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700607 surface->swapchain_handle = VK_NULL_HANDLE;
Yiwei Zhang3b88f312023-04-18 23:11:35 +0000608 surface->used_by_swapchain = false;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700609 int err = native_window_get_consumer_usage(surface->window.get(),
610 &surface->consumer_usage);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800611 if (err != android::OK) {
Yiwei Zhang6435b322018-05-08 11:12:17 -0700612 ALOGE("native_window_get_consumer_usage() failed: %s (%d)",
613 strerror(-err), err);
614 surface->~Surface();
615 allocator->pfnFree(allocator->pUserData, surface);
Yiwei Zhang70a21962019-05-31 17:26:52 -0700616 return VK_ERROR_SURFACE_LOST_KHR;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700617 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700618
Yiwei Zhang6435b322018-05-08 11:12:17 -0700619 err =
Jesse Hall1356b0d2015-11-23 17:24:58 -0800620 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800621 if (err != android::OK) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800622 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
623 err);
624 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800625 allocator->pfnFree(allocator->pUserData, surface);
Mike Stroyan762c8132017-02-22 11:43:09 -0700626 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800627 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700628
Jesse Hall1356b0d2015-11-23 17:24:58 -0800629 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700630 return VK_SUCCESS;
631}
632
Jesse Halle1b12782015-11-30 11:27:32 -0800633VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800634void DestroySurfaceKHR(VkInstance instance,
635 VkSurfaceKHR surface_handle,
636 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800637 ATRACE_CALL();
638
Jesse Hall1356b0d2015-11-23 17:24:58 -0800639 Surface* surface = SurfaceFromHandle(surface_handle);
640 if (!surface)
641 return;
642 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700643 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700644 "destroyed VkSurfaceKHR 0x%" PRIx64
645 " has active VkSwapchainKHR 0x%" PRIx64,
646 reinterpret_cast<uint64_t>(surface_handle),
647 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800648 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800649 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800650 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800651 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800652}
653
Jesse Halle1b12782015-11-30 11:27:32 -0800654VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800655VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
656 uint32_t /*queue_family*/,
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000657 VkSurfaceKHR /*surface_handle*/,
Chia-I Wu62262232016-03-26 07:06:44 +0800658 VkBool32* supported) {
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000659 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800660 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800661}
662
Jesse Halle1b12782015-11-30 11:27:32 -0800663VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800664VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Ian Elliott1ce053f2022-03-16 09:49:53 -0600665 VkPhysicalDevice pdev,
Jesse Hallb00daad2015-11-29 19:46:20 -0800666 VkSurfaceKHR surface,
667 VkSurfaceCapabilitiesKHR* capabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800668 ATRACE_CALL();
669
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000670 // Implement in terms of GetPhysicalDeviceSurfaceCapabilities2KHR
671
672 VkPhysicalDeviceSurfaceInfo2KHR info2 = {
673 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
674 nullptr,
675 surface
676 };
677
678 VkSurfaceCapabilities2KHR caps2 = {
679 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
680 nullptr,
681 {},
682 };
683
684 VkResult result = GetPhysicalDeviceSurfaceCapabilities2KHR(pdev, &info2, &caps2);
685 *capabilities = caps2.surfaceCapabilities;
686 return result;
687}
688
689// Does the call-twice and VK_INCOMPLETE handling for querying lists
690// of things, where we already have the full set built in a vector.
691template <typename T>
692VkResult CopyWithIncomplete(std::vector<T> const& things,
693 T* callerPtr, uint32_t* callerCount) {
694 VkResult result = VK_SUCCESS;
695 if (callerPtr) {
696 if (things.size() > *callerCount)
697 result = VK_INCOMPLETE;
698 *callerCount = std::min(uint32_t(things.size()), *callerCount);
699 std::copy(things.begin(), things.begin() + *callerCount, callerPtr);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600700 } else {
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000701 *callerCount = things.size();
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800702 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000703 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700704}
705
Jesse Halle1b12782015-11-30 11:27:32 -0800706VKAPI_ATTR
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700707VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
708 VkSurfaceKHR surface_handle,
Chia-I Wu62262232016-03-26 07:06:44 +0800709 uint32_t* count,
710 VkSurfaceFormatKHR* formats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800711 ATRACE_CALL();
712
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700713 const InstanceData& instance_data = GetData(pdev);
714
Ian Elliott1ce053f2022-03-16 09:49:53 -0600715 uint64_t consumer_usage = 0;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000716 bool colorspace_ext =
Ian Elliottf6df08e2022-03-16 21:27:49 -0600717 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600718 if (surface_handle == VK_NULL_HANDLE) {
719 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
720 bool surfaceless_enabled =
721 instance_data.hook_extensions.test(surfaceless);
722 if (!surfaceless_enabled) {
723 return VK_ERROR_SURFACE_LOST_KHR;
724 }
Chris Forbesb1de3b12022-10-20 09:05:48 +1300725 // Support for VK_GOOGLE_surfaceless_query.
Ian Elliott1ce053f2022-03-16 09:49:53 -0600726
727 // TODO(b/203826952): research proper value; temporarily use the
728 // values seen on Pixel
729 consumer_usage = AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
730 } else {
731 Surface& surface = *SurfaceFromHandle(surface_handle);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600732 consumer_usage = surface.consumer_usage;
Ian Elliott6ba85d92022-02-18 16:44:58 -0700733 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700734
Charlie Lao324191f2019-12-13 11:03:16 -0800735 AHardwareBuffer_Desc desc = {};
736 desc.width = 1;
737 desc.height = 1;
738 desc.layers = 1;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600739 desc.usage = consumer_usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
Charlie Lao324191f2019-12-13 11:03:16 -0800740 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
741
742 // We must support R8G8B8A8
743 std::vector<VkSurfaceFormatKHR> all_formats = {
744 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000745 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000746 };
Charlie Lao324191f2019-12-13 11:03:16 -0800747
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000748 if (colorspace_ext) {
749 all_formats.emplace_back(VkSurfaceFormatKHR{
Jason Macnakca506332022-11-09 11:00:36 -0800750 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
751 all_formats.emplace_back(VkSurfaceFormatKHR{
752 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_PASS_THROUGH_EXT});
753 all_formats.emplace_back(VkSurfaceFormatKHR{
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000754 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_BT709_LINEAR_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800755 all_formats.emplace_back(VkSurfaceFormatKHR{
756 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
757 all_formats.emplace_back(VkSurfaceFormatKHR{
758 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
759 }
760
Ian Elliott1ce053f2022-03-16 09:49:53 -0600761 // NOTE: Any new formats that are added must be coordinated across different
762 // Android users. This includes the ANGLE team (a layered implementation of
763 // OpenGL-ES).
764
Charlie Lao324191f2019-12-13 11:03:16 -0800765 desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
766 if (AHardwareBuffer_isSupported(&desc)) {
767 all_formats.emplace_back(VkSurfaceFormatKHR{
768 VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800769 if (colorspace_ext) {
770 all_formats.emplace_back(
771 VkSurfaceFormatKHR{VK_FORMAT_R5G6B5_UNORM_PACK16,
772 VK_COLOR_SPACE_PASS_THROUGH_EXT});
773 }
Charlie Lao324191f2019-12-13 11:03:16 -0800774 }
775
776 desc.format = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
777 if (AHardwareBuffer_isSupported(&desc)) {
778 all_formats.emplace_back(VkSurfaceFormatKHR{
779 VK_FORMAT_R16G16B16A16_SFLOAT, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800780 if (colorspace_ext) {
781 all_formats.emplace_back(
782 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
783 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800784 all_formats.emplace_back(
785 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
786 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT});
787 all_formats.emplace_back(
788 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
789 VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT});
790 }
791 }
792
793 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
794 if (AHardwareBuffer_isSupported(&desc)) {
795 all_formats.emplace_back(
796 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
797 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800798 if (colorspace_ext) {
799 all_formats.emplace_back(
800 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
801 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800802 all_formats.emplace_back(
803 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
804 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
805 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700806 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700807
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500808 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
809 if (AHardwareBuffer_isSupported(&desc)) {
Jason Macnakca506332022-11-09 11:00:36 -0800810 if (colorspace_ext) {
811 all_formats.emplace_back(VkSurfaceFormatKHR{
812 VK_FORMAT_R8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
813 }
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500814 }
815
Trevor David Black67e9b102023-03-07 05:28:15 +0000816 bool rgba10x6_formats_ext = false;
817 uint32_t exts_count;
818 const auto& driver = GetData(pdev).driver;
819 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
820 nullptr);
821 std::vector<VkExtensionProperties> props(exts_count);
822 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
823 props.data());
824 for (uint32_t i = 0; i < exts_count; i++) {
825 VkExtensionProperties prop = props[i];
826 if (strcmp(prop.extensionName,
827 VK_EXT_RGBA10X6_FORMATS_EXTENSION_NAME) == 0) {
828 rgba10x6_formats_ext = true;
829 }
830 }
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000831 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM;
Trevor David Black67e9b102023-03-07 05:28:15 +0000832 if (AHardwareBuffer_isSupported(&desc) && rgba10x6_formats_ext) {
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000833 all_formats.emplace_back(
834 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
835 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
836 if (colorspace_ext) {
837 all_formats.emplace_back(
838 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
839 VK_COLOR_SPACE_PASS_THROUGH_EXT});
840 all_formats.emplace_back(
841 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
842 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
843 }
844 }
845
Ian Elliott6ba85d92022-02-18 16:44:58 -0700846 // NOTE: Any new formats that are added must be coordinated across different
847 // Android users. This includes the ANGLE team (a layered implementation of
848 // OpenGL-ES).
849
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000850 return CopyWithIncomplete(all_formats, formats, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700851}
852
Jesse Halle1b12782015-11-30 11:27:32 -0800853VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300854VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
855 VkPhysicalDevice physicalDevice,
856 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
857 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800858 ATRACE_CALL();
859
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000860 auto surface = pSurfaceInfo->surface;
861 auto capabilities = &pSurfaceCapabilities->surfaceCapabilities;
Chris Forbes2452cf72017-03-16 16:30:17 +1300862
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000863 VkSurfacePresentModeEXT const *pPresentMode = nullptr;
864 for (auto pNext = reinterpret_cast<VkBaseInStructure const *>(pSurfaceInfo->pNext);
865 pNext; pNext = reinterpret_cast<VkBaseInStructure const *>(pNext->pNext)) {
866 switch (pNext->sType) {
867 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT:
868 pPresentMode = reinterpret_cast<VkSurfacePresentModeEXT const *>(pNext);
869 break;
Chris Forbes06bc0092017-03-16 16:46:05 +1300870
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000871 default:
872 break;
873 }
874 }
875
876 int err;
877 int width, height;
878 int transform_hint;
879 int max_buffer_count;
Trevor David Black1d3509e2023-06-08 00:17:40 +0000880 int min_undequeued_buffers;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000881 if (surface == VK_NULL_HANDLE) {
882 const InstanceData& instance_data = GetData(physicalDevice);
883 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
884 bool surfaceless_enabled =
885 instance_data.hook_extensions.test(surfaceless);
886 if (!surfaceless_enabled) {
887 // It is an error to pass a surface==VK_NULL_HANDLE unless the
888 // VK_GOOGLE_surfaceless_query extension is enabled
889 return VK_ERROR_SURFACE_LOST_KHR;
890 }
891 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
892 // extension for this function is for
893 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
894 // four values cannot be known without a surface. Default values will
895 // be supplied anyway, but cannot be relied upon.
896 width = 0xFFFFFFFF;
897 height = 0xFFFFFFFF;
898 transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
899 capabilities->minImageCount = 0xFFFFFFFF;
900 capabilities->maxImageCount = 0xFFFFFFFF;
901 } else {
902 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
903
904 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
905 if (err != android::OK) {
906 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
907 strerror(-err), err);
908 return VK_ERROR_SURFACE_LOST_KHR;
909 }
910 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
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
917 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
918 &transform_hint);
919 if (err != android::OK) {
920 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
921 strerror(-err), err);
922 return VK_ERROR_SURFACE_LOST_KHR;
923 }
924
925 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
926 &max_buffer_count);
927 if (err != android::OK) {
928 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
929 strerror(-err), err);
930 return VK_ERROR_SURFACE_LOST_KHR;
931 }
932
Trevor David Black1d3509e2023-06-08 00:17:40 +0000933 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
934 &min_undequeued_buffers);
935 if (err != android::OK) {
936 ALOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d)",
937 strerror(-err), err);
938 return VK_ERROR_SURFACE_LOST_KHR;
939 }
940
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000941 if (pPresentMode && IsSharedPresentMode(pPresentMode->presentMode)) {
942 capabilities->minImageCount = 1;
943 capabilities->maxImageCount = 1;
944 } else if (pPresentMode && pPresentMode->presentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
Trevor David Black1d3509e2023-06-08 00:17:40 +0000945 capabilities->minImageCount =
946 std::min(max_buffer_count, min_undequeued_buffers + 2);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000947 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
948 } else {
Trevor David Black1d3509e2023-06-08 00:17:40 +0000949 capabilities->minImageCount =
950 std::min(max_buffer_count, min_undequeued_buffers + 1);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000951 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
952 }
953 }
954
955 capabilities->currentExtent =
956 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
957
958 // TODO(http://b/134182502): Figure out what the max extent should be.
959 capabilities->minImageExtent = VkExtent2D{1, 1};
960 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
961
962 if (capabilities->maxImageExtent.height <
963 capabilities->currentExtent.height) {
964 capabilities->maxImageExtent.height =
965 capabilities->currentExtent.height;
966 }
967
968 if (capabilities->maxImageExtent.width <
969 capabilities->currentExtent.width) {
970 capabilities->maxImageExtent.width = capabilities->currentExtent.width;
971 }
972
973 capabilities->maxImageArrayLayers = 1;
974
975 capabilities->supportedTransforms = kSupportedTransforms;
976 capabilities->currentTransform =
977 TranslateNativeToVulkanTransform(transform_hint);
978
979 // On Android, window composition is a WindowManager property, not something
980 // associated with the bufferqueue. It can't be changed from here.
981 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
982
983 capabilities->supportedUsageFlags =
984 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
985 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
986 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
987 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
988
989 for (auto pNext = reinterpret_cast<VkBaseOutStructure*>(pSurfaceCapabilities->pNext);
990 pNext; pNext = reinterpret_cast<VkBaseOutStructure*>(pNext->pNext)) {
991
992 switch (pNext->sType) {
Chris Forbes06bc0092017-03-16 16:46:05 +1300993 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
994 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000995 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(pNext);
Chris Forbes06bc0092017-03-16 16:46:05 +1300996 // Claim same set of usage flags are supported for
997 // shared present modes as for other modes.
998 shared_caps->sharedPresentSupportedUsageFlags =
999 pSurfaceCapabilities->surfaceCapabilities
1000 .supportedUsageFlags;
1001 } break;
1002
Ian Elliottbb67b242022-03-16 09:52:28 -06001003 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
1004 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001005 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(pNext);
Ian Elliottbb67b242022-03-16 09:52:28 -06001006 protected_caps->supportsProtected = VK_TRUE;
1007 } break;
1008
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001009 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_SCALING_CAPABILITIES_EXT: {
1010 VkSurfacePresentScalingCapabilitiesEXT* scaling_caps =
1011 reinterpret_cast<VkSurfacePresentScalingCapabilitiesEXT*>(pNext);
1012 // By default, Android stretches the buffer to fit the window,
1013 // without preserving aspect ratio. Other modes are technically possible
1014 // but consult with CoGS team before exposing them here!
1015 scaling_caps->supportedPresentScaling = VK_PRESENT_SCALING_STRETCH_BIT_EXT;
1016
1017 // Since we always scale, we don't support any gravity.
1018 scaling_caps->supportedPresentGravityX = 0;
1019 scaling_caps->supportedPresentGravityY = 0;
1020
1021 // Scaled image limits are just the basic image limits
1022 scaling_caps->minScaledImageExtent = capabilities->minImageExtent;
1023 scaling_caps->maxScaledImageExtent = capabilities->maxImageExtent;
1024 } break;
1025
1026 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT: {
1027 VkSurfacePresentModeCompatibilityEXT* mode_caps =
1028 reinterpret_cast<VkSurfacePresentModeCompatibilityEXT*>(pNext);
1029
1030 ALOG_ASSERT(pPresentMode,
1031 "querying VkSurfacePresentModeCompatibilityEXT "
1032 "requires VkSurfacePresentModeEXT to be provided");
1033 std::vector<VkPresentModeKHR> compatibleModes;
1034 compatibleModes.push_back(pPresentMode->presentMode);
1035
1036 switch (pPresentMode->presentMode) {
1037 // Shared modes are both compatible with each other.
1038 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
1039 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
1040 break;
1041 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
1042 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1043 break;
1044 default:
1045 // Other modes are only compatible with themselves.
1046 // TODO: consider whether switching between FIFO and MAILBOX is reasonable
1047 break;
1048 }
1049
1050 // Note: this does not generate VK_INCOMPLETE since we're nested inside
1051 // a larger query and there would be no way to determine exactly where it came from.
1052 CopyWithIncomplete(compatibleModes, mode_caps->pPresentModes,
1053 &mode_caps->presentModeCount);
1054 } break;
1055
Chris Forbes06bc0092017-03-16 16:46:05 +13001056 default:
1057 // Ignore all other extension structs
1058 break;
1059 }
1060 }
1061
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001062 return VK_SUCCESS;
Chris Forbes2452cf72017-03-16 16:30:17 +13001063}
1064
1065VKAPI_ATTR
1066VkResult GetPhysicalDeviceSurfaceFormats2KHR(
1067 VkPhysicalDevice physicalDevice,
1068 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
1069 uint32_t* pSurfaceFormatCount,
1070 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001071 ATRACE_CALL();
1072
Chris Forbes2452cf72017-03-16 16:30:17 +13001073 if (!pSurfaceFormats) {
1074 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
1075 pSurfaceInfo->surface,
1076 pSurfaceFormatCount, nullptr);
Trevor David Black929e9cd2022-11-22 04:12:19 +00001077 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001078
Trevor David Black929e9cd2022-11-22 04:12:19 +00001079 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
1080 // after the call.
1081 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
1082 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
1083 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
1084 surface_formats.data());
Trevor David Black2cc44682022-03-09 00:31:38 +00001085
Trevor David Black929e9cd2022-11-22 04:12:19 +00001086 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
1087 return result;
1088 }
Trevor David Black2cc44682022-03-09 00:31:38 +00001089
Trevor David Black929e9cd2022-11-22 04:12:19 +00001090 const auto& driver = GetData(physicalDevice).driver;
1091
1092 // marshal results individually due to stride difference.
1093 uint32_t formats_to_marshal = *pSurfaceFormatCount;
1094 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
1095 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
1096
1097 // Query the compression properties for the surface format
1098 VkSurfaceFormat2KHR* pSurfaceFormat = &pSurfaceFormats[i];
1099 while (pSurfaceFormat->pNext) {
1100 pSurfaceFormat =
1101 reinterpret_cast<VkSurfaceFormat2KHR*>(pSurfaceFormat->pNext);
1102 switch (pSurfaceFormat->sType) {
1103 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT: {
Trevor David Black2cc44682022-03-09 00:31:38 +00001104 VkImageCompressionPropertiesEXT* surfaceCompressionProps =
1105 reinterpret_cast<VkImageCompressionPropertiesEXT*>(
Trevor David Black929e9cd2022-11-22 04:12:19 +00001106 pSurfaceFormat);
Trevor David Black2cc44682022-03-09 00:31:38 +00001107
1108 if (surfaceCompressionProps &&
1109 driver.GetPhysicalDeviceImageFormatProperties2KHR) {
1110 VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = {};
1111 imageFormatInfo.sType =
1112 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
1113 imageFormatInfo.format =
1114 pSurfaceFormats[i].surfaceFormat.format;
1115 imageFormatInfo.pNext = nullptr;
1116
1117 VkImageCompressionControlEXT compressionControl = {};
1118 compressionControl.sType =
1119 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT;
1120 compressionControl.pNext = imageFormatInfo.pNext;
1121
1122 imageFormatInfo.pNext = &compressionControl;
1123
1124 VkImageCompressionPropertiesEXT compressionProps = {};
1125 compressionProps.sType =
1126 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT;
1127 compressionProps.pNext = nullptr;
1128
1129 VkImageFormatProperties2KHR imageFormatProps = {};
1130 imageFormatProps.sType =
1131 VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
1132 imageFormatProps.pNext = &compressionProps;
1133
1134 VkResult compressionRes =
1135 driver.GetPhysicalDeviceImageFormatProperties2KHR(
1136 physicalDevice, &imageFormatInfo,
1137 &imageFormatProps);
1138 if (compressionRes == VK_SUCCESS) {
1139 surfaceCompressionProps->imageCompressionFlags =
1140 compressionProps.imageCompressionFlags;
1141 surfaceCompressionProps
1142 ->imageCompressionFixedRateFlags =
1143 compressionProps.imageCompressionFixedRateFlags;
1144 } else {
1145 return compressionRes;
1146 }
1147 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001148 } break;
1149
1150 default:
1151 // Ignore all other extension structs
1152 break;
Chris Forbes2452cf72017-03-16 16:30:17 +13001153 }
1154 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001155 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001156
1157 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +13001158}
1159
1160VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +13001161VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001162 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +08001163 uint32_t* count,
1164 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001165 ATRACE_CALL();
1166
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001167 int err;
1168 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -06001169 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -06001170 if (surface == VK_NULL_HANDLE) {
1171 const InstanceData& instance_data = GetData(pdev);
1172 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
1173 bool surfaceless_enabled =
1174 instance_data.hook_extensions.test(surfaceless);
1175 if (!surfaceless_enabled) {
1176 return VK_ERROR_SURFACE_LOST_KHR;
1177 }
1178 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
1179 // extension for this function is for
1180 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
1181 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
1182 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
Ian Elliott7e361142022-06-02 10:45:17 -06001183 // surface, and that cannot be relied upon. Therefore, don't return it.
Ian Elliott1ce053f2022-03-16 09:49:53 -06001184 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1185 } else {
1186 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1187
1188 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1189 &query_value);
1190 if (err != android::OK || query_value < 0) {
1191 ALOGE(
1192 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
1193 "value=%d",
1194 strerror(-err), err, query_value);
1195 return VK_ERROR_SURFACE_LOST_KHR;
1196 }
1197 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1198
1199 err =
1200 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
1201 if (err != android::OK || query_value < 0) {
1202 ALOGE(
1203 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
1204 strerror(-err), err, query_value);
1205 return VK_ERROR_SURFACE_LOST_KHR;
1206 }
1207 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
1208
1209 if (min_undequeued_buffers + 1 < max_buffer_count)
1210 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
1211 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1212 }
Chris Forbese8d79a62017-02-22 12:49:18 +13001213
1214 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -07001215 QueryPresentationProperties(pdev, &present_properties);
1216 if (present_properties.sharedImage) {
1217 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1218 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +13001219 }
1220
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001221 return CopyWithIncomplete(present_modes, modes, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001222}
1223
Jesse Halle1b12782015-11-30 11:27:32 -08001224VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001225VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001226 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001227 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001228 ATRACE_CALL();
1229
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001230 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
1231 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1232 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1233 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1234 pDeviceGroupPresentCapabilities->sType);
1235
1236 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1237 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1238
1239 // assume device group of size 1
1240 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1241 pDeviceGroupPresentCapabilities->modes =
1242 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1243
1244 return VK_SUCCESS;
1245}
1246
1247VKAPI_ATTR
1248VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001249 VkDevice,
1250 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001251 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001252 ATRACE_CALL();
1253
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001254 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1255 return VK_SUCCESS;
1256}
1257
1258VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001259VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001260 VkSurfaceKHR surface,
1261 uint32_t* pRectCount,
1262 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001263 ATRACE_CALL();
1264
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001265 if (!pRects) {
1266 *pRectCount = 1;
1267 } else {
1268 uint32_t count = std::min(*pRectCount, 1u);
1269 bool incomplete = *pRectCount < 1;
1270
1271 *pRectCount = count;
1272
1273 if (incomplete) {
1274 return VK_INCOMPLETE;
1275 }
1276
1277 int err;
1278 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1279
1280 int width = 0, height = 0;
1281 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001282 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001283 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1284 strerror(-err), err);
1285 }
1286 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001287 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001288 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1289 strerror(-err), err);
1290 }
1291
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001292 pRects[0].offset.x = 0;
1293 pRects[0].offset.y = 0;
1294 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1295 static_cast<uint32_t>(height)};
1296 }
1297 return VK_SUCCESS;
1298}
1299
Yiwei Zhang533cea92019-06-03 18:43:24 -07001300static void DestroySwapchainInternal(VkDevice device,
1301 VkSwapchainKHR swapchain_handle,
1302 const VkAllocationCallbacks* allocator) {
1303 ATRACE_CALL();
1304
1305 const auto& dispatch = GetData(device).driver;
1306 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1307 if (!swapchain) {
1308 return;
1309 }
1310
1311 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1312 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1313
1314 if (window && swapchain->frame_timestamps_enabled) {
1315 native_window_enable_frame_timestamps(window, false);
1316 }
1317
1318 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +00001319 ReleaseSwapchainImage(device, swapchain->shared, window, -1,
1320 swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001321 }
1322
1323 if (active) {
1324 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1325 }
1326
1327 if (!allocator) {
1328 allocator = &GetData(device).allocator;
1329 }
1330
1331 swapchain->~Swapchain();
1332 allocator->pfnFree(allocator->pUserData, swapchain);
1333}
1334
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001335VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001336VkResult CreateSwapchainKHR(VkDevice device,
1337 const VkSwapchainCreateInfoKHR* create_info,
1338 const VkAllocationCallbacks* allocator,
1339 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001340 ATRACE_CALL();
1341
Jesse Halld7b994a2015-09-07 14:17:37 -07001342 int err;
1343 VkResult result = VK_SUCCESS;
1344
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001345 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1346 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1347 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1348 " oldSwapchain=0x%" PRIx64,
1349 reinterpret_cast<uint64_t>(create_info->surface),
1350 create_info->minImageCount, create_info->imageFormat,
1351 create_info->imageColorSpace, create_info->imageExtent.width,
1352 create_info->imageExtent.height, create_info->imageUsage,
1353 create_info->preTransform, create_info->presentMode,
1354 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1355
Jesse Hall1f91d392015-12-11 16:28:44 -08001356 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001357 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001358
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001359 android::PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001360 GetNativePixelFormat(create_info->imageFormat);
1361 android_dataspace native_dataspace =
1362 GetNativeDataspace(create_info->imageColorSpace);
1363 if (native_dataspace == HAL_DATASPACE_UNKNOWN) {
1364 ALOGE(
1365 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1366 "failed: Unsupported color space",
1367 create_info->imageColorSpace);
1368 return VK_ERROR_INITIALIZATION_FAILED;
1369 }
1370
Jesse Hall42a9eec2016-06-03 12:39:49 -07001371 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001372 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001373 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001374 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001375 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001376 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001377 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001378 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001379 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1380 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001381 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001382 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001383
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001384 Surface& surface = *SurfaceFromHandle(create_info->surface);
1385
Jesse Halldc225072016-05-30 22:40:14 -07001386 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001387 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001388 " because it already has active swapchain 0x%" PRIx64
1389 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1390 reinterpret_cast<uint64_t>(create_info->surface),
1391 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1392 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1393 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1394 }
1395 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1396 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1397
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001398 // -- Reset the native window --
1399 // The native window might have been used previously, and had its properties
1400 // changed from defaults. That will affect the answer we get for queries
1401 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1402 // attempt such queries.
1403
Jesse Halldc225072016-05-30 22:40:14 -07001404 // The native window only allows dequeueing all buffers before any have
1405 // been queued, since after that point at least one is assumed to be in
1406 // non-FREE state at any given time. Disconnecting and re-connecting
1407 // orphans the previous buffers, getting us back to the state where we can
1408 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001409 //
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001410 // This is not necessary if the surface was never used previously.
1411 //
Yiwei Zhang70a21962019-05-31 17:26:52 -07001412 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001413 ANativeWindow* window = surface.window.get();
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001414 if (surface.used_by_swapchain) {
1415 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1416 ALOGW_IF(err != android::OK,
1417 "native_window_api_disconnect failed: %s (%d)", strerror(-err),
1418 err);
1419 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1420 ALOGW_IF(err != android::OK,
1421 "native_window_api_connect failed: %s (%d)", strerror(-err),
1422 err);
1423 }
Jesse Halldc225072016-05-30 22:40:14 -07001424
Nicolas Capens147b7da2021-04-09 14:53:06 -04001425 err =
1426 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001427 if (err != android::OK) {
1428 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1429 strerror(-err), err);
1430 return VK_ERROR_SURFACE_LOST_KHR;
1431 }
1432
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301433 int swap_interval =
1434 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001435 err = window->setSwapInterval(window, swap_interval);
1436 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001437 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1438 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001439 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001440 }
1441
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001442 err = native_window_set_shared_buffer_mode(window, false);
1443 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001444 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1445 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001446 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001447 }
1448
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001449 err = native_window_set_auto_refresh(window, false);
1450 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001451 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1452 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001453 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001454 }
1455
Jesse Halld7b994a2015-09-07 14:17:37 -07001456 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001457
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001458 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001459
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001460 err = native_window_set_buffers_format(window, native_pixel_format);
1461 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001462 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
1463 decodePixelFormat(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001464 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001465 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001466
1467 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
1468 if (native_dataspace != HAL_DATASPACE_ARBITRARY) {
1469 err = native_window_set_buffers_data_space(window, native_dataspace);
1470 if (err != android::OK) {
1471 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1472 native_dataspace, strerror(-err), err);
1473 return VK_ERROR_SURFACE_LOST_KHR;
1474 }
Jesse Hall517274a2016-02-10 00:07:18 -08001475 }
1476
Jesse Hall3dd678a2016-01-08 21:52:01 -08001477 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001478 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001479 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001480 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001481 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1482 create_info->imageExtent.width, create_info->imageExtent.height,
1483 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001484 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001485 }
1486
Jesse Hall178b6962016-02-24 15:39:50 -08001487 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1488 // applied during rendering. native_window_set_transform() expects the
1489 // inverse: the transform the app is requesting that the compositor perform
1490 // during composition. With native windows, pre-transform works by rendering
1491 // with the same transform the compositor is applying (as in Vulkan), but
1492 // then requesting the inverse transform, so that when the compositor does
1493 // it's job the two transforms cancel each other out and the compositor ends
1494 // up applying an identity transform to the app's buffer.
1495 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001496 window, InvertTransformToNative(create_info->preTransform));
1497 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001498 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1499 InvertTransformToNative(create_info->preTransform),
1500 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001501 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001502 }
1503
Jesse Hallf64ca122015-11-03 16:11:10 -08001504 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001505 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1506 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001507 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1508 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001509 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001510 }
1511
Chris Forbes97ef4612017-03-30 19:37:50 +13001512 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001513 if (IsSharedPresentMode(create_info->presentMode)) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001514 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001515 err = native_window_set_shared_buffer_mode(window, true);
1516 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001517 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1518 return VK_ERROR_SURFACE_LOST_KHR;
1519 }
1520 }
1521
1522 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001523 err = native_window_set_auto_refresh(window, true);
1524 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001525 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1526 return VK_ERROR_SURFACE_LOST_KHR;
1527 }
1528 }
1529
Ian Elliott16c443c2021-11-30 17:10:32 -07001530 int query_value;
1531 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1532 &query_value);
1533 if (err != android::OK || query_value < 0) {
1534 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1535 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001536 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001537 }
Ian Elliott16c443c2021-11-30 17:10:32 -07001538 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1539 const auto mailbox_num_images = std::max(3u, create_info->minImageCount);
1540 const auto requested_images =
1541 swap_interval ? create_info->minImageCount : mailbox_num_images;
1542 uint32_t num_images = requested_images - 1 + min_undequeued_buffers;
Chris Forbes2c8fc752017-03-17 11:28:32 +13001543
Ian Elliott5396b702021-12-13 19:32:34 -07001544 // Lower layer insists that we have at least min_undequeued_buffers + 1
1545 // buffers. This is wasteful and we'd like to relax it in the shared case,
1546 // but not all the pieces are in place for that to work yet. Note we only
1547 // lie to the lower layer--we don't want to give the app back a swapchain
1548 // with extra images (which they can't actually use!).
1549 uint32_t min_buffer_count = min_undequeued_buffers + 1;
1550 err = native_window_set_buffer_count(
1551 window, std::max(min_buffer_count, num_images));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001552 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001553 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", num_images,
1554 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001555 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001556 }
1557
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001558 // In shared mode the num_images must be one regardless of how many
1559 // buffers were allocated for the buffer queue.
1560 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1561 num_images = 1;
1562 }
1563
Trevor David Black2cc44682022-03-09 00:31:38 +00001564 void* usage_info_pNext = nullptr;
1565 VkImageCompressionControlEXT image_compression = {};
John Reck97678d42022-08-23 11:24:51 -04001566 uint64_t native_usage = 0;
Trevor David Black2cc44682022-03-09 00:31:38 +00001567 if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
1568 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1569 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1570 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1571 gralloc_usage_info.format = create_info->imageFormat;
1572 gralloc_usage_info.imageUsage = create_info->imageUsage;
1573
1574 // Look through the pNext chain for an image compression control struct
1575 // if one is found AND the appropriate extensions are enabled,
1576 // append it to be the gralloc usage pNext chain
1577 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1578 while (create_infos->pNext) {
1579 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1580 create_infos->pNext);
1581 switch (create_infos->sType) {
1582 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1583 const VkImageCompressionControlEXT* compression_infos =
1584 reinterpret_cast<const VkImageCompressionControlEXT*>(
1585 create_infos);
1586 image_compression = *compression_infos;
1587 image_compression.pNext = nullptr;
1588 usage_info_pNext = &image_compression;
1589 } break;
1590
1591 default:
1592 // Ignore all other info structs
1593 break;
1594 }
1595 }
1596 gralloc_usage_info.pNext = usage_info_pNext;
1597
1598 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1599 device, &gralloc_usage_info, &native_usage);
1600 ATRACE_END();
1601 if (result != VK_SUCCESS) {
1602 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
1603 return VK_ERROR_SURFACE_LOST_KHR;
1604 }
1605 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
Jesse Halld1abd742017-02-09 21:45:51 -08001606 uint64_t consumer_usage, producer_usage;
Yiwei Zhang533cea92019-06-03 18:43:24 -07001607 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
Courtney Goeltzenleuchter894780b2017-04-03 16:11:30 -06001608 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1609 device, create_info->imageFormat, create_info->imageUsage,
1610 swapchain_image_usage, &consumer_usage, &producer_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001611 ATRACE_END();
Chris Forbes8c47dc92017-01-12 11:13:58 +13001612 if (result != VK_SUCCESS) {
1613 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001614 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbes8c47dc92017-01-12 11:13:58 +13001615 }
John Reck97678d42022-08-23 11:24:51 -04001616 native_usage =
Trevor David Black2cc44682022-03-09 00:31:38 +00001617 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
Chris Forbes8c47dc92017-01-12 11:13:58 +13001618 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001619 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
John Reck97678d42022-08-23 11:24:51 -04001620 int32_t legacy_usage = 0;
Jesse Hall1f91d392015-12-11 16:28:44 -08001621 result = dispatch.GetSwapchainGrallocUsageANDROID(
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001622 device, create_info->imageFormat, create_info->imageUsage,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001623 &legacy_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001624 ATRACE_END();
Jesse Hall70f93352015-11-04 09:41:31 -08001625 if (result != VK_SUCCESS) {
1626 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001627 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001628 }
John Reck97678d42022-08-23 11:24:51 -04001629 native_usage = static_cast<uint64_t>(legacy_usage);
Jesse Hall70f93352015-11-04 09:41:31 -08001630 }
John Reck97678d42022-08-23 11:24:51 -04001631 native_usage |= surface.consumer_usage;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001632
1633 bool createProtectedSwapchain = false;
1634 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
1635 createProtectedSwapchain = true;
1636 native_usage |= BufferUsage::PROTECTED;
1637 }
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001638 err = native_window_set_usage(window, native_usage);
1639 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001640 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001641 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001642 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001643
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001644 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001645 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1646 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001647 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1648 strerror(-err), err);
1649 return VK_ERROR_SURFACE_LOST_KHR;
1650 }
1651
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001652 int64_t refresh_duration;
1653 err = native_window_get_refresh_cycle_duration(window, &refresh_duration);
1654 if (err != android::OK) {
1655 ALOGE("native_window_get_refresh_cycle_duration query failed: %s (%d)",
1656 strerror(-err), err);
1657 return VK_ERROR_SURFACE_LOST_KHR;
1658 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001659 // -- Allocate our Swapchain object --
1660 // After this point, we must deallocate the swapchain on error.
1661
Jesse Hall1f91d392015-12-11 16:28:44 -08001662 void* mem = allocator->pfnAllocation(allocator->pUserData,
1663 sizeof(Swapchain), alignof(Swapchain),
1664 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001665 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001666 return VK_ERROR_OUT_OF_HOST_MEMORY;
silence_dogood73597592019-05-23 16:57:37 -07001667 Swapchain* swapchain = new (mem)
1668 Swapchain(surface, num_images, create_info->presentMode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001669 TranslateVulkanToNativeTransform(create_info->preTransform),
1670 refresh_duration);
Chris Forbesb56287a2017-01-12 14:28:58 +13001671 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1672#pragma clang diagnostic push
1673#pragma clang diagnostic ignored "-Wold-style-cast"
1674 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1675#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00001676 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13001677 .usage = swapchain_image_usage,
1678 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001679 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001680#pragma clang diagnostic push
1681#pragma clang diagnostic ignored "-Wold-style-cast"
1682 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1683#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001684 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001685 };
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001686
Jesse Halld7b994a2015-09-07 14:17:37 -07001687 VkImageCreateInfo image_create = {
1688 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001689 .pNext = nullptr,
Nick Desaulnierse745a3e2019-10-18 10:38:45 -07001690 .flags = createProtectedSwapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07001691 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08001692 .format = create_info->imageFormat,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001693 .extent = {
1694 create_info->imageExtent.width,
1695 create_info->imageExtent.height,
1696 1
1697 },
Jesse Halld7b994a2015-09-07 14:17:37 -07001698 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08001699 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08001700 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07001701 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001702 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001703 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08001704 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07001705 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1706 };
1707
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001708 // Note: don't do deferred allocation for shared present modes. There's only one buffer
1709 // involved so very little benefit.
1710 if ((create_info->flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT) &&
1711 !IsSharedPresentMode(create_info->presentMode)) {
1712 // Don't want to touch the underlying gralloc buffers yet;
1713 // instead just create unbound VkImages which will later be bound to memory inside
1714 // AcquireNextImage.
1715 VkImageSwapchainCreateInfoKHR image_swapchain_create = {
1716 .sType = VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR,
1717 .pNext = nullptr,
1718 .swapchain = HandleFromSwapchain(swapchain),
1719 };
1720 image_create.pNext = &image_swapchain_create;
Jesse Halld7b994a2015-09-07 14:17:37 -07001721
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001722 for (uint32_t i = 0; i < num_images; i++) {
1723 Swapchain::Image& img = swapchain->images[i];
1724 img.buffer = nullptr;
1725 img.dequeued = false;
1726
1727 result = dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1728 if (result != VK_SUCCESS) {
1729 ALOGD("vkCreateImage w/ for deferred swapchain image failed: %u", result);
1730 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08001731 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001732 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001733 } else {
1734 // -- Dequeue all buffers and create a VkImage for each --
1735 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07001736
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001737 for (uint32_t i = 0; i < num_images; i++) {
1738 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07001739
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001740 ANativeWindowBuffer* buffer;
1741 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
1742 if (err != android::OK) {
1743 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
1744 switch (-err) {
1745 case ENOMEM:
1746 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
1747 break;
1748 default:
1749 result = VK_ERROR_SURFACE_LOST_KHR;
1750 break;
1751 }
1752 break;
1753 }
1754 img.buffer = buffer;
1755 img.dequeued = true;
1756
1757 image_native_buffer.handle = img.buffer->handle;
1758 image_native_buffer.stride = img.buffer->stride;
1759 image_native_buffer.format = img.buffer->format;
1760 image_native_buffer.usage = int(img.buffer->usage);
1761 android_convertGralloc0To1Usage(int(img.buffer->usage),
1762 &image_native_buffer.usage2.producer,
1763 &image_native_buffer.usage2.consumer);
1764 image_native_buffer.usage3 = img.buffer->usage;
1765 image_create.pNext = &image_native_buffer;
1766
1767 ATRACE_BEGIN("CreateImage");
1768 result =
1769 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1770 ATRACE_END();
1771 if (result != VK_SUCCESS) {
1772 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
1773 break;
1774 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001775 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001776
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001777 // -- Cancel all buffers, returning them to the queue --
1778 // If an error occurred before, also destroy the VkImage and release the
1779 // buffer reference. Otherwise, we retain a strong reference to the buffer.
1780 for (uint32_t i = 0; i < num_images; i++) {
1781 Swapchain::Image& img = swapchain->images[i];
1782 if (img.dequeued) {
1783 if (!swapchain->shared) {
1784 window->cancelBuffer(window, img.buffer.get(),
1785 img.dequeue_fence);
1786 img.dequeue_fence = -1;
1787 img.dequeued = false;
1788 }
Chris Forbese0ced032017-03-30 19:44:15 +13001789 }
Chris Forbes31b85c22018-05-29 15:03:28 -07001790 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001791 }
1792
1793 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001794 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
1795 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07001796 return result;
1797 }
1798
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001799 if (transform_hint != swapchain->pre_transform) {
1800 // Log that the app is not doing pre-rotation.
1801 android::GraphicsEnv::getInstance().setTargetStats(
1802 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
1803 }
1804
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00001805 // Set stats for creating a Vulkan swapchain
1806 android::GraphicsEnv::getInstance().setTargetStats(
1807 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
1808
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001809 surface.used_by_swapchain = true;
Jesse Halldc225072016-05-30 22:40:14 -07001810 surface.swapchain_handle = HandleFromSwapchain(swapchain);
1811 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001812 return VK_SUCCESS;
1813}
1814
Jesse Halle1b12782015-11-30 11:27:32 -08001815VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001816void DestroySwapchainKHR(VkDevice device,
1817 VkSwapchainKHR swapchain_handle,
1818 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001819 ATRACE_CALL();
1820
Yiwei Zhang533cea92019-06-03 18:43:24 -07001821 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001822}
1823
Jesse Halle1b12782015-11-30 11:27:32 -08001824VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001825VkResult GetSwapchainImagesKHR(VkDevice,
1826 VkSwapchainKHR swapchain_handle,
1827 uint32_t* count,
1828 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001829 ATRACE_CALL();
1830
Jesse Halld7b994a2015-09-07 14:17:37 -07001831 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07001832 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
1833 "getting images for non-active swapchain 0x%" PRIx64
1834 "; only dequeued image handles are valid",
1835 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07001836 VkResult result = VK_SUCCESS;
1837 if (images) {
1838 uint32_t n = swapchain.num_images;
1839 if (*count < swapchain.num_images) {
1840 n = *count;
1841 result = VK_INCOMPLETE;
1842 }
1843 for (uint32_t i = 0; i < n; i++)
1844 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07001845 *count = n;
1846 } else {
1847 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07001848 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001849 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001850}
1851
Jesse Halle1b12782015-11-30 11:27:32 -08001852VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001853VkResult AcquireNextImageKHR(VkDevice device,
1854 VkSwapchainKHR swapchain_handle,
1855 uint64_t timeout,
1856 VkSemaphore semaphore,
1857 VkFence vk_fence,
1858 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001859 ATRACE_CALL();
1860
Jesse Halld7b994a2015-09-07 14:17:37 -07001861 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001862 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07001863 VkResult result;
1864 int err;
1865
Jesse Halldc225072016-05-30 22:40:14 -07001866 if (swapchain.surface.swapchain_handle != swapchain_handle)
1867 return VK_ERROR_OUT_OF_DATE_KHR;
1868
Chris Forbesc88409c2017-03-30 19:47:37 +13001869 if (swapchain.shared) {
1870 // In shared mode, we keep the buffer dequeued all the time, so we don't
1871 // want to dequeue a buffer here. Instead, just ask the driver to ensure
1872 // the semaphore and fence passed to us will be signalled.
1873 *image_index = 0;
1874 result = GetData(device).driver.AcquireImageANDROID(
1875 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
1876 return result;
1877 }
1878
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001879 const nsecs_t acquire_next_image_timeout =
1880 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
1881 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
1882 // Cache the timeout to avoid the duplicate binder cost.
1883 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
1884 acquire_next_image_timeout);
1885 if (err != android::OK) {
1886 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1887 strerror(-err), err);
1888 return VK_ERROR_SURFACE_LOST_KHR;
1889 }
1890 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
1891 }
1892
Jesse Halld7b994a2015-09-07 14:17:37 -07001893 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08001894 int fence_fd;
1895 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07001896 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001897 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
1898 return timeout ? VK_TIMEOUT : VK_NOT_READY;
1899 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001900 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001901 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001902 }
1903
1904 uint32_t idx;
1905 for (idx = 0; idx < swapchain.num_images; idx++) {
1906 if (swapchain.images[idx].buffer.get() == buffer) {
1907 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08001908 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07001909 break;
1910 }
1911 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001912
1913 // If this is a deferred alloc swapchain, this may be the first time we've
1914 // seen a particular buffer. If so, there should be an empty slot. Find it,
1915 // and bind the gralloc buffer to the VkImage for that slot. If there is no
1916 // empty slot, then we dequeued an unexpected buffer. Non-deferred swapchains
1917 // will also take this path, but will never have an empty slot since we
1918 // populated them all upfront.
1919 if (idx == swapchain.num_images) {
1920 for (idx = 0; idx < swapchain.num_images; idx++) {
1921 if (!swapchain.images[idx].buffer) {
1922 // Note: this structure is technically required for
1923 // Vulkan correctness, even though the driver is probably going
1924 // to use everything from the VkNativeBufferANDROID below.
1925 // This is kindof silly, but it's how we did the ANB
1926 // side of VK_KHR_swapchain v69, so we're stuck with it unless
1927 // we want to go tinkering with the ANB spec some more.
1928 VkBindImageMemorySwapchainInfoKHR bimsi = {
1929 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR,
1930 .pNext = nullptr,
1931 .swapchain = swapchain_handle,
1932 .imageIndex = idx,
1933 };
1934 VkNativeBufferANDROID nb = {
1935 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1936 .pNext = &bimsi,
1937 .handle = buffer->handle,
1938 .stride = buffer->stride,
1939 .format = buffer->format,
1940 .usage = int(buffer->usage),
1941 };
1942 VkBindImageMemoryInfo bimi = {
1943 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO,
1944 .pNext = &nb,
1945 .image = swapchain.images[idx].image,
1946 .memory = VK_NULL_HANDLE,
1947 .memoryOffset = 0,
1948 };
1949 result = GetData(device).driver.BindImageMemory2(device, 1, &bimi);
1950 if (result != VK_SUCCESS) {
1951 // This shouldn't really happen. If it does, something is probably
1952 // unrecoverably wrong with the swapchain and its images. Cancel
1953 // the buffer and declare the swapchain broken.
1954 ALOGE("failed to do deferred gralloc buffer bind");
1955 window->cancelBuffer(window, buffer, fence_fd);
1956 return VK_ERROR_OUT_OF_DATE_KHR;
1957 }
1958
1959 swapchain.images[idx].dequeued = true;
1960 swapchain.images[idx].dequeue_fence = fence_fd;
1961 swapchain.images[idx].buffer = buffer;
1962 break;
1963 }
1964 }
1965 }
1966
1967 // The buffer doesn't match any slot. This shouldn't normally happen, but is
1968 // possible if the bufferqueue is reconfigured behind libvulkan's back. If this
1969 // happens, just declare the swapchain to be broken and the app will recreate it.
Jesse Halld7b994a2015-09-07 14:17:37 -07001970 if (idx == swapchain.num_images) {
1971 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08001972 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001973 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001974 }
1975
1976 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08001977 if (fence_fd != -1) {
1978 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001979 if (fence_clone == -1) {
1980 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
1981 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08001982 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07001983 }
1984 }
1985
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001986 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08001987 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001988 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001989 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
1990 // even if the call fails. We could close it ourselves on failure, but
1991 // that would create a race condition if the driver closes it on a
1992 // failure path: some other thread might create an fd with the same
1993 // number between the time the driver closes it and the time we close
1994 // it. We must assume one of: the driver *always* closes it even on
1995 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08001996 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001997 swapchain.images[idx].dequeued = false;
1998 swapchain.images[idx].dequeue_fence = -1;
1999 return result;
2000 }
2001
2002 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002003 return VK_SUCCESS;
2004}
2005
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002006VKAPI_ATTR
2007VkResult AcquireNextImage2KHR(VkDevice device,
2008 const VkAcquireNextImageInfoKHR* pAcquireInfo,
2009 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002010 ATRACE_CALL();
2011
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002012 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
2013 pAcquireInfo->timeout, pAcquireInfo->semaphore,
2014 pAcquireInfo->fence, pImageIndex);
2015}
2016
Jesse Halldc225072016-05-30 22:40:14 -07002017static VkResult WorstPresentResult(VkResult a, VkResult b) {
2018 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
2019 // (in spec version 1.0.14).
2020 static const VkResult kWorstToBest[] = {
2021 VK_ERROR_DEVICE_LOST,
2022 VK_ERROR_SURFACE_LOST_KHR,
2023 VK_ERROR_OUT_OF_DATE_KHR,
2024 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2025 VK_ERROR_OUT_OF_HOST_MEMORY,
2026 VK_SUBOPTIMAL_KHR,
2027 };
2028 for (auto result : kWorstToBest) {
2029 if (a == result || b == result)
2030 return result;
2031 }
2032 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
2033 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
2034 return a != VK_SUCCESS ? a : b;
2035}
2036
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002037// KHR_incremental_present aspect of QueuePresentKHR
2038static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
2039 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
2040 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
2041 auto const& rect = pRegion->pRectangles[i];
2042 if (rect.layer > 0) {
2043 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
2044 rect.layer);
2045 }
2046
2047 rects[i].left = rect.offset.x;
2048 rects[i].bottom = rect.offset.y;
2049 rects[i].right = rect.offset.x + rect.extent.width;
2050 rects[i].top = rect.offset.y + rect.extent.height;
2051 }
2052 native_window_set_surface_damage(window, rects.data(), rects.size());
2053}
2054
2055// GOOGLE_display_timing aspect of QueuePresentKHR
2056static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
2057 ANativeWindow *window = swapchain.surface.window.get();
2058
2059 // We don't know whether the app will actually use GOOGLE_display_timing
2060 // with a particular swapchain until QueuePresent; enable it on the BQ
2061 // now if needed
2062 if (!swapchain.frame_timestamps_enabled) {
2063 ALOGV("Calling native_window_enable_frame_timestamps(true)");
2064 native_window_enable_frame_timestamps(window, true);
2065 swapchain.frame_timestamps_enabled = true;
2066 }
2067
2068 // Record the nativeFrameId so it can be later correlated to
2069 // this present.
2070 uint64_t nativeFrameId = 0;
2071 int err = native_window_get_next_frame_id(
2072 window, &nativeFrameId);
2073 if (err != android::OK) {
2074 ALOGE("Failed to get next native frame ID.");
2075 }
2076
2077 // Add a new timing record with the user's presentID and
2078 // the nativeFrameId.
2079 swapchain.timing.emplace_back(pTime, nativeFrameId);
2080 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
2081 swapchain.timing.erase(
2082 swapchain.timing.begin(),
2083 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
2084 }
2085 if (pTime->desiredPresentTime) {
2086 ALOGV(
2087 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
2088 pTime->desiredPresentTime);
2089 native_window_set_buffers_timestamp(
2090 window,
2091 static_cast<int64_t>(pTime->desiredPresentTime));
2092 }
2093}
2094
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002095// EXT_swapchain_maintenance1 present mode change
2096static bool SetSwapchainPresentMode(ANativeWindow *window, VkPresentModeKHR mode) {
2097 // There is no dynamic switching between non-shared present modes.
2098 // All we support is switching between demand and continuous refresh.
2099 if (!IsSharedPresentMode(mode))
2100 return true;
2101
2102 int err = native_window_set_auto_refresh(window,
2103 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
2104 if (err != android::OK) {
2105 ALOGE("native_window_set_auto_refresh() failed: %s (%d)",
2106 strerror(-err), err);
2107 return false;
2108 }
2109
2110 return true;
2111}
2112
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002113static VkResult PresentOneSwapchain(
2114 VkQueue queue,
2115 Swapchain& swapchain,
2116 uint32_t imageIndex,
2117 const VkPresentRegionKHR *pRegion,
2118 const VkPresentTimeGOOGLE *pTime,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002119 VkFence presentFence,
2120 const VkPresentModeKHR *pPresentMode,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002121 uint32_t waitSemaphoreCount,
2122 const VkSemaphore *pWaitSemaphores) {
2123
2124 VkDevice device = GetData(queue).driver_device;
2125 const auto& dispatch = GetData(queue).driver;
2126
2127 Swapchain::Image& img = swapchain.images[imageIndex];
2128 VkResult swapchain_result = VK_SUCCESS;
2129 VkResult result;
2130 int err;
2131
2132 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
2133 // wait semaphores, so this doesn't actually work for the multiple swapchain
2134 // case.
2135 int fence = -1;
2136 result = dispatch.QueueSignalReleaseImageANDROID(
2137 queue, waitSemaphoreCount,
2138 pWaitSemaphores, img.image, &fence);
2139 if (result != VK_SUCCESS) {
2140 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
2141 swapchain_result = result;
2142 }
2143 if (img.release_fence >= 0)
2144 close(img.release_fence);
2145 img.release_fence = fence < 0 ? -1 : dup(fence);
2146
2147 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
2148 ANativeWindow* window = swapchain.surface.window.get();
2149 if (swapchain_result == VK_SUCCESS) {
2150
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002151 if (presentFence != VK_NULL_HANDLE) {
2152 int fence_copy = fence < 0 ? -1 : dup(fence);
2153 VkImportFenceFdInfoKHR iffi = {
2154 VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,
2155 nullptr,
2156 presentFence,
2157 VK_FENCE_IMPORT_TEMPORARY_BIT,
2158 VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,
2159 fence_copy,
2160 };
2161 if (VK_SUCCESS != dispatch.ImportFenceFdKHR(device, &iffi) && fence_copy >= 0) {
2162 // ImportFenceFdKHR takes ownership only if it succeeds
2163 close(fence_copy);
2164 }
2165 }
2166
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002167 if (pRegion) {
2168 SetSwapchainSurfaceDamage(window, pRegion);
2169 }
2170 if (pTime) {
2171 SetSwapchainFrameTimestamp(swapchain, pTime);
2172 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002173 if (pPresentMode) {
2174 if (!SetSwapchainPresentMode(window, *pPresentMode))
2175 swapchain_result = WorstPresentResult(swapchain_result,
2176 VK_ERROR_SURFACE_LOST_KHR);
2177 }
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002178
2179 err = window->queueBuffer(window, img.buffer.get(), fence);
2180 // queueBuffer always closes fence, even on error
2181 if (err != android::OK) {
2182 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
2183 swapchain_result = WorstPresentResult(
2184 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2185 } else {
2186 if (img.dequeue_fence >= 0) {
2187 close(img.dequeue_fence);
2188 img.dequeue_fence = -1;
2189 }
2190 img.dequeued = false;
2191 }
2192
2193 // If the swapchain is in shared mode, immediately dequeue the
2194 // buffer so it can be presented again without an intervening
2195 // call to AcquireNextImageKHR. We expect to get the same buffer
2196 // back from every call to dequeueBuffer in this mode.
2197 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
2198 ANativeWindowBuffer* buffer;
2199 int fence_fd;
2200 err = window->dequeueBuffer(window, &buffer, &fence_fd);
2201 if (err != android::OK) {
2202 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
2203 swapchain_result = WorstPresentResult(swapchain_result,
2204 VK_ERROR_SURFACE_LOST_KHR);
2205 } else if (img.buffer != buffer) {
2206 ALOGE("got wrong image back for shared swapchain");
2207 swapchain_result = WorstPresentResult(swapchain_result,
2208 VK_ERROR_SURFACE_LOST_KHR);
2209 } else {
2210 img.dequeue_fence = fence_fd;
2211 img.dequeued = true;
2212 }
2213 }
2214 }
2215 if (swapchain_result != VK_SUCCESS) {
2216 OrphanSwapchain(device, &swapchain);
2217 }
2218 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
2219 // and only when the window's transform/rotation changes. Extent
2220 // changes will not cause VK_SUBOPTIMAL_KHR because of the
2221 // application issues that were caused when the following transform
2222 // change was added.
2223 int window_transform_hint;
2224 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
2225 &window_transform_hint);
2226 if (err != android::OK) {
2227 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
2228 strerror(-err), err);
2229 swapchain_result = WorstPresentResult(
2230 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2231 }
2232 if (swapchain.pre_transform != window_transform_hint) {
2233 swapchain_result =
2234 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
2235 }
2236 } else {
2237 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
2238 img, true);
2239 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
2240 }
2241
2242 return swapchain_result;
2243}
2244
Jesse Halle1b12782015-11-30 11:27:32 -08002245VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002246VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002247 ATRACE_CALL();
2248
Jesse Halld7b994a2015-09-07 14:17:37 -07002249 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
2250 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
2251 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07002252
Jesse Halld7b994a2015-09-07 14:17:37 -07002253 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07002254
Ian Elliottcb351132016-12-13 10:30:40 -07002255 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002256 const VkPresentRegionsKHR* present_regions = nullptr;
2257 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002258 const VkSwapchainPresentFenceInfoEXT* present_fences = nullptr;
2259 const VkSwapchainPresentModeInfoEXT* present_modes = nullptr;
2260
Ian Elliottcb351132016-12-13 10:30:40 -07002261 const VkPresentRegionsKHR* next =
2262 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
2263 while (next) {
2264 switch (next->sType) {
2265 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
2266 present_regions = next;
2267 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07002268 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002269 present_times =
2270 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
2271 break;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002272 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT:
2273 present_fences =
2274 reinterpret_cast<const VkSwapchainPresentFenceInfoEXT*>(next);
2275 break;
2276 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT:
2277 present_modes =
2278 reinterpret_cast<const VkSwapchainPresentModeInfoEXT*>(next);
2279 break;
Ian Elliottcb351132016-12-13 10:30:40 -07002280 default:
2281 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
2282 next->sType);
2283 break;
2284 }
2285 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2286 }
2287 ALOGV_IF(
2288 present_regions &&
2289 present_regions->swapchainCount != present_info->swapchainCount,
2290 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002291 ALOGV_IF(present_times &&
2292 present_times->swapchainCount != present_info->swapchainCount,
2293 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2294 "VkPresentInfo::swapchainCount");
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002295 ALOGV_IF(present_fences &&
2296 present_fences->swapchainCount != present_info->swapchainCount,
2297 "VkSwapchainPresentFenceInfoEXT::swapchainCount != "
2298 "VkPresentInfo::swapchainCount");
2299 ALOGV_IF(present_modes &&
2300 present_modes->swapchainCount != present_info->swapchainCount,
2301 "VkSwapchainPresentModeInfoEXT::swapchainCount != "
2302 "VkPresentInfo::swapchainCount");
2303
Ian Elliottcb351132016-12-13 10:30:40 -07002304 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002305 (present_regions) ? present_regions->pRegions : nullptr;
2306 const VkPresentTimeGOOGLE* times =
2307 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002308
Jesse Halld7b994a2015-09-07 14:17:37 -07002309 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2310 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002311 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002312
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002313 VkResult swapchain_result = PresentOneSwapchain(
2314 queue,
2315 swapchain,
2316 present_info->pImageIndices[sc],
2317 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2318 times ? &times[sc] : nullptr,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002319 present_fences ? present_fences->pFences[sc] : VK_NULL_HANDLE,
2320 present_modes ? &present_modes->pPresentModes[sc] : nullptr,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002321 present_info->waitSemaphoreCount,
2322 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002323
Jesse Halla9e57032015-11-30 01:03:10 -08002324 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002325 present_info->pResults[sc] = swapchain_result;
2326
2327 if (swapchain_result != final_result)
2328 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002329 }
2330
2331 return final_result;
2332}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002333
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002334VKAPI_ATTR
2335VkResult GetRefreshCycleDurationGOOGLE(
2336 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002337 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002338 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002339 ATRACE_CALL();
2340
Ian Elliott62c48c92017-01-20 13:13:20 -07002341 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00002342 VkResult result = swapchain.get_refresh_duration(pDisplayTimingProperties->refreshDuration);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002343
2344 return result;
2345}
2346
2347VKAPI_ATTR
2348VkResult GetPastPresentationTimingGOOGLE(
2349 VkDevice,
2350 VkSwapchainKHR swapchain_handle,
2351 uint32_t* count,
2352 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002353 ATRACE_CALL();
2354
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002355 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002356 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2357 return VK_ERROR_OUT_OF_DATE_KHR;
2358 }
2359
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002360 ANativeWindow* window = swapchain.surface.window.get();
2361 VkResult result = VK_SUCCESS;
2362
2363 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002364 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002365 native_window_enable_frame_timestamps(window, true);
2366 swapchain.frame_timestamps_enabled = true;
2367 }
2368
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002369 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002370 // Get the latest ready timing count before copying, since the copied
2371 // timing info will be erased in copy_ready_timings function.
2372 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002373 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002374 // Check the *count here against the recorded ready timing count, since
2375 // *count can be overwritten per spec describes.
2376 if (*count < n) {
2377 result = VK_INCOMPLETE;
2378 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002379 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002380 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002381 }
2382
2383 return result;
2384}
2385
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002386VKAPI_ATTR
2387VkResult GetSwapchainStatusKHR(
2388 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002389 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002390 ATRACE_CALL();
2391
Chris Forbes4e18ba82017-01-20 12:50:17 +13002392 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002393 VkResult result = VK_SUCCESS;
2394
Chris Forbes4e18ba82017-01-20 12:50:17 +13002395 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2396 return VK_ERROR_OUT_OF_DATE_KHR;
2397 }
2398
Yiwei Zhanga885c062019-10-24 12:07:57 -07002399 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002400
2401 return result;
2402}
2403
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002404VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002405 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002406 uint32_t swapchainCount,
2407 const VkSwapchainKHR* pSwapchains,
2408 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002409 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002410
2411 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2412 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2413 if (!swapchain)
2414 continue;
2415
2416 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2417
2418 ANativeWindow* window = swapchain->surface.window.get();
2419
2420 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2421 const android_smpte2086_metadata smpteMetdata = {
2422 {vulkanMetadata.displayPrimaryRed.x,
2423 vulkanMetadata.displayPrimaryRed.y},
2424 {vulkanMetadata.displayPrimaryGreen.x,
2425 vulkanMetadata.displayPrimaryGreen.y},
2426 {vulkanMetadata.displayPrimaryBlue.x,
2427 vulkanMetadata.displayPrimaryBlue.y},
2428 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2429 vulkanMetadata.maxLuminance,
2430 vulkanMetadata.minLuminance};
2431 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2432
2433 const android_cta861_3_metadata cta8613Metadata = {
2434 vulkanMetadata.maxContentLightLevel,
2435 vulkanMetadata.maxFrameAverageLightLevel};
2436 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2437 }
2438
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002439 return;
2440}
2441
Yiwei Zhang0f475222019-04-11 19:38:00 -07002442static void InterceptBindImageMemory2(
2443 uint32_t bind_info_count,
2444 const VkBindImageMemoryInfo* bind_infos,
2445 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2446 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2447 out_native_buffers->clear();
2448 out_bind_infos->clear();
2449
2450 if (!bind_info_count)
2451 return;
2452
2453 std::unordered_set<uint32_t> intercepted_indexes;
2454
2455 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2456 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2457 bind_infos[idx].pNext);
2458 while (info &&
2459 info->sType !=
2460 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2461 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2462 info->pNext);
2463 }
2464
2465 if (!info)
2466 continue;
2467
2468 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2469 "swapchain handle must not be NULL");
2470 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2471 ALOG_ASSERT(
2472 info->imageIndex < swapchain->num_images,
2473 "imageIndex must be less than the number of images in swapchain");
2474
2475 ANativeWindowBuffer* buffer =
2476 swapchain->images[info->imageIndex].buffer.get();
2477 VkNativeBufferANDROID native_buffer = {
2478#pragma clang diagnostic push
2479#pragma clang diagnostic ignored "-Wold-style-cast"
2480 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2481#pragma clang diagnostic pop
2482 .pNext = bind_infos[idx].pNext,
2483 .handle = buffer->handle,
2484 .stride = buffer->stride,
2485 .format = buffer->format,
2486 .usage = int(buffer->usage),
2487 };
2488 // Reserve enough space to avoid letting re-allocation invalidate the
2489 // addresses of the elements inside.
2490 out_native_buffers->reserve(bind_info_count);
2491 out_native_buffers->emplace_back(native_buffer);
2492
2493 // Reserve the space now since we know how much is needed now.
2494 out_bind_infos->reserve(bind_info_count);
2495 out_bind_infos->emplace_back(bind_infos[idx]);
2496 out_bind_infos->back().pNext = &out_native_buffers->back();
2497
2498 intercepted_indexes.insert(idx);
2499 }
2500
2501 if (intercepted_indexes.empty())
2502 return;
2503
2504 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2505 if (intercepted_indexes.count(idx))
2506 continue;
2507 out_bind_infos->emplace_back(bind_infos[idx]);
2508 }
2509}
2510
Yiwei Zhang23143102019-04-10 18:24:05 -07002511VKAPI_ATTR
2512VkResult BindImageMemory2(VkDevice device,
2513 uint32_t bindInfoCount,
2514 const VkBindImageMemoryInfo* pBindInfos) {
2515 ATRACE_CALL();
2516
Yiwei Zhang0f475222019-04-11 19:38:00 -07002517 // out_native_buffers is for maintaining the lifecycle of the constructed
2518 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2519 std::vector<VkNativeBufferANDROID> out_native_buffers;
2520 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2521 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2522 &out_bind_infos);
2523 return GetData(device).driver.BindImageMemory2(
2524 device, bindInfoCount,
2525 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002526}
2527
2528VKAPI_ATTR
2529VkResult BindImageMemory2KHR(VkDevice device,
2530 uint32_t bindInfoCount,
2531 const VkBindImageMemoryInfo* pBindInfos) {
2532 ATRACE_CALL();
2533
Yiwei Zhang0f475222019-04-11 19:38:00 -07002534 std::vector<VkNativeBufferANDROID> out_native_buffers;
2535 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2536 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2537 &out_bind_infos);
2538 return GetData(device).driver.BindImageMemory2KHR(
2539 device, bindInfoCount,
2540 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002541}
2542
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002543VKAPI_ATTR
2544VkResult ReleaseSwapchainImagesEXT(VkDevice /*device*/,
2545 const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
2546 ATRACE_CALL();
2547
2548 Swapchain& swapchain = *SwapchainFromHandle(pReleaseInfo->swapchain);
2549 ANativeWindow* window = swapchain.surface.window.get();
2550
2551 // If in shared present mode, don't actually release the image back to the BQ.
2552 // Both sides share it forever.
2553 if (swapchain.shared)
2554 return VK_SUCCESS;
2555
2556 for (uint32_t i = 0; i < pReleaseInfo->imageIndexCount; i++) {
2557 Swapchain::Image& img = swapchain.images[pReleaseInfo->pImageIndices[i]];
2558 window->cancelBuffer(window, img.buffer.get(), img.dequeue_fence);
2559
2560 // cancelBuffer has taken ownership of the dequeue fence
2561 img.dequeue_fence = -1;
2562 // if we're still holding a release fence, get rid of it now
2563 if (img.release_fence >= 0) {
2564 close(img.release_fence);
2565 img.release_fence = -1;
2566 }
2567 img.dequeued = false;
2568 }
2569
2570 return VK_SUCCESS;
2571}
2572
Chia-I Wu62262232016-03-26 07:06:44 +08002573} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002574} // namespace vulkan