blob: 13141933ac04b0fa4817a6f94c5f4fcbb3f36b8e [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
Yuxin Huf768e042024-02-08 22:15:06 +000017#include "vulkan/vulkan_core.h"
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
sergiuferentz47989332023-09-26 10:24:36 +000020#include <aidl/android/hardware/graphics/common/Dataspace.h>
Trevor David Blackf499b5a2023-07-14 17:30:41 +000021#include <aidl/android/hardware/graphics/common/PixelFormat.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070022#include <android/hardware/graphics/common/1.0/types.h>
Trevor David Blackd7320ef2023-08-23 21:21:51 +000023#include <android/hardware_buffer.h>
Jesse Hall79927812017-03-23 11:03:23 -070024#include <grallocusage/GrallocUsageConversion.h>
Yiwei Zhang69395cd2019-07-03 16:55:39 -070025#include <graphicsenv/GraphicsEnv.h>
John Reck97678d42022-08-23 11:24:51 -040026#include <hardware/gralloc.h>
27#include <hardware/gralloc1.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070028#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070029#include <sync/sync.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070030#include <system/window.h>
31#include <ui/BufferQueueDefs.h>
Chia-I Wue8e689f2016-04-18 08:21:31 +080032#include <utils/StrongPointer.h>
Yiwei Zhang705c2e62019-12-18 23:12:43 -080033#include <utils/Timers.h>
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080034#include <utils/Trace.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070035
36#include <algorithm>
37#include <unordered_set>
38#include <vector>
Jesse Halld7b994a2015-09-07 14:17:37 -070039
Chia-I Wu4a6a9162016-03-26 07:17:34 +080040#include "driver.h"
Jesse Halld7b994a2015-09-07 14:17:37 -070041
Trevor David Blackf499b5a2023-07-14 17:30:41 +000042using PixelFormat = aidl::android::hardware::graphics::common::PixelFormat;
sergiuferentz47989332023-09-26 10:24:36 +000043using DataSpace = aidl::android::hardware::graphics::common::Dataspace;
Daniel Kochf25f5bb2017-10-05 00:26:58 -040044using android::hardware::graphics::common::V1_0::BufferUsage;
45
Chia-I Wu62262232016-03-26 07:06:44 +080046namespace vulkan {
47namespace driver {
Jesse Hall5ae3abb2015-10-08 14:00:22 -070048
Jesse Halld7b994a2015-09-07 14:17:37 -070049namespace {
50
John Reck97678d42022-08-23 11:24:51 -040051static uint64_t convertGralloc1ToBufferUsage(uint64_t producerUsage,
52 uint64_t consumerUsage) {
53 static_assert(uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) ==
54 uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN),
55 "expected ConsumerUsage and ProducerUsage CPU_READ_OFTEN "
56 "bits to match");
57 uint64_t merged = producerUsage | consumerUsage;
58 if ((merged & (GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN)) ==
59 GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) {
60 merged &= ~uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN);
61 merged |= BufferUsage::CPU_READ_OFTEN;
62 }
63 if ((merged & (GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN)) ==
64 GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) {
65 merged &= ~uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN);
66 merged |= BufferUsage::CPU_WRITE_OFTEN;
67 }
68 return merged;
69}
70
Jesse Hall55bc0972016-02-23 16:43:29 -080071const VkSurfaceTransformFlagsKHR kSupportedTransforms =
72 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
73 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
74 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
75 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
Yiwei Zhang70a21962019-05-31 17:26:52 -070076 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
77 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
78 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
79 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
Jesse Hall55bc0972016-02-23 16:43:29 -080080 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
81
82VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
83 // Native and Vulkan transforms are isomorphic, but are represented
84 // differently. Vulkan transforms are built up of an optional horizontal
85 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
86 // transforms are built up from a horizontal flip, vertical flip, and
87 // 90-degree rotation, all optional but always in that order.
88
Jesse Hall55bc0972016-02-23 16:43:29 -080089 switch (native) {
Yiwei Zhang70a21962019-05-31 17:26:52 -070090 case 0:
Jesse Hall55bc0972016-02-23 16:43:29 -080091 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070092 case NATIVE_WINDOW_TRANSFORM_FLIP_H:
93 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
94 case NATIVE_WINDOW_TRANSFORM_FLIP_V:
95 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
96 case NATIVE_WINDOW_TRANSFORM_ROT_180:
Jesse Hall55bc0972016-02-23 16:43:29 -080097 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070098 case NATIVE_WINDOW_TRANSFORM_ROT_90:
Jesse Hall55bc0972016-02-23 16:43:29 -080099 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -0700100 case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
101 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
102 case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
103 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
104 case NATIVE_WINDOW_TRANSFORM_ROT_270:
Jesse Hall55bc0972016-02-23 16:43:29 -0800105 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
106 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
107 default:
108 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
109 }
110}
111
Yiwei Zhang70a21962019-05-31 17:26:52 -0700112int TranslateVulkanToNativeTransform(VkSurfaceTransformFlagBitsKHR transform) {
113 switch (transform) {
114 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
115 return NATIVE_WINDOW_TRANSFORM_ROT_90;
116 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
117 return NATIVE_WINDOW_TRANSFORM_ROT_180;
118 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
119 return NATIVE_WINDOW_TRANSFORM_ROT_270;
120 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
121 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
122 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
123 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
124 NATIVE_WINDOW_TRANSFORM_ROT_90;
125 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
126 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
127 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
128 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
129 NATIVE_WINDOW_TRANSFORM_ROT_90;
130 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
131 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
132 default:
133 return 0;
134 }
135}
136
Jesse Hall178b6962016-02-24 15:39:50 -0800137int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
138 switch (transform) {
139 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
140 return NATIVE_WINDOW_TRANSFORM_ROT_270;
141 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
142 return NATIVE_WINDOW_TRANSFORM_ROT_180;
143 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
144 return NATIVE_WINDOW_TRANSFORM_ROT_90;
Yiwei Zhang70a21962019-05-31 17:26:52 -0700145 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
146 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
147 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
148 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
149 NATIVE_WINDOW_TRANSFORM_ROT_90;
150 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
151 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
152 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
153 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
154 NATIVE_WINDOW_TRANSFORM_ROT_90;
Jesse Hall178b6962016-02-24 15:39:50 -0800155 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
156 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
157 default:
158 return 0;
159 }
160}
161
Yuxin Hu7facd572024-02-08 22:54:23 +0000162const static VkColorSpaceKHR colorSpaceSupportedByVkEXTSwapchainColorspace[] = {
163 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT,
164 VK_COLOR_SPACE_DISPLAY_P3_LINEAR_EXT,
165 VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT,
166 VK_COLOR_SPACE_BT709_LINEAR_EXT,
167 VK_COLOR_SPACE_BT709_NONLINEAR_EXT,
168 VK_COLOR_SPACE_BT2020_LINEAR_EXT,
169 VK_COLOR_SPACE_HDR10_ST2084_EXT,
170 VK_COLOR_SPACE_HDR10_HLG_EXT,
171 VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT,
172 VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT,
173 VK_COLOR_SPACE_PASS_THROUGH_EXT,
174 VK_COLOR_SPACE_DCI_P3_LINEAR_EXT};
175
176const static VkColorSpaceKHR
177 colorSpaceSupportedByVkEXTSwapchainColorspaceOnFP16SurfaceOnly[] = {
178 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT,
179 VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT};
180
Ian Elliott8a977262017-01-19 09:05:58 -0700181class TimingInfo {
182 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800183 TimingInfo(const VkPresentTimeGOOGLE* qp, uint64_t nativeFrameId)
Ian Elliott2c6355d2017-01-19 11:02:13 -0700184 : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
Brian Anderson1049d1d2016-12-16 17:25:57 -0800185 native_frame_id_(nativeFrameId) {}
186 bool ready() const {
Brian Andersondc96fdf2017-03-20 16:54:25 -0700187 return (timestamp_desired_present_time_ !=
188 NATIVE_WINDOW_TIMESTAMP_PENDING &&
189 timestamp_actual_present_time_ !=
190 NATIVE_WINDOW_TIMESTAMP_PENDING &&
191 timestamp_render_complete_time_ !=
192 NATIVE_WINDOW_TIMESTAMP_PENDING &&
193 timestamp_composition_latch_time_ !=
194 NATIVE_WINDOW_TIMESTAMP_PENDING);
Ian Elliott8a977262017-01-19 09:05:58 -0700195 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700196 void calculate(int64_t rdur) {
197 bool anyTimestampInvalid =
198 (timestamp_actual_present_time_ ==
199 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
200 (timestamp_render_complete_time_ ==
201 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
202 (timestamp_composition_latch_time_ ==
203 NATIVE_WINDOW_TIMESTAMP_INVALID);
204 if (anyTimestampInvalid) {
205 ALOGE("Unexpectedly received invalid timestamp.");
206 vals_.actualPresentTime = 0;
207 vals_.earliestPresentTime = 0;
208 vals_.presentMargin = 0;
209 return;
210 }
211
212 vals_.actualPresentTime =
213 static_cast<uint64_t>(timestamp_actual_present_time_);
214 int64_t margin = (timestamp_composition_latch_time_ -
Ian Elliott8a977262017-01-19 09:05:58 -0700215 timestamp_render_complete_time_);
216 // Calculate vals_.earliestPresentTime, and potentially adjust
217 // vals_.presentMargin. The initial value of vals_.earliestPresentTime
218 // is vals_.actualPresentTime. If we can subtract rdur (the duration
219 // of a refresh cycle) from vals_.earliestPresentTime (and also from
220 // vals_.presentMargin) and still leave a positive margin, then we can
221 // report to the application that it could have presented earlier than
222 // it did (per the extension specification). If for some reason, we
223 // can do this subtraction repeatedly, we do, since
224 // vals_.earliestPresentTime really is supposed to be the "earliest".
Brian Andersondc96fdf2017-03-20 16:54:25 -0700225 int64_t early_time = timestamp_actual_present_time_;
Ian Elliott8a977262017-01-19 09:05:58 -0700226 while ((margin > rdur) &&
227 ((early_time - rdur) > timestamp_composition_latch_time_)) {
228 early_time -= rdur;
229 margin -= rdur;
230 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700231 vals_.earliestPresentTime = static_cast<uint64_t>(early_time);
232 vals_.presentMargin = static_cast<uint64_t>(margin);
Ian Elliott8a977262017-01-19 09:05:58 -0700233 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800234 void get_values(VkPastPresentationTimingGOOGLE* values) const {
235 *values = vals_;
236 }
Ian Elliott8a977262017-01-19 09:05:58 -0700237
238 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800239 VkPastPresentationTimingGOOGLE vals_ { 0, 0, 0, 0, 0 };
Ian Elliott8a977262017-01-19 09:05:58 -0700240
Brian Anderson1049d1d2016-12-16 17:25:57 -0800241 uint64_t native_frame_id_ { 0 };
Brian Andersondc96fdf2017-03-20 16:54:25 -0700242 int64_t timestamp_desired_present_time_{ NATIVE_WINDOW_TIMESTAMP_PENDING };
243 int64_t timestamp_actual_present_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
244 int64_t timestamp_render_complete_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
245 int64_t timestamp_composition_latch_time_
246 { NATIVE_WINDOW_TIMESTAMP_PENDING };
Ian Elliott8a977262017-01-19 09:05:58 -0700247};
248
Jesse Hall1356b0d2015-11-23 17:24:58 -0800249struct Surface {
Chia-I Wue8e689f2016-04-18 08:21:31 +0800250 android::sp<ANativeWindow> window;
Jesse Halldc225072016-05-30 22:40:14 -0700251 VkSwapchainKHR swapchain_handle;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700252 uint64_t consumer_usage;
Yiwei Zhang3b88f312023-04-18 23:11:35 +0000253
254 // Indicate whether this surface has been used by a swapchain, no matter the
255 // swapchain is still current or has been destroyed.
256 bool used_by_swapchain;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800257};
258
259VkSurfaceKHR HandleFromSurface(Surface* surface) {
260 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
261}
262
263Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800264 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800265}
266
Ian Elliott8a977262017-01-19 09:05:58 -0700267// Maximum number of TimingInfo structs to keep per swapchain:
268enum { MAX_TIMING_INFOS = 10 };
269// Minimum number of frames to look for in the past (so we don't cause
270// syncronous requests to Surface Flinger):
271enum { MIN_NUM_FRAMES_AGO = 5 };
272
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300273bool IsSharedPresentMode(VkPresentModeKHR mode) {
274 return mode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
275 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR;
276}
277
Jesse Hall1356b0d2015-11-23 17:24:58 -0800278struct Swapchain {
Ian Elliottffedb652017-02-14 10:58:30 -0700279 Swapchain(Surface& surface_,
280 uint32_t num_images_,
silence_dogood73597592019-05-23 16:57:37 -0700281 VkPresentModeKHR present_mode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000282 int pre_transform_,
283 int64_t refresh_duration_)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700284 : surface(surface_),
285 num_images(num_images_),
Ian Elliottffedb652017-02-14 10:58:30 -0700286 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
silence_dogood73597592019-05-23 16:57:37 -0700287 pre_transform(pre_transform_),
Chris Forbesf8835642017-03-30 19:31:40 +1300288 frame_timestamps_enabled(false),
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000289 refresh_duration(refresh_duration_),
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800290 acquire_next_image_timeout(-1),
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300291 shared(IsSharedPresentMode(present_mode)) {
Ian Elliott8a977262017-01-19 09:05:58 -0700292 }
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000293
294 VkResult get_refresh_duration(uint64_t& outRefreshDuration)
Ian Elliott3568bfe2019-05-03 15:54:46 -0600295 {
296 ANativeWindow* window = surface.window.get();
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000297 int err = native_window_get_refresh_cycle_duration(
Ian Elliott3568bfe2019-05-03 15:54:46 -0600298 window,
299 &refresh_duration);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000300 if (err != android::OK) {
301 ALOGE("%s:native_window_get_refresh_cycle_duration failed: %s (%d)",
302 __func__, strerror(-err), err );
303 return VK_ERROR_SURFACE_LOST_KHR;
304 }
305 outRefreshDuration = refresh_duration;
306 return VK_SUCCESS;
Ian Elliott3568bfe2019-05-03 15:54:46 -0600307 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800308
309 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700310 uint32_t num_images;
Ian Elliottffedb652017-02-14 10:58:30 -0700311 bool mailbox_mode;
silence_dogood73597592019-05-23 16:57:37 -0700312 int pre_transform;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700313 bool frame_timestamps_enabled;
Brian Andersondc96fdf2017-03-20 16:54:25 -0700314 int64_t refresh_duration;
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800315 nsecs_t acquire_next_image_timeout;
Chris Forbesf8835642017-03-30 19:31:40 +1300316 bool shared;
Jesse Halld7b994a2015-09-07 14:17:37 -0700317
318 struct Image {
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700319 Image()
320 : image(VK_NULL_HANDLE),
321 dequeue_fence(-1),
322 release_fence(-1),
323 dequeued(false) {}
Jesse Halld7b994a2015-09-07 14:17:37 -0700324 VkImage image;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000325 // If the image is bound to memory, an sp to the underlying gralloc buffer.
326 // Otherwise, nullptr; the image will be bound to memory as part of
327 // AcquireNextImage.
Chia-I Wue8e689f2016-04-18 08:21:31 +0800328 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700329 // The fence is only valid when the buffer is dequeued, and should be
330 // -1 any other time. When valid, we own the fd, and must ensure it is
331 // closed: either by closing it explicitly when queueing the buffer,
332 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
333 int dequeue_fence;
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700334 // This fence is a dup of the sync fd returned from the driver via
335 // vkQueueSignalReleaseImageANDROID upon vkQueuePresentKHR. We must
336 // ensure it is closed upon re-presenting or releasing the image.
337 int release_fence;
Jesse Halld7b994a2015-09-07 14:17:37 -0700338 bool dequeued;
Pawin Vongmasa6e1193a2017-03-07 13:08:40 -0800339 } images[android::BufferQueueDefs::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700340
Yiwei Zhang5e862202019-06-21 14:59:16 -0700341 std::vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700342};
343
344VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
345 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
346}
347
348Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800349 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700350}
351
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700352static bool IsFencePending(int fd) {
353 if (fd < 0)
354 return false;
355
356 errno = 0;
357 return sync_wait(fd, 0 /* timeout */) == -1 && errno == ETIME;
358}
359
Jesse Halldc225072016-05-30 22:40:14 -0700360void ReleaseSwapchainImage(VkDevice device,
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000361 bool shared_present,
Jesse Halldc225072016-05-30 22:40:14 -0700362 ANativeWindow* window,
363 int release_fence,
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700364 Swapchain::Image& image,
365 bool defer_if_pending) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700366 ATRACE_CALL();
367
Jesse Halldc225072016-05-30 22:40:14 -0700368 ALOG_ASSERT(release_fence == -1 || image.dequeued,
369 "ReleaseSwapchainImage: can't provide a release fence for "
370 "non-dequeued images");
371
372 if (image.dequeued) {
373 if (release_fence >= 0) {
374 // We get here from vkQueuePresentKHR. The application is
375 // responsible for creating an execution dependency chain from
376 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
377 // (release_fence), so we can drop the dequeue_fence here.
378 if (image.dequeue_fence >= 0)
379 close(image.dequeue_fence);
380 } else {
381 // We get here during swapchain destruction, or various serious
382 // error cases e.g. when we can't create the release_fence during
383 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
384 // have already signalled, since the swapchain images are supposed
385 // to be idle before the swapchain is destroyed. In error cases,
386 // there may be rendering in flight to the image, but since we
387 // weren't able to create a release_fence, waiting for the
388 // dequeue_fence is about the best we can do.
389 release_fence = image.dequeue_fence;
390 }
391 image.dequeue_fence = -1;
392
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000393 // It's invalid to call cancelBuffer on a shared buffer
394 if (window && !shared_present) {
Jesse Halldc225072016-05-30 22:40:14 -0700395 window->cancelBuffer(window, image.buffer.get(), release_fence);
396 } else {
397 if (release_fence >= 0) {
398 sync_wait(release_fence, -1 /* forever */);
399 close(release_fence);
400 }
401 }
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700402 release_fence = -1;
Jesse Halldc225072016-05-30 22:40:14 -0700403 image.dequeued = false;
404 }
405
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700406 if (defer_if_pending && IsFencePending(image.release_fence))
407 return;
408
409 if (image.release_fence >= 0) {
410 close(image.release_fence);
411 image.release_fence = -1;
412 }
413
Jesse Halldc225072016-05-30 22:40:14 -0700414 if (image.image) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700415 ATRACE_BEGIN("DestroyImage");
Jesse Halldc225072016-05-30 22:40:14 -0700416 GetData(device).driver.DestroyImage(device, image.image, nullptr);
Yiwei Zhang533cea92019-06-03 18:43:24 -0700417 ATRACE_END();
Jesse Halldc225072016-05-30 22:40:14 -0700418 image.image = VK_NULL_HANDLE;
419 }
420
421 image.buffer.clear();
422}
423
424void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
425 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
426 return;
Jesse Halldc225072016-05-30 22:40:14 -0700427 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000428 if (!swapchain->images[i].dequeued) {
429 ReleaseSwapchainImage(device, swapchain->shared, nullptr, -1,
430 swapchain->images[i], true);
431 }
Jesse Halldc225072016-05-30 22:40:14 -0700432 }
433 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700434 swapchain->timing.clear();
435}
436
437uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800438 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
439 return 0;
440 }
Ian Elliott8a977262017-01-19 09:05:58 -0700441
Brian Anderson1049d1d2016-12-16 17:25:57 -0800442 uint32_t num_ready = 0;
443 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
444 for (uint32_t i = 0; i < num_timings; i++) {
Yiwei Zhang5e862202019-06-21 14:59:16 -0700445 TimingInfo& ti = swapchain.timing[i];
Brian Anderson1049d1d2016-12-16 17:25:57 -0800446 if (ti.ready()) {
447 // This TimingInfo is ready to be reported to the user. Add it
448 // to the num_ready.
449 num_ready++;
450 continue;
451 }
452 // This TimingInfo is not yet ready to be reported to the user,
453 // and so we should look for any available timestamps that
454 // might make it ready.
455 int64_t desired_present_time = 0;
456 int64_t render_complete_time = 0;
457 int64_t composition_latch_time = 0;
458 int64_t actual_present_time = 0;
459 // Obtain timestamps:
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800460 int err = native_window_get_frame_timestamps(
Brian Anderson1049d1d2016-12-16 17:25:57 -0800461 swapchain.surface.window.get(), ti.native_frame_id_,
462 &desired_present_time, &render_complete_time,
463 &composition_latch_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700464 nullptr, //&first_composition_start_time,
465 nullptr, //&last_composition_start_time,
466 nullptr, //&composition_finish_time,
Brian Anderson1049d1d2016-12-16 17:25:57 -0800467 &actual_present_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700468 nullptr, //&dequeue_ready_time,
469 nullptr /*&reads_done_time*/);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800470
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800471 if (err != android::OK) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800472 continue;
473 }
474
475 // Record the timestamp(s) we received, and then see if this TimingInfo
476 // is ready to be reported to the user:
Brian Andersondc96fdf2017-03-20 16:54:25 -0700477 ti.timestamp_desired_present_time_ = desired_present_time;
478 ti.timestamp_actual_present_time_ = actual_present_time;
479 ti.timestamp_render_complete_time_ = render_complete_time;
480 ti.timestamp_composition_latch_time_ = composition_latch_time;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800481
482 if (ti.ready()) {
483 // The TimingInfo has received enough timestamps, and should now
484 // use those timestamps to calculate the info that should be
485 // reported to the user:
486 ti.calculate(swapchain.refresh_duration);
487 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700488 }
489 }
490 return num_ready;
491}
492
Ian Elliott8a977262017-01-19 09:05:58 -0700493void copy_ready_timings(Swapchain& swapchain,
494 uint32_t* count,
495 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800496 if (swapchain.timing.empty()) {
497 *count = 0;
498 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700499 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800500
501 size_t last_ready = swapchain.timing.size() - 1;
502 while (!swapchain.timing[last_ready].ready()) {
503 if (last_ready == 0) {
504 *count = 0;
505 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700506 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800507 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700508 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800509
510 uint32_t num_copied = 0;
Yiwei Zhang5e862202019-06-21 14:59:16 -0700511 int32_t num_to_remove = 0;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800512 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
513 const TimingInfo& ti = swapchain.timing[i];
514 if (ti.ready()) {
515 ti.get_values(&timings[num_copied]);
516 num_copied++;
517 }
518 num_to_remove++;
519 }
520
521 // Discard old frames that aren't ready if newer frames are ready.
522 // We don't expect to get the timing info for those old frames.
Yiwei Zhang5e862202019-06-21 14:59:16 -0700523 swapchain.timing.erase(swapchain.timing.begin(),
524 swapchain.timing.begin() + num_to_remove);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800525
Ian Elliott8a977262017-01-19 09:05:58 -0700526 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700527}
528
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000529PixelFormat GetNativePixelFormat(VkFormat format) {
530 PixelFormat native_format = PixelFormat::RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700531 switch (format) {
532 case VK_FORMAT_R8G8B8A8_UNORM:
533 case VK_FORMAT_R8G8B8A8_SRGB:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000534 native_format = PixelFormat::RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700535 break;
536 case VK_FORMAT_R5G6B5_UNORM_PACK16:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000537 native_format = PixelFormat::RGB_565;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700538 break;
539 case VK_FORMAT_R16G16B16A16_SFLOAT:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000540 native_format = PixelFormat::RGBA_FP16;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700541 break;
Yiwei Zhangc1ea8152019-02-05 15:11:32 -0800542 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000543 native_format = PixelFormat::RGBA_1010102;
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500544 break;
545 case VK_FORMAT_R8_UNORM:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000546 native_format = PixelFormat::R_8;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700547 break;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000548 case VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000549 native_format = PixelFormat::RGBA_10101010;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000550 break;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700551 default:
552 ALOGV("unsupported swapchain format %d", format);
553 break;
554 }
555 return native_format;
556}
557
sergiuferentz47989332023-09-26 10:24:36 +0000558DataSpace GetNativeDataspace(VkColorSpaceKHR colorspace,
559 PixelFormat pixelFormat) {
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700560 switch (colorspace) {
561 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
sergiuferentz47989332023-09-26 10:24:36 +0000562 return DataSpace::SRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700563 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000564 return DataSpace::DISPLAY_P3;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700565 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000566 return DataSpace::SCRGB_LINEAR;
Courtney Goeltzenleuchterb52abee2017-08-07 17:13:04 -0600567 case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000568 return DataSpace::SCRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700569 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000570 return DataSpace::DCI_P3_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700571 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000572 return DataSpace::DCI_P3;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700573 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000574 return DataSpace::SRGB_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700575 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000576 return DataSpace::SRGB;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600577 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
Sally Qiaa238972023-07-17 12:52:05 +0800578 if (pixelFormat == PixelFormat::RGBA_FP16) {
sergiuferentz47989332023-09-26 10:24:36 +0000579 return DataSpace::BT2020_LINEAR_EXTENDED;
Sally Qiaa238972023-07-17 12:52:05 +0800580 } else {
sergiuferentz47989332023-09-26 10:24:36 +0000581 return DataSpace::BT2020_LINEAR;
Sally Qiaa238972023-07-17 12:52:05 +0800582 }
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600583 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000584 return DataSpace::BT2020_PQ;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600585 case VK_COLOR_SPACE_DOLBYVISION_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000586 return DataSpace::BT2020_PQ;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600587 case VK_COLOR_SPACE_HDR10_HLG_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000588 return DataSpace::BT2020_HLG;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700589 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000590 return DataSpace::ADOBE_RGB_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700591 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000592 return DataSpace::ADOBE_RGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700593 // Pass through is intended to allow app to provide data that is passed
594 // to the display system without modification.
595 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000596 return DataSpace::ARBITRARY;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700597
598 default:
599 // This indicates that we don't know about the
600 // dataspace specified and we should indicate that
601 // it's unsupported
sergiuferentz47989332023-09-26 10:24:36 +0000602 return DataSpace::UNKNOWN;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700603 }
604}
605
Jesse Halld7b994a2015-09-07 14:17:37 -0700606} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700607
Jesse Halle1b12782015-11-30 11:27:32 -0800608VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800609VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800610 VkInstance instance,
611 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
612 const VkAllocationCallbacks* allocator,
613 VkSurfaceKHR* out_surface) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800614 ATRACE_CALL();
615
Jesse Hall1f91d392015-12-11 16:28:44 -0800616 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800617 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800618 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
619 alignof(Surface),
620 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800621 if (!mem)
622 return VK_ERROR_OUT_OF_HOST_MEMORY;
623 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700624
Chia-I Wue8e689f2016-04-18 08:21:31 +0800625 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700626 surface->swapchain_handle = VK_NULL_HANDLE;
Yiwei Zhang3b88f312023-04-18 23:11:35 +0000627 surface->used_by_swapchain = false;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700628 int err = native_window_get_consumer_usage(surface->window.get(),
629 &surface->consumer_usage);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800630 if (err != android::OK) {
Yiwei Zhang6435b322018-05-08 11:12:17 -0700631 ALOGE("native_window_get_consumer_usage() failed: %s (%d)",
632 strerror(-err), err);
633 surface->~Surface();
634 allocator->pfnFree(allocator->pUserData, surface);
Yiwei Zhang70a21962019-05-31 17:26:52 -0700635 return VK_ERROR_SURFACE_LOST_KHR;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700636 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700637
Yiwei Zhang6435b322018-05-08 11:12:17 -0700638 err =
Jesse Hall1356b0d2015-11-23 17:24:58 -0800639 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800640 if (err != android::OK) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800641 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
642 err);
643 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800644 allocator->pfnFree(allocator->pUserData, surface);
Mike Stroyan762c8132017-02-22 11:43:09 -0700645 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800646 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700647
Jesse Hall1356b0d2015-11-23 17:24:58 -0800648 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700649 return VK_SUCCESS;
650}
651
Jesse Halle1b12782015-11-30 11:27:32 -0800652VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800653void DestroySurfaceKHR(VkInstance instance,
654 VkSurfaceKHR surface_handle,
655 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800656 ATRACE_CALL();
657
Jesse Hall1356b0d2015-11-23 17:24:58 -0800658 Surface* surface = SurfaceFromHandle(surface_handle);
659 if (!surface)
660 return;
661 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700662 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700663 "destroyed VkSurfaceKHR 0x%" PRIx64
664 " has active VkSwapchainKHR 0x%" PRIx64,
665 reinterpret_cast<uint64_t>(surface_handle),
666 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800667 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800668 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800669 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800670 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800671}
672
Jesse Halle1b12782015-11-30 11:27:32 -0800673VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800674VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
675 uint32_t /*queue_family*/,
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000676 VkSurfaceKHR /*surface_handle*/,
Chia-I Wu62262232016-03-26 07:06:44 +0800677 VkBool32* supported) {
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000678 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800679 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800680}
681
Jesse Halle1b12782015-11-30 11:27:32 -0800682VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800683VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Ian Elliott1ce053f2022-03-16 09:49:53 -0600684 VkPhysicalDevice pdev,
Jesse Hallb00daad2015-11-29 19:46:20 -0800685 VkSurfaceKHR surface,
686 VkSurfaceCapabilitiesKHR* capabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800687 ATRACE_CALL();
688
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000689 // Implement in terms of GetPhysicalDeviceSurfaceCapabilities2KHR
690
691 VkPhysicalDeviceSurfaceInfo2KHR info2 = {
692 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
693 nullptr,
694 surface
695 };
696
697 VkSurfaceCapabilities2KHR caps2 = {
698 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
699 nullptr,
700 {},
701 };
702
703 VkResult result = GetPhysicalDeviceSurfaceCapabilities2KHR(pdev, &info2, &caps2);
704 *capabilities = caps2.surfaceCapabilities;
705 return result;
706}
707
708// Does the call-twice and VK_INCOMPLETE handling for querying lists
709// of things, where we already have the full set built in a vector.
710template <typename T>
711VkResult CopyWithIncomplete(std::vector<T> const& things,
712 T* callerPtr, uint32_t* callerCount) {
713 VkResult result = VK_SUCCESS;
714 if (callerPtr) {
715 if (things.size() > *callerCount)
716 result = VK_INCOMPLETE;
717 *callerCount = std::min(uint32_t(things.size()), *callerCount);
718 std::copy(things.begin(), things.begin() + *callerCount, callerPtr);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600719 } else {
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000720 *callerCount = things.size();
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800721 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000722 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700723}
724
Jesse Halle1b12782015-11-30 11:27:32 -0800725VKAPI_ATTR
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700726VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
727 VkSurfaceKHR surface_handle,
Chia-I Wu62262232016-03-26 07:06:44 +0800728 uint32_t* count,
729 VkSurfaceFormatKHR* formats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800730 ATRACE_CALL();
731
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700732 const InstanceData& instance_data = GetData(pdev);
733
Ian Elliott1ce053f2022-03-16 09:49:53 -0600734 uint64_t consumer_usage = 0;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000735 bool colorspace_ext =
Ian Elliottf6df08e2022-03-16 21:27:49 -0600736 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600737 if (surface_handle == VK_NULL_HANDLE) {
738 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
739 bool surfaceless_enabled =
740 instance_data.hook_extensions.test(surfaceless);
741 if (!surfaceless_enabled) {
742 return VK_ERROR_SURFACE_LOST_KHR;
743 }
Chris Forbesb1de3b12022-10-20 09:05:48 +1300744 // Support for VK_GOOGLE_surfaceless_query.
Ian Elliott1ce053f2022-03-16 09:49:53 -0600745
746 // TODO(b/203826952): research proper value; temporarily use the
747 // values seen on Pixel
748 consumer_usage = AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
749 } else {
750 Surface& surface = *SurfaceFromHandle(surface_handle);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600751 consumer_usage = surface.consumer_usage;
Ian Elliott6ba85d92022-02-18 16:44:58 -0700752 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700753
Charlie Lao324191f2019-12-13 11:03:16 -0800754 AHardwareBuffer_Desc desc = {};
755 desc.width = 1;
756 desc.height = 1;
757 desc.layers = 1;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600758 desc.usage = consumer_usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
Charlie Lao324191f2019-12-13 11:03:16 -0800759 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
760
761 // We must support R8G8B8A8
762 std::vector<VkSurfaceFormatKHR> all_formats = {
763 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000764 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000765 };
Charlie Lao324191f2019-12-13 11:03:16 -0800766
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000767 if (colorspace_ext) {
Yuxin Hu7facd572024-02-08 22:54:23 +0000768 for (VkColorSpaceKHR colorSpace :
769 colorSpaceSupportedByVkEXTSwapchainColorspace) {
770 if (GetNativeDataspace(colorSpace, GetNativePixelFormat(
771 VK_FORMAT_R8G8B8A8_UNORM)) !=
772 DataSpace::UNKNOWN) {
773 all_formats.emplace_back(
774 VkSurfaceFormatKHR{VK_FORMAT_R8G8B8A8_UNORM, colorSpace});
775 }
776
777 if (GetNativeDataspace(colorSpace, GetNativePixelFormat(
778 VK_FORMAT_R8G8B8A8_SRGB)) !=
779 DataSpace::UNKNOWN) {
780 all_formats.emplace_back(
781 VkSurfaceFormatKHR{VK_FORMAT_R8G8B8A8_SRGB, colorSpace});
782 }
783 }
Charlie Lao324191f2019-12-13 11:03:16 -0800784 }
785
Ian Elliott1ce053f2022-03-16 09:49:53 -0600786 // NOTE: Any new formats that are added must be coordinated across different
787 // Android users. This includes the ANGLE team (a layered implementation of
788 // OpenGL-ES).
789
Charlie Lao324191f2019-12-13 11:03:16 -0800790 desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
791 if (AHardwareBuffer_isSupported(&desc)) {
792 all_formats.emplace_back(VkSurfaceFormatKHR{
793 VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800794 if (colorspace_ext) {
Yuxin Hu7facd572024-02-08 22:54:23 +0000795 for (VkColorSpaceKHR colorSpace :
796 colorSpaceSupportedByVkEXTSwapchainColorspace) {
797 if (GetNativeDataspace(
798 colorSpace,
799 GetNativePixelFormat(VK_FORMAT_R5G6B5_UNORM_PACK16)) !=
800 DataSpace::UNKNOWN) {
801 all_formats.emplace_back(VkSurfaceFormatKHR{
802 VK_FORMAT_R5G6B5_UNORM_PACK16, colorSpace});
803 }
804 }
Jason Macnakca506332022-11-09 11:00:36 -0800805 }
Charlie Lao324191f2019-12-13 11:03:16 -0800806 }
807
808 desc.format = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
809 if (AHardwareBuffer_isSupported(&desc)) {
810 all_formats.emplace_back(VkSurfaceFormatKHR{
811 VK_FORMAT_R16G16B16A16_SFLOAT, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800812 if (colorspace_ext) {
Yuxin Hu7facd572024-02-08 22:54:23 +0000813 for (VkColorSpaceKHR colorSpace :
814 colorSpaceSupportedByVkEXTSwapchainColorspace) {
815 if (GetNativeDataspace(
816 colorSpace,
817 GetNativePixelFormat(VK_FORMAT_R16G16B16A16_SFLOAT)) !=
818 DataSpace::UNKNOWN) {
819 all_formats.emplace_back(VkSurfaceFormatKHR{
820 VK_FORMAT_R16G16B16A16_SFLOAT, colorSpace});
821 }
822 }
823
824 for (
825 VkColorSpaceKHR colorSpace :
826 colorSpaceSupportedByVkEXTSwapchainColorspaceOnFP16SurfaceOnly) {
827 if (GetNativeDataspace(
828 colorSpace,
829 GetNativePixelFormat(VK_FORMAT_R16G16B16A16_SFLOAT)) !=
830 DataSpace::UNKNOWN) {
831 all_formats.emplace_back(VkSurfaceFormatKHR{
832 VK_FORMAT_R16G16B16A16_SFLOAT, colorSpace});
833 }
834 }
Charlie Lao324191f2019-12-13 11:03:16 -0800835 }
836 }
837
838 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
839 if (AHardwareBuffer_isSupported(&desc)) {
840 all_formats.emplace_back(
841 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
842 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800843 if (colorspace_ext) {
Yuxin Hu7facd572024-02-08 22:54:23 +0000844 for (VkColorSpaceKHR colorSpace :
845 colorSpaceSupportedByVkEXTSwapchainColorspace) {
846 if (GetNativeDataspace(
847 colorSpace, GetNativePixelFormat(
848 VK_FORMAT_A2B10G10R10_UNORM_PACK32)) !=
849 DataSpace::UNKNOWN) {
850 all_formats.emplace_back(VkSurfaceFormatKHR{
851 VK_FORMAT_A2B10G10R10_UNORM_PACK32, colorSpace});
852 }
853 }
Charlie Lao324191f2019-12-13 11:03:16 -0800854 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700855 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700856
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500857 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
858 if (AHardwareBuffer_isSupported(&desc)) {
Jason Macnakca506332022-11-09 11:00:36 -0800859 if (colorspace_ext) {
860 all_formats.emplace_back(VkSurfaceFormatKHR{
861 VK_FORMAT_R8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
862 }
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500863 }
864
Trevor David Black67e9b102023-03-07 05:28:15 +0000865 bool rgba10x6_formats_ext = false;
866 uint32_t exts_count;
867 const auto& driver = GetData(pdev).driver;
868 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
869 nullptr);
870 std::vector<VkExtensionProperties> props(exts_count);
871 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
872 props.data());
873 for (uint32_t i = 0; i < exts_count; i++) {
874 VkExtensionProperties prop = props[i];
875 if (strcmp(prop.extensionName,
876 VK_EXT_RGBA10X6_FORMATS_EXTENSION_NAME) == 0) {
877 rgba10x6_formats_ext = true;
878 }
879 }
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000880 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM;
Trevor David Black67e9b102023-03-07 05:28:15 +0000881 if (AHardwareBuffer_isSupported(&desc) && rgba10x6_formats_ext) {
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000882 all_formats.emplace_back(
883 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
884 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
885 if (colorspace_ext) {
Yuxin Hu7facd572024-02-08 22:54:23 +0000886 for (VkColorSpaceKHR colorSpace :
887 colorSpaceSupportedByVkEXTSwapchainColorspace) {
888 if (GetNativeDataspace(
889 colorSpace,
890 GetNativePixelFormat(
891 VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16)) !=
892 DataSpace::UNKNOWN) {
893 all_formats.emplace_back(VkSurfaceFormatKHR{
894 VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
895 colorSpace});
896 }
897 }
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000898 }
899 }
900
Ian Elliott6ba85d92022-02-18 16:44:58 -0700901 // NOTE: Any new formats that are added must be coordinated across different
902 // Android users. This includes the ANGLE team (a layered implementation of
903 // OpenGL-ES).
904
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000905 return CopyWithIncomplete(all_formats, formats, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700906}
907
Jesse Halle1b12782015-11-30 11:27:32 -0800908VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300909VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
910 VkPhysicalDevice physicalDevice,
911 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
912 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800913 ATRACE_CALL();
914
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000915 auto surface = pSurfaceInfo->surface;
916 auto capabilities = &pSurfaceCapabilities->surfaceCapabilities;
Chris Forbes2452cf72017-03-16 16:30:17 +1300917
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000918 VkSurfacePresentModeEXT const *pPresentMode = nullptr;
919 for (auto pNext = reinterpret_cast<VkBaseInStructure const *>(pSurfaceInfo->pNext);
920 pNext; pNext = reinterpret_cast<VkBaseInStructure const *>(pNext->pNext)) {
921 switch (pNext->sType) {
922 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT:
923 pPresentMode = reinterpret_cast<VkSurfacePresentModeEXT const *>(pNext);
924 break;
Chris Forbes06bc0092017-03-16 16:46:05 +1300925
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000926 default:
927 break;
928 }
929 }
930
931 int err;
932 int width, height;
933 int transform_hint;
934 int max_buffer_count;
Trevor David Black1d3509e2023-06-08 00:17:40 +0000935 int min_undequeued_buffers;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000936 if (surface == VK_NULL_HANDLE) {
937 const InstanceData& instance_data = GetData(physicalDevice);
938 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
939 bool surfaceless_enabled =
940 instance_data.hook_extensions.test(surfaceless);
941 if (!surfaceless_enabled) {
942 // It is an error to pass a surface==VK_NULL_HANDLE unless the
943 // VK_GOOGLE_surfaceless_query extension is enabled
944 return VK_ERROR_SURFACE_LOST_KHR;
945 }
946 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
947 // extension for this function is for
948 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
949 // four values cannot be known without a surface. Default values will
950 // be supplied anyway, but cannot be relied upon.
951 width = 0xFFFFFFFF;
952 height = 0xFFFFFFFF;
953 transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
954 capabilities->minImageCount = 0xFFFFFFFF;
955 capabilities->maxImageCount = 0xFFFFFFFF;
956 } else {
957 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
958
959 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
960 if (err != android::OK) {
961 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
962 strerror(-err), err);
963 return VK_ERROR_SURFACE_LOST_KHR;
964 }
965 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
966 if (err != android::OK) {
967 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
968 strerror(-err), err);
969 return VK_ERROR_SURFACE_LOST_KHR;
970 }
971
972 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
973 &transform_hint);
974 if (err != android::OK) {
975 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
976 strerror(-err), err);
977 return VK_ERROR_SURFACE_LOST_KHR;
978 }
979
980 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
981 &max_buffer_count);
982 if (err != android::OK) {
983 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
984 strerror(-err), err);
985 return VK_ERROR_SURFACE_LOST_KHR;
986 }
987
Trevor David Black1d3509e2023-06-08 00:17:40 +0000988 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
989 &min_undequeued_buffers);
990 if (err != android::OK) {
991 ALOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d)",
992 strerror(-err), err);
993 return VK_ERROR_SURFACE_LOST_KHR;
994 }
995
Trevor David Blacke4d23b92023-09-26 20:30:42 +0000996 // Additional buffer count over min_undequeued_buffers in vulkan came from 2 total
997 // being technically enough for fifo (although a poor experience) vs 3 being the
998 // absolute minimum for mailbox to be useful. So min_undequeued_buffers + 2 is sensible
999 static constexpr int default_additional_buffers = 2;
1000
Trevor David Blacka93e21f2023-08-30 23:42:20 +00001001 if(pPresentMode != nullptr) {
1002 switch (pPresentMode->presentMode) {
1003 case VK_PRESENT_MODE_IMMEDIATE_KHR:
1004 ALOGE("Swapchain present mode VK_PRESENT_MODE_IMMEDIATE_KHR is not supported");
1005 break;
1006 case VK_PRESENT_MODE_MAILBOX_KHR:
1007 case VK_PRESENT_MODE_FIFO_KHR:
Trevor David Blacke4d23b92023-09-26 20:30:42 +00001008 capabilities->minImageCount = std::min(max_buffer_count,
1009 min_undequeued_buffers + default_additional_buffers);
Trevor David Blacka93e21f2023-08-30 23:42:20 +00001010 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
1011 break;
1012 case VK_PRESENT_MODE_FIFO_RELAXED_KHR:
1013 ALOGE("Swapchain present mode VK_PRESENT_MODE_FIFO_RELEAXED_KHR "
1014 "is not supported");
1015 break;
1016 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
1017 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
1018 capabilities->minImageCount = 1;
1019 capabilities->maxImageCount = 1;
1020 break;
1021
1022 default:
1023 ALOGE("Unrecognized swapchain present mode %u is not supported",
1024 pPresentMode->presentMode);
1025 break;
1026 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001027 } else {
Trevor David Blacke4d23b92023-09-26 20:30:42 +00001028 capabilities->minImageCount = std::min(max_buffer_count,
1029 min_undequeued_buffers + default_additional_buffers);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001030 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
1031 }
1032 }
1033
1034 capabilities->currentExtent =
1035 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
1036
1037 // TODO(http://b/134182502): Figure out what the max extent should be.
1038 capabilities->minImageExtent = VkExtent2D{1, 1};
1039 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
1040
1041 if (capabilities->maxImageExtent.height <
1042 capabilities->currentExtent.height) {
1043 capabilities->maxImageExtent.height =
1044 capabilities->currentExtent.height;
1045 }
1046
1047 if (capabilities->maxImageExtent.width <
1048 capabilities->currentExtent.width) {
1049 capabilities->maxImageExtent.width = capabilities->currentExtent.width;
1050 }
1051
1052 capabilities->maxImageArrayLayers = 1;
1053
1054 capabilities->supportedTransforms = kSupportedTransforms;
1055 capabilities->currentTransform =
1056 TranslateNativeToVulkanTransform(transform_hint);
1057
1058 // On Android, window composition is a WindowManager property, not something
1059 // associated with the bufferqueue. It can't be changed from here.
1060 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
1061
1062 capabilities->supportedUsageFlags =
1063 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
1064 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
1065 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
1066 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
1067
1068 for (auto pNext = reinterpret_cast<VkBaseOutStructure*>(pSurfaceCapabilities->pNext);
1069 pNext; pNext = reinterpret_cast<VkBaseOutStructure*>(pNext->pNext)) {
1070
1071 switch (pNext->sType) {
Chris Forbes06bc0092017-03-16 16:46:05 +13001072 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
1073 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001074 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(pNext);
Chris Forbes06bc0092017-03-16 16:46:05 +13001075 // Claim same set of usage flags are supported for
1076 // shared present modes as for other modes.
1077 shared_caps->sharedPresentSupportedUsageFlags =
1078 pSurfaceCapabilities->surfaceCapabilities
1079 .supportedUsageFlags;
1080 } break;
1081
Ian Elliottbb67b242022-03-16 09:52:28 -06001082 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
1083 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001084 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(pNext);
Ian Elliottbb67b242022-03-16 09:52:28 -06001085 protected_caps->supportsProtected = VK_TRUE;
1086 } break;
1087
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001088 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_SCALING_CAPABILITIES_EXT: {
1089 VkSurfacePresentScalingCapabilitiesEXT* scaling_caps =
1090 reinterpret_cast<VkSurfacePresentScalingCapabilitiesEXT*>(pNext);
1091 // By default, Android stretches the buffer to fit the window,
1092 // without preserving aspect ratio. Other modes are technically possible
1093 // but consult with CoGS team before exposing them here!
1094 scaling_caps->supportedPresentScaling = VK_PRESENT_SCALING_STRETCH_BIT_EXT;
1095
1096 // Since we always scale, we don't support any gravity.
1097 scaling_caps->supportedPresentGravityX = 0;
1098 scaling_caps->supportedPresentGravityY = 0;
1099
1100 // Scaled image limits are just the basic image limits
1101 scaling_caps->minScaledImageExtent = capabilities->minImageExtent;
1102 scaling_caps->maxScaledImageExtent = capabilities->maxImageExtent;
1103 } break;
1104
1105 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT: {
1106 VkSurfacePresentModeCompatibilityEXT* mode_caps =
1107 reinterpret_cast<VkSurfacePresentModeCompatibilityEXT*>(pNext);
1108
1109 ALOG_ASSERT(pPresentMode,
1110 "querying VkSurfacePresentModeCompatibilityEXT "
1111 "requires VkSurfacePresentModeEXT to be provided");
1112 std::vector<VkPresentModeKHR> compatibleModes;
1113 compatibleModes.push_back(pPresentMode->presentMode);
1114
1115 switch (pPresentMode->presentMode) {
1116 // Shared modes are both compatible with each other.
1117 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
1118 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
1119 break;
1120 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
1121 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1122 break;
1123 default:
1124 // Other modes are only compatible with themselves.
1125 // TODO: consider whether switching between FIFO and MAILBOX is reasonable
1126 break;
1127 }
1128
1129 // Note: this does not generate VK_INCOMPLETE since we're nested inside
1130 // a larger query and there would be no way to determine exactly where it came from.
1131 CopyWithIncomplete(compatibleModes, mode_caps->pPresentModes,
1132 &mode_caps->presentModeCount);
1133 } break;
1134
Chris Forbes06bc0092017-03-16 16:46:05 +13001135 default:
1136 // Ignore all other extension structs
1137 break;
1138 }
1139 }
1140
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001141 return VK_SUCCESS;
Chris Forbes2452cf72017-03-16 16:30:17 +13001142}
1143
1144VKAPI_ATTR
1145VkResult GetPhysicalDeviceSurfaceFormats2KHR(
1146 VkPhysicalDevice physicalDevice,
1147 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
1148 uint32_t* pSurfaceFormatCount,
1149 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001150 ATRACE_CALL();
1151
Chris Forbes2452cf72017-03-16 16:30:17 +13001152 if (!pSurfaceFormats) {
1153 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
1154 pSurfaceInfo->surface,
1155 pSurfaceFormatCount, nullptr);
Trevor David Black929e9cd2022-11-22 04:12:19 +00001156 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001157
Trevor David Black929e9cd2022-11-22 04:12:19 +00001158 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
1159 // after the call.
1160 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
1161 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
1162 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
1163 surface_formats.data());
Trevor David Black2cc44682022-03-09 00:31:38 +00001164
Trevor David Black929e9cd2022-11-22 04:12:19 +00001165 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
1166 return result;
1167 }
Trevor David Black2cc44682022-03-09 00:31:38 +00001168
Trevor David Black929e9cd2022-11-22 04:12:19 +00001169 const auto& driver = GetData(physicalDevice).driver;
1170
1171 // marshal results individually due to stride difference.
1172 uint32_t formats_to_marshal = *pSurfaceFormatCount;
1173 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
1174 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
1175
1176 // Query the compression properties for the surface format
1177 VkSurfaceFormat2KHR* pSurfaceFormat = &pSurfaceFormats[i];
1178 while (pSurfaceFormat->pNext) {
1179 pSurfaceFormat =
1180 reinterpret_cast<VkSurfaceFormat2KHR*>(pSurfaceFormat->pNext);
1181 switch (pSurfaceFormat->sType) {
1182 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT: {
Trevor David Black2cc44682022-03-09 00:31:38 +00001183 VkImageCompressionPropertiesEXT* surfaceCompressionProps =
1184 reinterpret_cast<VkImageCompressionPropertiesEXT*>(
Trevor David Black929e9cd2022-11-22 04:12:19 +00001185 pSurfaceFormat);
Trevor David Black2cc44682022-03-09 00:31:38 +00001186
1187 if (surfaceCompressionProps &&
1188 driver.GetPhysicalDeviceImageFormatProperties2KHR) {
1189 VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = {};
1190 imageFormatInfo.sType =
1191 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
1192 imageFormatInfo.format =
1193 pSurfaceFormats[i].surfaceFormat.format;
Trevor David Blacka4298c92023-06-20 17:11:58 +00001194 imageFormatInfo.type = VK_IMAGE_TYPE_2D;
1195 imageFormatInfo.usage =
1196 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
Trevor David Black2cc44682022-03-09 00:31:38 +00001197 imageFormatInfo.pNext = nullptr;
1198
1199 VkImageCompressionControlEXT compressionControl = {};
1200 compressionControl.sType =
1201 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT;
1202 compressionControl.pNext = imageFormatInfo.pNext;
Trevor David Blacka4298c92023-06-20 17:11:58 +00001203 compressionControl.flags =
1204 VK_IMAGE_COMPRESSION_FIXED_RATE_DEFAULT_EXT;
Trevor David Black2cc44682022-03-09 00:31:38 +00001205
1206 imageFormatInfo.pNext = &compressionControl;
1207
1208 VkImageCompressionPropertiesEXT compressionProps = {};
1209 compressionProps.sType =
1210 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT;
1211 compressionProps.pNext = nullptr;
1212
1213 VkImageFormatProperties2KHR imageFormatProps = {};
1214 imageFormatProps.sType =
1215 VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
1216 imageFormatProps.pNext = &compressionProps;
1217
1218 VkResult compressionRes =
1219 driver.GetPhysicalDeviceImageFormatProperties2KHR(
1220 physicalDevice, &imageFormatInfo,
1221 &imageFormatProps);
1222 if (compressionRes == VK_SUCCESS) {
1223 surfaceCompressionProps->imageCompressionFlags =
1224 compressionProps.imageCompressionFlags;
1225 surfaceCompressionProps
1226 ->imageCompressionFixedRateFlags =
1227 compressionProps.imageCompressionFixedRateFlags;
1228 } else {
1229 return compressionRes;
1230 }
1231 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001232 } break;
1233
1234 default:
1235 // Ignore all other extension structs
1236 break;
Chris Forbes2452cf72017-03-16 16:30:17 +13001237 }
1238 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001239 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001240
1241 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +13001242}
1243
1244VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +13001245VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001246 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +08001247 uint32_t* count,
1248 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001249 ATRACE_CALL();
1250
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001251 int err;
1252 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -06001253 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -06001254 if (surface == VK_NULL_HANDLE) {
1255 const InstanceData& instance_data = GetData(pdev);
1256 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
1257 bool surfaceless_enabled =
1258 instance_data.hook_extensions.test(surfaceless);
1259 if (!surfaceless_enabled) {
1260 return VK_ERROR_SURFACE_LOST_KHR;
1261 }
1262 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
1263 // extension for this function is for
1264 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
1265 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
1266 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
Ian Elliott7e361142022-06-02 10:45:17 -06001267 // surface, and that cannot be relied upon. Therefore, don't return it.
Ian Elliott1ce053f2022-03-16 09:49:53 -06001268 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1269 } else {
1270 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1271
1272 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1273 &query_value);
1274 if (err != android::OK || query_value < 0) {
1275 ALOGE(
1276 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
1277 "value=%d",
1278 strerror(-err), err, query_value);
1279 return VK_ERROR_SURFACE_LOST_KHR;
1280 }
1281 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1282
1283 err =
1284 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
1285 if (err != android::OK || query_value < 0) {
1286 ALOGE(
1287 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
1288 strerror(-err), err, query_value);
1289 return VK_ERROR_SURFACE_LOST_KHR;
1290 }
1291 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
1292
1293 if (min_undequeued_buffers + 1 < max_buffer_count)
1294 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
1295 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1296 }
Chris Forbese8d79a62017-02-22 12:49:18 +13001297
1298 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -07001299 QueryPresentationProperties(pdev, &present_properties);
1300 if (present_properties.sharedImage) {
1301 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1302 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +13001303 }
1304
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001305 return CopyWithIncomplete(present_modes, modes, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001306}
1307
Jesse Halle1b12782015-11-30 11:27:32 -08001308VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001309VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001310 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001311 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001312 ATRACE_CALL();
1313
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001314 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
1315 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1316 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1317 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1318 pDeviceGroupPresentCapabilities->sType);
1319
1320 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1321 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1322
1323 // assume device group of size 1
1324 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1325 pDeviceGroupPresentCapabilities->modes =
1326 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1327
1328 return VK_SUCCESS;
1329}
1330
1331VKAPI_ATTR
1332VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001333 VkDevice,
1334 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001335 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001336 ATRACE_CALL();
1337
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001338 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1339 return VK_SUCCESS;
1340}
1341
1342VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001343VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001344 VkSurfaceKHR surface,
1345 uint32_t* pRectCount,
1346 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001347 ATRACE_CALL();
1348
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001349 if (!pRects) {
1350 *pRectCount = 1;
1351 } else {
1352 uint32_t count = std::min(*pRectCount, 1u);
1353 bool incomplete = *pRectCount < 1;
1354
1355 *pRectCount = count;
1356
1357 if (incomplete) {
1358 return VK_INCOMPLETE;
1359 }
1360
1361 int err;
1362 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1363
1364 int width = 0, height = 0;
1365 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001366 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001367 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1368 strerror(-err), err);
1369 }
1370 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001371 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001372 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1373 strerror(-err), err);
1374 }
1375
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001376 pRects[0].offset.x = 0;
1377 pRects[0].offset.y = 0;
1378 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1379 static_cast<uint32_t>(height)};
1380 }
1381 return VK_SUCCESS;
1382}
1383
Yiwei Zhang533cea92019-06-03 18:43:24 -07001384static void DestroySwapchainInternal(VkDevice device,
1385 VkSwapchainKHR swapchain_handle,
1386 const VkAllocationCallbacks* allocator) {
1387 ATRACE_CALL();
1388
1389 const auto& dispatch = GetData(device).driver;
1390 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1391 if (!swapchain) {
1392 return;
1393 }
1394
1395 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1396 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1397
1398 if (window && swapchain->frame_timestamps_enabled) {
1399 native_window_enable_frame_timestamps(window, false);
1400 }
1401
1402 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +00001403 ReleaseSwapchainImage(device, swapchain->shared, window, -1,
1404 swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001405 }
1406
1407 if (active) {
1408 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1409 }
1410
1411 if (!allocator) {
1412 allocator = &GetData(device).allocator;
1413 }
1414
1415 swapchain->~Swapchain();
1416 allocator->pfnFree(allocator->pUserData, swapchain);
1417}
1418
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001419static VkResult getProducerUsage(const VkDevice& device,
1420 const VkSwapchainCreateInfoKHR* create_info,
1421 const VkSwapchainImageUsageFlagsANDROID swapchain_image_usage,
1422 bool create_protected_swapchain,
1423 uint64_t* producer_usage) {
1424 // Get the physical device to query the appropriate producer usage
1425 const VkPhysicalDevice& pdev = GetData(device).driver_physical_device;
1426 const InstanceData& instance_data = GetData(pdev);
1427 const InstanceDriverTable& instance_dispatch = instance_data.driver;
Trevor David Black02926f52024-01-04 18:44:20 +00001428 if (instance_dispatch.GetPhysicalDeviceImageFormatProperties2 ||
1429 instance_dispatch.GetPhysicalDeviceImageFormatProperties2KHR) {
1430 // Look through the create_info pNext chain passed to createSwapchainKHR
1431 // for an image compression control struct.
1432 // if one is found AND the appropriate extensions are enabled, create a
1433 // VkImageCompressionControlEXT structure to pass on to
1434 // GetPhysicalDeviceImageFormatProperties2
1435 void* compression_control_pNext = nullptr;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001436 VkImageCompressionControlEXT image_compression = {};
Trevor David Black02926f52024-01-04 18:44:20 +00001437 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1438 while (create_infos->pNext) {
1439 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(create_infos->pNext);
1440 switch (create_infos->sType) {
1441 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1442 const VkImageCompressionControlEXT* compression_infos =
1443 reinterpret_cast<const VkImageCompressionControlEXT*>(create_infos);
1444 image_compression = *compression_infos;
1445 image_compression.pNext = nullptr;
1446 compression_control_pNext = &image_compression;
1447 } break;
1448 default:
1449 // Ignore all other info structs
1450 break;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001451 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001452 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001453
Trevor David Black02926f52024-01-04 18:44:20 +00001454 // call GetPhysicalDeviceImageFormatProperties2KHR
1455 VkPhysicalDeviceExternalImageFormatInfo external_image_format_info = {
1456 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1457 .pNext = compression_control_pNext,
1458 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID,
1459 };
1460
1461 // AHB does not have an sRGB format so we can't pass it to GPDIFP
1462 // We need to convert the format to unorm if it is srgb
1463 VkFormat format = create_info->imageFormat;
1464 if (format == VK_FORMAT_R8G8B8A8_SRGB) {
1465 format = VK_FORMAT_R8G8B8A8_UNORM;
1466 }
1467
1468 VkPhysicalDeviceImageFormatInfo2 image_format_info = {
1469 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1470 .pNext = &external_image_format_info,
1471 .format = format,
1472 .type = VK_IMAGE_TYPE_2D,
1473 .tiling = VK_IMAGE_TILING_OPTIMAL,
1474 .usage = create_info->imageUsage,
1475 .flags = create_protected_swapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
1476 };
1477
1478 VkAndroidHardwareBufferUsageANDROID ahb_usage;
1479 ahb_usage.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_USAGE_ANDROID;
1480 ahb_usage.pNext = nullptr;
1481
1482 VkImageFormatProperties2 image_format_properties;
1483 image_format_properties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
1484 image_format_properties.pNext = &ahb_usage;
1485
1486 if (instance_dispatch.GetPhysicalDeviceImageFormatProperties2) {
1487 VkResult result = instance_dispatch.GetPhysicalDeviceImageFormatProperties2(
1488 pdev, &image_format_info, &image_format_properties);
1489 if (result != VK_SUCCESS) {
1490 ALOGE("VkGetPhysicalDeviceImageFormatProperties2 for AHB usage failed: %d", result);
1491 return VK_ERROR_SURFACE_LOST_KHR;
1492 }
1493 }
1494 else {
1495 VkResult result = instance_dispatch.GetPhysicalDeviceImageFormatProperties2KHR(
1496 pdev, &image_format_info,
1497 &image_format_properties);
1498 if (result != VK_SUCCESS) {
1499 ALOGE("VkGetPhysicalDeviceImageFormatProperties2KHR for AHB usage failed: %d",
1500 result);
1501 return VK_ERROR_SURFACE_LOST_KHR;
1502 }
1503 }
1504
1505 // Determine if USAGE_FRONT_BUFFER is needed.
1506 // GPDIFP2 has no means of using VkSwapchainImageUsageFlagsANDROID when
1507 // querying for producer_usage. So androidHardwareBufferUsage will not
1508 // contain USAGE_FRONT_BUFFER. We need to manually check for usage here.
1509 if (!(swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID)) {
1510 *producer_usage = ahb_usage.androidHardwareBufferUsage;
1511 return VK_SUCCESS;
1512 }
1513
1514 // Check if USAGE_FRONT_BUFFER is supported for this swapchain
1515 AHardwareBuffer_Desc ahb_desc = {
1516 .width = create_info->imageExtent.width,
1517 .height = create_info->imageExtent.height,
1518 .layers = create_info->imageArrayLayers,
1519 .format = create_info->imageFormat,
1520 .usage = ahb_usage.androidHardwareBufferUsage | AHARDWAREBUFFER_USAGE_FRONT_BUFFER,
1521 .stride = 0, // stride is always ignored when calling isSupported()
1522 };
1523
1524 // If FRONT_BUFFER is not supported,
1525 // then we need to call GetSwapchainGrallocUsageXAndroid below
1526 if (AHardwareBuffer_isSupported(&ahb_desc)) {
1527 *producer_usage = ahb_usage.androidHardwareBufferUsage;
1528 *producer_usage |= AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
1529 return VK_SUCCESS;
1530 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001531 }
1532
Trevor David Black02926f52024-01-04 18:44:20 +00001533 uint64_t native_usage = 0;
1534 void* usage_info_pNext = nullptr;
1535 VkResult result;
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001536 VkImageCompressionControlEXT image_compression = {};
Trevor David Black02926f52024-01-04 18:44:20 +00001537 const auto& dispatch = GetData(device).driver;
1538 if (dispatch.GetSwapchainGrallocUsage4ANDROID) {
1539 ATRACE_BEGIN("GetSwapchainGrallocUsage4ANDROID");
1540 VkGrallocUsageInfo2ANDROID gralloc_usage_info = {};
1541 gralloc_usage_info.sType =
1542 VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_2_ANDROID;
1543 gralloc_usage_info.format = create_info->imageFormat;
1544 gralloc_usage_info.imageUsage = create_info->imageUsage;
1545 gralloc_usage_info.swapchainImageUsage = swapchain_image_usage;
1546
1547 // Look through the pNext chain for an image compression control struct
1548 // if one is found AND the appropriate extensions are enabled,
1549 // append it to be the gralloc usage pNext chain
1550 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1551 while (create_infos->pNext) {
1552 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1553 create_infos->pNext);
1554 switch (create_infos->sType) {
1555 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1556 const VkImageCompressionControlEXT* compression_infos =
1557 reinterpret_cast<const VkImageCompressionControlEXT*>(
1558 create_infos);
1559 image_compression = *compression_infos;
1560 image_compression.pNext = nullptr;
1561 usage_info_pNext = &image_compression;
1562 } break;
1563
1564 default:
1565 // Ignore all other info structs
1566 break;
1567 }
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001568 }
Trevor David Black02926f52024-01-04 18:44:20 +00001569 gralloc_usage_info.pNext = usage_info_pNext;
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001570
Trevor David Black02926f52024-01-04 18:44:20 +00001571 result = dispatch.GetSwapchainGrallocUsage4ANDROID(
1572 device, &gralloc_usage_info, &native_usage);
1573 ATRACE_END();
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001574 if (result != VK_SUCCESS) {
Trevor David Black02926f52024-01-04 18:44:20 +00001575 ALOGE("vkGetSwapchainGrallocUsage4ANDROID failed: %d", result);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001576 return VK_ERROR_SURFACE_LOST_KHR;
1577 }
Trevor David Black02926f52024-01-04 18:44:20 +00001578 } else if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
1579 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1580 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1581 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1582 gralloc_usage_info.format = create_info->imageFormat;
1583 gralloc_usage_info.imageUsage = create_info->imageUsage;
1584
1585 // Look through the pNext chain for an image compression control struct
1586 // if one is found AND the appropriate extensions are enabled,
1587 // append it to be the gralloc usage pNext chain
1588 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1589 while (create_infos->pNext) {
1590 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1591 create_infos->pNext);
1592 switch (create_infos->sType) {
1593 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1594 const VkImageCompressionControlEXT* compression_infos =
1595 reinterpret_cast<const VkImageCompressionControlEXT*>(
1596 create_infos);
1597 image_compression = *compression_infos;
1598 image_compression.pNext = nullptr;
1599 usage_info_pNext = &image_compression;
1600 } break;
1601
1602 default:
1603 // Ignore all other info structs
1604 break;
1605 }
1606 }
1607 gralloc_usage_info.pNext = usage_info_pNext;
1608
1609 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1610 device, &gralloc_usage_info, &native_usage);
1611 ATRACE_END();
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001612 if (result != VK_SUCCESS) {
Trevor David Black02926f52024-01-04 18:44:20 +00001613 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001614 return VK_ERROR_SURFACE_LOST_KHR;
1615 }
Trevor David Black02926f52024-01-04 18:44:20 +00001616 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
1617 uint64_t consumer_usage, producer_usage;
1618 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
1619 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1620 device, create_info->imageFormat, create_info->imageUsage,
1621 swapchain_image_usage, &consumer_usage, &producer_usage);
1622 ATRACE_END();
1623 if (result != VK_SUCCESS) {
1624 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
1625 return VK_ERROR_SURFACE_LOST_KHR;
1626 }
1627 native_usage =
1628 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
1629 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
1630 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
1631 int32_t legacy_usage = 0;
1632 result = dispatch.GetSwapchainGrallocUsageANDROID(
1633 device, create_info->imageFormat, create_info->imageUsage,
1634 &legacy_usage);
1635 ATRACE_END();
1636 if (result != VK_SUCCESS) {
1637 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
1638 return VK_ERROR_SURFACE_LOST_KHR;
1639 }
1640 native_usage = static_cast<uint64_t>(legacy_usage);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001641 }
Trevor David Black02926f52024-01-04 18:44:20 +00001642 *producer_usage = native_usage;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001643
1644 return VK_SUCCESS;
1645}
1646
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001647VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001648VkResult CreateSwapchainKHR(VkDevice device,
1649 const VkSwapchainCreateInfoKHR* create_info,
1650 const VkAllocationCallbacks* allocator,
1651 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001652 ATRACE_CALL();
1653
Jesse Halld7b994a2015-09-07 14:17:37 -07001654 int err;
1655 VkResult result = VK_SUCCESS;
1656
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001657 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1658 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1659 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1660 " oldSwapchain=0x%" PRIx64,
1661 reinterpret_cast<uint64_t>(create_info->surface),
1662 create_info->minImageCount, create_info->imageFormat,
1663 create_info->imageColorSpace, create_info->imageExtent.width,
1664 create_info->imageExtent.height, create_info->imageUsage,
1665 create_info->preTransform, create_info->presentMode,
1666 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1667
Jesse Hall1f91d392015-12-11 16:28:44 -08001668 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001669 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001670
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001671 PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001672 GetNativePixelFormat(create_info->imageFormat);
sergiuferentz47989332023-09-26 10:24:36 +00001673 DataSpace native_dataspace =
Sally Qiaa238972023-07-17 12:52:05 +08001674 GetNativeDataspace(create_info->imageColorSpace, native_pixel_format);
sergiuferentz47989332023-09-26 10:24:36 +00001675 if (native_dataspace == DataSpace::UNKNOWN) {
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001676 ALOGE(
1677 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1678 "failed: Unsupported color space",
1679 create_info->imageColorSpace);
1680 return VK_ERROR_INITIALIZATION_FAILED;
1681 }
1682
Jesse Hall42a9eec2016-06-03 12:39:49 -07001683 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001684 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001685 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001686 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001687 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001688 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001689 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001690 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001691 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1692 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001693 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001694 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001695
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001696 Surface& surface = *SurfaceFromHandle(create_info->surface);
1697
Jesse Halldc225072016-05-30 22:40:14 -07001698 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001699 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001700 " because it already has active swapchain 0x%" PRIx64
1701 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1702 reinterpret_cast<uint64_t>(create_info->surface),
1703 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1704 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1705 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1706 }
1707 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1708 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1709
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001710 // -- Reset the native window --
1711 // The native window might have been used previously, and had its properties
1712 // changed from defaults. That will affect the answer we get for queries
1713 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1714 // attempt such queries.
1715
Jesse Halldc225072016-05-30 22:40:14 -07001716 // The native window only allows dequeueing all buffers before any have
1717 // been queued, since after that point at least one is assumed to be in
1718 // non-FREE state at any given time. Disconnecting and re-connecting
1719 // orphans the previous buffers, getting us back to the state where we can
1720 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001721 //
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001722 // This is not necessary if the surface was never used previously.
1723 //
Yiwei Zhang70a21962019-05-31 17:26:52 -07001724 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001725 ANativeWindow* window = surface.window.get();
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001726 if (surface.used_by_swapchain) {
1727 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1728 ALOGW_IF(err != android::OK,
1729 "native_window_api_disconnect failed: %s (%d)", strerror(-err),
1730 err);
1731 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1732 ALOGW_IF(err != android::OK,
1733 "native_window_api_connect failed: %s (%d)", strerror(-err),
1734 err);
1735 }
Jesse Halldc225072016-05-30 22:40:14 -07001736
Nicolas Capens147b7da2021-04-09 14:53:06 -04001737 err =
1738 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001739 if (err != android::OK) {
1740 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1741 strerror(-err), err);
1742 return VK_ERROR_SURFACE_LOST_KHR;
1743 }
1744
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301745 int swap_interval =
1746 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001747 err = window->setSwapInterval(window, swap_interval);
1748 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001749 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1750 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001751 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001752 }
1753
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001754 err = native_window_set_shared_buffer_mode(window, false);
1755 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001756 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1757 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001758 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001759 }
1760
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001761 err = native_window_set_auto_refresh(window, false);
1762 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001763 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1764 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001765 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001766 }
1767
Jesse Halld7b994a2015-09-07 14:17:37 -07001768 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001769
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001770 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001771
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001772 err = native_window_set_buffers_format(
1773 window, static_cast<int>(native_pixel_format));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001774 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001775 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001776 toString(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001777 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001778 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001779
1780 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
sergiuferentz47989332023-09-26 10:24:36 +00001781 if (native_dataspace != DataSpace::ARBITRARY) {
1782 err = native_window_set_buffers_data_space(
1783 window, static_cast<android_dataspace_t>(native_dataspace));
Yiwei Zhang51572c22022-07-22 23:08:30 +00001784 if (err != android::OK) {
1785 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1786 native_dataspace, strerror(-err), err);
1787 return VK_ERROR_SURFACE_LOST_KHR;
1788 }
Jesse Hall517274a2016-02-10 00:07:18 -08001789 }
1790
Jesse Hall3dd678a2016-01-08 21:52:01 -08001791 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001792 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001793 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001794 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001795 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1796 create_info->imageExtent.width, create_info->imageExtent.height,
1797 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001798 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001799 }
1800
Jesse Hall178b6962016-02-24 15:39:50 -08001801 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1802 // applied during rendering. native_window_set_transform() expects the
1803 // inverse: the transform the app is requesting that the compositor perform
1804 // during composition. With native windows, pre-transform works by rendering
1805 // with the same transform the compositor is applying (as in Vulkan), but
1806 // then requesting the inverse transform, so that when the compositor does
1807 // it's job the two transforms cancel each other out and the compositor ends
1808 // up applying an identity transform to the app's buffer.
1809 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001810 window, InvertTransformToNative(create_info->preTransform));
1811 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001812 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1813 InvertTransformToNative(create_info->preTransform),
1814 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001815 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001816 }
1817
Jesse Hallf64ca122015-11-03 16:11:10 -08001818 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001819 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1820 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001821 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1822 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001823 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001824 }
1825
Chris Forbes97ef4612017-03-30 19:37:50 +13001826 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001827 if (IsSharedPresentMode(create_info->presentMode)) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001828 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001829 err = native_window_set_shared_buffer_mode(window, true);
1830 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001831 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1832 return VK_ERROR_SURFACE_LOST_KHR;
1833 }
1834 }
1835
1836 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001837 err = native_window_set_auto_refresh(window, true);
1838 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001839 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1840 return VK_ERROR_SURFACE_LOST_KHR;
1841 }
1842 }
1843
Ian Elliott16c443c2021-11-30 17:10:32 -07001844 int query_value;
Trevor David Blackabab5a02023-12-19 20:27:07 +00001845 // TODO: Now that we are calling into GPDSC2 directly, this query may be redundant
1846 // the call to std::max(min_buffer_count, num_images) may be redundant as well
Ian Elliott16c443c2021-11-30 17:10:32 -07001847 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1848 &query_value);
1849 if (err != android::OK || query_value < 0) {
1850 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1851 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001852 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001853 }
Trevor David Black8c0122e2023-09-07 20:33:54 +00001854 const uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
Chris Forbes2c8fc752017-03-17 11:28:32 +13001855
Ian Elliott5396b702021-12-13 19:32:34 -07001856 // Lower layer insists that we have at least min_undequeued_buffers + 1
1857 // buffers. This is wasteful and we'd like to relax it in the shared case,
1858 // but not all the pieces are in place for that to work yet. Note we only
1859 // lie to the lower layer--we don't want to give the app back a swapchain
1860 // with extra images (which they can't actually use!).
Trevor David Black8c0122e2023-09-07 20:33:54 +00001861 const uint32_t min_buffer_count = min_undequeued_buffers + 1;
1862
Trevor David Blackabab5a02023-12-19 20:27:07 +00001863 // Call into GPDSC2 to get the minimum and maximum allowable buffer count for the surface of
1864 // interest. This step is only necessary if the app requests a number of images
1865 // (create_info->minImageCount) that is less or more than the surface capabilities.
1866 // An app should be calling GPDSC2 and using those values to set create_info, but in the
1867 // event that the app has hard-coded image counts an error can occur
1868 VkSurfacePresentModeEXT present_mode = {
1869 VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT,
1870 nullptr,
1871 create_info->presentMode
1872 };
1873 VkPhysicalDeviceSurfaceInfo2KHR surface_info2 = {
1874 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
1875 &present_mode,
1876 create_info->surface
1877 };
1878 VkSurfaceCapabilities2KHR surface_capabilities2 = {
1879 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
1880 nullptr,
1881 {},
1882 };
1883 result = GetPhysicalDeviceSurfaceCapabilities2KHR(GetData(device).driver_physical_device,
1884 &surface_info2, &surface_capabilities2);
1885
1886 uint32_t num_images = create_info->minImageCount;
1887 num_images = std::clamp(num_images,
1888 surface_capabilities2.surfaceCapabilities.minImageCount,
1889 surface_capabilities2.surfaceCapabilities.maxImageCount);
Trevor David Black8c0122e2023-09-07 20:33:54 +00001890
1891 const uint32_t buffer_count = std::max(min_buffer_count, num_images);
1892 err = native_window_set_buffer_count(window, buffer_count);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001893 if (err != android::OK) {
Trevor David Black8c0122e2023-09-07 20:33:54 +00001894 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", buffer_count,
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001895 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001896 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001897 }
1898
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001899 // In shared mode the num_images must be one regardless of how many
1900 // buffers were allocated for the buffer queue.
1901 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1902 num_images = 1;
1903 }
1904
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001905 // Look through the create_info pNext chain passed to createSwapchainKHR
1906 // for an image compression control struct.
1907 // if one is found AND the appropriate extensions are enabled, create a
1908 // VkImageCompressionControlEXT structure to pass on to VkImageCreateInfo
1909 // TODO check for imageCompressionControlSwapchain feature is enabled
Trevor David Black2cc44682022-03-09 00:31:38 +00001910 void* usage_info_pNext = nullptr;
1911 VkImageCompressionControlEXT image_compression = {};
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001912 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1913 while (create_infos->pNext) {
1914 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(create_infos->pNext);
1915 switch (create_infos->sType) {
1916 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1917 const VkImageCompressionControlEXT* compression_infos =
1918 reinterpret_cast<const VkImageCompressionControlEXT*>(create_infos);
1919 image_compression = *compression_infos;
1920 image_compression.pNext = nullptr;
1921 usage_info_pNext = &image_compression;
1922 } break;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001923
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001924 default:
1925 // Ignore all other info structs
1926 break;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001927 }
Jesse Hall70f93352015-11-04 09:41:31 -08001928 }
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001929
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001930 // Get the appropriate native_usage for the images
1931 // Get the consumer usage
1932 uint64_t native_usage = surface.consumer_usage;
1933 // Determine if the swapchain is protected
1934 bool create_protected_swapchain = false;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001935 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001936 create_protected_swapchain = true;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001937 native_usage |= BufferUsage::PROTECTED;
1938 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001939 // Get the producer usage
1940 uint64_t producer_usage;
1941 result = getProducerUsage(device, create_info, swapchain_image_usage, create_protected_swapchain, &producer_usage);
1942 if (result != VK_SUCCESS) {
1943 return result;
1944 }
1945 native_usage |= producer_usage;
1946
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001947 err = native_window_set_usage(window, native_usage);
1948 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001949 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001950 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001951 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001952
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001953 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001954 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1955 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001956 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1957 strerror(-err), err);
1958 return VK_ERROR_SURFACE_LOST_KHR;
1959 }
1960
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001961 int64_t refresh_duration;
1962 err = native_window_get_refresh_cycle_duration(window, &refresh_duration);
1963 if (err != android::OK) {
1964 ALOGE("native_window_get_refresh_cycle_duration query failed: %s (%d)",
1965 strerror(-err), err);
1966 return VK_ERROR_SURFACE_LOST_KHR;
1967 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001968 // -- Allocate our Swapchain object --
1969 // After this point, we must deallocate the swapchain on error.
1970
Jesse Hall1f91d392015-12-11 16:28:44 -08001971 void* mem = allocator->pfnAllocation(allocator->pUserData,
1972 sizeof(Swapchain), alignof(Swapchain),
1973 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001974
Jesse Hall1356b0d2015-11-23 17:24:58 -08001975 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001976 return VK_ERROR_OUT_OF_HOST_MEMORY;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001977
silence_dogood73597592019-05-23 16:57:37 -07001978 Swapchain* swapchain = new (mem)
1979 Swapchain(surface, num_images, create_info->presentMode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001980 TranslateVulkanToNativeTransform(create_info->preTransform),
1981 refresh_duration);
Chris Forbesb56287a2017-01-12 14:28:58 +13001982 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1983#pragma clang diagnostic push
1984#pragma clang diagnostic ignored "-Wold-style-cast"
1985 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1986#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00001987 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13001988 .usage = swapchain_image_usage,
1989 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001990 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001991#pragma clang diagnostic push
1992#pragma clang diagnostic ignored "-Wold-style-cast"
1993 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1994#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001995 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001996 };
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001997
Jesse Halld7b994a2015-09-07 14:17:37 -07001998 VkImageCreateInfo image_create = {
1999 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002000 .pNext = nullptr,
Trevor David Blackd7320ef2023-08-23 21:21:51 +00002001 .flags = create_protected_swapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07002002 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08002003 .format = create_info->imageFormat,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002004 .extent = {
2005 create_info->imageExtent.width,
2006 create_info->imageExtent.height,
2007 1
2008 },
Jesse Halld7b994a2015-09-07 14:17:37 -07002009 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08002010 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08002011 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07002012 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08002013 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08002014 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08002015 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07002016 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
2017 };
2018
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002019 // Note: don't do deferred allocation for shared present modes. There's only one buffer
2020 // involved so very little benefit.
2021 if ((create_info->flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT) &&
2022 !IsSharedPresentMode(create_info->presentMode)) {
2023 // Don't want to touch the underlying gralloc buffers yet;
2024 // instead just create unbound VkImages which will later be bound to memory inside
2025 // AcquireNextImage.
2026 VkImageSwapchainCreateInfoKHR image_swapchain_create = {
2027 .sType = VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR,
2028 .pNext = nullptr,
2029 .swapchain = HandleFromSwapchain(swapchain),
2030 };
2031 image_create.pNext = &image_swapchain_create;
Jesse Halld7b994a2015-09-07 14:17:37 -07002032
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002033 for (uint32_t i = 0; i < num_images; i++) {
2034 Swapchain::Image& img = swapchain->images[i];
2035 img.buffer = nullptr;
2036 img.dequeued = false;
2037
2038 result = dispatch.CreateImage(device, &image_create, nullptr, &img.image);
2039 if (result != VK_SUCCESS) {
2040 ALOGD("vkCreateImage w/ for deferred swapchain image failed: %u", result);
2041 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08002042 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002043 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002044 } else {
2045 // -- Dequeue all buffers and create a VkImage for each --
2046 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07002047
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002048 for (uint32_t i = 0; i < num_images; i++) {
2049 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07002050
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002051 ANativeWindowBuffer* buffer;
2052 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
2053 if (err != android::OK) {
2054 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
2055 switch (-err) {
2056 case ENOMEM:
2057 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
2058 break;
2059 default:
2060 result = VK_ERROR_SURFACE_LOST_KHR;
2061 break;
2062 }
2063 break;
2064 }
2065 img.buffer = buffer;
2066 img.dequeued = true;
2067
2068 image_native_buffer.handle = img.buffer->handle;
2069 image_native_buffer.stride = img.buffer->stride;
2070 image_native_buffer.format = img.buffer->format;
2071 image_native_buffer.usage = int(img.buffer->usage);
2072 android_convertGralloc0To1Usage(int(img.buffer->usage),
2073 &image_native_buffer.usage2.producer,
2074 &image_native_buffer.usage2.consumer);
2075 image_native_buffer.usage3 = img.buffer->usage;
Trevor David Black0db7a092023-12-11 23:46:36 +00002076 image_native_buffer.ahb =
2077 ANativeWindowBuffer_getHardwareBuffer(img.buffer.get());
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002078 image_create.pNext = &image_native_buffer;
2079
2080 ATRACE_BEGIN("CreateImage");
2081 result =
2082 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
2083 ATRACE_END();
2084 if (result != VK_SUCCESS) {
2085 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
2086 break;
2087 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002088 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002089
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002090 // -- Cancel all buffers, returning them to the queue --
2091 // If an error occurred before, also destroy the VkImage and release the
2092 // buffer reference. Otherwise, we retain a strong reference to the buffer.
2093 for (uint32_t i = 0; i < num_images; i++) {
2094 Swapchain::Image& img = swapchain->images[i];
2095 if (img.dequeued) {
2096 if (!swapchain->shared) {
2097 window->cancelBuffer(window, img.buffer.get(),
2098 img.dequeue_fence);
2099 img.dequeue_fence = -1;
2100 img.dequeued = false;
2101 }
Chris Forbese0ced032017-03-30 19:44:15 +13002102 }
Chris Forbes31b85c22018-05-29 15:03:28 -07002103 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002104 }
2105
2106 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07002107 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
2108 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07002109 return result;
2110 }
2111
Yiwei Zhang69395cd2019-07-03 16:55:39 -07002112 if (transform_hint != swapchain->pre_transform) {
2113 // Log that the app is not doing pre-rotation.
2114 android::GraphicsEnv::getInstance().setTargetStats(
2115 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
2116 }
2117
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00002118 // Set stats for creating a Vulkan swapchain
2119 android::GraphicsEnv::getInstance().setTargetStats(
2120 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
2121
Yiwei Zhang3b88f312023-04-18 23:11:35 +00002122 surface.used_by_swapchain = true;
Jesse Halldc225072016-05-30 22:40:14 -07002123 surface.swapchain_handle = HandleFromSwapchain(swapchain);
2124 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002125 return VK_SUCCESS;
2126}
2127
Jesse Halle1b12782015-11-30 11:27:32 -08002128VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002129void DestroySwapchainKHR(VkDevice device,
2130 VkSwapchainKHR swapchain_handle,
2131 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002132 ATRACE_CALL();
2133
Yiwei Zhang533cea92019-06-03 18:43:24 -07002134 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07002135}
2136
Jesse Halle1b12782015-11-30 11:27:32 -08002137VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002138VkResult GetSwapchainImagesKHR(VkDevice,
2139 VkSwapchainKHR swapchain_handle,
2140 uint32_t* count,
2141 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002142 ATRACE_CALL();
2143
Jesse Halld7b994a2015-09-07 14:17:37 -07002144 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07002145 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
2146 "getting images for non-active swapchain 0x%" PRIx64
2147 "; only dequeued image handles are valid",
2148 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07002149 VkResult result = VK_SUCCESS;
2150 if (images) {
2151 uint32_t n = swapchain.num_images;
2152 if (*count < swapchain.num_images) {
2153 n = *count;
2154 result = VK_INCOMPLETE;
2155 }
2156 for (uint32_t i = 0; i < n; i++)
2157 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07002158 *count = n;
2159 } else {
2160 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07002161 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002162 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002163}
2164
Jesse Halle1b12782015-11-30 11:27:32 -08002165VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002166VkResult AcquireNextImageKHR(VkDevice device,
2167 VkSwapchainKHR swapchain_handle,
2168 uint64_t timeout,
2169 VkSemaphore semaphore,
2170 VkFence vk_fence,
2171 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002172 ATRACE_CALL();
2173
Jesse Halld7b994a2015-09-07 14:17:37 -07002174 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08002175 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07002176 VkResult result;
2177 int err;
2178
Jesse Halldc225072016-05-30 22:40:14 -07002179 if (swapchain.surface.swapchain_handle != swapchain_handle)
2180 return VK_ERROR_OUT_OF_DATE_KHR;
2181
Chris Forbesc88409c2017-03-30 19:47:37 +13002182 if (swapchain.shared) {
2183 // In shared mode, we keep the buffer dequeued all the time, so we don't
2184 // want to dequeue a buffer here. Instead, just ask the driver to ensure
2185 // the semaphore and fence passed to us will be signalled.
2186 *image_index = 0;
2187 result = GetData(device).driver.AcquireImageANDROID(
2188 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
2189 return result;
2190 }
2191
Yiwei Zhang705c2e62019-12-18 23:12:43 -08002192 const nsecs_t acquire_next_image_timeout =
2193 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
2194 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
2195 // Cache the timeout to avoid the duplicate binder cost.
2196 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
2197 acquire_next_image_timeout);
2198 if (err != android::OK) {
2199 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
2200 strerror(-err), err);
2201 return VK_ERROR_SURFACE_LOST_KHR;
2202 }
2203 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
2204 }
2205
Jesse Halld7b994a2015-09-07 14:17:37 -07002206 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08002207 int fence_fd;
2208 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07002209 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08002210 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
2211 return timeout ? VK_TIMEOUT : VK_NOT_READY;
2212 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07002213 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07002214 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002215 }
2216
2217 uint32_t idx;
2218 for (idx = 0; idx < swapchain.num_images; idx++) {
2219 if (swapchain.images[idx].buffer.get() == buffer) {
2220 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08002221 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07002222 break;
2223 }
2224 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002225
2226 // If this is a deferred alloc swapchain, this may be the first time we've
2227 // seen a particular buffer. If so, there should be an empty slot. Find it,
2228 // and bind the gralloc buffer to the VkImage for that slot. If there is no
2229 // empty slot, then we dequeued an unexpected buffer. Non-deferred swapchains
2230 // will also take this path, but will never have an empty slot since we
2231 // populated them all upfront.
2232 if (idx == swapchain.num_images) {
2233 for (idx = 0; idx < swapchain.num_images; idx++) {
2234 if (!swapchain.images[idx].buffer) {
2235 // Note: this structure is technically required for
2236 // Vulkan correctness, even though the driver is probably going
2237 // to use everything from the VkNativeBufferANDROID below.
2238 // This is kindof silly, but it's how we did the ANB
2239 // side of VK_KHR_swapchain v69, so we're stuck with it unless
2240 // we want to go tinkering with the ANB spec some more.
2241 VkBindImageMemorySwapchainInfoKHR bimsi = {
2242 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR,
2243 .pNext = nullptr,
2244 .swapchain = swapchain_handle,
2245 .imageIndex = idx,
2246 };
2247 VkNativeBufferANDROID nb = {
2248 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2249 .pNext = &bimsi,
2250 .handle = buffer->handle,
2251 .stride = buffer->stride,
2252 .format = buffer->format,
2253 .usage = int(buffer->usage),
Trevor David Black0db7a092023-12-11 23:46:36 +00002254 .usage3 = buffer->usage,
2255 .ahb = ANativeWindowBuffer_getHardwareBuffer(buffer),
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002256 };
Trevor David Black0db7a092023-12-11 23:46:36 +00002257 android_convertGralloc0To1Usage(int(buffer->usage),
2258 &nb.usage2.producer,
2259 &nb.usage2.consumer);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002260 VkBindImageMemoryInfo bimi = {
2261 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO,
2262 .pNext = &nb,
2263 .image = swapchain.images[idx].image,
2264 .memory = VK_NULL_HANDLE,
2265 .memoryOffset = 0,
2266 };
2267 result = GetData(device).driver.BindImageMemory2(device, 1, &bimi);
2268 if (result != VK_SUCCESS) {
2269 // This shouldn't really happen. If it does, something is probably
2270 // unrecoverably wrong with the swapchain and its images. Cancel
2271 // the buffer and declare the swapchain broken.
2272 ALOGE("failed to do deferred gralloc buffer bind");
2273 window->cancelBuffer(window, buffer, fence_fd);
2274 return VK_ERROR_OUT_OF_DATE_KHR;
2275 }
2276
2277 swapchain.images[idx].dequeued = true;
2278 swapchain.images[idx].dequeue_fence = fence_fd;
2279 swapchain.images[idx].buffer = buffer;
2280 break;
2281 }
2282 }
2283 }
2284
2285 // The buffer doesn't match any slot. This shouldn't normally happen, but is
2286 // possible if the bufferqueue is reconfigured behind libvulkan's back. If this
2287 // happens, just declare the swapchain to be broken and the app will recreate it.
Jesse Halld7b994a2015-09-07 14:17:37 -07002288 if (idx == swapchain.num_images) {
2289 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08002290 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002291 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002292 }
2293
2294 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08002295 if (fence_fd != -1) {
2296 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002297 if (fence_clone == -1) {
2298 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
2299 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08002300 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07002301 }
2302 }
2303
Chia-I Wu4a6a9162016-03-26 07:17:34 +08002304 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08002305 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07002306 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08002307 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
2308 // even if the call fails. We could close it ourselves on failure, but
2309 // that would create a race condition if the driver closes it on a
2310 // failure path: some other thread might create an fd with the same
2311 // number between the time the driver closes it and the time we close
2312 // it. We must assume one of: the driver *always* closes it even on
2313 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08002314 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002315 swapchain.images[idx].dequeued = false;
2316 swapchain.images[idx].dequeue_fence = -1;
2317 return result;
2318 }
2319
2320 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002321 return VK_SUCCESS;
2322}
2323
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002324VKAPI_ATTR
2325VkResult AcquireNextImage2KHR(VkDevice device,
2326 const VkAcquireNextImageInfoKHR* pAcquireInfo,
2327 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002328 ATRACE_CALL();
2329
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002330 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
2331 pAcquireInfo->timeout, pAcquireInfo->semaphore,
2332 pAcquireInfo->fence, pImageIndex);
2333}
2334
Jesse Halldc225072016-05-30 22:40:14 -07002335static VkResult WorstPresentResult(VkResult a, VkResult b) {
2336 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
2337 // (in spec version 1.0.14).
2338 static const VkResult kWorstToBest[] = {
2339 VK_ERROR_DEVICE_LOST,
2340 VK_ERROR_SURFACE_LOST_KHR,
2341 VK_ERROR_OUT_OF_DATE_KHR,
2342 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2343 VK_ERROR_OUT_OF_HOST_MEMORY,
2344 VK_SUBOPTIMAL_KHR,
2345 };
2346 for (auto result : kWorstToBest) {
2347 if (a == result || b == result)
2348 return result;
2349 }
2350 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
2351 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
2352 return a != VK_SUCCESS ? a : b;
2353}
2354
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002355// KHR_incremental_present aspect of QueuePresentKHR
2356static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
2357 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
2358 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
2359 auto const& rect = pRegion->pRectangles[i];
2360 if (rect.layer > 0) {
2361 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
2362 rect.layer);
2363 }
2364
2365 rects[i].left = rect.offset.x;
2366 rects[i].bottom = rect.offset.y;
2367 rects[i].right = rect.offset.x + rect.extent.width;
2368 rects[i].top = rect.offset.y + rect.extent.height;
2369 }
2370 native_window_set_surface_damage(window, rects.data(), rects.size());
2371}
2372
2373// GOOGLE_display_timing aspect of QueuePresentKHR
2374static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
2375 ANativeWindow *window = swapchain.surface.window.get();
2376
2377 // We don't know whether the app will actually use GOOGLE_display_timing
2378 // with a particular swapchain until QueuePresent; enable it on the BQ
2379 // now if needed
2380 if (!swapchain.frame_timestamps_enabled) {
2381 ALOGV("Calling native_window_enable_frame_timestamps(true)");
2382 native_window_enable_frame_timestamps(window, true);
2383 swapchain.frame_timestamps_enabled = true;
2384 }
2385
2386 // Record the nativeFrameId so it can be later correlated to
2387 // this present.
2388 uint64_t nativeFrameId = 0;
2389 int err = native_window_get_next_frame_id(
2390 window, &nativeFrameId);
2391 if (err != android::OK) {
2392 ALOGE("Failed to get next native frame ID.");
2393 }
2394
2395 // Add a new timing record with the user's presentID and
2396 // the nativeFrameId.
2397 swapchain.timing.emplace_back(pTime, nativeFrameId);
2398 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
2399 swapchain.timing.erase(
2400 swapchain.timing.begin(),
2401 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
2402 }
2403 if (pTime->desiredPresentTime) {
2404 ALOGV(
2405 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
2406 pTime->desiredPresentTime);
2407 native_window_set_buffers_timestamp(
2408 window,
2409 static_cast<int64_t>(pTime->desiredPresentTime));
2410 }
2411}
2412
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002413// EXT_swapchain_maintenance1 present mode change
2414static bool SetSwapchainPresentMode(ANativeWindow *window, VkPresentModeKHR mode) {
2415 // There is no dynamic switching between non-shared present modes.
2416 // All we support is switching between demand and continuous refresh.
2417 if (!IsSharedPresentMode(mode))
2418 return true;
2419
2420 int err = native_window_set_auto_refresh(window,
2421 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
2422 if (err != android::OK) {
2423 ALOGE("native_window_set_auto_refresh() failed: %s (%d)",
2424 strerror(-err), err);
2425 return false;
2426 }
2427
2428 return true;
2429}
2430
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002431static VkResult PresentOneSwapchain(
2432 VkQueue queue,
2433 Swapchain& swapchain,
2434 uint32_t imageIndex,
2435 const VkPresentRegionKHR *pRegion,
2436 const VkPresentTimeGOOGLE *pTime,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002437 VkFence presentFence,
2438 const VkPresentModeKHR *pPresentMode,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002439 uint32_t waitSemaphoreCount,
2440 const VkSemaphore *pWaitSemaphores) {
2441
2442 VkDevice device = GetData(queue).driver_device;
2443 const auto& dispatch = GetData(queue).driver;
2444
2445 Swapchain::Image& img = swapchain.images[imageIndex];
2446 VkResult swapchain_result = VK_SUCCESS;
2447 VkResult result;
2448 int err;
2449
2450 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
2451 // wait semaphores, so this doesn't actually work for the multiple swapchain
2452 // case.
2453 int fence = -1;
2454 result = dispatch.QueueSignalReleaseImageANDROID(
2455 queue, waitSemaphoreCount,
2456 pWaitSemaphores, img.image, &fence);
2457 if (result != VK_SUCCESS) {
2458 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
2459 swapchain_result = result;
2460 }
2461 if (img.release_fence >= 0)
2462 close(img.release_fence);
2463 img.release_fence = fence < 0 ? -1 : dup(fence);
2464
2465 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
2466 ANativeWindow* window = swapchain.surface.window.get();
2467 if (swapchain_result == VK_SUCCESS) {
2468
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002469 if (presentFence != VK_NULL_HANDLE) {
2470 int fence_copy = fence < 0 ? -1 : dup(fence);
2471 VkImportFenceFdInfoKHR iffi = {
2472 VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,
2473 nullptr,
2474 presentFence,
2475 VK_FENCE_IMPORT_TEMPORARY_BIT,
2476 VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,
2477 fence_copy,
2478 };
2479 if (VK_SUCCESS != dispatch.ImportFenceFdKHR(device, &iffi) && fence_copy >= 0) {
2480 // ImportFenceFdKHR takes ownership only if it succeeds
2481 close(fence_copy);
2482 }
2483 }
2484
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002485 if (pRegion) {
2486 SetSwapchainSurfaceDamage(window, pRegion);
2487 }
2488 if (pTime) {
2489 SetSwapchainFrameTimestamp(swapchain, pTime);
2490 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002491 if (pPresentMode) {
2492 if (!SetSwapchainPresentMode(window, *pPresentMode))
2493 swapchain_result = WorstPresentResult(swapchain_result,
2494 VK_ERROR_SURFACE_LOST_KHR);
2495 }
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002496
2497 err = window->queueBuffer(window, img.buffer.get(), fence);
2498 // queueBuffer always closes fence, even on error
2499 if (err != android::OK) {
2500 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
2501 swapchain_result = WorstPresentResult(
2502 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2503 } else {
2504 if (img.dequeue_fence >= 0) {
2505 close(img.dequeue_fence);
2506 img.dequeue_fence = -1;
2507 }
2508 img.dequeued = false;
2509 }
2510
2511 // If the swapchain is in shared mode, immediately dequeue the
2512 // buffer so it can be presented again without an intervening
2513 // call to AcquireNextImageKHR. We expect to get the same buffer
2514 // back from every call to dequeueBuffer in this mode.
2515 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
2516 ANativeWindowBuffer* buffer;
2517 int fence_fd;
2518 err = window->dequeueBuffer(window, &buffer, &fence_fd);
2519 if (err != android::OK) {
2520 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
2521 swapchain_result = WorstPresentResult(swapchain_result,
2522 VK_ERROR_SURFACE_LOST_KHR);
2523 } else if (img.buffer != buffer) {
2524 ALOGE("got wrong image back for shared swapchain");
2525 swapchain_result = WorstPresentResult(swapchain_result,
2526 VK_ERROR_SURFACE_LOST_KHR);
2527 } else {
2528 img.dequeue_fence = fence_fd;
2529 img.dequeued = true;
2530 }
2531 }
2532 }
2533 if (swapchain_result != VK_SUCCESS) {
2534 OrphanSwapchain(device, &swapchain);
2535 }
2536 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
2537 // and only when the window's transform/rotation changes. Extent
2538 // changes will not cause VK_SUBOPTIMAL_KHR because of the
2539 // application issues that were caused when the following transform
2540 // change was added.
2541 int window_transform_hint;
2542 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
2543 &window_transform_hint);
2544 if (err != android::OK) {
2545 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
2546 strerror(-err), err);
2547 swapchain_result = WorstPresentResult(
2548 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2549 }
2550 if (swapchain.pre_transform != window_transform_hint) {
2551 swapchain_result =
2552 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
2553 }
2554 } else {
2555 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
2556 img, true);
2557 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
2558 }
2559
2560 return swapchain_result;
2561}
2562
Jesse Halle1b12782015-11-30 11:27:32 -08002563VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002564VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002565 ATRACE_CALL();
2566
Jesse Halld7b994a2015-09-07 14:17:37 -07002567 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
2568 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
2569 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07002570
Jesse Halld7b994a2015-09-07 14:17:37 -07002571 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07002572
Ian Elliottcb351132016-12-13 10:30:40 -07002573 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002574 const VkPresentRegionsKHR* present_regions = nullptr;
2575 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002576 const VkSwapchainPresentFenceInfoEXT* present_fences = nullptr;
2577 const VkSwapchainPresentModeInfoEXT* present_modes = nullptr;
2578
Ian Elliottcb351132016-12-13 10:30:40 -07002579 const VkPresentRegionsKHR* next =
2580 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
2581 while (next) {
2582 switch (next->sType) {
2583 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
2584 present_regions = next;
2585 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07002586 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002587 present_times =
2588 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
2589 break;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002590 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT:
2591 present_fences =
2592 reinterpret_cast<const VkSwapchainPresentFenceInfoEXT*>(next);
2593 break;
2594 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT:
2595 present_modes =
2596 reinterpret_cast<const VkSwapchainPresentModeInfoEXT*>(next);
2597 break;
Ian Elliottcb351132016-12-13 10:30:40 -07002598 default:
2599 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
2600 next->sType);
2601 break;
2602 }
2603 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2604 }
2605 ALOGV_IF(
2606 present_regions &&
2607 present_regions->swapchainCount != present_info->swapchainCount,
2608 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002609 ALOGV_IF(present_times &&
2610 present_times->swapchainCount != present_info->swapchainCount,
2611 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2612 "VkPresentInfo::swapchainCount");
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002613 ALOGV_IF(present_fences &&
2614 present_fences->swapchainCount != present_info->swapchainCount,
2615 "VkSwapchainPresentFenceInfoEXT::swapchainCount != "
2616 "VkPresentInfo::swapchainCount");
2617 ALOGV_IF(present_modes &&
2618 present_modes->swapchainCount != present_info->swapchainCount,
2619 "VkSwapchainPresentModeInfoEXT::swapchainCount != "
2620 "VkPresentInfo::swapchainCount");
2621
Ian Elliottcb351132016-12-13 10:30:40 -07002622 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002623 (present_regions) ? present_regions->pRegions : nullptr;
2624 const VkPresentTimeGOOGLE* times =
2625 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002626
Jesse Halld7b994a2015-09-07 14:17:37 -07002627 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2628 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002629 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002630
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002631 VkResult swapchain_result = PresentOneSwapchain(
2632 queue,
2633 swapchain,
2634 present_info->pImageIndices[sc],
2635 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2636 times ? &times[sc] : nullptr,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002637 present_fences ? present_fences->pFences[sc] : VK_NULL_HANDLE,
2638 present_modes ? &present_modes->pPresentModes[sc] : nullptr,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002639 present_info->waitSemaphoreCount,
2640 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002641
Jesse Halla9e57032015-11-30 01:03:10 -08002642 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002643 present_info->pResults[sc] = swapchain_result;
2644
2645 if (swapchain_result != final_result)
2646 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002647 }
2648
2649 return final_result;
2650}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002651
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002652VKAPI_ATTR
2653VkResult GetRefreshCycleDurationGOOGLE(
2654 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002655 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002656 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002657 ATRACE_CALL();
2658
Ian Elliott62c48c92017-01-20 13:13:20 -07002659 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00002660 VkResult result = swapchain.get_refresh_duration(pDisplayTimingProperties->refreshDuration);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002661
2662 return result;
2663}
2664
2665VKAPI_ATTR
2666VkResult GetPastPresentationTimingGOOGLE(
2667 VkDevice,
2668 VkSwapchainKHR swapchain_handle,
2669 uint32_t* count,
2670 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002671 ATRACE_CALL();
2672
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002673 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002674 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2675 return VK_ERROR_OUT_OF_DATE_KHR;
2676 }
2677
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002678 ANativeWindow* window = swapchain.surface.window.get();
2679 VkResult result = VK_SUCCESS;
2680
2681 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002682 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002683 native_window_enable_frame_timestamps(window, true);
2684 swapchain.frame_timestamps_enabled = true;
2685 }
2686
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002687 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002688 // Get the latest ready timing count before copying, since the copied
2689 // timing info will be erased in copy_ready_timings function.
2690 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002691 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002692 // Check the *count here against the recorded ready timing count, since
2693 // *count can be overwritten per spec describes.
2694 if (*count < n) {
2695 result = VK_INCOMPLETE;
2696 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002697 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002698 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002699 }
2700
2701 return result;
2702}
2703
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002704VKAPI_ATTR
2705VkResult GetSwapchainStatusKHR(
2706 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002707 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002708 ATRACE_CALL();
2709
Chris Forbes4e18ba82017-01-20 12:50:17 +13002710 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002711 VkResult result = VK_SUCCESS;
2712
Chris Forbes4e18ba82017-01-20 12:50:17 +13002713 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2714 return VK_ERROR_OUT_OF_DATE_KHR;
2715 }
2716
Yiwei Zhanga885c062019-10-24 12:07:57 -07002717 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002718
2719 return result;
2720}
2721
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002722VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002723 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002724 uint32_t swapchainCount,
2725 const VkSwapchainKHR* pSwapchains,
2726 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002727 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002728
2729 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2730 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2731 if (!swapchain)
2732 continue;
2733
2734 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2735
2736 ANativeWindow* window = swapchain->surface.window.get();
2737
2738 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2739 const android_smpte2086_metadata smpteMetdata = {
2740 {vulkanMetadata.displayPrimaryRed.x,
2741 vulkanMetadata.displayPrimaryRed.y},
2742 {vulkanMetadata.displayPrimaryGreen.x,
2743 vulkanMetadata.displayPrimaryGreen.y},
2744 {vulkanMetadata.displayPrimaryBlue.x,
2745 vulkanMetadata.displayPrimaryBlue.y},
2746 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2747 vulkanMetadata.maxLuminance,
2748 vulkanMetadata.minLuminance};
2749 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2750
2751 const android_cta861_3_metadata cta8613Metadata = {
2752 vulkanMetadata.maxContentLightLevel,
2753 vulkanMetadata.maxFrameAverageLightLevel};
2754 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2755 }
2756
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002757 return;
2758}
2759
Yiwei Zhang0f475222019-04-11 19:38:00 -07002760static void InterceptBindImageMemory2(
2761 uint32_t bind_info_count,
2762 const VkBindImageMemoryInfo* bind_infos,
2763 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2764 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2765 out_native_buffers->clear();
2766 out_bind_infos->clear();
2767
2768 if (!bind_info_count)
2769 return;
2770
2771 std::unordered_set<uint32_t> intercepted_indexes;
2772
2773 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2774 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2775 bind_infos[idx].pNext);
2776 while (info &&
2777 info->sType !=
2778 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2779 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2780 info->pNext);
2781 }
2782
2783 if (!info)
2784 continue;
2785
2786 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2787 "swapchain handle must not be NULL");
2788 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2789 ALOG_ASSERT(
2790 info->imageIndex < swapchain->num_images,
2791 "imageIndex must be less than the number of images in swapchain");
2792
2793 ANativeWindowBuffer* buffer =
2794 swapchain->images[info->imageIndex].buffer.get();
2795 VkNativeBufferANDROID native_buffer = {
2796#pragma clang diagnostic push
2797#pragma clang diagnostic ignored "-Wold-style-cast"
2798 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2799#pragma clang diagnostic pop
2800 .pNext = bind_infos[idx].pNext,
2801 .handle = buffer->handle,
2802 .stride = buffer->stride,
2803 .format = buffer->format,
2804 .usage = int(buffer->usage),
Trevor David Black0db7a092023-12-11 23:46:36 +00002805 .usage3 = buffer->usage,
2806 .ahb = ANativeWindowBuffer_getHardwareBuffer(buffer),
Yiwei Zhang0f475222019-04-11 19:38:00 -07002807 };
Trevor David Black0db7a092023-12-11 23:46:36 +00002808 android_convertGralloc0To1Usage(int(buffer->usage),
2809 &native_buffer.usage2.producer,
2810 &native_buffer.usage2.consumer);
Yiwei Zhang0f475222019-04-11 19:38:00 -07002811 // Reserve enough space to avoid letting re-allocation invalidate the
2812 // addresses of the elements inside.
2813 out_native_buffers->reserve(bind_info_count);
2814 out_native_buffers->emplace_back(native_buffer);
2815
2816 // Reserve the space now since we know how much is needed now.
2817 out_bind_infos->reserve(bind_info_count);
2818 out_bind_infos->emplace_back(bind_infos[idx]);
2819 out_bind_infos->back().pNext = &out_native_buffers->back();
2820
2821 intercepted_indexes.insert(idx);
2822 }
2823
2824 if (intercepted_indexes.empty())
2825 return;
2826
2827 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2828 if (intercepted_indexes.count(idx))
2829 continue;
2830 out_bind_infos->emplace_back(bind_infos[idx]);
2831 }
2832}
2833
Yiwei Zhang23143102019-04-10 18:24:05 -07002834VKAPI_ATTR
2835VkResult BindImageMemory2(VkDevice device,
2836 uint32_t bindInfoCount,
2837 const VkBindImageMemoryInfo* pBindInfos) {
2838 ATRACE_CALL();
2839
Yiwei Zhang0f475222019-04-11 19:38:00 -07002840 // out_native_buffers is for maintaining the lifecycle of the constructed
2841 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2842 std::vector<VkNativeBufferANDROID> out_native_buffers;
2843 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2844 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2845 &out_bind_infos);
2846 return GetData(device).driver.BindImageMemory2(
2847 device, bindInfoCount,
2848 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002849}
2850
2851VKAPI_ATTR
2852VkResult BindImageMemory2KHR(VkDevice device,
2853 uint32_t bindInfoCount,
2854 const VkBindImageMemoryInfo* pBindInfos) {
2855 ATRACE_CALL();
2856
Yiwei Zhang0f475222019-04-11 19:38:00 -07002857 std::vector<VkNativeBufferANDROID> out_native_buffers;
2858 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2859 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2860 &out_bind_infos);
2861 return GetData(device).driver.BindImageMemory2KHR(
2862 device, bindInfoCount,
2863 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002864}
2865
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002866VKAPI_ATTR
2867VkResult ReleaseSwapchainImagesEXT(VkDevice /*device*/,
2868 const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
2869 ATRACE_CALL();
2870
2871 Swapchain& swapchain = *SwapchainFromHandle(pReleaseInfo->swapchain);
2872 ANativeWindow* window = swapchain.surface.window.get();
2873
2874 // If in shared present mode, don't actually release the image back to the BQ.
2875 // Both sides share it forever.
2876 if (swapchain.shared)
2877 return VK_SUCCESS;
2878
2879 for (uint32_t i = 0; i < pReleaseInfo->imageIndexCount; i++) {
2880 Swapchain::Image& img = swapchain.images[pReleaseInfo->pImageIndices[i]];
2881 window->cancelBuffer(window, img.buffer.get(), img.dequeue_fence);
2882
2883 // cancelBuffer has taken ownership of the dequeue fence
2884 img.dequeue_fence = -1;
2885 // if we're still holding a release fence, get rid of it now
2886 if (img.release_fence >= 0) {
2887 close(img.release_fence);
2888 img.release_fence = -1;
2889 }
2890 img.dequeued = false;
2891 }
2892
2893 return VK_SUCCESS;
2894}
2895
Chia-I Wu62262232016-03-26 07:06:44 +08002896} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002897} // namespace vulkan