blob: 0df5e77181085bced5af789fb324fc646d4f5d12 [file] [log] [blame]
Jesse Hallb1352bc2015-09-04 16:12:33 -07001/*
2 * Copyright 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080017#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
sergiuferentz47989332023-09-26 10:24:36 +000019#include <aidl/android/hardware/graphics/common/Dataspace.h>
Trevor David Blackf499b5a2023-07-14 17:30:41 +000020#include <aidl/android/hardware/graphics/common/PixelFormat.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070021#include <android/hardware/graphics/common/1.0/types.h>
Trevor David Blackd7320ef2023-08-23 21:21:51 +000022#include <android/hardware_buffer.h>
Jesse Hall79927812017-03-23 11:03:23 -070023#include <grallocusage/GrallocUsageConversion.h>
Yiwei Zhang69395cd2019-07-03 16:55:39 -070024#include <graphicsenv/GraphicsEnv.h>
John Reck97678d42022-08-23 11:24:51 -040025#include <hardware/gralloc.h>
26#include <hardware/gralloc1.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070027#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070028#include <sync/sync.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070029#include <system/window.h>
30#include <ui/BufferQueueDefs.h>
Chia-I Wue8e689f2016-04-18 08:21:31 +080031#include <utils/StrongPointer.h>
Yiwei Zhang705c2e62019-12-18 23:12:43 -080032#include <utils/Timers.h>
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080033#include <utils/Trace.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070034
35#include <algorithm>
36#include <unordered_set>
37#include <vector>
Jesse Halld7b994a2015-09-07 14:17:37 -070038
Chia-I Wu4a6a9162016-03-26 07:17:34 +080039#include "driver.h"
Jesse Halld7b994a2015-09-07 14:17:37 -070040
Trevor David Blackf499b5a2023-07-14 17:30:41 +000041using PixelFormat = aidl::android::hardware::graphics::common::PixelFormat;
sergiuferentz47989332023-09-26 10:24:36 +000042using DataSpace = aidl::android::hardware::graphics::common::Dataspace;
Daniel Kochf25f5bb2017-10-05 00:26:58 -040043using android::hardware::graphics::common::V1_0::BufferUsage;
44
Chia-I Wu62262232016-03-26 07:06:44 +080045namespace vulkan {
46namespace driver {
Jesse Hall5ae3abb2015-10-08 14:00:22 -070047
Jesse Halld7b994a2015-09-07 14:17:37 -070048namespace {
49
John Reck97678d42022-08-23 11:24:51 -040050static uint64_t convertGralloc1ToBufferUsage(uint64_t producerUsage,
51 uint64_t consumerUsage) {
52 static_assert(uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) ==
53 uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN),
54 "expected ConsumerUsage and ProducerUsage CPU_READ_OFTEN "
55 "bits to match");
56 uint64_t merged = producerUsage | consumerUsage;
57 if ((merged & (GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN)) ==
58 GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) {
59 merged &= ~uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN);
60 merged |= BufferUsage::CPU_READ_OFTEN;
61 }
62 if ((merged & (GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN)) ==
63 GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) {
64 merged &= ~uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN);
65 merged |= BufferUsage::CPU_WRITE_OFTEN;
66 }
67 return merged;
68}
69
Jesse Hall55bc0972016-02-23 16:43:29 -080070const VkSurfaceTransformFlagsKHR kSupportedTransforms =
71 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
72 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
73 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
74 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
Yiwei Zhang70a21962019-05-31 17:26:52 -070075 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
76 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
77 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
78 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
Jesse Hall55bc0972016-02-23 16:43:29 -080079 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
80
81VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
82 // Native and Vulkan transforms are isomorphic, but are represented
83 // differently. Vulkan transforms are built up of an optional horizontal
84 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
85 // transforms are built up from a horizontal flip, vertical flip, and
86 // 90-degree rotation, all optional but always in that order.
87
Jesse Hall55bc0972016-02-23 16:43:29 -080088 switch (native) {
Yiwei Zhang70a21962019-05-31 17:26:52 -070089 case 0:
Jesse Hall55bc0972016-02-23 16:43:29 -080090 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070091 case NATIVE_WINDOW_TRANSFORM_FLIP_H:
92 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
93 case NATIVE_WINDOW_TRANSFORM_FLIP_V:
94 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
95 case NATIVE_WINDOW_TRANSFORM_ROT_180:
Jesse Hall55bc0972016-02-23 16:43:29 -080096 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070097 case NATIVE_WINDOW_TRANSFORM_ROT_90:
Jesse Hall55bc0972016-02-23 16:43:29 -080098 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070099 case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
100 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
101 case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
102 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
103 case NATIVE_WINDOW_TRANSFORM_ROT_270:
Jesse Hall55bc0972016-02-23 16:43:29 -0800104 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
105 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
106 default:
107 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
108 }
109}
110
Yiwei Zhang70a21962019-05-31 17:26:52 -0700111int TranslateVulkanToNativeTransform(VkSurfaceTransformFlagBitsKHR transform) {
112 switch (transform) {
113 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
114 return NATIVE_WINDOW_TRANSFORM_ROT_90;
115 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
116 return NATIVE_WINDOW_TRANSFORM_ROT_180;
117 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
118 return NATIVE_WINDOW_TRANSFORM_ROT_270;
119 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
120 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
121 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
122 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
123 NATIVE_WINDOW_TRANSFORM_ROT_90;
124 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
125 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
126 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
127 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
128 NATIVE_WINDOW_TRANSFORM_ROT_90;
129 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
130 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
131 default:
132 return 0;
133 }
134}
135
Jesse Hall178b6962016-02-24 15:39:50 -0800136int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
137 switch (transform) {
138 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
139 return NATIVE_WINDOW_TRANSFORM_ROT_270;
140 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
141 return NATIVE_WINDOW_TRANSFORM_ROT_180;
142 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
143 return NATIVE_WINDOW_TRANSFORM_ROT_90;
Yiwei Zhang70a21962019-05-31 17:26:52 -0700144 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
145 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
146 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
147 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
148 NATIVE_WINDOW_TRANSFORM_ROT_90;
149 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
150 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
151 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
152 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
153 NATIVE_WINDOW_TRANSFORM_ROT_90;
Jesse Hall178b6962016-02-24 15:39:50 -0800154 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
155 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
156 default:
157 return 0;
158 }
159}
160
Ian Elliott8a977262017-01-19 09:05:58 -0700161class TimingInfo {
162 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800163 TimingInfo(const VkPresentTimeGOOGLE* qp, uint64_t nativeFrameId)
Ian Elliott2c6355d2017-01-19 11:02:13 -0700164 : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
Brian Anderson1049d1d2016-12-16 17:25:57 -0800165 native_frame_id_(nativeFrameId) {}
166 bool ready() const {
Brian Andersondc96fdf2017-03-20 16:54:25 -0700167 return (timestamp_desired_present_time_ !=
168 NATIVE_WINDOW_TIMESTAMP_PENDING &&
169 timestamp_actual_present_time_ !=
170 NATIVE_WINDOW_TIMESTAMP_PENDING &&
171 timestamp_render_complete_time_ !=
172 NATIVE_WINDOW_TIMESTAMP_PENDING &&
173 timestamp_composition_latch_time_ !=
174 NATIVE_WINDOW_TIMESTAMP_PENDING);
Ian Elliott8a977262017-01-19 09:05:58 -0700175 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700176 void calculate(int64_t rdur) {
177 bool anyTimestampInvalid =
178 (timestamp_actual_present_time_ ==
179 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
180 (timestamp_render_complete_time_ ==
181 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
182 (timestamp_composition_latch_time_ ==
183 NATIVE_WINDOW_TIMESTAMP_INVALID);
184 if (anyTimestampInvalid) {
185 ALOGE("Unexpectedly received invalid timestamp.");
186 vals_.actualPresentTime = 0;
187 vals_.earliestPresentTime = 0;
188 vals_.presentMargin = 0;
189 return;
190 }
191
192 vals_.actualPresentTime =
193 static_cast<uint64_t>(timestamp_actual_present_time_);
194 int64_t margin = (timestamp_composition_latch_time_ -
Ian Elliott8a977262017-01-19 09:05:58 -0700195 timestamp_render_complete_time_);
196 // Calculate vals_.earliestPresentTime, and potentially adjust
197 // vals_.presentMargin. The initial value of vals_.earliestPresentTime
198 // is vals_.actualPresentTime. If we can subtract rdur (the duration
199 // of a refresh cycle) from vals_.earliestPresentTime (and also from
200 // vals_.presentMargin) and still leave a positive margin, then we can
201 // report to the application that it could have presented earlier than
202 // it did (per the extension specification). If for some reason, we
203 // can do this subtraction repeatedly, we do, since
204 // vals_.earliestPresentTime really is supposed to be the "earliest".
Brian Andersondc96fdf2017-03-20 16:54:25 -0700205 int64_t early_time = timestamp_actual_present_time_;
Ian Elliott8a977262017-01-19 09:05:58 -0700206 while ((margin > rdur) &&
207 ((early_time - rdur) > timestamp_composition_latch_time_)) {
208 early_time -= rdur;
209 margin -= rdur;
210 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700211 vals_.earliestPresentTime = static_cast<uint64_t>(early_time);
212 vals_.presentMargin = static_cast<uint64_t>(margin);
Ian Elliott8a977262017-01-19 09:05:58 -0700213 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800214 void get_values(VkPastPresentationTimingGOOGLE* values) const {
215 *values = vals_;
216 }
Ian Elliott8a977262017-01-19 09:05:58 -0700217
218 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800219 VkPastPresentationTimingGOOGLE vals_ { 0, 0, 0, 0, 0 };
Ian Elliott8a977262017-01-19 09:05:58 -0700220
Brian Anderson1049d1d2016-12-16 17:25:57 -0800221 uint64_t native_frame_id_ { 0 };
Brian Andersondc96fdf2017-03-20 16:54:25 -0700222 int64_t timestamp_desired_present_time_{ NATIVE_WINDOW_TIMESTAMP_PENDING };
223 int64_t timestamp_actual_present_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
224 int64_t timestamp_render_complete_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
225 int64_t timestamp_composition_latch_time_
226 { NATIVE_WINDOW_TIMESTAMP_PENDING };
Ian Elliott8a977262017-01-19 09:05:58 -0700227};
228
Jesse Hall1356b0d2015-11-23 17:24:58 -0800229struct Surface {
Chia-I Wue8e689f2016-04-18 08:21:31 +0800230 android::sp<ANativeWindow> window;
Jesse Halldc225072016-05-30 22:40:14 -0700231 VkSwapchainKHR swapchain_handle;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700232 uint64_t consumer_usage;
Yiwei Zhang3b88f312023-04-18 23:11:35 +0000233
234 // Indicate whether this surface has been used by a swapchain, no matter the
235 // swapchain is still current or has been destroyed.
236 bool used_by_swapchain;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800237};
238
239VkSurfaceKHR HandleFromSurface(Surface* surface) {
240 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
241}
242
243Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800244 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800245}
246
Ian Elliott8a977262017-01-19 09:05:58 -0700247// Maximum number of TimingInfo structs to keep per swapchain:
248enum { MAX_TIMING_INFOS = 10 };
249// Minimum number of frames to look for in the past (so we don't cause
250// syncronous requests to Surface Flinger):
251enum { MIN_NUM_FRAMES_AGO = 5 };
252
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300253bool IsSharedPresentMode(VkPresentModeKHR mode) {
254 return mode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
255 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR;
256}
257
Jesse Hall1356b0d2015-11-23 17:24:58 -0800258struct Swapchain {
Ian Elliottffedb652017-02-14 10:58:30 -0700259 Swapchain(Surface& surface_,
260 uint32_t num_images_,
silence_dogood73597592019-05-23 16:57:37 -0700261 VkPresentModeKHR present_mode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000262 int pre_transform_,
263 int64_t refresh_duration_)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700264 : surface(surface_),
265 num_images(num_images_),
Ian Elliottffedb652017-02-14 10:58:30 -0700266 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
silence_dogood73597592019-05-23 16:57:37 -0700267 pre_transform(pre_transform_),
Chris Forbesf8835642017-03-30 19:31:40 +1300268 frame_timestamps_enabled(false),
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000269 refresh_duration(refresh_duration_),
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800270 acquire_next_image_timeout(-1),
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300271 shared(IsSharedPresentMode(present_mode)) {
Ian Elliott8a977262017-01-19 09:05:58 -0700272 }
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000273
274 VkResult get_refresh_duration(uint64_t& outRefreshDuration)
Ian Elliott3568bfe2019-05-03 15:54:46 -0600275 {
276 ANativeWindow* window = surface.window.get();
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000277 int err = native_window_get_refresh_cycle_duration(
Ian Elliott3568bfe2019-05-03 15:54:46 -0600278 window,
279 &refresh_duration);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000280 if (err != android::OK) {
281 ALOGE("%s:native_window_get_refresh_cycle_duration failed: %s (%d)",
282 __func__, strerror(-err), err );
283 return VK_ERROR_SURFACE_LOST_KHR;
284 }
285 outRefreshDuration = refresh_duration;
286 return VK_SUCCESS;
Ian Elliott3568bfe2019-05-03 15:54:46 -0600287 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800288
289 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700290 uint32_t num_images;
Ian Elliottffedb652017-02-14 10:58:30 -0700291 bool mailbox_mode;
silence_dogood73597592019-05-23 16:57:37 -0700292 int pre_transform;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700293 bool frame_timestamps_enabled;
Brian Andersondc96fdf2017-03-20 16:54:25 -0700294 int64_t refresh_duration;
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800295 nsecs_t acquire_next_image_timeout;
Chris Forbesf8835642017-03-30 19:31:40 +1300296 bool shared;
Jesse Halld7b994a2015-09-07 14:17:37 -0700297
298 struct Image {
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700299 Image()
300 : image(VK_NULL_HANDLE),
301 dequeue_fence(-1),
302 release_fence(-1),
303 dequeued(false) {}
Jesse Halld7b994a2015-09-07 14:17:37 -0700304 VkImage image;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000305 // If the image is bound to memory, an sp to the underlying gralloc buffer.
306 // Otherwise, nullptr; the image will be bound to memory as part of
307 // AcquireNextImage.
Chia-I Wue8e689f2016-04-18 08:21:31 +0800308 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700309 // The fence is only valid when the buffer is dequeued, and should be
310 // -1 any other time. When valid, we own the fd, and must ensure it is
311 // closed: either by closing it explicitly when queueing the buffer,
312 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
313 int dequeue_fence;
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700314 // This fence is a dup of the sync fd returned from the driver via
315 // vkQueueSignalReleaseImageANDROID upon vkQueuePresentKHR. We must
316 // ensure it is closed upon re-presenting or releasing the image.
317 int release_fence;
Jesse Halld7b994a2015-09-07 14:17:37 -0700318 bool dequeued;
Pawin Vongmasa6e1193a2017-03-07 13:08:40 -0800319 } images[android::BufferQueueDefs::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700320
Yiwei Zhang5e862202019-06-21 14:59:16 -0700321 std::vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700322};
323
324VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
325 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
326}
327
328Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800329 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700330}
331
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700332static bool IsFencePending(int fd) {
333 if (fd < 0)
334 return false;
335
336 errno = 0;
337 return sync_wait(fd, 0 /* timeout */) == -1 && errno == ETIME;
338}
339
Jesse Halldc225072016-05-30 22:40:14 -0700340void ReleaseSwapchainImage(VkDevice device,
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000341 bool shared_present,
Jesse Halldc225072016-05-30 22:40:14 -0700342 ANativeWindow* window,
343 int release_fence,
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700344 Swapchain::Image& image,
345 bool defer_if_pending) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700346 ATRACE_CALL();
347
Jesse Halldc225072016-05-30 22:40:14 -0700348 ALOG_ASSERT(release_fence == -1 || image.dequeued,
349 "ReleaseSwapchainImage: can't provide a release fence for "
350 "non-dequeued images");
351
352 if (image.dequeued) {
353 if (release_fence >= 0) {
354 // We get here from vkQueuePresentKHR. The application is
355 // responsible for creating an execution dependency chain from
356 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
357 // (release_fence), so we can drop the dequeue_fence here.
358 if (image.dequeue_fence >= 0)
359 close(image.dequeue_fence);
360 } else {
361 // We get here during swapchain destruction, or various serious
362 // error cases e.g. when we can't create the release_fence during
363 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
364 // have already signalled, since the swapchain images are supposed
365 // to be idle before the swapchain is destroyed. In error cases,
366 // there may be rendering in flight to the image, but since we
367 // weren't able to create a release_fence, waiting for the
368 // dequeue_fence is about the best we can do.
369 release_fence = image.dequeue_fence;
370 }
371 image.dequeue_fence = -1;
372
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000373 // It's invalid to call cancelBuffer on a shared buffer
374 if (window && !shared_present) {
Jesse Halldc225072016-05-30 22:40:14 -0700375 window->cancelBuffer(window, image.buffer.get(), release_fence);
376 } else {
377 if (release_fence >= 0) {
378 sync_wait(release_fence, -1 /* forever */);
379 close(release_fence);
380 }
381 }
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700382 release_fence = -1;
Jesse Halldc225072016-05-30 22:40:14 -0700383 image.dequeued = false;
384 }
385
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700386 if (defer_if_pending && IsFencePending(image.release_fence))
387 return;
388
389 if (image.release_fence >= 0) {
390 close(image.release_fence);
391 image.release_fence = -1;
392 }
393
Jesse Halldc225072016-05-30 22:40:14 -0700394 if (image.image) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700395 ATRACE_BEGIN("DestroyImage");
Jesse Halldc225072016-05-30 22:40:14 -0700396 GetData(device).driver.DestroyImage(device, image.image, nullptr);
Yiwei Zhang533cea92019-06-03 18:43:24 -0700397 ATRACE_END();
Jesse Halldc225072016-05-30 22:40:14 -0700398 image.image = VK_NULL_HANDLE;
399 }
400
401 image.buffer.clear();
402}
403
404void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
405 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
406 return;
Jesse Halldc225072016-05-30 22:40:14 -0700407 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000408 if (!swapchain->images[i].dequeued) {
409 ReleaseSwapchainImage(device, swapchain->shared, nullptr, -1,
410 swapchain->images[i], true);
411 }
Jesse Halldc225072016-05-30 22:40:14 -0700412 }
413 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700414 swapchain->timing.clear();
415}
416
417uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800418 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
419 return 0;
420 }
Ian Elliott8a977262017-01-19 09:05:58 -0700421
Brian Anderson1049d1d2016-12-16 17:25:57 -0800422 uint32_t num_ready = 0;
423 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
424 for (uint32_t i = 0; i < num_timings; i++) {
Yiwei Zhang5e862202019-06-21 14:59:16 -0700425 TimingInfo& ti = swapchain.timing[i];
Brian Anderson1049d1d2016-12-16 17:25:57 -0800426 if (ti.ready()) {
427 // This TimingInfo is ready to be reported to the user. Add it
428 // to the num_ready.
429 num_ready++;
430 continue;
431 }
432 // This TimingInfo is not yet ready to be reported to the user,
433 // and so we should look for any available timestamps that
434 // might make it ready.
435 int64_t desired_present_time = 0;
436 int64_t render_complete_time = 0;
437 int64_t composition_latch_time = 0;
438 int64_t actual_present_time = 0;
439 // Obtain timestamps:
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800440 int err = native_window_get_frame_timestamps(
Brian Anderson1049d1d2016-12-16 17:25:57 -0800441 swapchain.surface.window.get(), ti.native_frame_id_,
442 &desired_present_time, &render_complete_time,
443 &composition_latch_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700444 nullptr, //&first_composition_start_time,
445 nullptr, //&last_composition_start_time,
446 nullptr, //&composition_finish_time,
Brian Anderson1049d1d2016-12-16 17:25:57 -0800447 &actual_present_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700448 nullptr, //&dequeue_ready_time,
449 nullptr /*&reads_done_time*/);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800450
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800451 if (err != android::OK) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800452 continue;
453 }
454
455 // Record the timestamp(s) we received, and then see if this TimingInfo
456 // is ready to be reported to the user:
Brian Andersondc96fdf2017-03-20 16:54:25 -0700457 ti.timestamp_desired_present_time_ = desired_present_time;
458 ti.timestamp_actual_present_time_ = actual_present_time;
459 ti.timestamp_render_complete_time_ = render_complete_time;
460 ti.timestamp_composition_latch_time_ = composition_latch_time;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800461
462 if (ti.ready()) {
463 // The TimingInfo has received enough timestamps, and should now
464 // use those timestamps to calculate the info that should be
465 // reported to the user:
466 ti.calculate(swapchain.refresh_duration);
467 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700468 }
469 }
470 return num_ready;
471}
472
Ian Elliott8a977262017-01-19 09:05:58 -0700473void copy_ready_timings(Swapchain& swapchain,
474 uint32_t* count,
475 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800476 if (swapchain.timing.empty()) {
477 *count = 0;
478 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700479 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800480
481 size_t last_ready = swapchain.timing.size() - 1;
482 while (!swapchain.timing[last_ready].ready()) {
483 if (last_ready == 0) {
484 *count = 0;
485 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700486 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800487 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700488 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800489
490 uint32_t num_copied = 0;
Yiwei Zhang5e862202019-06-21 14:59:16 -0700491 int32_t num_to_remove = 0;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800492 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
493 const TimingInfo& ti = swapchain.timing[i];
494 if (ti.ready()) {
495 ti.get_values(&timings[num_copied]);
496 num_copied++;
497 }
498 num_to_remove++;
499 }
500
501 // Discard old frames that aren't ready if newer frames are ready.
502 // We don't expect to get the timing info for those old frames.
Yiwei Zhang5e862202019-06-21 14:59:16 -0700503 swapchain.timing.erase(swapchain.timing.begin(),
504 swapchain.timing.begin() + num_to_remove);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800505
Ian Elliott8a977262017-01-19 09:05:58 -0700506 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700507}
508
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000509PixelFormat GetNativePixelFormat(VkFormat format) {
510 PixelFormat native_format = PixelFormat::RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700511 switch (format) {
512 case VK_FORMAT_R8G8B8A8_UNORM:
513 case VK_FORMAT_R8G8B8A8_SRGB:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000514 native_format = PixelFormat::RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700515 break;
516 case VK_FORMAT_R5G6B5_UNORM_PACK16:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000517 native_format = PixelFormat::RGB_565;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700518 break;
519 case VK_FORMAT_R16G16B16A16_SFLOAT:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000520 native_format = PixelFormat::RGBA_FP16;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700521 break;
Yiwei Zhangc1ea8152019-02-05 15:11:32 -0800522 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000523 native_format = PixelFormat::RGBA_1010102;
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500524 break;
525 case VK_FORMAT_R8_UNORM:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000526 native_format = PixelFormat::R_8;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700527 break;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000528 case VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000529 native_format = PixelFormat::RGBA_10101010;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000530 break;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700531 default:
532 ALOGV("unsupported swapchain format %d", format);
533 break;
534 }
535 return native_format;
536}
537
sergiuferentz47989332023-09-26 10:24:36 +0000538DataSpace GetNativeDataspace(VkColorSpaceKHR colorspace,
539 PixelFormat pixelFormat) {
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700540 switch (colorspace) {
541 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
sergiuferentz47989332023-09-26 10:24:36 +0000542 return DataSpace::SRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700543 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000544 return DataSpace::DISPLAY_P3;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700545 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000546 return DataSpace::SCRGB_LINEAR;
Courtney Goeltzenleuchterb52abee2017-08-07 17:13:04 -0600547 case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000548 return DataSpace::SCRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700549 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000550 return DataSpace::DCI_P3_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700551 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000552 return DataSpace::DCI_P3;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700553 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000554 return DataSpace::SRGB_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700555 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000556 return DataSpace::SRGB;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600557 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
Sally Qiaa238972023-07-17 12:52:05 +0800558 if (pixelFormat == PixelFormat::RGBA_FP16) {
sergiuferentz47989332023-09-26 10:24:36 +0000559 return DataSpace::BT2020_LINEAR_EXTENDED;
Sally Qiaa238972023-07-17 12:52:05 +0800560 } else {
sergiuferentz47989332023-09-26 10:24:36 +0000561 return DataSpace::BT2020_LINEAR;
Sally Qiaa238972023-07-17 12:52:05 +0800562 }
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600563 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000564 return DataSpace::BT2020_PQ;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600565 case VK_COLOR_SPACE_DOLBYVISION_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000566 return DataSpace::BT2020_PQ;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600567 case VK_COLOR_SPACE_HDR10_HLG_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000568 return DataSpace::BT2020_HLG;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700569 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000570 return DataSpace::ADOBE_RGB_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700571 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000572 return DataSpace::ADOBE_RGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700573 // Pass through is intended to allow app to provide data that is passed
574 // to the display system without modification.
575 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000576 return DataSpace::ARBITRARY;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700577
578 default:
579 // This indicates that we don't know about the
580 // dataspace specified and we should indicate that
581 // it's unsupported
sergiuferentz47989332023-09-26 10:24:36 +0000582 return DataSpace::UNKNOWN;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700583 }
584}
585
Jesse Halld7b994a2015-09-07 14:17:37 -0700586} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700587
Jesse Halle1b12782015-11-30 11:27:32 -0800588VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800589VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800590 VkInstance instance,
591 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
592 const VkAllocationCallbacks* allocator,
593 VkSurfaceKHR* out_surface) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800594 ATRACE_CALL();
595
Jesse Hall1f91d392015-12-11 16:28:44 -0800596 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800597 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800598 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
599 alignof(Surface),
600 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800601 if (!mem)
602 return VK_ERROR_OUT_OF_HOST_MEMORY;
603 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700604
Chia-I Wue8e689f2016-04-18 08:21:31 +0800605 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700606 surface->swapchain_handle = VK_NULL_HANDLE;
Yiwei Zhang3b88f312023-04-18 23:11:35 +0000607 surface->used_by_swapchain = false;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700608 int err = native_window_get_consumer_usage(surface->window.get(),
609 &surface->consumer_usage);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800610 if (err != android::OK) {
Yiwei Zhang6435b322018-05-08 11:12:17 -0700611 ALOGE("native_window_get_consumer_usage() failed: %s (%d)",
612 strerror(-err), err);
613 surface->~Surface();
614 allocator->pfnFree(allocator->pUserData, surface);
Yiwei Zhang70a21962019-05-31 17:26:52 -0700615 return VK_ERROR_SURFACE_LOST_KHR;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700616 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700617
Yiwei Zhang6435b322018-05-08 11:12:17 -0700618 err =
Jesse Hall1356b0d2015-11-23 17:24:58 -0800619 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800620 if (err != android::OK) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800621 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
622 err);
623 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800624 allocator->pfnFree(allocator->pUserData, surface);
Mike Stroyan762c8132017-02-22 11:43:09 -0700625 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800626 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700627
Jesse Hall1356b0d2015-11-23 17:24:58 -0800628 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700629 return VK_SUCCESS;
630}
631
Jesse Halle1b12782015-11-30 11:27:32 -0800632VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800633void DestroySurfaceKHR(VkInstance instance,
634 VkSurfaceKHR surface_handle,
635 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800636 ATRACE_CALL();
637
Jesse Hall1356b0d2015-11-23 17:24:58 -0800638 Surface* surface = SurfaceFromHandle(surface_handle);
639 if (!surface)
640 return;
641 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700642 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700643 "destroyed VkSurfaceKHR 0x%" PRIx64
644 " has active VkSwapchainKHR 0x%" PRIx64,
645 reinterpret_cast<uint64_t>(surface_handle),
646 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800647 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800648 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800649 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800650 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800651}
652
Jesse Halle1b12782015-11-30 11:27:32 -0800653VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800654VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
655 uint32_t /*queue_family*/,
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000656 VkSurfaceKHR /*surface_handle*/,
Chia-I Wu62262232016-03-26 07:06:44 +0800657 VkBool32* supported) {
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000658 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800659 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800660}
661
Jesse Halle1b12782015-11-30 11:27:32 -0800662VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800663VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Ian Elliott1ce053f2022-03-16 09:49:53 -0600664 VkPhysicalDevice pdev,
Jesse Hallb00daad2015-11-29 19:46:20 -0800665 VkSurfaceKHR surface,
666 VkSurfaceCapabilitiesKHR* capabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800667 ATRACE_CALL();
668
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000669 // Implement in terms of GetPhysicalDeviceSurfaceCapabilities2KHR
670
671 VkPhysicalDeviceSurfaceInfo2KHR info2 = {
672 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
673 nullptr,
674 surface
675 };
676
677 VkSurfaceCapabilities2KHR caps2 = {
678 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
679 nullptr,
680 {},
681 };
682
683 VkResult result = GetPhysicalDeviceSurfaceCapabilities2KHR(pdev, &info2, &caps2);
684 *capabilities = caps2.surfaceCapabilities;
685 return result;
686}
687
688// Does the call-twice and VK_INCOMPLETE handling for querying lists
689// of things, where we already have the full set built in a vector.
690template <typename T>
691VkResult CopyWithIncomplete(std::vector<T> const& things,
692 T* callerPtr, uint32_t* callerCount) {
693 VkResult result = VK_SUCCESS;
694 if (callerPtr) {
695 if (things.size() > *callerCount)
696 result = VK_INCOMPLETE;
697 *callerCount = std::min(uint32_t(things.size()), *callerCount);
698 std::copy(things.begin(), things.begin() + *callerCount, callerPtr);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600699 } else {
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000700 *callerCount = things.size();
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800701 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000702 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700703}
704
Jesse Halle1b12782015-11-30 11:27:32 -0800705VKAPI_ATTR
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700706VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
707 VkSurfaceKHR surface_handle,
Chia-I Wu62262232016-03-26 07:06:44 +0800708 uint32_t* count,
709 VkSurfaceFormatKHR* formats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800710 ATRACE_CALL();
711
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700712 const InstanceData& instance_data = GetData(pdev);
713
Ian Elliott1ce053f2022-03-16 09:49:53 -0600714 uint64_t consumer_usage = 0;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000715 bool colorspace_ext =
Ian Elliottf6df08e2022-03-16 21:27:49 -0600716 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600717 if (surface_handle == VK_NULL_HANDLE) {
718 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
719 bool surfaceless_enabled =
720 instance_data.hook_extensions.test(surfaceless);
721 if (!surfaceless_enabled) {
722 return VK_ERROR_SURFACE_LOST_KHR;
723 }
Chris Forbesb1de3b12022-10-20 09:05:48 +1300724 // Support for VK_GOOGLE_surfaceless_query.
Ian Elliott1ce053f2022-03-16 09:49:53 -0600725
726 // TODO(b/203826952): research proper value; temporarily use the
727 // values seen on Pixel
728 consumer_usage = AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
729 } else {
730 Surface& surface = *SurfaceFromHandle(surface_handle);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600731 consumer_usage = surface.consumer_usage;
Ian Elliott6ba85d92022-02-18 16:44:58 -0700732 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700733
Charlie Lao324191f2019-12-13 11:03:16 -0800734 AHardwareBuffer_Desc desc = {};
735 desc.width = 1;
736 desc.height = 1;
737 desc.layers = 1;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600738 desc.usage = consumer_usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
Charlie Lao324191f2019-12-13 11:03:16 -0800739 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
740
741 // We must support R8G8B8A8
742 std::vector<VkSurfaceFormatKHR> all_formats = {
743 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000744 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000745 };
Charlie Lao324191f2019-12-13 11:03:16 -0800746
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000747 if (colorspace_ext) {
748 all_formats.emplace_back(VkSurfaceFormatKHR{
Jason Macnakca506332022-11-09 11:00:36 -0800749 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
750 all_formats.emplace_back(VkSurfaceFormatKHR{
751 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_PASS_THROUGH_EXT});
752 all_formats.emplace_back(VkSurfaceFormatKHR{
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000753 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_BT709_LINEAR_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800754 all_formats.emplace_back(VkSurfaceFormatKHR{
755 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
756 all_formats.emplace_back(VkSurfaceFormatKHR{
757 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
758 }
759
Ian Elliott1ce053f2022-03-16 09:49:53 -0600760 // NOTE: Any new formats that are added must be coordinated across different
761 // Android users. This includes the ANGLE team (a layered implementation of
762 // OpenGL-ES).
763
Charlie Lao324191f2019-12-13 11:03:16 -0800764 desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
765 if (AHardwareBuffer_isSupported(&desc)) {
766 all_formats.emplace_back(VkSurfaceFormatKHR{
767 VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800768 if (colorspace_ext) {
769 all_formats.emplace_back(
770 VkSurfaceFormatKHR{VK_FORMAT_R5G6B5_UNORM_PACK16,
771 VK_COLOR_SPACE_PASS_THROUGH_EXT});
772 }
Charlie Lao324191f2019-12-13 11:03:16 -0800773 }
774
775 desc.format = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
776 if (AHardwareBuffer_isSupported(&desc)) {
777 all_formats.emplace_back(VkSurfaceFormatKHR{
778 VK_FORMAT_R16G16B16A16_SFLOAT, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800779 if (colorspace_ext) {
780 all_formats.emplace_back(
781 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
782 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800783 all_formats.emplace_back(
784 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
785 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT});
786 all_formats.emplace_back(
787 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
788 VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT});
789 }
790 }
791
792 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
793 if (AHardwareBuffer_isSupported(&desc)) {
794 all_formats.emplace_back(
795 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
796 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800797 if (colorspace_ext) {
798 all_formats.emplace_back(
799 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
800 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800801 all_formats.emplace_back(
802 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
803 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
804 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700805 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700806
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500807 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
808 if (AHardwareBuffer_isSupported(&desc)) {
Jason Macnakca506332022-11-09 11:00:36 -0800809 if (colorspace_ext) {
810 all_formats.emplace_back(VkSurfaceFormatKHR{
811 VK_FORMAT_R8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
812 }
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500813 }
814
Trevor David Black67e9b102023-03-07 05:28:15 +0000815 bool rgba10x6_formats_ext = false;
816 uint32_t exts_count;
817 const auto& driver = GetData(pdev).driver;
818 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
819 nullptr);
820 std::vector<VkExtensionProperties> props(exts_count);
821 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
822 props.data());
823 for (uint32_t i = 0; i < exts_count; i++) {
824 VkExtensionProperties prop = props[i];
825 if (strcmp(prop.extensionName,
826 VK_EXT_RGBA10X6_FORMATS_EXTENSION_NAME) == 0) {
827 rgba10x6_formats_ext = true;
828 }
829 }
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000830 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM;
Trevor David Black67e9b102023-03-07 05:28:15 +0000831 if (AHardwareBuffer_isSupported(&desc) && rgba10x6_formats_ext) {
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000832 all_formats.emplace_back(
833 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
834 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
835 if (colorspace_ext) {
836 all_formats.emplace_back(
837 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
838 VK_COLOR_SPACE_PASS_THROUGH_EXT});
839 all_formats.emplace_back(
840 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
841 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
842 }
843 }
844
Ian Elliott6ba85d92022-02-18 16:44:58 -0700845 // NOTE: Any new formats that are added must be coordinated across different
846 // Android users. This includes the ANGLE team (a layered implementation of
847 // OpenGL-ES).
848
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000849 return CopyWithIncomplete(all_formats, formats, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700850}
851
Jesse Halle1b12782015-11-30 11:27:32 -0800852VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300853VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
854 VkPhysicalDevice physicalDevice,
855 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
856 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800857 ATRACE_CALL();
858
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000859 auto surface = pSurfaceInfo->surface;
860 auto capabilities = &pSurfaceCapabilities->surfaceCapabilities;
Chris Forbes2452cf72017-03-16 16:30:17 +1300861
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000862 VkSurfacePresentModeEXT const *pPresentMode = nullptr;
863 for (auto pNext = reinterpret_cast<VkBaseInStructure const *>(pSurfaceInfo->pNext);
864 pNext; pNext = reinterpret_cast<VkBaseInStructure const *>(pNext->pNext)) {
865 switch (pNext->sType) {
866 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT:
867 pPresentMode = reinterpret_cast<VkSurfacePresentModeEXT const *>(pNext);
868 break;
Chris Forbes06bc0092017-03-16 16:46:05 +1300869
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000870 default:
871 break;
872 }
873 }
874
875 int err;
876 int width, height;
877 int transform_hint;
878 int max_buffer_count;
Trevor David Black1d3509e2023-06-08 00:17:40 +0000879 int min_undequeued_buffers;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000880 if (surface == VK_NULL_HANDLE) {
881 const InstanceData& instance_data = GetData(physicalDevice);
882 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
883 bool surfaceless_enabled =
884 instance_data.hook_extensions.test(surfaceless);
885 if (!surfaceless_enabled) {
886 // It is an error to pass a surface==VK_NULL_HANDLE unless the
887 // VK_GOOGLE_surfaceless_query extension is enabled
888 return VK_ERROR_SURFACE_LOST_KHR;
889 }
890 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
891 // extension for this function is for
892 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
893 // four values cannot be known without a surface. Default values will
894 // be supplied anyway, but cannot be relied upon.
895 width = 0xFFFFFFFF;
896 height = 0xFFFFFFFF;
897 transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
898 capabilities->minImageCount = 0xFFFFFFFF;
899 capabilities->maxImageCount = 0xFFFFFFFF;
900 } else {
901 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
902
903 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
904 if (err != android::OK) {
905 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
906 strerror(-err), err);
907 return VK_ERROR_SURFACE_LOST_KHR;
908 }
909 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
910 if (err != android::OK) {
911 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
912 strerror(-err), err);
913 return VK_ERROR_SURFACE_LOST_KHR;
914 }
915
916 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
917 &transform_hint);
918 if (err != android::OK) {
919 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
920 strerror(-err), err);
921 return VK_ERROR_SURFACE_LOST_KHR;
922 }
923
924 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
925 &max_buffer_count);
926 if (err != android::OK) {
927 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
928 strerror(-err), err);
929 return VK_ERROR_SURFACE_LOST_KHR;
930 }
931
Trevor David Black1d3509e2023-06-08 00:17:40 +0000932 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
933 &min_undequeued_buffers);
934 if (err != android::OK) {
935 ALOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d)",
936 strerror(-err), err);
937 return VK_ERROR_SURFACE_LOST_KHR;
938 }
939
Trevor David Blacke4d23b92023-09-26 20:30:42 +0000940 // Additional buffer count over min_undequeued_buffers in vulkan came from 2 total
941 // being technically enough for fifo (although a poor experience) vs 3 being the
942 // absolute minimum for mailbox to be useful. So min_undequeued_buffers + 2 is sensible
943 static constexpr int default_additional_buffers = 2;
944
Trevor David Blacka93e21f2023-08-30 23:42:20 +0000945 if(pPresentMode != nullptr) {
946 switch (pPresentMode->presentMode) {
947 case VK_PRESENT_MODE_IMMEDIATE_KHR:
948 ALOGE("Swapchain present mode VK_PRESENT_MODE_IMMEDIATE_KHR is not supported");
949 break;
950 case VK_PRESENT_MODE_MAILBOX_KHR:
951 case VK_PRESENT_MODE_FIFO_KHR:
Trevor David Blacke4d23b92023-09-26 20:30:42 +0000952 capabilities->minImageCount = std::min(max_buffer_count,
953 min_undequeued_buffers + default_additional_buffers);
Trevor David Blacka93e21f2023-08-30 23:42:20 +0000954 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
955 break;
956 case VK_PRESENT_MODE_FIFO_RELAXED_KHR:
957 ALOGE("Swapchain present mode VK_PRESENT_MODE_FIFO_RELEAXED_KHR "
958 "is not supported");
959 break;
960 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
961 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
962 capabilities->minImageCount = 1;
963 capabilities->maxImageCount = 1;
964 break;
965
966 default:
967 ALOGE("Unrecognized swapchain present mode %u is not supported",
968 pPresentMode->presentMode);
969 break;
970 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000971 } else {
Trevor David Blacke4d23b92023-09-26 20:30:42 +0000972 capabilities->minImageCount = std::min(max_buffer_count,
973 min_undequeued_buffers + default_additional_buffers);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000974 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
975 }
976 }
977
978 capabilities->currentExtent =
979 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
980
981 // TODO(http://b/134182502): Figure out what the max extent should be.
982 capabilities->minImageExtent = VkExtent2D{1, 1};
983 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
984
985 if (capabilities->maxImageExtent.height <
986 capabilities->currentExtent.height) {
987 capabilities->maxImageExtent.height =
988 capabilities->currentExtent.height;
989 }
990
991 if (capabilities->maxImageExtent.width <
992 capabilities->currentExtent.width) {
993 capabilities->maxImageExtent.width = capabilities->currentExtent.width;
994 }
995
996 capabilities->maxImageArrayLayers = 1;
997
998 capabilities->supportedTransforms = kSupportedTransforms;
999 capabilities->currentTransform =
1000 TranslateNativeToVulkanTransform(transform_hint);
1001
1002 // On Android, window composition is a WindowManager property, not something
1003 // associated with the bufferqueue. It can't be changed from here.
1004 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
1005
1006 capabilities->supportedUsageFlags =
1007 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
1008 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
1009 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
1010 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
1011
1012 for (auto pNext = reinterpret_cast<VkBaseOutStructure*>(pSurfaceCapabilities->pNext);
1013 pNext; pNext = reinterpret_cast<VkBaseOutStructure*>(pNext->pNext)) {
1014
1015 switch (pNext->sType) {
Chris Forbes06bc0092017-03-16 16:46:05 +13001016 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
1017 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001018 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(pNext);
Chris Forbes06bc0092017-03-16 16:46:05 +13001019 // Claim same set of usage flags are supported for
1020 // shared present modes as for other modes.
1021 shared_caps->sharedPresentSupportedUsageFlags =
1022 pSurfaceCapabilities->surfaceCapabilities
1023 .supportedUsageFlags;
1024 } break;
1025
Ian Elliottbb67b242022-03-16 09:52:28 -06001026 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
1027 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001028 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(pNext);
Ian Elliottbb67b242022-03-16 09:52:28 -06001029 protected_caps->supportsProtected = VK_TRUE;
1030 } break;
1031
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001032 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_SCALING_CAPABILITIES_EXT: {
1033 VkSurfacePresentScalingCapabilitiesEXT* scaling_caps =
1034 reinterpret_cast<VkSurfacePresentScalingCapabilitiesEXT*>(pNext);
1035 // By default, Android stretches the buffer to fit the window,
1036 // without preserving aspect ratio. Other modes are technically possible
1037 // but consult with CoGS team before exposing them here!
1038 scaling_caps->supportedPresentScaling = VK_PRESENT_SCALING_STRETCH_BIT_EXT;
1039
1040 // Since we always scale, we don't support any gravity.
1041 scaling_caps->supportedPresentGravityX = 0;
1042 scaling_caps->supportedPresentGravityY = 0;
1043
1044 // Scaled image limits are just the basic image limits
1045 scaling_caps->minScaledImageExtent = capabilities->minImageExtent;
1046 scaling_caps->maxScaledImageExtent = capabilities->maxImageExtent;
1047 } break;
1048
1049 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT: {
1050 VkSurfacePresentModeCompatibilityEXT* mode_caps =
1051 reinterpret_cast<VkSurfacePresentModeCompatibilityEXT*>(pNext);
1052
1053 ALOG_ASSERT(pPresentMode,
1054 "querying VkSurfacePresentModeCompatibilityEXT "
1055 "requires VkSurfacePresentModeEXT to be provided");
1056 std::vector<VkPresentModeKHR> compatibleModes;
1057 compatibleModes.push_back(pPresentMode->presentMode);
1058
1059 switch (pPresentMode->presentMode) {
1060 // Shared modes are both compatible with each other.
1061 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
1062 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
1063 break;
1064 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
1065 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1066 break;
1067 default:
1068 // Other modes are only compatible with themselves.
1069 // TODO: consider whether switching between FIFO and MAILBOX is reasonable
1070 break;
1071 }
1072
1073 // Note: this does not generate VK_INCOMPLETE since we're nested inside
1074 // a larger query and there would be no way to determine exactly where it came from.
1075 CopyWithIncomplete(compatibleModes, mode_caps->pPresentModes,
1076 &mode_caps->presentModeCount);
1077 } break;
1078
Chris Forbes06bc0092017-03-16 16:46:05 +13001079 default:
1080 // Ignore all other extension structs
1081 break;
1082 }
1083 }
1084
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001085 return VK_SUCCESS;
Chris Forbes2452cf72017-03-16 16:30:17 +13001086}
1087
1088VKAPI_ATTR
1089VkResult GetPhysicalDeviceSurfaceFormats2KHR(
1090 VkPhysicalDevice physicalDevice,
1091 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
1092 uint32_t* pSurfaceFormatCount,
1093 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001094 ATRACE_CALL();
1095
Chris Forbes2452cf72017-03-16 16:30:17 +13001096 if (!pSurfaceFormats) {
1097 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
1098 pSurfaceInfo->surface,
1099 pSurfaceFormatCount, nullptr);
Trevor David Black929e9cd2022-11-22 04:12:19 +00001100 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001101
Trevor David Black929e9cd2022-11-22 04:12:19 +00001102 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
1103 // after the call.
1104 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
1105 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
1106 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
1107 surface_formats.data());
Trevor David Black2cc44682022-03-09 00:31:38 +00001108
Trevor David Black929e9cd2022-11-22 04:12:19 +00001109 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
1110 return result;
1111 }
Trevor David Black2cc44682022-03-09 00:31:38 +00001112
Trevor David Black929e9cd2022-11-22 04:12:19 +00001113 const auto& driver = GetData(physicalDevice).driver;
1114
1115 // marshal results individually due to stride difference.
1116 uint32_t formats_to_marshal = *pSurfaceFormatCount;
1117 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
1118 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
1119
1120 // Query the compression properties for the surface format
1121 VkSurfaceFormat2KHR* pSurfaceFormat = &pSurfaceFormats[i];
1122 while (pSurfaceFormat->pNext) {
1123 pSurfaceFormat =
1124 reinterpret_cast<VkSurfaceFormat2KHR*>(pSurfaceFormat->pNext);
1125 switch (pSurfaceFormat->sType) {
1126 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT: {
Trevor David Black2cc44682022-03-09 00:31:38 +00001127 VkImageCompressionPropertiesEXT* surfaceCompressionProps =
1128 reinterpret_cast<VkImageCompressionPropertiesEXT*>(
Trevor David Black929e9cd2022-11-22 04:12:19 +00001129 pSurfaceFormat);
Trevor David Black2cc44682022-03-09 00:31:38 +00001130
1131 if (surfaceCompressionProps &&
1132 driver.GetPhysicalDeviceImageFormatProperties2KHR) {
1133 VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = {};
1134 imageFormatInfo.sType =
1135 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
1136 imageFormatInfo.format =
1137 pSurfaceFormats[i].surfaceFormat.format;
Trevor David Blacka4298c92023-06-20 17:11:58 +00001138 imageFormatInfo.type = VK_IMAGE_TYPE_2D;
1139 imageFormatInfo.usage =
1140 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
Trevor David Black2cc44682022-03-09 00:31:38 +00001141 imageFormatInfo.pNext = nullptr;
1142
1143 VkImageCompressionControlEXT compressionControl = {};
1144 compressionControl.sType =
1145 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT;
1146 compressionControl.pNext = imageFormatInfo.pNext;
Trevor David Blacka4298c92023-06-20 17:11:58 +00001147 compressionControl.flags =
1148 VK_IMAGE_COMPRESSION_FIXED_RATE_DEFAULT_EXT;
Trevor David Black2cc44682022-03-09 00:31:38 +00001149
1150 imageFormatInfo.pNext = &compressionControl;
1151
1152 VkImageCompressionPropertiesEXT compressionProps = {};
1153 compressionProps.sType =
1154 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT;
1155 compressionProps.pNext = nullptr;
1156
1157 VkImageFormatProperties2KHR imageFormatProps = {};
1158 imageFormatProps.sType =
1159 VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
1160 imageFormatProps.pNext = &compressionProps;
1161
1162 VkResult compressionRes =
1163 driver.GetPhysicalDeviceImageFormatProperties2KHR(
1164 physicalDevice, &imageFormatInfo,
1165 &imageFormatProps);
1166 if (compressionRes == VK_SUCCESS) {
1167 surfaceCompressionProps->imageCompressionFlags =
1168 compressionProps.imageCompressionFlags;
1169 surfaceCompressionProps
1170 ->imageCompressionFixedRateFlags =
1171 compressionProps.imageCompressionFixedRateFlags;
1172 } else {
1173 return compressionRes;
1174 }
1175 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001176 } break;
1177
1178 default:
1179 // Ignore all other extension structs
1180 break;
Chris Forbes2452cf72017-03-16 16:30:17 +13001181 }
1182 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001183 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001184
1185 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +13001186}
1187
1188VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +13001189VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001190 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +08001191 uint32_t* count,
1192 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001193 ATRACE_CALL();
1194
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001195 int err;
1196 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -06001197 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -06001198 if (surface == VK_NULL_HANDLE) {
1199 const InstanceData& instance_data = GetData(pdev);
1200 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
1201 bool surfaceless_enabled =
1202 instance_data.hook_extensions.test(surfaceless);
1203 if (!surfaceless_enabled) {
1204 return VK_ERROR_SURFACE_LOST_KHR;
1205 }
1206 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
1207 // extension for this function is for
1208 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
1209 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
1210 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
Ian Elliott7e361142022-06-02 10:45:17 -06001211 // surface, and that cannot be relied upon. Therefore, don't return it.
Ian Elliott1ce053f2022-03-16 09:49:53 -06001212 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1213 } else {
1214 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1215
1216 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1217 &query_value);
1218 if (err != android::OK || query_value < 0) {
1219 ALOGE(
1220 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
1221 "value=%d",
1222 strerror(-err), err, query_value);
1223 return VK_ERROR_SURFACE_LOST_KHR;
1224 }
1225 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1226
1227 err =
1228 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
1229 if (err != android::OK || query_value < 0) {
1230 ALOGE(
1231 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
1232 strerror(-err), err, query_value);
1233 return VK_ERROR_SURFACE_LOST_KHR;
1234 }
1235 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
1236
1237 if (min_undequeued_buffers + 1 < max_buffer_count)
1238 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
1239 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1240 }
Chris Forbese8d79a62017-02-22 12:49:18 +13001241
1242 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -07001243 QueryPresentationProperties(pdev, &present_properties);
1244 if (present_properties.sharedImage) {
1245 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1246 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +13001247 }
1248
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001249 return CopyWithIncomplete(present_modes, modes, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001250}
1251
Jesse Halle1b12782015-11-30 11:27:32 -08001252VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001253VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001254 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001255 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001256 ATRACE_CALL();
1257
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001258 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
1259 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1260 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1261 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1262 pDeviceGroupPresentCapabilities->sType);
1263
1264 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1265 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1266
1267 // assume device group of size 1
1268 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1269 pDeviceGroupPresentCapabilities->modes =
1270 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1271
1272 return VK_SUCCESS;
1273}
1274
1275VKAPI_ATTR
1276VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001277 VkDevice,
1278 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001279 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001280 ATRACE_CALL();
1281
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001282 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1283 return VK_SUCCESS;
1284}
1285
1286VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001287VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001288 VkSurfaceKHR surface,
1289 uint32_t* pRectCount,
1290 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001291 ATRACE_CALL();
1292
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001293 if (!pRects) {
1294 *pRectCount = 1;
1295 } else {
1296 uint32_t count = std::min(*pRectCount, 1u);
1297 bool incomplete = *pRectCount < 1;
1298
1299 *pRectCount = count;
1300
1301 if (incomplete) {
1302 return VK_INCOMPLETE;
1303 }
1304
1305 int err;
1306 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1307
1308 int width = 0, height = 0;
1309 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001310 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001311 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1312 strerror(-err), err);
1313 }
1314 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001315 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001316 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1317 strerror(-err), err);
1318 }
1319
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001320 pRects[0].offset.x = 0;
1321 pRects[0].offset.y = 0;
1322 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1323 static_cast<uint32_t>(height)};
1324 }
1325 return VK_SUCCESS;
1326}
1327
Yiwei Zhang533cea92019-06-03 18:43:24 -07001328static void DestroySwapchainInternal(VkDevice device,
1329 VkSwapchainKHR swapchain_handle,
1330 const VkAllocationCallbacks* allocator) {
1331 ATRACE_CALL();
1332
1333 const auto& dispatch = GetData(device).driver;
1334 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1335 if (!swapchain) {
1336 return;
1337 }
1338
1339 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1340 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1341
1342 if (window && swapchain->frame_timestamps_enabled) {
1343 native_window_enable_frame_timestamps(window, false);
1344 }
1345
1346 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +00001347 ReleaseSwapchainImage(device, swapchain->shared, window, -1,
1348 swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001349 }
1350
1351 if (active) {
1352 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1353 }
1354
1355 if (!allocator) {
1356 allocator = &GetData(device).allocator;
1357 }
1358
1359 swapchain->~Swapchain();
1360 allocator->pfnFree(allocator->pUserData, swapchain);
1361}
1362
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001363static VkResult getProducerUsage(const VkDevice& device,
1364 const VkSwapchainCreateInfoKHR* create_info,
1365 const VkSwapchainImageUsageFlagsANDROID swapchain_image_usage,
1366 bool create_protected_swapchain,
1367 uint64_t* producer_usage) {
1368 // Get the physical device to query the appropriate producer usage
1369 const VkPhysicalDevice& pdev = GetData(device).driver_physical_device;
1370 const InstanceData& instance_data = GetData(pdev);
1371 const InstanceDriverTable& instance_dispatch = instance_data.driver;
1372 if (!instance_dispatch.GetPhysicalDeviceImageFormatProperties2 &&
1373 !instance_dispatch.GetPhysicalDeviceImageFormatProperties2KHR) {
1374 uint64_t native_usage = 0;
1375 void* usage_info_pNext = nullptr;
1376 VkResult result;
1377 VkImageCompressionControlEXT image_compression = {};
1378 const auto& dispatch = GetData(device).driver;
1379 if (dispatch.GetSwapchainGrallocUsage4ANDROID) {
1380 ATRACE_BEGIN("GetSwapchainGrallocUsage4ANDROID");
1381 VkGrallocUsageInfo2ANDROID gralloc_usage_info = {};
1382 gralloc_usage_info.sType =
1383 VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_2_ANDROID;
1384 gralloc_usage_info.format = create_info->imageFormat;
1385 gralloc_usage_info.imageUsage = create_info->imageUsage;
1386 gralloc_usage_info.swapchainImageUsage = swapchain_image_usage;
1387
1388 // Look through the pNext chain for an image compression control struct
1389 // if one is found AND the appropriate extensions are enabled,
1390 // append it to be the gralloc usage pNext chain
1391 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1392 while (create_infos->pNext) {
1393 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1394 create_infos->pNext);
1395 switch (create_infos->sType) {
1396 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1397 const VkImageCompressionControlEXT* compression_infos =
1398 reinterpret_cast<const VkImageCompressionControlEXT*>(
1399 create_infos);
1400 image_compression = *compression_infos;
1401 image_compression.pNext = nullptr;
1402 usage_info_pNext = &image_compression;
1403 } break;
1404
1405 default:
1406 // Ignore all other info structs
1407 break;
1408 }
1409 }
1410 gralloc_usage_info.pNext = usage_info_pNext;
1411
1412 result = dispatch.GetSwapchainGrallocUsage4ANDROID(
1413 device, &gralloc_usage_info, &native_usage);
1414 ATRACE_END();
1415 if (result != VK_SUCCESS) {
1416 ALOGE("vkGetSwapchainGrallocUsage4ANDROID failed: %d", result);
1417 return VK_ERROR_SURFACE_LOST_KHR;
1418 }
1419 } else if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
1420 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1421 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1422 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1423 gralloc_usage_info.format = create_info->imageFormat;
1424 gralloc_usage_info.imageUsage = create_info->imageUsage;
1425
1426 // Look through the pNext chain for an image compression control struct
1427 // if one is found AND the appropriate extensions are enabled,
1428 // append it to be the gralloc usage pNext chain
1429 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1430 while (create_infos->pNext) {
1431 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1432 create_infos->pNext);
1433 switch (create_infos->sType) {
1434 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1435 const VkImageCompressionControlEXT* compression_infos =
1436 reinterpret_cast<const VkImageCompressionControlEXT*>(
1437 create_infos);
1438 image_compression = *compression_infos;
1439 image_compression.pNext = nullptr;
1440 usage_info_pNext = &image_compression;
1441 } break;
1442
1443 default:
1444 // Ignore all other info structs
1445 break;
1446 }
1447 }
1448 gralloc_usage_info.pNext = usage_info_pNext;
1449
1450 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1451 device, &gralloc_usage_info, &native_usage);
1452 ATRACE_END();
1453 if (result != VK_SUCCESS) {
1454 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
1455 return VK_ERROR_SURFACE_LOST_KHR;
1456 }
1457 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
1458 uint64_t consumer_usage, producer_usage;
1459 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
1460 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1461 device, create_info->imageFormat, create_info->imageUsage,
1462 swapchain_image_usage, &consumer_usage, &producer_usage);
1463 ATRACE_END();
1464 if (result != VK_SUCCESS) {
1465 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
1466 return VK_ERROR_SURFACE_LOST_KHR;
1467 }
1468 native_usage =
1469 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
1470 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
1471 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
1472 int32_t legacy_usage = 0;
1473 result = dispatch.GetSwapchainGrallocUsageANDROID(
1474 device, create_info->imageFormat, create_info->imageUsage,
1475 &legacy_usage);
1476 ATRACE_END();
1477 if (result != VK_SUCCESS) {
1478 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
1479 return VK_ERROR_SURFACE_LOST_KHR;
1480 }
1481 native_usage = static_cast<uint64_t>(legacy_usage);
1482 }
1483 *producer_usage = native_usage;
1484
1485 return VK_SUCCESS;
1486 }
1487
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001488 // Look through the create_info pNext chain passed to createSwapchainKHR
1489 // for an image compression control struct.
1490 // if one is found AND the appropriate extensions are enabled, create a
1491 // VkImageCompressionControlEXT structure to pass on to GetPhysicalDeviceImageFormatProperties2
1492 void* compression_control_pNext = nullptr;
1493 VkImageCompressionControlEXT image_compression = {};
1494 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1495 while (create_infos->pNext) {
1496 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(create_infos->pNext);
1497 switch (create_infos->sType) {
1498 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1499 const VkImageCompressionControlEXT* compression_infos =
1500 reinterpret_cast<const VkImageCompressionControlEXT*>(create_infos);
1501 image_compression = *compression_infos;
1502 image_compression.pNext = nullptr;
1503 compression_control_pNext = &image_compression;
1504 } break;
1505 default:
1506 // Ignore all other info structs
1507 break;
1508 }
1509 }
1510
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001511 // call GetPhysicalDeviceImageFormatProperties2KHR
1512 VkPhysicalDeviceExternalImageFormatInfo external_image_format_info = {
1513 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001514 .pNext = compression_control_pNext,
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001515 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID,
1516 };
1517
1518 // AHB does not have an sRGB format so we can't pass it to GPDIFP
1519 // We need to convert the format to unorm if it is srgb
1520 VkFormat format = create_info->imageFormat;
1521 if (format == VK_FORMAT_R8G8B8A8_SRGB) {
1522 format = VK_FORMAT_R8G8B8A8_UNORM;
1523 }
1524
1525 VkPhysicalDeviceImageFormatInfo2 image_format_info = {
1526 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1527 .pNext = &external_image_format_info,
1528 .format = format,
1529 .type = VK_IMAGE_TYPE_2D,
1530 .tiling = VK_IMAGE_TILING_OPTIMAL,
1531 .usage = create_info->imageUsage,
1532 .flags = create_protected_swapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
1533 };
1534
1535 VkAndroidHardwareBufferUsageANDROID ahb_usage;
1536 ahb_usage.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_USAGE_ANDROID;
1537 ahb_usage.pNext = nullptr;
1538
1539 VkImageFormatProperties2 image_format_properties;
1540 image_format_properties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
1541 image_format_properties.pNext = &ahb_usage;
1542
1543 if (instance_dispatch.GetPhysicalDeviceImageFormatProperties2) {
1544 VkResult result = instance_dispatch.GetPhysicalDeviceImageFormatProperties2(
1545 pdev, &image_format_info, &image_format_properties);
1546 if (result != VK_SUCCESS) {
1547 ALOGE("VkGetPhysicalDeviceImageFormatProperties2 for AHB usage failed: %d", result);
1548 return VK_ERROR_SURFACE_LOST_KHR;
1549 }
1550 }
1551 else {
1552 VkResult result = instance_dispatch.GetPhysicalDeviceImageFormatProperties2KHR(
1553 pdev, &image_format_info,
1554 &image_format_properties);
1555 if (result != VK_SUCCESS) {
1556 ALOGE("VkGetPhysicalDeviceImageFormatProperties2KHR for AHB usage failed: %d",
1557 result);
1558 return VK_ERROR_SURFACE_LOST_KHR;
1559 }
1560 }
1561
1562 *producer_usage = ahb_usage.androidHardwareBufferUsage;
1563
1564 return VK_SUCCESS;
1565}
1566
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001567VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001568VkResult CreateSwapchainKHR(VkDevice device,
1569 const VkSwapchainCreateInfoKHR* create_info,
1570 const VkAllocationCallbacks* allocator,
1571 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001572 ATRACE_CALL();
1573
Jesse Halld7b994a2015-09-07 14:17:37 -07001574 int err;
1575 VkResult result = VK_SUCCESS;
1576
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001577 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1578 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1579 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1580 " oldSwapchain=0x%" PRIx64,
1581 reinterpret_cast<uint64_t>(create_info->surface),
1582 create_info->minImageCount, create_info->imageFormat,
1583 create_info->imageColorSpace, create_info->imageExtent.width,
1584 create_info->imageExtent.height, create_info->imageUsage,
1585 create_info->preTransform, create_info->presentMode,
1586 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1587
Jesse Hall1f91d392015-12-11 16:28:44 -08001588 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001589 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001590
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001591 PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001592 GetNativePixelFormat(create_info->imageFormat);
sergiuferentz47989332023-09-26 10:24:36 +00001593 DataSpace native_dataspace =
Sally Qiaa238972023-07-17 12:52:05 +08001594 GetNativeDataspace(create_info->imageColorSpace, native_pixel_format);
sergiuferentz47989332023-09-26 10:24:36 +00001595 if (native_dataspace == DataSpace::UNKNOWN) {
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001596 ALOGE(
1597 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1598 "failed: Unsupported color space",
1599 create_info->imageColorSpace);
1600 return VK_ERROR_INITIALIZATION_FAILED;
1601 }
1602
Jesse Hall42a9eec2016-06-03 12:39:49 -07001603 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001604 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001605 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001606 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001607 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001608 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001609 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001610 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001611 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1612 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001613 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001614 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001615
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001616 Surface& surface = *SurfaceFromHandle(create_info->surface);
1617
Jesse Halldc225072016-05-30 22:40:14 -07001618 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001619 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001620 " because it already has active swapchain 0x%" PRIx64
1621 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1622 reinterpret_cast<uint64_t>(create_info->surface),
1623 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1624 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1625 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1626 }
1627 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1628 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1629
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001630 // -- Reset the native window --
1631 // The native window might have been used previously, and had its properties
1632 // changed from defaults. That will affect the answer we get for queries
1633 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1634 // attempt such queries.
1635
Jesse Halldc225072016-05-30 22:40:14 -07001636 // The native window only allows dequeueing all buffers before any have
1637 // been queued, since after that point at least one is assumed to be in
1638 // non-FREE state at any given time. Disconnecting and re-connecting
1639 // orphans the previous buffers, getting us back to the state where we can
1640 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001641 //
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001642 // This is not necessary if the surface was never used previously.
1643 //
Yiwei Zhang70a21962019-05-31 17:26:52 -07001644 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001645 ANativeWindow* window = surface.window.get();
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001646 if (surface.used_by_swapchain) {
1647 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1648 ALOGW_IF(err != android::OK,
1649 "native_window_api_disconnect failed: %s (%d)", strerror(-err),
1650 err);
1651 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1652 ALOGW_IF(err != android::OK,
1653 "native_window_api_connect failed: %s (%d)", strerror(-err),
1654 err);
1655 }
Jesse Halldc225072016-05-30 22:40:14 -07001656
Nicolas Capens147b7da2021-04-09 14:53:06 -04001657 err =
1658 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001659 if (err != android::OK) {
1660 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1661 strerror(-err), err);
1662 return VK_ERROR_SURFACE_LOST_KHR;
1663 }
1664
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301665 int swap_interval =
1666 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001667 err = window->setSwapInterval(window, swap_interval);
1668 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001669 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1670 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001671 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001672 }
1673
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001674 err = native_window_set_shared_buffer_mode(window, false);
1675 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001676 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1677 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001678 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001679 }
1680
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001681 err = native_window_set_auto_refresh(window, false);
1682 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001683 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1684 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001685 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001686 }
1687
Jesse Halld7b994a2015-09-07 14:17:37 -07001688 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001689
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001690 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001691
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001692 err = native_window_set_buffers_format(
1693 window, static_cast<int>(native_pixel_format));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001694 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001695 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001696 toString(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001697 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001698 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001699
1700 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
sergiuferentz47989332023-09-26 10:24:36 +00001701 if (native_dataspace != DataSpace::ARBITRARY) {
1702 err = native_window_set_buffers_data_space(
1703 window, static_cast<android_dataspace_t>(native_dataspace));
Yiwei Zhang51572c22022-07-22 23:08:30 +00001704 if (err != android::OK) {
1705 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1706 native_dataspace, strerror(-err), err);
1707 return VK_ERROR_SURFACE_LOST_KHR;
1708 }
Jesse Hall517274a2016-02-10 00:07:18 -08001709 }
1710
Jesse Hall3dd678a2016-01-08 21:52:01 -08001711 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001712 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001713 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001714 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001715 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1716 create_info->imageExtent.width, create_info->imageExtent.height,
1717 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001718 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001719 }
1720
Jesse Hall178b6962016-02-24 15:39:50 -08001721 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1722 // applied during rendering. native_window_set_transform() expects the
1723 // inverse: the transform the app is requesting that the compositor perform
1724 // during composition. With native windows, pre-transform works by rendering
1725 // with the same transform the compositor is applying (as in Vulkan), but
1726 // then requesting the inverse transform, so that when the compositor does
1727 // it's job the two transforms cancel each other out and the compositor ends
1728 // up applying an identity transform to the app's buffer.
1729 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001730 window, InvertTransformToNative(create_info->preTransform));
1731 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001732 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1733 InvertTransformToNative(create_info->preTransform),
1734 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001735 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001736 }
1737
Jesse Hallf64ca122015-11-03 16:11:10 -08001738 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001739 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1740 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001741 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1742 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001743 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001744 }
1745
Chris Forbes97ef4612017-03-30 19:37:50 +13001746 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001747 if (IsSharedPresentMode(create_info->presentMode)) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001748 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001749 err = native_window_set_shared_buffer_mode(window, true);
1750 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001751 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1752 return VK_ERROR_SURFACE_LOST_KHR;
1753 }
1754 }
1755
1756 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001757 err = native_window_set_auto_refresh(window, true);
1758 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001759 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1760 return VK_ERROR_SURFACE_LOST_KHR;
1761 }
1762 }
1763
Ian Elliott16c443c2021-11-30 17:10:32 -07001764 int query_value;
1765 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1766 &query_value);
1767 if (err != android::OK || query_value < 0) {
1768 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1769 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001770 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001771 }
Trevor David Black8c0122e2023-09-07 20:33:54 +00001772 const uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
Chris Forbes2c8fc752017-03-17 11:28:32 +13001773
Ian Elliott5396b702021-12-13 19:32:34 -07001774 // Lower layer insists that we have at least min_undequeued_buffers + 1
1775 // buffers. This is wasteful and we'd like to relax it in the shared case,
1776 // but not all the pieces are in place for that to work yet. Note we only
1777 // lie to the lower layer--we don't want to give the app back a swapchain
1778 // with extra images (which they can't actually use!).
Trevor David Black8c0122e2023-09-07 20:33:54 +00001779 const uint32_t min_buffer_count = min_undequeued_buffers + 1;
1780
1781 uint32_t num_images;
1782 if (create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
1783 num_images = std::max(3u, create_info->minImageCount);
1784 } else {
1785 num_images = create_info->minImageCount;
1786 }
1787
1788 const uint32_t buffer_count = std::max(min_buffer_count, num_images);
1789 err = native_window_set_buffer_count(window, buffer_count);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001790 if (err != android::OK) {
Trevor David Black8c0122e2023-09-07 20:33:54 +00001791 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", buffer_count,
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001792 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001793 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001794 }
1795
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001796 // In shared mode the num_images must be one regardless of how many
1797 // buffers were allocated for the buffer queue.
1798 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1799 num_images = 1;
1800 }
1801
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001802 // Look through the create_info pNext chain passed to createSwapchainKHR
1803 // for an image compression control struct.
1804 // if one is found AND the appropriate extensions are enabled, create a
1805 // VkImageCompressionControlEXT structure to pass on to VkImageCreateInfo
1806 // TODO check for imageCompressionControlSwapchain feature is enabled
Trevor David Black2cc44682022-03-09 00:31:38 +00001807 void* usage_info_pNext = nullptr;
1808 VkImageCompressionControlEXT image_compression = {};
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001809 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1810 while (create_infos->pNext) {
1811 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(create_infos->pNext);
1812 switch (create_infos->sType) {
1813 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1814 const VkImageCompressionControlEXT* compression_infos =
1815 reinterpret_cast<const VkImageCompressionControlEXT*>(create_infos);
1816 image_compression = *compression_infos;
1817 image_compression.pNext = nullptr;
1818 usage_info_pNext = &image_compression;
1819 } break;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001820
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001821 default:
1822 // Ignore all other info structs
1823 break;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001824 }
Jesse Hall70f93352015-11-04 09:41:31 -08001825 }
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001826
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001827 // Get the appropriate native_usage for the images
1828 // Get the consumer usage
1829 uint64_t native_usage = surface.consumer_usage;
1830 // Determine if the swapchain is protected
1831 bool create_protected_swapchain = false;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001832 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001833 create_protected_swapchain = true;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001834 native_usage |= BufferUsage::PROTECTED;
1835 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001836 // Get the producer usage
1837 uint64_t producer_usage;
1838 result = getProducerUsage(device, create_info, swapchain_image_usage, create_protected_swapchain, &producer_usage);
1839 if (result != VK_SUCCESS) {
1840 return result;
1841 }
1842 native_usage |= producer_usage;
1843
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001844 err = native_window_set_usage(window, native_usage);
1845 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001846 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001847 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001848 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001849
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001850 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001851 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1852 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001853 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1854 strerror(-err), err);
1855 return VK_ERROR_SURFACE_LOST_KHR;
1856 }
1857
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001858 int64_t refresh_duration;
1859 err = native_window_get_refresh_cycle_duration(window, &refresh_duration);
1860 if (err != android::OK) {
1861 ALOGE("native_window_get_refresh_cycle_duration query failed: %s (%d)",
1862 strerror(-err), err);
1863 return VK_ERROR_SURFACE_LOST_KHR;
1864 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001865 // -- Allocate our Swapchain object --
1866 // After this point, we must deallocate the swapchain on error.
1867
Jesse Hall1f91d392015-12-11 16:28:44 -08001868 void* mem = allocator->pfnAllocation(allocator->pUserData,
1869 sizeof(Swapchain), alignof(Swapchain),
1870 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001871
Jesse Hall1356b0d2015-11-23 17:24:58 -08001872 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001873 return VK_ERROR_OUT_OF_HOST_MEMORY;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001874
silence_dogood73597592019-05-23 16:57:37 -07001875 Swapchain* swapchain = new (mem)
1876 Swapchain(surface, num_images, create_info->presentMode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001877 TranslateVulkanToNativeTransform(create_info->preTransform),
1878 refresh_duration);
Chris Forbesb56287a2017-01-12 14:28:58 +13001879 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1880#pragma clang diagnostic push
1881#pragma clang diagnostic ignored "-Wold-style-cast"
1882 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1883#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00001884 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13001885 .usage = swapchain_image_usage,
1886 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001887 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001888#pragma clang diagnostic push
1889#pragma clang diagnostic ignored "-Wold-style-cast"
1890 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1891#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001892 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001893 };
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001894
Jesse Halld7b994a2015-09-07 14:17:37 -07001895 VkImageCreateInfo image_create = {
1896 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001897 .pNext = nullptr,
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001898 .flags = create_protected_swapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07001899 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08001900 .format = create_info->imageFormat,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001901 .extent = {
1902 create_info->imageExtent.width,
1903 create_info->imageExtent.height,
1904 1
1905 },
Jesse Halld7b994a2015-09-07 14:17:37 -07001906 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08001907 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08001908 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07001909 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001910 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001911 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08001912 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07001913 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1914 };
1915
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001916 // Note: don't do deferred allocation for shared present modes. There's only one buffer
1917 // involved so very little benefit.
1918 if ((create_info->flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT) &&
1919 !IsSharedPresentMode(create_info->presentMode)) {
1920 // Don't want to touch the underlying gralloc buffers yet;
1921 // instead just create unbound VkImages which will later be bound to memory inside
1922 // AcquireNextImage.
1923 VkImageSwapchainCreateInfoKHR image_swapchain_create = {
1924 .sType = VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR,
1925 .pNext = nullptr,
1926 .swapchain = HandleFromSwapchain(swapchain),
1927 };
1928 image_create.pNext = &image_swapchain_create;
Jesse Halld7b994a2015-09-07 14:17:37 -07001929
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001930 for (uint32_t i = 0; i < num_images; i++) {
1931 Swapchain::Image& img = swapchain->images[i];
1932 img.buffer = nullptr;
1933 img.dequeued = false;
1934
1935 result = dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1936 if (result != VK_SUCCESS) {
1937 ALOGD("vkCreateImage w/ for deferred swapchain image failed: %u", result);
1938 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08001939 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001940 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001941 } else {
1942 // -- Dequeue all buffers and create a VkImage for each --
1943 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07001944
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001945 for (uint32_t i = 0; i < num_images; i++) {
1946 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07001947
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001948 ANativeWindowBuffer* buffer;
1949 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
1950 if (err != android::OK) {
1951 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
1952 switch (-err) {
1953 case ENOMEM:
1954 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
1955 break;
1956 default:
1957 result = VK_ERROR_SURFACE_LOST_KHR;
1958 break;
1959 }
1960 break;
1961 }
1962 img.buffer = buffer;
1963 img.dequeued = true;
1964
1965 image_native_buffer.handle = img.buffer->handle;
1966 image_native_buffer.stride = img.buffer->stride;
1967 image_native_buffer.format = img.buffer->format;
1968 image_native_buffer.usage = int(img.buffer->usage);
1969 android_convertGralloc0To1Usage(int(img.buffer->usage),
1970 &image_native_buffer.usage2.producer,
1971 &image_native_buffer.usage2.consumer);
1972 image_native_buffer.usage3 = img.buffer->usage;
Trevor David Black0db7a092023-12-11 23:46:36 +00001973 image_native_buffer.ahb =
1974 ANativeWindowBuffer_getHardwareBuffer(img.buffer.get());
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001975 image_create.pNext = &image_native_buffer;
1976
1977 ATRACE_BEGIN("CreateImage");
1978 result =
1979 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1980 ATRACE_END();
1981 if (result != VK_SUCCESS) {
1982 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
1983 break;
1984 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001985 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001986
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001987 // -- Cancel all buffers, returning them to the queue --
1988 // If an error occurred before, also destroy the VkImage and release the
1989 // buffer reference. Otherwise, we retain a strong reference to the buffer.
1990 for (uint32_t i = 0; i < num_images; i++) {
1991 Swapchain::Image& img = swapchain->images[i];
1992 if (img.dequeued) {
1993 if (!swapchain->shared) {
1994 window->cancelBuffer(window, img.buffer.get(),
1995 img.dequeue_fence);
1996 img.dequeue_fence = -1;
1997 img.dequeued = false;
1998 }
Chris Forbese0ced032017-03-30 19:44:15 +13001999 }
Chris Forbes31b85c22018-05-29 15:03:28 -07002000 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002001 }
2002
2003 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07002004 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
2005 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07002006 return result;
2007 }
2008
Yiwei Zhang69395cd2019-07-03 16:55:39 -07002009 if (transform_hint != swapchain->pre_transform) {
2010 // Log that the app is not doing pre-rotation.
2011 android::GraphicsEnv::getInstance().setTargetStats(
2012 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
2013 }
2014
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00002015 // Set stats for creating a Vulkan swapchain
2016 android::GraphicsEnv::getInstance().setTargetStats(
2017 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
2018
Yiwei Zhang3b88f312023-04-18 23:11:35 +00002019 surface.used_by_swapchain = true;
Jesse Halldc225072016-05-30 22:40:14 -07002020 surface.swapchain_handle = HandleFromSwapchain(swapchain);
2021 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002022 return VK_SUCCESS;
2023}
2024
Jesse Halle1b12782015-11-30 11:27:32 -08002025VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002026void DestroySwapchainKHR(VkDevice device,
2027 VkSwapchainKHR swapchain_handle,
2028 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002029 ATRACE_CALL();
2030
Yiwei Zhang533cea92019-06-03 18:43:24 -07002031 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07002032}
2033
Jesse Halle1b12782015-11-30 11:27:32 -08002034VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002035VkResult GetSwapchainImagesKHR(VkDevice,
2036 VkSwapchainKHR swapchain_handle,
2037 uint32_t* count,
2038 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002039 ATRACE_CALL();
2040
Jesse Halld7b994a2015-09-07 14:17:37 -07002041 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07002042 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
2043 "getting images for non-active swapchain 0x%" PRIx64
2044 "; only dequeued image handles are valid",
2045 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07002046 VkResult result = VK_SUCCESS;
2047 if (images) {
2048 uint32_t n = swapchain.num_images;
2049 if (*count < swapchain.num_images) {
2050 n = *count;
2051 result = VK_INCOMPLETE;
2052 }
2053 for (uint32_t i = 0; i < n; i++)
2054 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07002055 *count = n;
2056 } else {
2057 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07002058 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002059 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002060}
2061
Jesse Halle1b12782015-11-30 11:27:32 -08002062VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002063VkResult AcquireNextImageKHR(VkDevice device,
2064 VkSwapchainKHR swapchain_handle,
2065 uint64_t timeout,
2066 VkSemaphore semaphore,
2067 VkFence vk_fence,
2068 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002069 ATRACE_CALL();
2070
Jesse Halld7b994a2015-09-07 14:17:37 -07002071 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08002072 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07002073 VkResult result;
2074 int err;
2075
Jesse Halldc225072016-05-30 22:40:14 -07002076 if (swapchain.surface.swapchain_handle != swapchain_handle)
2077 return VK_ERROR_OUT_OF_DATE_KHR;
2078
Chris Forbesc88409c2017-03-30 19:47:37 +13002079 if (swapchain.shared) {
2080 // In shared mode, we keep the buffer dequeued all the time, so we don't
2081 // want to dequeue a buffer here. Instead, just ask the driver to ensure
2082 // the semaphore and fence passed to us will be signalled.
2083 *image_index = 0;
2084 result = GetData(device).driver.AcquireImageANDROID(
2085 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
2086 return result;
2087 }
2088
Yiwei Zhang705c2e62019-12-18 23:12:43 -08002089 const nsecs_t acquire_next_image_timeout =
2090 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
2091 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
2092 // Cache the timeout to avoid the duplicate binder cost.
2093 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
2094 acquire_next_image_timeout);
2095 if (err != android::OK) {
2096 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
2097 strerror(-err), err);
2098 return VK_ERROR_SURFACE_LOST_KHR;
2099 }
2100 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
2101 }
2102
Jesse Halld7b994a2015-09-07 14:17:37 -07002103 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08002104 int fence_fd;
2105 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07002106 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08002107 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
2108 return timeout ? VK_TIMEOUT : VK_NOT_READY;
2109 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07002110 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07002111 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002112 }
2113
2114 uint32_t idx;
2115 for (idx = 0; idx < swapchain.num_images; idx++) {
2116 if (swapchain.images[idx].buffer.get() == buffer) {
2117 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08002118 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07002119 break;
2120 }
2121 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002122
2123 // If this is a deferred alloc swapchain, this may be the first time we've
2124 // seen a particular buffer. If so, there should be an empty slot. Find it,
2125 // and bind the gralloc buffer to the VkImage for that slot. If there is no
2126 // empty slot, then we dequeued an unexpected buffer. Non-deferred swapchains
2127 // will also take this path, but will never have an empty slot since we
2128 // populated them all upfront.
2129 if (idx == swapchain.num_images) {
2130 for (idx = 0; idx < swapchain.num_images; idx++) {
2131 if (!swapchain.images[idx].buffer) {
2132 // Note: this structure is technically required for
2133 // Vulkan correctness, even though the driver is probably going
2134 // to use everything from the VkNativeBufferANDROID below.
2135 // This is kindof silly, but it's how we did the ANB
2136 // side of VK_KHR_swapchain v69, so we're stuck with it unless
2137 // we want to go tinkering with the ANB spec some more.
2138 VkBindImageMemorySwapchainInfoKHR bimsi = {
2139 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR,
2140 .pNext = nullptr,
2141 .swapchain = swapchain_handle,
2142 .imageIndex = idx,
2143 };
2144 VkNativeBufferANDROID nb = {
2145 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2146 .pNext = &bimsi,
2147 .handle = buffer->handle,
2148 .stride = buffer->stride,
2149 .format = buffer->format,
2150 .usage = int(buffer->usage),
Trevor David Black0db7a092023-12-11 23:46:36 +00002151 .usage3 = buffer->usage,
2152 .ahb = ANativeWindowBuffer_getHardwareBuffer(buffer),
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002153 };
Trevor David Black0db7a092023-12-11 23:46:36 +00002154 android_convertGralloc0To1Usage(int(buffer->usage),
2155 &nb.usage2.producer,
2156 &nb.usage2.consumer);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002157 VkBindImageMemoryInfo bimi = {
2158 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO,
2159 .pNext = &nb,
2160 .image = swapchain.images[idx].image,
2161 .memory = VK_NULL_HANDLE,
2162 .memoryOffset = 0,
2163 };
2164 result = GetData(device).driver.BindImageMemory2(device, 1, &bimi);
2165 if (result != VK_SUCCESS) {
2166 // This shouldn't really happen. If it does, something is probably
2167 // unrecoverably wrong with the swapchain and its images. Cancel
2168 // the buffer and declare the swapchain broken.
2169 ALOGE("failed to do deferred gralloc buffer bind");
2170 window->cancelBuffer(window, buffer, fence_fd);
2171 return VK_ERROR_OUT_OF_DATE_KHR;
2172 }
2173
2174 swapchain.images[idx].dequeued = true;
2175 swapchain.images[idx].dequeue_fence = fence_fd;
2176 swapchain.images[idx].buffer = buffer;
2177 break;
2178 }
2179 }
2180 }
2181
2182 // The buffer doesn't match any slot. This shouldn't normally happen, but is
2183 // possible if the bufferqueue is reconfigured behind libvulkan's back. If this
2184 // happens, just declare the swapchain to be broken and the app will recreate it.
Jesse Halld7b994a2015-09-07 14:17:37 -07002185 if (idx == swapchain.num_images) {
2186 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08002187 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002188 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002189 }
2190
2191 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08002192 if (fence_fd != -1) {
2193 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002194 if (fence_clone == -1) {
2195 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
2196 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08002197 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07002198 }
2199 }
2200
Chia-I Wu4a6a9162016-03-26 07:17:34 +08002201 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08002202 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07002203 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08002204 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
2205 // even if the call fails. We could close it ourselves on failure, but
2206 // that would create a race condition if the driver closes it on a
2207 // failure path: some other thread might create an fd with the same
2208 // number between the time the driver closes it and the time we close
2209 // it. We must assume one of: the driver *always* closes it even on
2210 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08002211 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002212 swapchain.images[idx].dequeued = false;
2213 swapchain.images[idx].dequeue_fence = -1;
2214 return result;
2215 }
2216
2217 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002218 return VK_SUCCESS;
2219}
2220
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002221VKAPI_ATTR
2222VkResult AcquireNextImage2KHR(VkDevice device,
2223 const VkAcquireNextImageInfoKHR* pAcquireInfo,
2224 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002225 ATRACE_CALL();
2226
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002227 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
2228 pAcquireInfo->timeout, pAcquireInfo->semaphore,
2229 pAcquireInfo->fence, pImageIndex);
2230}
2231
Jesse Halldc225072016-05-30 22:40:14 -07002232static VkResult WorstPresentResult(VkResult a, VkResult b) {
2233 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
2234 // (in spec version 1.0.14).
2235 static const VkResult kWorstToBest[] = {
2236 VK_ERROR_DEVICE_LOST,
2237 VK_ERROR_SURFACE_LOST_KHR,
2238 VK_ERROR_OUT_OF_DATE_KHR,
2239 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2240 VK_ERROR_OUT_OF_HOST_MEMORY,
2241 VK_SUBOPTIMAL_KHR,
2242 };
2243 for (auto result : kWorstToBest) {
2244 if (a == result || b == result)
2245 return result;
2246 }
2247 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
2248 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
2249 return a != VK_SUCCESS ? a : b;
2250}
2251
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002252// KHR_incremental_present aspect of QueuePresentKHR
2253static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
2254 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
2255 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
2256 auto const& rect = pRegion->pRectangles[i];
2257 if (rect.layer > 0) {
2258 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
2259 rect.layer);
2260 }
2261
2262 rects[i].left = rect.offset.x;
2263 rects[i].bottom = rect.offset.y;
2264 rects[i].right = rect.offset.x + rect.extent.width;
2265 rects[i].top = rect.offset.y + rect.extent.height;
2266 }
2267 native_window_set_surface_damage(window, rects.data(), rects.size());
2268}
2269
2270// GOOGLE_display_timing aspect of QueuePresentKHR
2271static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
2272 ANativeWindow *window = swapchain.surface.window.get();
2273
2274 // We don't know whether the app will actually use GOOGLE_display_timing
2275 // with a particular swapchain until QueuePresent; enable it on the BQ
2276 // now if needed
2277 if (!swapchain.frame_timestamps_enabled) {
2278 ALOGV("Calling native_window_enable_frame_timestamps(true)");
2279 native_window_enable_frame_timestamps(window, true);
2280 swapchain.frame_timestamps_enabled = true;
2281 }
2282
2283 // Record the nativeFrameId so it can be later correlated to
2284 // this present.
2285 uint64_t nativeFrameId = 0;
2286 int err = native_window_get_next_frame_id(
2287 window, &nativeFrameId);
2288 if (err != android::OK) {
2289 ALOGE("Failed to get next native frame ID.");
2290 }
2291
2292 // Add a new timing record with the user's presentID and
2293 // the nativeFrameId.
2294 swapchain.timing.emplace_back(pTime, nativeFrameId);
2295 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
2296 swapchain.timing.erase(
2297 swapchain.timing.begin(),
2298 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
2299 }
2300 if (pTime->desiredPresentTime) {
2301 ALOGV(
2302 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
2303 pTime->desiredPresentTime);
2304 native_window_set_buffers_timestamp(
2305 window,
2306 static_cast<int64_t>(pTime->desiredPresentTime));
2307 }
2308}
2309
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002310// EXT_swapchain_maintenance1 present mode change
2311static bool SetSwapchainPresentMode(ANativeWindow *window, VkPresentModeKHR mode) {
2312 // There is no dynamic switching between non-shared present modes.
2313 // All we support is switching between demand and continuous refresh.
2314 if (!IsSharedPresentMode(mode))
2315 return true;
2316
2317 int err = native_window_set_auto_refresh(window,
2318 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
2319 if (err != android::OK) {
2320 ALOGE("native_window_set_auto_refresh() failed: %s (%d)",
2321 strerror(-err), err);
2322 return false;
2323 }
2324
2325 return true;
2326}
2327
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002328static VkResult PresentOneSwapchain(
2329 VkQueue queue,
2330 Swapchain& swapchain,
2331 uint32_t imageIndex,
2332 const VkPresentRegionKHR *pRegion,
2333 const VkPresentTimeGOOGLE *pTime,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002334 VkFence presentFence,
2335 const VkPresentModeKHR *pPresentMode,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002336 uint32_t waitSemaphoreCount,
2337 const VkSemaphore *pWaitSemaphores) {
2338
2339 VkDevice device = GetData(queue).driver_device;
2340 const auto& dispatch = GetData(queue).driver;
2341
2342 Swapchain::Image& img = swapchain.images[imageIndex];
2343 VkResult swapchain_result = VK_SUCCESS;
2344 VkResult result;
2345 int err;
2346
2347 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
2348 // wait semaphores, so this doesn't actually work for the multiple swapchain
2349 // case.
2350 int fence = -1;
2351 result = dispatch.QueueSignalReleaseImageANDROID(
2352 queue, waitSemaphoreCount,
2353 pWaitSemaphores, img.image, &fence);
2354 if (result != VK_SUCCESS) {
2355 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
2356 swapchain_result = result;
2357 }
2358 if (img.release_fence >= 0)
2359 close(img.release_fence);
2360 img.release_fence = fence < 0 ? -1 : dup(fence);
2361
2362 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
2363 ANativeWindow* window = swapchain.surface.window.get();
2364 if (swapchain_result == VK_SUCCESS) {
2365
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002366 if (presentFence != VK_NULL_HANDLE) {
2367 int fence_copy = fence < 0 ? -1 : dup(fence);
2368 VkImportFenceFdInfoKHR iffi = {
2369 VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,
2370 nullptr,
2371 presentFence,
2372 VK_FENCE_IMPORT_TEMPORARY_BIT,
2373 VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,
2374 fence_copy,
2375 };
2376 if (VK_SUCCESS != dispatch.ImportFenceFdKHR(device, &iffi) && fence_copy >= 0) {
2377 // ImportFenceFdKHR takes ownership only if it succeeds
2378 close(fence_copy);
2379 }
2380 }
2381
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002382 if (pRegion) {
2383 SetSwapchainSurfaceDamage(window, pRegion);
2384 }
2385 if (pTime) {
2386 SetSwapchainFrameTimestamp(swapchain, pTime);
2387 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002388 if (pPresentMode) {
2389 if (!SetSwapchainPresentMode(window, *pPresentMode))
2390 swapchain_result = WorstPresentResult(swapchain_result,
2391 VK_ERROR_SURFACE_LOST_KHR);
2392 }
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002393
2394 err = window->queueBuffer(window, img.buffer.get(), fence);
2395 // queueBuffer always closes fence, even on error
2396 if (err != android::OK) {
2397 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
2398 swapchain_result = WorstPresentResult(
2399 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2400 } else {
2401 if (img.dequeue_fence >= 0) {
2402 close(img.dequeue_fence);
2403 img.dequeue_fence = -1;
2404 }
2405 img.dequeued = false;
2406 }
2407
2408 // If the swapchain is in shared mode, immediately dequeue the
2409 // buffer so it can be presented again without an intervening
2410 // call to AcquireNextImageKHR. We expect to get the same buffer
2411 // back from every call to dequeueBuffer in this mode.
2412 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
2413 ANativeWindowBuffer* buffer;
2414 int fence_fd;
2415 err = window->dequeueBuffer(window, &buffer, &fence_fd);
2416 if (err != android::OK) {
2417 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
2418 swapchain_result = WorstPresentResult(swapchain_result,
2419 VK_ERROR_SURFACE_LOST_KHR);
2420 } else if (img.buffer != buffer) {
2421 ALOGE("got wrong image back for shared swapchain");
2422 swapchain_result = WorstPresentResult(swapchain_result,
2423 VK_ERROR_SURFACE_LOST_KHR);
2424 } else {
2425 img.dequeue_fence = fence_fd;
2426 img.dequeued = true;
2427 }
2428 }
2429 }
2430 if (swapchain_result != VK_SUCCESS) {
2431 OrphanSwapchain(device, &swapchain);
2432 }
2433 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
2434 // and only when the window's transform/rotation changes. Extent
2435 // changes will not cause VK_SUBOPTIMAL_KHR because of the
2436 // application issues that were caused when the following transform
2437 // change was added.
2438 int window_transform_hint;
2439 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
2440 &window_transform_hint);
2441 if (err != android::OK) {
2442 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
2443 strerror(-err), err);
2444 swapchain_result = WorstPresentResult(
2445 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2446 }
2447 if (swapchain.pre_transform != window_transform_hint) {
2448 swapchain_result =
2449 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
2450 }
2451 } else {
2452 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
2453 img, true);
2454 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
2455 }
2456
2457 return swapchain_result;
2458}
2459
Jesse Halle1b12782015-11-30 11:27:32 -08002460VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002461VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002462 ATRACE_CALL();
2463
Jesse Halld7b994a2015-09-07 14:17:37 -07002464 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
2465 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
2466 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07002467
Jesse Halld7b994a2015-09-07 14:17:37 -07002468 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07002469
Ian Elliottcb351132016-12-13 10:30:40 -07002470 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002471 const VkPresentRegionsKHR* present_regions = nullptr;
2472 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002473 const VkSwapchainPresentFenceInfoEXT* present_fences = nullptr;
2474 const VkSwapchainPresentModeInfoEXT* present_modes = nullptr;
2475
Ian Elliottcb351132016-12-13 10:30:40 -07002476 const VkPresentRegionsKHR* next =
2477 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
2478 while (next) {
2479 switch (next->sType) {
2480 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
2481 present_regions = next;
2482 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07002483 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002484 present_times =
2485 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
2486 break;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002487 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT:
2488 present_fences =
2489 reinterpret_cast<const VkSwapchainPresentFenceInfoEXT*>(next);
2490 break;
2491 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT:
2492 present_modes =
2493 reinterpret_cast<const VkSwapchainPresentModeInfoEXT*>(next);
2494 break;
Ian Elliottcb351132016-12-13 10:30:40 -07002495 default:
2496 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
2497 next->sType);
2498 break;
2499 }
2500 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2501 }
2502 ALOGV_IF(
2503 present_regions &&
2504 present_regions->swapchainCount != present_info->swapchainCount,
2505 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002506 ALOGV_IF(present_times &&
2507 present_times->swapchainCount != present_info->swapchainCount,
2508 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2509 "VkPresentInfo::swapchainCount");
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002510 ALOGV_IF(present_fences &&
2511 present_fences->swapchainCount != present_info->swapchainCount,
2512 "VkSwapchainPresentFenceInfoEXT::swapchainCount != "
2513 "VkPresentInfo::swapchainCount");
2514 ALOGV_IF(present_modes &&
2515 present_modes->swapchainCount != present_info->swapchainCount,
2516 "VkSwapchainPresentModeInfoEXT::swapchainCount != "
2517 "VkPresentInfo::swapchainCount");
2518
Ian Elliottcb351132016-12-13 10:30:40 -07002519 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002520 (present_regions) ? present_regions->pRegions : nullptr;
2521 const VkPresentTimeGOOGLE* times =
2522 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002523
Jesse Halld7b994a2015-09-07 14:17:37 -07002524 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2525 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002526 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002527
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002528 VkResult swapchain_result = PresentOneSwapchain(
2529 queue,
2530 swapchain,
2531 present_info->pImageIndices[sc],
2532 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2533 times ? &times[sc] : nullptr,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002534 present_fences ? present_fences->pFences[sc] : VK_NULL_HANDLE,
2535 present_modes ? &present_modes->pPresentModes[sc] : nullptr,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002536 present_info->waitSemaphoreCount,
2537 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002538
Jesse Halla9e57032015-11-30 01:03:10 -08002539 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002540 present_info->pResults[sc] = swapchain_result;
2541
2542 if (swapchain_result != final_result)
2543 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002544 }
2545
2546 return final_result;
2547}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002548
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002549VKAPI_ATTR
2550VkResult GetRefreshCycleDurationGOOGLE(
2551 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002552 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002553 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002554 ATRACE_CALL();
2555
Ian Elliott62c48c92017-01-20 13:13:20 -07002556 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00002557 VkResult result = swapchain.get_refresh_duration(pDisplayTimingProperties->refreshDuration);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002558
2559 return result;
2560}
2561
2562VKAPI_ATTR
2563VkResult GetPastPresentationTimingGOOGLE(
2564 VkDevice,
2565 VkSwapchainKHR swapchain_handle,
2566 uint32_t* count,
2567 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002568 ATRACE_CALL();
2569
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002570 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002571 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2572 return VK_ERROR_OUT_OF_DATE_KHR;
2573 }
2574
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002575 ANativeWindow* window = swapchain.surface.window.get();
2576 VkResult result = VK_SUCCESS;
2577
2578 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002579 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002580 native_window_enable_frame_timestamps(window, true);
2581 swapchain.frame_timestamps_enabled = true;
2582 }
2583
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002584 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002585 // Get the latest ready timing count before copying, since the copied
2586 // timing info will be erased in copy_ready_timings function.
2587 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002588 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002589 // Check the *count here against the recorded ready timing count, since
2590 // *count can be overwritten per spec describes.
2591 if (*count < n) {
2592 result = VK_INCOMPLETE;
2593 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002594 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002595 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002596 }
2597
2598 return result;
2599}
2600
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002601VKAPI_ATTR
2602VkResult GetSwapchainStatusKHR(
2603 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002604 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002605 ATRACE_CALL();
2606
Chris Forbes4e18ba82017-01-20 12:50:17 +13002607 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002608 VkResult result = VK_SUCCESS;
2609
Chris Forbes4e18ba82017-01-20 12:50:17 +13002610 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2611 return VK_ERROR_OUT_OF_DATE_KHR;
2612 }
2613
Yiwei Zhanga885c062019-10-24 12:07:57 -07002614 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002615
2616 return result;
2617}
2618
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002619VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002620 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002621 uint32_t swapchainCount,
2622 const VkSwapchainKHR* pSwapchains,
2623 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002624 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002625
2626 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2627 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2628 if (!swapchain)
2629 continue;
2630
2631 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2632
2633 ANativeWindow* window = swapchain->surface.window.get();
2634
2635 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2636 const android_smpte2086_metadata smpteMetdata = {
2637 {vulkanMetadata.displayPrimaryRed.x,
2638 vulkanMetadata.displayPrimaryRed.y},
2639 {vulkanMetadata.displayPrimaryGreen.x,
2640 vulkanMetadata.displayPrimaryGreen.y},
2641 {vulkanMetadata.displayPrimaryBlue.x,
2642 vulkanMetadata.displayPrimaryBlue.y},
2643 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2644 vulkanMetadata.maxLuminance,
2645 vulkanMetadata.minLuminance};
2646 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2647
2648 const android_cta861_3_metadata cta8613Metadata = {
2649 vulkanMetadata.maxContentLightLevel,
2650 vulkanMetadata.maxFrameAverageLightLevel};
2651 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2652 }
2653
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002654 return;
2655}
2656
Yiwei Zhang0f475222019-04-11 19:38:00 -07002657static void InterceptBindImageMemory2(
2658 uint32_t bind_info_count,
2659 const VkBindImageMemoryInfo* bind_infos,
2660 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2661 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2662 out_native_buffers->clear();
2663 out_bind_infos->clear();
2664
2665 if (!bind_info_count)
2666 return;
2667
2668 std::unordered_set<uint32_t> intercepted_indexes;
2669
2670 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2671 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2672 bind_infos[idx].pNext);
2673 while (info &&
2674 info->sType !=
2675 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2676 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2677 info->pNext);
2678 }
2679
2680 if (!info)
2681 continue;
2682
2683 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2684 "swapchain handle must not be NULL");
2685 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2686 ALOG_ASSERT(
2687 info->imageIndex < swapchain->num_images,
2688 "imageIndex must be less than the number of images in swapchain");
2689
2690 ANativeWindowBuffer* buffer =
2691 swapchain->images[info->imageIndex].buffer.get();
2692 VkNativeBufferANDROID native_buffer = {
2693#pragma clang diagnostic push
2694#pragma clang diagnostic ignored "-Wold-style-cast"
2695 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2696#pragma clang diagnostic pop
2697 .pNext = bind_infos[idx].pNext,
2698 .handle = buffer->handle,
2699 .stride = buffer->stride,
2700 .format = buffer->format,
2701 .usage = int(buffer->usage),
Trevor David Black0db7a092023-12-11 23:46:36 +00002702 .usage3 = buffer->usage,
2703 .ahb = ANativeWindowBuffer_getHardwareBuffer(buffer),
Yiwei Zhang0f475222019-04-11 19:38:00 -07002704 };
Trevor David Black0db7a092023-12-11 23:46:36 +00002705 android_convertGralloc0To1Usage(int(buffer->usage),
2706 &native_buffer.usage2.producer,
2707 &native_buffer.usage2.consumer);
Yiwei Zhang0f475222019-04-11 19:38:00 -07002708 // Reserve enough space to avoid letting re-allocation invalidate the
2709 // addresses of the elements inside.
2710 out_native_buffers->reserve(bind_info_count);
2711 out_native_buffers->emplace_back(native_buffer);
2712
2713 // Reserve the space now since we know how much is needed now.
2714 out_bind_infos->reserve(bind_info_count);
2715 out_bind_infos->emplace_back(bind_infos[idx]);
2716 out_bind_infos->back().pNext = &out_native_buffers->back();
2717
2718 intercepted_indexes.insert(idx);
2719 }
2720
2721 if (intercepted_indexes.empty())
2722 return;
2723
2724 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2725 if (intercepted_indexes.count(idx))
2726 continue;
2727 out_bind_infos->emplace_back(bind_infos[idx]);
2728 }
2729}
2730
Yiwei Zhang23143102019-04-10 18:24:05 -07002731VKAPI_ATTR
2732VkResult BindImageMemory2(VkDevice device,
2733 uint32_t bindInfoCount,
2734 const VkBindImageMemoryInfo* pBindInfos) {
2735 ATRACE_CALL();
2736
Yiwei Zhang0f475222019-04-11 19:38:00 -07002737 // out_native_buffers is for maintaining the lifecycle of the constructed
2738 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2739 std::vector<VkNativeBufferANDROID> out_native_buffers;
2740 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2741 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2742 &out_bind_infos);
2743 return GetData(device).driver.BindImageMemory2(
2744 device, bindInfoCount,
2745 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002746}
2747
2748VKAPI_ATTR
2749VkResult BindImageMemory2KHR(VkDevice device,
2750 uint32_t bindInfoCount,
2751 const VkBindImageMemoryInfo* pBindInfos) {
2752 ATRACE_CALL();
2753
Yiwei Zhang0f475222019-04-11 19:38:00 -07002754 std::vector<VkNativeBufferANDROID> out_native_buffers;
2755 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2756 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2757 &out_bind_infos);
2758 return GetData(device).driver.BindImageMemory2KHR(
2759 device, bindInfoCount,
2760 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002761}
2762
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002763VKAPI_ATTR
2764VkResult ReleaseSwapchainImagesEXT(VkDevice /*device*/,
2765 const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
2766 ATRACE_CALL();
2767
2768 Swapchain& swapchain = *SwapchainFromHandle(pReleaseInfo->swapchain);
2769 ANativeWindow* window = swapchain.surface.window.get();
2770
2771 // If in shared present mode, don't actually release the image back to the BQ.
2772 // Both sides share it forever.
2773 if (swapchain.shared)
2774 return VK_SUCCESS;
2775
2776 for (uint32_t i = 0; i < pReleaseInfo->imageIndexCount; i++) {
2777 Swapchain::Image& img = swapchain.images[pReleaseInfo->pImageIndices[i]];
2778 window->cancelBuffer(window, img.buffer.get(), img.dequeue_fence);
2779
2780 // cancelBuffer has taken ownership of the dequeue fence
2781 img.dequeue_fence = -1;
2782 // if we're still holding a release fence, get rid of it now
2783 if (img.release_fence >= 0) {
2784 close(img.release_fence);
2785 img.release_fence = -1;
2786 }
2787 img.dequeued = false;
2788 }
2789
2790 return VK_SUCCESS;
2791}
2792
Chia-I Wu62262232016-03-26 07:06:44 +08002793} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002794} // namespace vulkan