blob: 3eeb6b14e0ea83e264a9b94e05a99a269bb8960c [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 Zhang3aef18e2024-03-18 22:01:42 +0000253 int default_format;
Yiwei Zhang3b88f312023-04-18 23:11:35 +0000254
255 // Indicate whether this surface has been used by a swapchain, no matter the
256 // swapchain is still current or has been destroyed.
257 bool used_by_swapchain;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800258};
259
260VkSurfaceKHR HandleFromSurface(Surface* surface) {
261 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
262}
263
264Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800265 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800266}
267
Ian Elliott8a977262017-01-19 09:05:58 -0700268// Maximum number of TimingInfo structs to keep per swapchain:
269enum { MAX_TIMING_INFOS = 10 };
270// Minimum number of frames to look for in the past (so we don't cause
271// syncronous requests to Surface Flinger):
272enum { MIN_NUM_FRAMES_AGO = 5 };
273
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300274bool IsSharedPresentMode(VkPresentModeKHR mode) {
275 return mode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
276 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR;
277}
278
Jesse Hall1356b0d2015-11-23 17:24:58 -0800279struct Swapchain {
Ian Elliottffedb652017-02-14 10:58:30 -0700280 Swapchain(Surface& surface_,
281 uint32_t num_images_,
silence_dogood73597592019-05-23 16:57:37 -0700282 VkPresentModeKHR present_mode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000283 int pre_transform_,
284 int64_t refresh_duration_)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700285 : surface(surface_),
286 num_images(num_images_),
Ian Elliottffedb652017-02-14 10:58:30 -0700287 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
silence_dogood73597592019-05-23 16:57:37 -0700288 pre_transform(pre_transform_),
Chris Forbesf8835642017-03-30 19:31:40 +1300289 frame_timestamps_enabled(false),
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000290 refresh_duration(refresh_duration_),
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800291 acquire_next_image_timeout(-1),
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300292 shared(IsSharedPresentMode(present_mode)) {
Ian Elliott8a977262017-01-19 09:05:58 -0700293 }
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000294
295 VkResult get_refresh_duration(uint64_t& outRefreshDuration)
Ian Elliott3568bfe2019-05-03 15:54:46 -0600296 {
297 ANativeWindow* window = surface.window.get();
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000298 int err = native_window_get_refresh_cycle_duration(
Ian Elliott3568bfe2019-05-03 15:54:46 -0600299 window,
300 &refresh_duration);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000301 if (err != android::OK) {
302 ALOGE("%s:native_window_get_refresh_cycle_duration failed: %s (%d)",
303 __func__, strerror(-err), err );
304 return VK_ERROR_SURFACE_LOST_KHR;
305 }
306 outRefreshDuration = refresh_duration;
307 return VK_SUCCESS;
Ian Elliott3568bfe2019-05-03 15:54:46 -0600308 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800309
310 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700311 uint32_t num_images;
Ian Elliottffedb652017-02-14 10:58:30 -0700312 bool mailbox_mode;
silence_dogood73597592019-05-23 16:57:37 -0700313 int pre_transform;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700314 bool frame_timestamps_enabled;
Brian Andersondc96fdf2017-03-20 16:54:25 -0700315 int64_t refresh_duration;
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800316 nsecs_t acquire_next_image_timeout;
Chris Forbesf8835642017-03-30 19:31:40 +1300317 bool shared;
Jesse Halld7b994a2015-09-07 14:17:37 -0700318
319 struct Image {
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700320 Image()
321 : image(VK_NULL_HANDLE),
322 dequeue_fence(-1),
323 release_fence(-1),
324 dequeued(false) {}
Jesse Halld7b994a2015-09-07 14:17:37 -0700325 VkImage image;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000326 // If the image is bound to memory, an sp to the underlying gralloc buffer.
327 // Otherwise, nullptr; the image will be bound to memory as part of
328 // AcquireNextImage.
Chia-I Wue8e689f2016-04-18 08:21:31 +0800329 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700330 // The fence is only valid when the buffer is dequeued, and should be
331 // -1 any other time. When valid, we own the fd, and must ensure it is
332 // closed: either by closing it explicitly when queueing the buffer,
333 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
334 int dequeue_fence;
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700335 // This fence is a dup of the sync fd returned from the driver via
336 // vkQueueSignalReleaseImageANDROID upon vkQueuePresentKHR. We must
337 // ensure it is closed upon re-presenting or releasing the image.
338 int release_fence;
Jesse Halld7b994a2015-09-07 14:17:37 -0700339 bool dequeued;
Pawin Vongmasa6e1193a2017-03-07 13:08:40 -0800340 } images[android::BufferQueueDefs::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700341
Yiwei Zhang5e862202019-06-21 14:59:16 -0700342 std::vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700343};
344
345VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
346 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
347}
348
349Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800350 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700351}
352
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700353static bool IsFencePending(int fd) {
354 if (fd < 0)
355 return false;
356
357 errno = 0;
358 return sync_wait(fd, 0 /* timeout */) == -1 && errno == ETIME;
359}
360
Jesse Halldc225072016-05-30 22:40:14 -0700361void ReleaseSwapchainImage(VkDevice device,
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000362 bool shared_present,
Jesse Halldc225072016-05-30 22:40:14 -0700363 ANativeWindow* window,
364 int release_fence,
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700365 Swapchain::Image& image,
366 bool defer_if_pending) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700367 ATRACE_CALL();
368
Jesse Halldc225072016-05-30 22:40:14 -0700369 ALOG_ASSERT(release_fence == -1 || image.dequeued,
370 "ReleaseSwapchainImage: can't provide a release fence for "
371 "non-dequeued images");
372
373 if (image.dequeued) {
374 if (release_fence >= 0) {
375 // We get here from vkQueuePresentKHR. The application is
376 // responsible for creating an execution dependency chain from
377 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
378 // (release_fence), so we can drop the dequeue_fence here.
379 if (image.dequeue_fence >= 0)
380 close(image.dequeue_fence);
381 } else {
382 // We get here during swapchain destruction, or various serious
383 // error cases e.g. when we can't create the release_fence during
384 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
385 // have already signalled, since the swapchain images are supposed
386 // to be idle before the swapchain is destroyed. In error cases,
387 // there may be rendering in flight to the image, but since we
388 // weren't able to create a release_fence, waiting for the
389 // dequeue_fence is about the best we can do.
390 release_fence = image.dequeue_fence;
391 }
392 image.dequeue_fence = -1;
393
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000394 // It's invalid to call cancelBuffer on a shared buffer
395 if (window && !shared_present) {
Jesse Halldc225072016-05-30 22:40:14 -0700396 window->cancelBuffer(window, image.buffer.get(), release_fence);
397 } else {
398 if (release_fence >= 0) {
399 sync_wait(release_fence, -1 /* forever */);
400 close(release_fence);
401 }
402 }
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700403 release_fence = -1;
Jesse Halldc225072016-05-30 22:40:14 -0700404 image.dequeued = false;
405 }
406
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700407 if (defer_if_pending && IsFencePending(image.release_fence))
408 return;
409
410 if (image.release_fence >= 0) {
411 close(image.release_fence);
412 image.release_fence = -1;
413 }
414
Jesse Halldc225072016-05-30 22:40:14 -0700415 if (image.image) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700416 ATRACE_BEGIN("DestroyImage");
Jesse Halldc225072016-05-30 22:40:14 -0700417 GetData(device).driver.DestroyImage(device, image.image, nullptr);
Yiwei Zhang533cea92019-06-03 18:43:24 -0700418 ATRACE_END();
Jesse Halldc225072016-05-30 22:40:14 -0700419 image.image = VK_NULL_HANDLE;
420 }
421
422 image.buffer.clear();
423}
424
425void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
426 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
427 return;
Jesse Halldc225072016-05-30 22:40:14 -0700428 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000429 if (!swapchain->images[i].dequeued) {
430 ReleaseSwapchainImage(device, swapchain->shared, nullptr, -1,
431 swapchain->images[i], true);
432 }
Jesse Halldc225072016-05-30 22:40:14 -0700433 }
434 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700435 swapchain->timing.clear();
436}
437
438uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800439 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
440 return 0;
441 }
Ian Elliott8a977262017-01-19 09:05:58 -0700442
Brian Anderson1049d1d2016-12-16 17:25:57 -0800443 uint32_t num_ready = 0;
444 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
445 for (uint32_t i = 0; i < num_timings; i++) {
Yiwei Zhang5e862202019-06-21 14:59:16 -0700446 TimingInfo& ti = swapchain.timing[i];
Brian Anderson1049d1d2016-12-16 17:25:57 -0800447 if (ti.ready()) {
448 // This TimingInfo is ready to be reported to the user. Add it
449 // to the num_ready.
450 num_ready++;
451 continue;
452 }
453 // This TimingInfo is not yet ready to be reported to the user,
454 // and so we should look for any available timestamps that
455 // might make it ready.
456 int64_t desired_present_time = 0;
457 int64_t render_complete_time = 0;
458 int64_t composition_latch_time = 0;
459 int64_t actual_present_time = 0;
460 // Obtain timestamps:
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800461 int err = native_window_get_frame_timestamps(
Brian Anderson1049d1d2016-12-16 17:25:57 -0800462 swapchain.surface.window.get(), ti.native_frame_id_,
463 &desired_present_time, &render_complete_time,
464 &composition_latch_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700465 nullptr, //&first_composition_start_time,
466 nullptr, //&last_composition_start_time,
467 nullptr, //&composition_finish_time,
Brian Anderson1049d1d2016-12-16 17:25:57 -0800468 &actual_present_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700469 nullptr, //&dequeue_ready_time,
470 nullptr /*&reads_done_time*/);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800471
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800472 if (err != android::OK) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800473 continue;
474 }
475
476 // Record the timestamp(s) we received, and then see if this TimingInfo
477 // is ready to be reported to the user:
Brian Andersondc96fdf2017-03-20 16:54:25 -0700478 ti.timestamp_desired_present_time_ = desired_present_time;
479 ti.timestamp_actual_present_time_ = actual_present_time;
480 ti.timestamp_render_complete_time_ = render_complete_time;
481 ti.timestamp_composition_latch_time_ = composition_latch_time;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800482
483 if (ti.ready()) {
484 // The TimingInfo has received enough timestamps, and should now
485 // use those timestamps to calculate the info that should be
486 // reported to the user:
487 ti.calculate(swapchain.refresh_duration);
488 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700489 }
490 }
491 return num_ready;
492}
493
Ian Elliott8a977262017-01-19 09:05:58 -0700494void copy_ready_timings(Swapchain& swapchain,
495 uint32_t* count,
496 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800497 if (swapchain.timing.empty()) {
498 *count = 0;
499 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700500 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800501
502 size_t last_ready = swapchain.timing.size() - 1;
503 while (!swapchain.timing[last_ready].ready()) {
504 if (last_ready == 0) {
505 *count = 0;
506 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700507 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800508 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700509 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800510
511 uint32_t num_copied = 0;
Yiwei Zhang5e862202019-06-21 14:59:16 -0700512 int32_t num_to_remove = 0;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800513 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
514 const TimingInfo& ti = swapchain.timing[i];
515 if (ti.ready()) {
516 ti.get_values(&timings[num_copied]);
517 num_copied++;
518 }
519 num_to_remove++;
520 }
521
522 // Discard old frames that aren't ready if newer frames are ready.
523 // We don't expect to get the timing info for those old frames.
Yiwei Zhang5e862202019-06-21 14:59:16 -0700524 swapchain.timing.erase(swapchain.timing.begin(),
525 swapchain.timing.begin() + num_to_remove);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800526
Ian Elliott8a977262017-01-19 09:05:58 -0700527 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700528}
529
Yiwei Zhang3aef18e2024-03-18 22:01:42 +0000530PixelFormat GetNativePixelFormat(VkFormat format,
531 VkCompositeAlphaFlagBitsKHR alpha) {
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000532 PixelFormat native_format = PixelFormat::RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700533 switch (format) {
534 case VK_FORMAT_R8G8B8A8_UNORM:
535 case VK_FORMAT_R8G8B8A8_SRGB:
Yiwei Zhang3aef18e2024-03-18 22:01:42 +0000536 native_format = alpha == VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR
537 ? PixelFormat::RGBX_8888
538 : PixelFormat::RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700539 break;
540 case VK_FORMAT_R5G6B5_UNORM_PACK16:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000541 native_format = PixelFormat::RGB_565;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700542 break;
543 case VK_FORMAT_R16G16B16A16_SFLOAT:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000544 native_format = PixelFormat::RGBA_FP16;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700545 break;
Yiwei Zhangc1ea8152019-02-05 15:11:32 -0800546 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000547 native_format = PixelFormat::RGBA_1010102;
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500548 break;
549 case VK_FORMAT_R8_UNORM:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000550 native_format = PixelFormat::R_8;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700551 break;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000552 case VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
Trevor David Blackf499b5a2023-07-14 17:30:41 +0000553 native_format = PixelFormat::RGBA_10101010;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000554 break;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700555 default:
556 ALOGV("unsupported swapchain format %d", format);
557 break;
558 }
559 return native_format;
560}
561
Yiwei Zhang959f5182024-03-12 02:46:36 +0000562DataSpace GetNativeDataspace(VkColorSpaceKHR colorspace, VkFormat format) {
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700563 switch (colorspace) {
564 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
sergiuferentz47989332023-09-26 10:24:36 +0000565 return DataSpace::SRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700566 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000567 return DataSpace::DISPLAY_P3;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700568 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000569 return DataSpace::SCRGB_LINEAR;
Courtney Goeltzenleuchterb52abee2017-08-07 17:13:04 -0600570 case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000571 return DataSpace::SCRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700572 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000573 return DataSpace::DCI_P3_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700574 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000575 return DataSpace::DCI_P3;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700576 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000577 return DataSpace::SRGB_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700578 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000579 return DataSpace::SRGB;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600580 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
Yiwei Zhang959f5182024-03-12 02:46:36 +0000581 if (format == VK_FORMAT_R16G16B16A16_SFLOAT) {
sergiuferentz47989332023-09-26 10:24:36 +0000582 return DataSpace::BT2020_LINEAR_EXTENDED;
Sally Qiaa238972023-07-17 12:52:05 +0800583 } else {
sergiuferentz47989332023-09-26 10:24:36 +0000584 return DataSpace::BT2020_LINEAR;
Sally Qiaa238972023-07-17 12:52:05 +0800585 }
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600586 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000587 return DataSpace::BT2020_PQ;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600588 case VK_COLOR_SPACE_DOLBYVISION_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000589 return DataSpace::BT2020_PQ;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600590 case VK_COLOR_SPACE_HDR10_HLG_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000591 return DataSpace::BT2020_HLG;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700592 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000593 return DataSpace::ADOBE_RGB_LINEAR;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700594 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000595 return DataSpace::ADOBE_RGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700596 // Pass through is intended to allow app to provide data that is passed
597 // to the display system without modification.
598 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
sergiuferentz47989332023-09-26 10:24:36 +0000599 return DataSpace::ARBITRARY;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700600
601 default:
602 // This indicates that we don't know about the
603 // dataspace specified and we should indicate that
604 // it's unsupported
sergiuferentz47989332023-09-26 10:24:36 +0000605 return DataSpace::UNKNOWN;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700606 }
607}
608
Jesse Halld7b994a2015-09-07 14:17:37 -0700609} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700610
Jesse Halle1b12782015-11-30 11:27:32 -0800611VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800612VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800613 VkInstance instance,
614 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
615 const VkAllocationCallbacks* allocator,
616 VkSurfaceKHR* out_surface) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800617 ATRACE_CALL();
618
Jesse Hall1f91d392015-12-11 16:28:44 -0800619 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800620 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800621 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
622 alignof(Surface),
623 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800624 if (!mem)
625 return VK_ERROR_OUT_OF_HOST_MEMORY;
626 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700627
Yiwei Zhang3aef18e2024-03-18 22:01:42 +0000628 ANativeWindow* window = pCreateInfo->window;
629 surface->window = window;
Jesse Halldc225072016-05-30 22:40:14 -0700630 surface->swapchain_handle = VK_NULL_HANDLE;
Yiwei Zhang3b88f312023-04-18 23:11:35 +0000631 surface->used_by_swapchain = false;
Yiwei Zhang3aef18e2024-03-18 22:01:42 +0000632 int err =
633 native_window_get_consumer_usage(window, &surface->consumer_usage);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800634 if (err != android::OK) {
Yiwei Zhang6435b322018-05-08 11:12:17 -0700635 ALOGE("native_window_get_consumer_usage() failed: %s (%d)",
636 strerror(-err), err);
637 surface->~Surface();
638 allocator->pfnFree(allocator->pUserData, surface);
Yiwei Zhang70a21962019-05-31 17:26:52 -0700639 return VK_ERROR_SURFACE_LOST_KHR;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700640 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700641
Yiwei Zhang3aef18e2024-03-18 22:01:42 +0000642 err = window->query(window, NATIVE_WINDOW_FORMAT, &surface->default_format);
643 if (err != android::OK) {
644 ALOGE("NATIVE_WINDOW_FORMAT query failed: %s (%d)", strerror(-err),
645 err);
646 surface->~Surface();
647 allocator->pfnFree(allocator->pUserData, surface);
648 return VK_ERROR_SURFACE_LOST_KHR;
649 }
650
651 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800652 if (err != android::OK) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800653 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
654 err);
655 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800656 allocator->pfnFree(allocator->pUserData, surface);
Mike Stroyan762c8132017-02-22 11:43:09 -0700657 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800658 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700659
Jesse Hall1356b0d2015-11-23 17:24:58 -0800660 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700661 return VK_SUCCESS;
662}
663
Jesse Halle1b12782015-11-30 11:27:32 -0800664VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800665void DestroySurfaceKHR(VkInstance instance,
666 VkSurfaceKHR surface_handle,
667 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800668 ATRACE_CALL();
669
Jesse Hall1356b0d2015-11-23 17:24:58 -0800670 Surface* surface = SurfaceFromHandle(surface_handle);
671 if (!surface)
672 return;
673 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700674 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700675 "destroyed VkSurfaceKHR 0x%" PRIx64
676 " has active VkSwapchainKHR 0x%" PRIx64,
677 reinterpret_cast<uint64_t>(surface_handle),
678 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800679 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800680 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800681 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800682 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800683}
684
Jesse Halle1b12782015-11-30 11:27:32 -0800685VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800686VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
687 uint32_t /*queue_family*/,
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000688 VkSurfaceKHR /*surface_handle*/,
Chia-I Wu62262232016-03-26 07:06:44 +0800689 VkBool32* supported) {
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000690 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800691 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800692}
693
Jesse Halle1b12782015-11-30 11:27:32 -0800694VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800695VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Ian Elliott1ce053f2022-03-16 09:49:53 -0600696 VkPhysicalDevice pdev,
Jesse Hallb00daad2015-11-29 19:46:20 -0800697 VkSurfaceKHR surface,
698 VkSurfaceCapabilitiesKHR* capabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800699 ATRACE_CALL();
700
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000701 // Implement in terms of GetPhysicalDeviceSurfaceCapabilities2KHR
702
703 VkPhysicalDeviceSurfaceInfo2KHR info2 = {
704 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
705 nullptr,
706 surface
707 };
708
709 VkSurfaceCapabilities2KHR caps2 = {
710 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
711 nullptr,
712 {},
713 };
714
715 VkResult result = GetPhysicalDeviceSurfaceCapabilities2KHR(pdev, &info2, &caps2);
716 *capabilities = caps2.surfaceCapabilities;
717 return result;
718}
719
720// Does the call-twice and VK_INCOMPLETE handling for querying lists
721// of things, where we already have the full set built in a vector.
722template <typename T>
723VkResult CopyWithIncomplete(std::vector<T> const& things,
724 T* callerPtr, uint32_t* callerCount) {
725 VkResult result = VK_SUCCESS;
726 if (callerPtr) {
727 if (things.size() > *callerCount)
728 result = VK_INCOMPLETE;
729 *callerCount = std::min(uint32_t(things.size()), *callerCount);
730 std::copy(things.begin(), things.begin() + *callerCount, callerPtr);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600731 } else {
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000732 *callerCount = things.size();
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800733 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000734 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700735}
736
Jesse Halle1b12782015-11-30 11:27:32 -0800737VKAPI_ATTR
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700738VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
739 VkSurfaceKHR surface_handle,
Chia-I Wu62262232016-03-26 07:06:44 +0800740 uint32_t* count,
741 VkSurfaceFormatKHR* formats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800742 ATRACE_CALL();
743
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700744 const InstanceData& instance_data = GetData(pdev);
745
Ian Elliott1ce053f2022-03-16 09:49:53 -0600746 uint64_t consumer_usage = 0;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000747 bool colorspace_ext =
Ian Elliottf6df08e2022-03-16 21:27:49 -0600748 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600749 if (surface_handle == VK_NULL_HANDLE) {
750 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
751 bool surfaceless_enabled =
752 instance_data.hook_extensions.test(surfaceless);
753 if (!surfaceless_enabled) {
754 return VK_ERROR_SURFACE_LOST_KHR;
755 }
Chris Forbesb1de3b12022-10-20 09:05:48 +1300756 // Support for VK_GOOGLE_surfaceless_query.
Ian Elliott1ce053f2022-03-16 09:49:53 -0600757
758 // TODO(b/203826952): research proper value; temporarily use the
759 // values seen on Pixel
760 consumer_usage = AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
761 } else {
762 Surface& surface = *SurfaceFromHandle(surface_handle);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600763 consumer_usage = surface.consumer_usage;
Ian Elliott6ba85d92022-02-18 16:44:58 -0700764 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700765
Charlie Lao324191f2019-12-13 11:03:16 -0800766 AHardwareBuffer_Desc desc = {};
767 desc.width = 1;
768 desc.height = 1;
769 desc.layers = 1;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600770 desc.usage = consumer_usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
Charlie Lao324191f2019-12-13 11:03:16 -0800771 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
772
773 // We must support R8G8B8A8
774 std::vector<VkSurfaceFormatKHR> all_formats = {
775 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000776 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000777 };
Charlie Lao324191f2019-12-13 11:03:16 -0800778
Yiwei Zhang959f5182024-03-12 02:46:36 +0000779 VkFormat format = VK_FORMAT_UNDEFINED;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000780 if (colorspace_ext) {
Yuxin Hu7facd572024-02-08 22:54:23 +0000781 for (VkColorSpaceKHR colorSpace :
782 colorSpaceSupportedByVkEXTSwapchainColorspace) {
Yiwei Zhang959f5182024-03-12 02:46:36 +0000783 format = VK_FORMAT_R8G8B8A8_UNORM;
784 if (GetNativeDataspace(colorSpace, format) != DataSpace::UNKNOWN) {
Yuxin Hu7facd572024-02-08 22:54:23 +0000785 all_formats.emplace_back(
Yiwei Zhang959f5182024-03-12 02:46:36 +0000786 VkSurfaceFormatKHR{format, colorSpace});
Yuxin Hu7facd572024-02-08 22:54:23 +0000787 }
788
Yiwei Zhang959f5182024-03-12 02:46:36 +0000789 format = VK_FORMAT_R8G8B8A8_SRGB;
790 if (GetNativeDataspace(colorSpace, format) != DataSpace::UNKNOWN) {
Yuxin Hu7facd572024-02-08 22:54:23 +0000791 all_formats.emplace_back(
Yiwei Zhang959f5182024-03-12 02:46:36 +0000792 VkSurfaceFormatKHR{format, colorSpace});
Yuxin Hu7facd572024-02-08 22:54:23 +0000793 }
794 }
Charlie Lao324191f2019-12-13 11:03:16 -0800795 }
796
Ian Elliott1ce053f2022-03-16 09:49:53 -0600797 // NOTE: Any new formats that are added must be coordinated across different
798 // Android users. This includes the ANGLE team (a layered implementation of
799 // OpenGL-ES).
800
Yiwei Zhang959f5182024-03-12 02:46:36 +0000801 format = VK_FORMAT_R5G6B5_UNORM_PACK16;
Charlie Lao324191f2019-12-13 11:03:16 -0800802 desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
803 if (AHardwareBuffer_isSupported(&desc)) {
Yiwei Zhang959f5182024-03-12 02:46:36 +0000804 all_formats.emplace_back(
805 VkSurfaceFormatKHR{format, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800806 if (colorspace_ext) {
Yuxin Hu7facd572024-02-08 22:54:23 +0000807 for (VkColorSpaceKHR colorSpace :
808 colorSpaceSupportedByVkEXTSwapchainColorspace) {
Yiwei Zhang959f5182024-03-12 02:46:36 +0000809 if (GetNativeDataspace(colorSpace, format) !=
Yuxin Hu7facd572024-02-08 22:54:23 +0000810 DataSpace::UNKNOWN) {
Yiwei Zhang959f5182024-03-12 02:46:36 +0000811 all_formats.emplace_back(
812 VkSurfaceFormatKHR{format, colorSpace});
Yuxin Hu7facd572024-02-08 22:54:23 +0000813 }
814 }
Jason Macnakca506332022-11-09 11:00:36 -0800815 }
Charlie Lao324191f2019-12-13 11:03:16 -0800816 }
817
Yiwei Zhang959f5182024-03-12 02:46:36 +0000818 format = VK_FORMAT_R16G16B16A16_SFLOAT;
Charlie Lao324191f2019-12-13 11:03:16 -0800819 desc.format = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
820 if (AHardwareBuffer_isSupported(&desc)) {
Yiwei Zhang959f5182024-03-12 02:46:36 +0000821 all_formats.emplace_back(
822 VkSurfaceFormatKHR{format, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800823 if (colorspace_ext) {
Yuxin Hu7facd572024-02-08 22:54:23 +0000824 for (VkColorSpaceKHR colorSpace :
825 colorSpaceSupportedByVkEXTSwapchainColorspace) {
Yiwei Zhang959f5182024-03-12 02:46:36 +0000826 if (GetNativeDataspace(colorSpace, format) !=
Yuxin Hu7facd572024-02-08 22:54:23 +0000827 DataSpace::UNKNOWN) {
Yiwei Zhang959f5182024-03-12 02:46:36 +0000828 all_formats.emplace_back(
829 VkSurfaceFormatKHR{format, colorSpace});
Yuxin Hu7facd572024-02-08 22:54:23 +0000830 }
831 }
832
833 for (
834 VkColorSpaceKHR colorSpace :
835 colorSpaceSupportedByVkEXTSwapchainColorspaceOnFP16SurfaceOnly) {
Yiwei Zhang959f5182024-03-12 02:46:36 +0000836 if (GetNativeDataspace(colorSpace, format) !=
Yuxin Hu7facd572024-02-08 22:54:23 +0000837 DataSpace::UNKNOWN) {
Yiwei Zhang959f5182024-03-12 02:46:36 +0000838 all_formats.emplace_back(
839 VkSurfaceFormatKHR{format, colorSpace});
Yuxin Hu7facd572024-02-08 22:54:23 +0000840 }
841 }
Charlie Lao324191f2019-12-13 11:03:16 -0800842 }
843 }
844
Yiwei Zhang959f5182024-03-12 02:46:36 +0000845 format = VK_FORMAT_A2B10G10R10_UNORM_PACK32;
Charlie Lao324191f2019-12-13 11:03:16 -0800846 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
847 if (AHardwareBuffer_isSupported(&desc)) {
848 all_formats.emplace_back(
Yiwei Zhang959f5182024-03-12 02:46:36 +0000849 VkSurfaceFormatKHR{format, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800850 if (colorspace_ext) {
Yuxin Hu7facd572024-02-08 22:54:23 +0000851 for (VkColorSpaceKHR colorSpace :
852 colorSpaceSupportedByVkEXTSwapchainColorspace) {
Yiwei Zhang959f5182024-03-12 02:46:36 +0000853 if (GetNativeDataspace(colorSpace, format) !=
Yuxin Hu7facd572024-02-08 22:54:23 +0000854 DataSpace::UNKNOWN) {
Yiwei Zhang959f5182024-03-12 02:46:36 +0000855 all_formats.emplace_back(
856 VkSurfaceFormatKHR{format, colorSpace});
Yuxin Hu7facd572024-02-08 22:54:23 +0000857 }
858 }
Charlie Lao324191f2019-12-13 11:03:16 -0800859 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700860 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700861
Yiwei Zhang959f5182024-03-12 02:46:36 +0000862 format = VK_FORMAT_R8_UNORM;
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500863 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
864 if (AHardwareBuffer_isSupported(&desc)) {
Jason Macnakca506332022-11-09 11:00:36 -0800865 if (colorspace_ext) {
Yiwei Zhang959f5182024-03-12 02:46:36 +0000866 all_formats.emplace_back(
867 VkSurfaceFormatKHR{format, VK_COLOR_SPACE_PASS_THROUGH_EXT});
Jason Macnakca506332022-11-09 11:00:36 -0800868 }
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500869 }
870
Trevor David Black67e9b102023-03-07 05:28:15 +0000871 bool rgba10x6_formats_ext = false;
872 uint32_t exts_count;
873 const auto& driver = GetData(pdev).driver;
874 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
875 nullptr);
876 std::vector<VkExtensionProperties> props(exts_count);
877 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
878 props.data());
879 for (uint32_t i = 0; i < exts_count; i++) {
880 VkExtensionProperties prop = props[i];
881 if (strcmp(prop.extensionName,
882 VK_EXT_RGBA10X6_FORMATS_EXTENSION_NAME) == 0) {
883 rgba10x6_formats_ext = true;
884 }
885 }
Yiwei Zhang959f5182024-03-12 02:46:36 +0000886 format = VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000887 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM;
Trevor David Black67e9b102023-03-07 05:28:15 +0000888 if (AHardwareBuffer_isSupported(&desc) && rgba10x6_formats_ext) {
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000889 all_formats.emplace_back(
Yiwei Zhang959f5182024-03-12 02:46:36 +0000890 VkSurfaceFormatKHR{format, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000891 if (colorspace_ext) {
Yuxin Hu7facd572024-02-08 22:54:23 +0000892 for (VkColorSpaceKHR colorSpace :
893 colorSpaceSupportedByVkEXTSwapchainColorspace) {
Yiwei Zhang959f5182024-03-12 02:46:36 +0000894 if (GetNativeDataspace(colorSpace, format) !=
Yuxin Hu7facd572024-02-08 22:54:23 +0000895 DataSpace::UNKNOWN) {
Yiwei Zhang959f5182024-03-12 02:46:36 +0000896 all_formats.emplace_back(
897 VkSurfaceFormatKHR{format, colorSpace});
Yuxin Hu7facd572024-02-08 22:54:23 +0000898 }
899 }
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000900 }
901 }
902
Ian Elliott6ba85d92022-02-18 16:44:58 -0700903 // NOTE: Any new formats that are added must be coordinated across different
904 // Android users. This includes the ANGLE team (a layered implementation of
905 // OpenGL-ES).
906
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000907 return CopyWithIncomplete(all_formats, formats, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700908}
909
Jesse Halle1b12782015-11-30 11:27:32 -0800910VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300911VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
912 VkPhysicalDevice physicalDevice,
913 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
914 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800915 ATRACE_CALL();
916
Yiwei Zhang3aef18e2024-03-18 22:01:42 +0000917 auto surface_handle = pSurfaceInfo->surface;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000918 auto capabilities = &pSurfaceCapabilities->surfaceCapabilities;
Chris Forbes2452cf72017-03-16 16:30:17 +1300919
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000920 VkSurfacePresentModeEXT const *pPresentMode = nullptr;
921 for (auto pNext = reinterpret_cast<VkBaseInStructure const *>(pSurfaceInfo->pNext);
922 pNext; pNext = reinterpret_cast<VkBaseInStructure const *>(pNext->pNext)) {
923 switch (pNext->sType) {
924 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT:
925 pPresentMode = reinterpret_cast<VkSurfacePresentModeEXT const *>(pNext);
926 break;
Chris Forbes06bc0092017-03-16 16:46:05 +1300927
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000928 default:
929 break;
930 }
931 }
932
933 int err;
934 int width, height;
935 int transform_hint;
936 int max_buffer_count;
Trevor David Black1d3509e2023-06-08 00:17:40 +0000937 int min_undequeued_buffers;
Yiwei Zhang3aef18e2024-03-18 22:01:42 +0000938 VkCompositeAlphaFlagsKHR composite_alpha =
939 VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
940 if (surface_handle == VK_NULL_HANDLE) {
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000941 const InstanceData& instance_data = GetData(physicalDevice);
942 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
943 bool surfaceless_enabled =
944 instance_data.hook_extensions.test(surfaceless);
945 if (!surfaceless_enabled) {
946 // It is an error to pass a surface==VK_NULL_HANDLE unless the
947 // VK_GOOGLE_surfaceless_query extension is enabled
948 return VK_ERROR_SURFACE_LOST_KHR;
949 }
950 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
951 // extension for this function is for
952 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
953 // four values cannot be known without a surface. Default values will
954 // be supplied anyway, but cannot be relied upon.
955 width = 0xFFFFFFFF;
956 height = 0xFFFFFFFF;
957 transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
958 capabilities->minImageCount = 0xFFFFFFFF;
959 capabilities->maxImageCount = 0xFFFFFFFF;
960 } else {
Yiwei Zhang3aef18e2024-03-18 22:01:42 +0000961 Surface& surface = *SurfaceFromHandle(surface_handle);
962 ANativeWindow* window = surface.window.get();
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000963
964 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
965 if (err != android::OK) {
966 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
967 strerror(-err), err);
968 return VK_ERROR_SURFACE_LOST_KHR;
969 }
970 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
971 if (err != android::OK) {
972 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
973 strerror(-err), err);
974 return VK_ERROR_SURFACE_LOST_KHR;
975 }
976
977 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
978 &transform_hint);
979 if (err != android::OK) {
980 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
981 strerror(-err), err);
982 return VK_ERROR_SURFACE_LOST_KHR;
983 }
984
985 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
986 &max_buffer_count);
987 if (err != android::OK) {
988 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
989 strerror(-err), err);
990 return VK_ERROR_SURFACE_LOST_KHR;
991 }
992
Trevor David Black1d3509e2023-06-08 00:17:40 +0000993 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
994 &min_undequeued_buffers);
995 if (err != android::OK) {
996 ALOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d)",
997 strerror(-err), err);
998 return VK_ERROR_SURFACE_LOST_KHR;
999 }
1000
Trevor David Blacke4d23b92023-09-26 20:30:42 +00001001 // Additional buffer count over min_undequeued_buffers in vulkan came from 2 total
1002 // being technically enough for fifo (although a poor experience) vs 3 being the
1003 // absolute minimum for mailbox to be useful. So min_undequeued_buffers + 2 is sensible
1004 static constexpr int default_additional_buffers = 2;
1005
Trevor David Blacka93e21f2023-08-30 23:42:20 +00001006 if(pPresentMode != nullptr) {
1007 switch (pPresentMode->presentMode) {
1008 case VK_PRESENT_MODE_IMMEDIATE_KHR:
1009 ALOGE("Swapchain present mode VK_PRESENT_MODE_IMMEDIATE_KHR is not supported");
1010 break;
1011 case VK_PRESENT_MODE_MAILBOX_KHR:
1012 case VK_PRESENT_MODE_FIFO_KHR:
Trevor David Blacke4d23b92023-09-26 20:30:42 +00001013 capabilities->minImageCount = std::min(max_buffer_count,
1014 min_undequeued_buffers + default_additional_buffers);
Trevor David Blacka93e21f2023-08-30 23:42:20 +00001015 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
1016 break;
1017 case VK_PRESENT_MODE_FIFO_RELAXED_KHR:
1018 ALOGE("Swapchain present mode VK_PRESENT_MODE_FIFO_RELEAXED_KHR "
1019 "is not supported");
1020 break;
1021 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
1022 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
1023 capabilities->minImageCount = 1;
1024 capabilities->maxImageCount = 1;
1025 break;
1026
1027 default:
1028 ALOGE("Unrecognized swapchain present mode %u is not supported",
1029 pPresentMode->presentMode);
1030 break;
1031 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001032 } else {
Trevor David Blacke4d23b92023-09-26 20:30:42 +00001033 capabilities->minImageCount = std::min(max_buffer_count,
1034 min_undequeued_buffers + default_additional_buffers);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001035 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
1036 }
Yiwei Zhang3aef18e2024-03-18 22:01:42 +00001037
1038 // The surface default format can be either of below:
1039 // - consumer side default format
1040 // - platform EGL resolved format and we get here via ANGLE
1041 //
1042 // For any of above, advertise OPAQUE bit so that later swapchain
1043 // creation can resolve VK_FORMAT_R8G8B8A8_* to RGBX_8888 only if the
1044 // client also requests OPAQUE bit for compositeAlpha.
1045 if (surface.default_format == (int)PixelFormat::RGBX_8888) {
1046 composite_alpha |= VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
1047 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001048 }
1049
1050 capabilities->currentExtent =
1051 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
1052
1053 // TODO(http://b/134182502): Figure out what the max extent should be.
1054 capabilities->minImageExtent = VkExtent2D{1, 1};
1055 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
1056
1057 if (capabilities->maxImageExtent.height <
1058 capabilities->currentExtent.height) {
1059 capabilities->maxImageExtent.height =
1060 capabilities->currentExtent.height;
1061 }
1062
1063 if (capabilities->maxImageExtent.width <
1064 capabilities->currentExtent.width) {
1065 capabilities->maxImageExtent.width = capabilities->currentExtent.width;
1066 }
1067
1068 capabilities->maxImageArrayLayers = 1;
1069
1070 capabilities->supportedTransforms = kSupportedTransforms;
1071 capabilities->currentTransform =
1072 TranslateNativeToVulkanTransform(transform_hint);
1073
Yiwei Zhang3aef18e2024-03-18 22:01:42 +00001074 capabilities->supportedCompositeAlpha = composite_alpha;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001075
1076 capabilities->supportedUsageFlags =
1077 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
1078 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
1079 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
1080 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
1081
1082 for (auto pNext = reinterpret_cast<VkBaseOutStructure*>(pSurfaceCapabilities->pNext);
1083 pNext; pNext = reinterpret_cast<VkBaseOutStructure*>(pNext->pNext)) {
1084
1085 switch (pNext->sType) {
Chris Forbes06bc0092017-03-16 16:46:05 +13001086 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
1087 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001088 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(pNext);
Chris Forbes06bc0092017-03-16 16:46:05 +13001089 // Claim same set of usage flags are supported for
1090 // shared present modes as for other modes.
1091 shared_caps->sharedPresentSupportedUsageFlags =
1092 pSurfaceCapabilities->surfaceCapabilities
1093 .supportedUsageFlags;
1094 } break;
1095
Ian Elliottbb67b242022-03-16 09:52:28 -06001096 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
1097 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001098 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(pNext);
Ian Elliottbb67b242022-03-16 09:52:28 -06001099 protected_caps->supportsProtected = VK_TRUE;
1100 } break;
1101
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001102 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_SCALING_CAPABILITIES_EXT: {
1103 VkSurfacePresentScalingCapabilitiesEXT* scaling_caps =
1104 reinterpret_cast<VkSurfacePresentScalingCapabilitiesEXT*>(pNext);
1105 // By default, Android stretches the buffer to fit the window,
1106 // without preserving aspect ratio. Other modes are technically possible
1107 // but consult with CoGS team before exposing them here!
1108 scaling_caps->supportedPresentScaling = VK_PRESENT_SCALING_STRETCH_BIT_EXT;
1109
1110 // Since we always scale, we don't support any gravity.
1111 scaling_caps->supportedPresentGravityX = 0;
1112 scaling_caps->supportedPresentGravityY = 0;
1113
1114 // Scaled image limits are just the basic image limits
1115 scaling_caps->minScaledImageExtent = capabilities->minImageExtent;
1116 scaling_caps->maxScaledImageExtent = capabilities->maxImageExtent;
1117 } break;
1118
1119 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT: {
1120 VkSurfacePresentModeCompatibilityEXT* mode_caps =
1121 reinterpret_cast<VkSurfacePresentModeCompatibilityEXT*>(pNext);
1122
1123 ALOG_ASSERT(pPresentMode,
1124 "querying VkSurfacePresentModeCompatibilityEXT "
1125 "requires VkSurfacePresentModeEXT to be provided");
1126 std::vector<VkPresentModeKHR> compatibleModes;
1127 compatibleModes.push_back(pPresentMode->presentMode);
1128
1129 switch (pPresentMode->presentMode) {
1130 // Shared modes are both compatible with each other.
1131 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
1132 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
1133 break;
1134 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
1135 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1136 break;
1137 default:
1138 // Other modes are only compatible with themselves.
1139 // TODO: consider whether switching between FIFO and MAILBOX is reasonable
1140 break;
1141 }
1142
1143 // Note: this does not generate VK_INCOMPLETE since we're nested inside
1144 // a larger query and there would be no way to determine exactly where it came from.
1145 CopyWithIncomplete(compatibleModes, mode_caps->pPresentModes,
1146 &mode_caps->presentModeCount);
1147 } break;
1148
Chris Forbes06bc0092017-03-16 16:46:05 +13001149 default:
1150 // Ignore all other extension structs
1151 break;
1152 }
1153 }
1154
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001155 return VK_SUCCESS;
Chris Forbes2452cf72017-03-16 16:30:17 +13001156}
1157
1158VKAPI_ATTR
1159VkResult GetPhysicalDeviceSurfaceFormats2KHR(
1160 VkPhysicalDevice physicalDevice,
1161 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
1162 uint32_t* pSurfaceFormatCount,
1163 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001164 ATRACE_CALL();
1165
Chris Forbes2452cf72017-03-16 16:30:17 +13001166 if (!pSurfaceFormats) {
1167 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
1168 pSurfaceInfo->surface,
1169 pSurfaceFormatCount, nullptr);
Trevor David Black929e9cd2022-11-22 04:12:19 +00001170 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001171
Trevor David Black929e9cd2022-11-22 04:12:19 +00001172 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
1173 // after the call.
1174 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
1175 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
1176 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
1177 surface_formats.data());
Trevor David Black2cc44682022-03-09 00:31:38 +00001178
Trevor David Black929e9cd2022-11-22 04:12:19 +00001179 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
1180 return result;
1181 }
Trevor David Black2cc44682022-03-09 00:31:38 +00001182
Trevor David Black929e9cd2022-11-22 04:12:19 +00001183 const auto& driver = GetData(physicalDevice).driver;
1184
1185 // marshal results individually due to stride difference.
1186 uint32_t formats_to_marshal = *pSurfaceFormatCount;
1187 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
1188 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
1189
1190 // Query the compression properties for the surface format
1191 VkSurfaceFormat2KHR* pSurfaceFormat = &pSurfaceFormats[i];
1192 while (pSurfaceFormat->pNext) {
1193 pSurfaceFormat =
1194 reinterpret_cast<VkSurfaceFormat2KHR*>(pSurfaceFormat->pNext);
1195 switch (pSurfaceFormat->sType) {
1196 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT: {
Trevor David Black2cc44682022-03-09 00:31:38 +00001197 VkImageCompressionPropertiesEXT* surfaceCompressionProps =
1198 reinterpret_cast<VkImageCompressionPropertiesEXT*>(
Trevor David Black929e9cd2022-11-22 04:12:19 +00001199 pSurfaceFormat);
Trevor David Black2cc44682022-03-09 00:31:38 +00001200
1201 if (surfaceCompressionProps &&
1202 driver.GetPhysicalDeviceImageFormatProperties2KHR) {
1203 VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = {};
1204 imageFormatInfo.sType =
1205 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
1206 imageFormatInfo.format =
1207 pSurfaceFormats[i].surfaceFormat.format;
Trevor David Blacka4298c92023-06-20 17:11:58 +00001208 imageFormatInfo.type = VK_IMAGE_TYPE_2D;
1209 imageFormatInfo.usage =
1210 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
Trevor David Black2cc44682022-03-09 00:31:38 +00001211 imageFormatInfo.pNext = nullptr;
1212
1213 VkImageCompressionControlEXT compressionControl = {};
1214 compressionControl.sType =
1215 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT;
1216 compressionControl.pNext = imageFormatInfo.pNext;
Trevor David Blacka4298c92023-06-20 17:11:58 +00001217 compressionControl.flags =
1218 VK_IMAGE_COMPRESSION_FIXED_RATE_DEFAULT_EXT;
Trevor David Black2cc44682022-03-09 00:31:38 +00001219
1220 imageFormatInfo.pNext = &compressionControl;
1221
1222 VkImageCompressionPropertiesEXT compressionProps = {};
1223 compressionProps.sType =
1224 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT;
1225 compressionProps.pNext = nullptr;
1226
1227 VkImageFormatProperties2KHR imageFormatProps = {};
1228 imageFormatProps.sType =
1229 VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
1230 imageFormatProps.pNext = &compressionProps;
1231
1232 VkResult compressionRes =
1233 driver.GetPhysicalDeviceImageFormatProperties2KHR(
1234 physicalDevice, &imageFormatInfo,
1235 &imageFormatProps);
1236 if (compressionRes == VK_SUCCESS) {
1237 surfaceCompressionProps->imageCompressionFlags =
1238 compressionProps.imageCompressionFlags;
1239 surfaceCompressionProps
1240 ->imageCompressionFixedRateFlags =
1241 compressionProps.imageCompressionFixedRateFlags;
1242 } else {
1243 return compressionRes;
1244 }
1245 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001246 } break;
1247
1248 default:
1249 // Ignore all other extension structs
1250 break;
Chris Forbes2452cf72017-03-16 16:30:17 +13001251 }
1252 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001253 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001254
1255 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +13001256}
1257
1258VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +13001259VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001260 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +08001261 uint32_t* count,
1262 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001263 ATRACE_CALL();
1264
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001265 int err;
1266 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -06001267 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -06001268 if (surface == VK_NULL_HANDLE) {
1269 const InstanceData& instance_data = GetData(pdev);
1270 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
1271 bool surfaceless_enabled =
1272 instance_data.hook_extensions.test(surfaceless);
1273 if (!surfaceless_enabled) {
1274 return VK_ERROR_SURFACE_LOST_KHR;
1275 }
1276 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
1277 // extension for this function is for
1278 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
1279 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
1280 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
Ian Elliott7e361142022-06-02 10:45:17 -06001281 // surface, and that cannot be relied upon. Therefore, don't return it.
Ian Elliott1ce053f2022-03-16 09:49:53 -06001282 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1283 } else {
1284 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1285
1286 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1287 &query_value);
1288 if (err != android::OK || query_value < 0) {
1289 ALOGE(
1290 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
1291 "value=%d",
1292 strerror(-err), err, query_value);
1293 return VK_ERROR_SURFACE_LOST_KHR;
1294 }
1295 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1296
1297 err =
1298 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
1299 if (err != android::OK || query_value < 0) {
1300 ALOGE(
1301 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
1302 strerror(-err), err, query_value);
1303 return VK_ERROR_SURFACE_LOST_KHR;
1304 }
1305 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
1306
1307 if (min_undequeued_buffers + 1 < max_buffer_count)
1308 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
1309 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1310 }
Chris Forbese8d79a62017-02-22 12:49:18 +13001311
1312 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -07001313 QueryPresentationProperties(pdev, &present_properties);
1314 if (present_properties.sharedImage) {
1315 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1316 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +13001317 }
1318
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001319 return CopyWithIncomplete(present_modes, modes, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001320}
1321
Jesse Halle1b12782015-11-30 11:27:32 -08001322VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001323VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001324 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001325 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001326 ATRACE_CALL();
1327
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001328 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
1329 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1330 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1331 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1332 pDeviceGroupPresentCapabilities->sType);
1333
1334 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1335 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1336
1337 // assume device group of size 1
1338 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1339 pDeviceGroupPresentCapabilities->modes =
1340 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1341
1342 return VK_SUCCESS;
1343}
1344
1345VKAPI_ATTR
1346VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001347 VkDevice,
1348 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001349 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001350 ATRACE_CALL();
1351
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001352 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1353 return VK_SUCCESS;
1354}
1355
1356VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001357VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001358 VkSurfaceKHR surface,
1359 uint32_t* pRectCount,
1360 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001361 ATRACE_CALL();
1362
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001363 if (!pRects) {
1364 *pRectCount = 1;
1365 } else {
1366 uint32_t count = std::min(*pRectCount, 1u);
1367 bool incomplete = *pRectCount < 1;
1368
1369 *pRectCount = count;
1370
1371 if (incomplete) {
1372 return VK_INCOMPLETE;
1373 }
1374
1375 int err;
1376 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1377
1378 int width = 0, height = 0;
1379 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001380 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001381 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1382 strerror(-err), err);
1383 }
1384 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001385 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001386 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1387 strerror(-err), err);
1388 }
1389
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001390 pRects[0].offset.x = 0;
1391 pRects[0].offset.y = 0;
1392 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1393 static_cast<uint32_t>(height)};
1394 }
1395 return VK_SUCCESS;
1396}
1397
Yiwei Zhang533cea92019-06-03 18:43:24 -07001398static void DestroySwapchainInternal(VkDevice device,
1399 VkSwapchainKHR swapchain_handle,
1400 const VkAllocationCallbacks* allocator) {
1401 ATRACE_CALL();
1402
1403 const auto& dispatch = GetData(device).driver;
1404 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1405 if (!swapchain) {
1406 return;
1407 }
1408
1409 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1410 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1411
1412 if (window && swapchain->frame_timestamps_enabled) {
1413 native_window_enable_frame_timestamps(window, false);
1414 }
1415
1416 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +00001417 ReleaseSwapchainImage(device, swapchain->shared, window, -1,
1418 swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001419 }
1420
1421 if (active) {
1422 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1423 }
1424
1425 if (!allocator) {
1426 allocator = &GetData(device).allocator;
1427 }
1428
1429 swapchain->~Swapchain();
1430 allocator->pfnFree(allocator->pUserData, swapchain);
1431}
1432
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001433static VkResult getProducerUsage(const VkDevice& device,
1434 const VkSwapchainCreateInfoKHR* create_info,
1435 const VkSwapchainImageUsageFlagsANDROID swapchain_image_usage,
1436 bool create_protected_swapchain,
1437 uint64_t* producer_usage) {
1438 // Get the physical device to query the appropriate producer usage
1439 const VkPhysicalDevice& pdev = GetData(device).driver_physical_device;
1440 const InstanceData& instance_data = GetData(pdev);
1441 const InstanceDriverTable& instance_dispatch = instance_data.driver;
Trevor David Black02926f52024-01-04 18:44:20 +00001442 if (instance_dispatch.GetPhysicalDeviceImageFormatProperties2 ||
1443 instance_dispatch.GetPhysicalDeviceImageFormatProperties2KHR) {
1444 // Look through the create_info pNext chain passed to createSwapchainKHR
1445 // for an image compression control struct.
1446 // if one is found AND the appropriate extensions are enabled, create a
1447 // VkImageCompressionControlEXT structure to pass on to
1448 // GetPhysicalDeviceImageFormatProperties2
1449 void* compression_control_pNext = nullptr;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001450 VkImageCompressionControlEXT image_compression = {};
Trevor David Black02926f52024-01-04 18:44:20 +00001451 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1452 while (create_infos->pNext) {
1453 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(create_infos->pNext);
1454 switch (create_infos->sType) {
1455 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1456 const VkImageCompressionControlEXT* compression_infos =
1457 reinterpret_cast<const VkImageCompressionControlEXT*>(create_infos);
1458 image_compression = *compression_infos;
1459 image_compression.pNext = nullptr;
1460 compression_control_pNext = &image_compression;
1461 } break;
1462 default:
1463 // Ignore all other info structs
1464 break;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001465 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001466 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001467
Trevor David Black02926f52024-01-04 18:44:20 +00001468 // call GetPhysicalDeviceImageFormatProperties2KHR
1469 VkPhysicalDeviceExternalImageFormatInfo external_image_format_info = {
1470 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1471 .pNext = compression_control_pNext,
1472 .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID,
1473 };
1474
1475 // AHB does not have an sRGB format so we can't pass it to GPDIFP
1476 // We need to convert the format to unorm if it is srgb
1477 VkFormat format = create_info->imageFormat;
1478 if (format == VK_FORMAT_R8G8B8A8_SRGB) {
1479 format = VK_FORMAT_R8G8B8A8_UNORM;
1480 }
1481
1482 VkPhysicalDeviceImageFormatInfo2 image_format_info = {
1483 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1484 .pNext = &external_image_format_info,
1485 .format = format,
1486 .type = VK_IMAGE_TYPE_2D,
1487 .tiling = VK_IMAGE_TILING_OPTIMAL,
1488 .usage = create_info->imageUsage,
1489 .flags = create_protected_swapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
1490 };
1491
1492 VkAndroidHardwareBufferUsageANDROID ahb_usage;
1493 ahb_usage.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_USAGE_ANDROID;
1494 ahb_usage.pNext = nullptr;
1495
1496 VkImageFormatProperties2 image_format_properties;
1497 image_format_properties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
1498 image_format_properties.pNext = &ahb_usage;
1499
1500 if (instance_dispatch.GetPhysicalDeviceImageFormatProperties2) {
1501 VkResult result = instance_dispatch.GetPhysicalDeviceImageFormatProperties2(
1502 pdev, &image_format_info, &image_format_properties);
1503 if (result != VK_SUCCESS) {
1504 ALOGE("VkGetPhysicalDeviceImageFormatProperties2 for AHB usage failed: %d", result);
1505 return VK_ERROR_SURFACE_LOST_KHR;
1506 }
1507 }
1508 else {
1509 VkResult result = instance_dispatch.GetPhysicalDeviceImageFormatProperties2KHR(
1510 pdev, &image_format_info,
1511 &image_format_properties);
1512 if (result != VK_SUCCESS) {
1513 ALOGE("VkGetPhysicalDeviceImageFormatProperties2KHR for AHB usage failed: %d",
1514 result);
1515 return VK_ERROR_SURFACE_LOST_KHR;
1516 }
1517 }
1518
1519 // Determine if USAGE_FRONT_BUFFER is needed.
1520 // GPDIFP2 has no means of using VkSwapchainImageUsageFlagsANDROID when
1521 // querying for producer_usage. So androidHardwareBufferUsage will not
1522 // contain USAGE_FRONT_BUFFER. We need to manually check for usage here.
1523 if (!(swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID)) {
1524 *producer_usage = ahb_usage.androidHardwareBufferUsage;
1525 return VK_SUCCESS;
1526 }
1527
1528 // Check if USAGE_FRONT_BUFFER is supported for this swapchain
1529 AHardwareBuffer_Desc ahb_desc = {
1530 .width = create_info->imageExtent.width,
1531 .height = create_info->imageExtent.height,
1532 .layers = create_info->imageArrayLayers,
1533 .format = create_info->imageFormat,
1534 .usage = ahb_usage.androidHardwareBufferUsage | AHARDWAREBUFFER_USAGE_FRONT_BUFFER,
1535 .stride = 0, // stride is always ignored when calling isSupported()
1536 };
1537
1538 // If FRONT_BUFFER is not supported,
1539 // then we need to call GetSwapchainGrallocUsageXAndroid below
1540 if (AHardwareBuffer_isSupported(&ahb_desc)) {
1541 *producer_usage = ahb_usage.androidHardwareBufferUsage;
1542 *producer_usage |= AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
1543 return VK_SUCCESS;
1544 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001545 }
1546
Trevor David Black02926f52024-01-04 18:44:20 +00001547 uint64_t native_usage = 0;
1548 void* usage_info_pNext = nullptr;
1549 VkResult result;
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001550 VkImageCompressionControlEXT image_compression = {};
Trevor David Black02926f52024-01-04 18:44:20 +00001551 const auto& dispatch = GetData(device).driver;
1552 if (dispatch.GetSwapchainGrallocUsage4ANDROID) {
1553 ATRACE_BEGIN("GetSwapchainGrallocUsage4ANDROID");
1554 VkGrallocUsageInfo2ANDROID gralloc_usage_info = {};
1555 gralloc_usage_info.sType =
1556 VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_2_ANDROID;
1557 gralloc_usage_info.format = create_info->imageFormat;
1558 gralloc_usage_info.imageUsage = create_info->imageUsage;
1559 gralloc_usage_info.swapchainImageUsage = swapchain_image_usage;
1560
1561 // Look through the pNext chain for an image compression control struct
1562 // if one is found AND the appropriate extensions are enabled,
1563 // append it to be the gralloc usage pNext chain
1564 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1565 while (create_infos->pNext) {
1566 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1567 create_infos->pNext);
1568 switch (create_infos->sType) {
1569 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1570 const VkImageCompressionControlEXT* compression_infos =
1571 reinterpret_cast<const VkImageCompressionControlEXT*>(
1572 create_infos);
1573 image_compression = *compression_infos;
1574 image_compression.pNext = nullptr;
1575 usage_info_pNext = &image_compression;
1576 } break;
1577
1578 default:
1579 // Ignore all other info structs
1580 break;
1581 }
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001582 }
Trevor David Black02926f52024-01-04 18:44:20 +00001583 gralloc_usage_info.pNext = usage_info_pNext;
Vamsidhar reddy Gaddam7a844312023-11-14 10:59:05 +00001584
Trevor David Black02926f52024-01-04 18:44:20 +00001585 result = dispatch.GetSwapchainGrallocUsage4ANDROID(
1586 device, &gralloc_usage_info, &native_usage);
1587 ATRACE_END();
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001588 if (result != VK_SUCCESS) {
Trevor David Black02926f52024-01-04 18:44:20 +00001589 ALOGE("vkGetSwapchainGrallocUsage4ANDROID failed: %d", result);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001590 return VK_ERROR_SURFACE_LOST_KHR;
1591 }
Trevor David Black02926f52024-01-04 18:44:20 +00001592 } else if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
1593 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1594 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1595 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1596 gralloc_usage_info.format = create_info->imageFormat;
1597 gralloc_usage_info.imageUsage = create_info->imageUsage;
1598
1599 // Look through the pNext chain for an image compression control struct
1600 // if one is found AND the appropriate extensions are enabled,
1601 // append it to be the gralloc usage pNext chain
1602 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1603 while (create_infos->pNext) {
1604 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1605 create_infos->pNext);
1606 switch (create_infos->sType) {
1607 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1608 const VkImageCompressionControlEXT* compression_infos =
1609 reinterpret_cast<const VkImageCompressionControlEXT*>(
1610 create_infos);
1611 image_compression = *compression_infos;
1612 image_compression.pNext = nullptr;
1613 usage_info_pNext = &image_compression;
1614 } break;
1615
1616 default:
1617 // Ignore all other info structs
1618 break;
1619 }
1620 }
1621 gralloc_usage_info.pNext = usage_info_pNext;
1622
1623 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1624 device, &gralloc_usage_info, &native_usage);
1625 ATRACE_END();
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001626 if (result != VK_SUCCESS) {
Trevor David Black02926f52024-01-04 18:44:20 +00001627 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001628 return VK_ERROR_SURFACE_LOST_KHR;
1629 }
Trevor David Black02926f52024-01-04 18:44:20 +00001630 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
1631 uint64_t consumer_usage, producer_usage;
1632 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
1633 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1634 device, create_info->imageFormat, create_info->imageUsage,
1635 swapchain_image_usage, &consumer_usage, &producer_usage);
1636 ATRACE_END();
1637 if (result != VK_SUCCESS) {
1638 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
1639 return VK_ERROR_SURFACE_LOST_KHR;
1640 }
1641 native_usage =
1642 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
1643 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
1644 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
1645 int32_t legacy_usage = 0;
1646 result = dispatch.GetSwapchainGrallocUsageANDROID(
1647 device, create_info->imageFormat, create_info->imageUsage,
1648 &legacy_usage);
1649 ATRACE_END();
1650 if (result != VK_SUCCESS) {
1651 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
1652 return VK_ERROR_SURFACE_LOST_KHR;
1653 }
1654 native_usage = static_cast<uint64_t>(legacy_usage);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001655 }
Trevor David Black02926f52024-01-04 18:44:20 +00001656 *producer_usage = native_usage;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001657
1658 return VK_SUCCESS;
1659}
1660
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001661VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001662VkResult CreateSwapchainKHR(VkDevice device,
1663 const VkSwapchainCreateInfoKHR* create_info,
1664 const VkAllocationCallbacks* allocator,
1665 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001666 ATRACE_CALL();
1667
Jesse Halld7b994a2015-09-07 14:17:37 -07001668 int err;
1669 VkResult result = VK_SUCCESS;
1670
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001671 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1672 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
Yiwei Zhang3aef18e2024-03-18 22:01:42 +00001673 " imageExtent=%ux%u imageUsage=%#x preTransform=%u compositeAlpha=%u"
1674 " presentMode=%u oldSwapchain=0x%" PRIx64,
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001675 reinterpret_cast<uint64_t>(create_info->surface),
1676 create_info->minImageCount, create_info->imageFormat,
1677 create_info->imageColorSpace, create_info->imageExtent.width,
1678 create_info->imageExtent.height, create_info->imageUsage,
Yiwei Zhang3aef18e2024-03-18 22:01:42 +00001679 create_info->preTransform, create_info->compositeAlpha,
1680 create_info->presentMode,
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001681 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1682
Jesse Hall1f91d392015-12-11 16:28:44 -08001683 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001684 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001685
Yiwei Zhang3aef18e2024-03-18 22:01:42 +00001686 PixelFormat native_pixel_format = GetNativePixelFormat(
1687 create_info->imageFormat, create_info->compositeAlpha);
Yiwei Zhang959f5182024-03-12 02:46:36 +00001688 DataSpace native_dataspace = GetNativeDataspace(
1689 create_info->imageColorSpace, create_info->imageFormat);
sergiuferentz47989332023-09-26 10:24:36 +00001690 if (native_dataspace == DataSpace::UNKNOWN) {
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001691 ALOGE(
1692 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1693 "failed: Unsupported color space",
1694 create_info->imageColorSpace);
1695 return VK_ERROR_INITIALIZATION_FAILED;
1696 }
1697
Jesse Hall42a9eec2016-06-03 12:39:49 -07001698 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001699 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001700 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001701 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001702 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001703 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001704 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001705 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001706 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1707 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001708 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001709 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001710
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001711 Surface& surface = *SurfaceFromHandle(create_info->surface);
1712
Jesse Halldc225072016-05-30 22:40:14 -07001713 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001714 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001715 " because it already has active swapchain 0x%" PRIx64
1716 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1717 reinterpret_cast<uint64_t>(create_info->surface),
1718 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1719 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1720 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1721 }
1722 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1723 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1724
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001725 // -- Reset the native window --
1726 // The native window might have been used previously, and had its properties
1727 // changed from defaults. That will affect the answer we get for queries
1728 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1729 // attempt such queries.
1730
Jesse Halldc225072016-05-30 22:40:14 -07001731 // The native window only allows dequeueing all buffers before any have
1732 // been queued, since after that point at least one is assumed to be in
1733 // non-FREE state at any given time. Disconnecting and re-connecting
1734 // orphans the previous buffers, getting us back to the state where we can
1735 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001736 //
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001737 // This is not necessary if the surface was never used previously.
1738 //
Yiwei Zhang70a21962019-05-31 17:26:52 -07001739 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001740 ANativeWindow* window = surface.window.get();
Yiwei Zhang3b88f312023-04-18 23:11:35 +00001741 if (surface.used_by_swapchain) {
1742 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1743 ALOGW_IF(err != android::OK,
1744 "native_window_api_disconnect failed: %s (%d)", strerror(-err),
1745 err);
1746 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1747 ALOGW_IF(err != android::OK,
1748 "native_window_api_connect failed: %s (%d)", strerror(-err),
1749 err);
1750 }
Jesse Halldc225072016-05-30 22:40:14 -07001751
Nicolas Capens147b7da2021-04-09 14:53:06 -04001752 err =
1753 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001754 if (err != android::OK) {
1755 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1756 strerror(-err), err);
1757 return VK_ERROR_SURFACE_LOST_KHR;
1758 }
1759
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301760 int swap_interval =
1761 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001762 err = window->setSwapInterval(window, swap_interval);
1763 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001764 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1765 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001766 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001767 }
1768
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001769 err = native_window_set_shared_buffer_mode(window, false);
1770 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001771 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1772 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001773 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001774 }
1775
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001776 err = native_window_set_auto_refresh(window, false);
1777 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001778 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1779 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001780 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001781 }
1782
Jesse Halld7b994a2015-09-07 14:17:37 -07001783 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001784
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001785 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001786
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001787 err = native_window_set_buffers_format(
1788 window, static_cast<int>(native_pixel_format));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001789 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001790 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
Trevor David Blackf499b5a2023-07-14 17:30:41 +00001791 toString(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001792 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001793 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001794
1795 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
sergiuferentz47989332023-09-26 10:24:36 +00001796 if (native_dataspace != DataSpace::ARBITRARY) {
1797 err = native_window_set_buffers_data_space(
1798 window, static_cast<android_dataspace_t>(native_dataspace));
Yiwei Zhang51572c22022-07-22 23:08:30 +00001799 if (err != android::OK) {
1800 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1801 native_dataspace, strerror(-err), err);
1802 return VK_ERROR_SURFACE_LOST_KHR;
1803 }
Jesse Hall517274a2016-02-10 00:07:18 -08001804 }
1805
Jesse Hall3dd678a2016-01-08 21:52:01 -08001806 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001807 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001808 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001809 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001810 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1811 create_info->imageExtent.width, create_info->imageExtent.height,
1812 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001813 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001814 }
1815
Jesse Hall178b6962016-02-24 15:39:50 -08001816 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1817 // applied during rendering. native_window_set_transform() expects the
1818 // inverse: the transform the app is requesting that the compositor perform
1819 // during composition. With native windows, pre-transform works by rendering
1820 // with the same transform the compositor is applying (as in Vulkan), but
1821 // then requesting the inverse transform, so that when the compositor does
1822 // it's job the two transforms cancel each other out and the compositor ends
1823 // up applying an identity transform to the app's buffer.
1824 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001825 window, InvertTransformToNative(create_info->preTransform));
1826 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001827 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1828 InvertTransformToNative(create_info->preTransform),
1829 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001830 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001831 }
1832
Jesse Hallf64ca122015-11-03 16:11:10 -08001833 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001834 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1835 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001836 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1837 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001838 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001839 }
1840
Chris Forbes97ef4612017-03-30 19:37:50 +13001841 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001842 if (IsSharedPresentMode(create_info->presentMode)) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001843 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001844 err = native_window_set_shared_buffer_mode(window, true);
1845 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001846 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1847 return VK_ERROR_SURFACE_LOST_KHR;
1848 }
1849 }
1850
1851 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001852 err = native_window_set_auto_refresh(window, true);
1853 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001854 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1855 return VK_ERROR_SURFACE_LOST_KHR;
1856 }
1857 }
1858
Ian Elliott16c443c2021-11-30 17:10:32 -07001859 int query_value;
Trevor David Blackabab5a02023-12-19 20:27:07 +00001860 // TODO: Now that we are calling into GPDSC2 directly, this query may be redundant
1861 // the call to std::max(min_buffer_count, num_images) may be redundant as well
Ian Elliott16c443c2021-11-30 17:10:32 -07001862 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1863 &query_value);
1864 if (err != android::OK || query_value < 0) {
1865 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1866 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001867 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001868 }
Trevor David Black8c0122e2023-09-07 20:33:54 +00001869 const uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
Chris Forbes2c8fc752017-03-17 11:28:32 +13001870
Ian Elliott5396b702021-12-13 19:32:34 -07001871 // Lower layer insists that we have at least min_undequeued_buffers + 1
1872 // buffers. This is wasteful and we'd like to relax it in the shared case,
1873 // but not all the pieces are in place for that to work yet. Note we only
1874 // lie to the lower layer--we don't want to give the app back a swapchain
1875 // with extra images (which they can't actually use!).
Trevor David Black8c0122e2023-09-07 20:33:54 +00001876 const uint32_t min_buffer_count = min_undequeued_buffers + 1;
1877
Trevor David Blackabab5a02023-12-19 20:27:07 +00001878 // Call into GPDSC2 to get the minimum and maximum allowable buffer count for the surface of
1879 // interest. This step is only necessary if the app requests a number of images
1880 // (create_info->minImageCount) that is less or more than the surface capabilities.
1881 // An app should be calling GPDSC2 and using those values to set create_info, but in the
1882 // event that the app has hard-coded image counts an error can occur
1883 VkSurfacePresentModeEXT present_mode = {
1884 VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT,
1885 nullptr,
1886 create_info->presentMode
1887 };
1888 VkPhysicalDeviceSurfaceInfo2KHR surface_info2 = {
1889 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
1890 &present_mode,
1891 create_info->surface
1892 };
1893 VkSurfaceCapabilities2KHR surface_capabilities2 = {
1894 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
1895 nullptr,
1896 {},
1897 };
1898 result = GetPhysicalDeviceSurfaceCapabilities2KHR(GetData(device).driver_physical_device,
1899 &surface_info2, &surface_capabilities2);
1900
1901 uint32_t num_images = create_info->minImageCount;
1902 num_images = std::clamp(num_images,
1903 surface_capabilities2.surfaceCapabilities.minImageCount,
1904 surface_capabilities2.surfaceCapabilities.maxImageCount);
Trevor David Black8c0122e2023-09-07 20:33:54 +00001905
1906 const uint32_t buffer_count = std::max(min_buffer_count, num_images);
1907 err = native_window_set_buffer_count(window, buffer_count);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001908 if (err != android::OK) {
Trevor David Black8c0122e2023-09-07 20:33:54 +00001909 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", buffer_count,
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001910 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001911 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001912 }
1913
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001914 // In shared mode the num_images must be one regardless of how many
1915 // buffers were allocated for the buffer queue.
1916 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1917 num_images = 1;
1918 }
1919
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001920 // Look through the create_info pNext chain passed to createSwapchainKHR
1921 // for an image compression control struct.
1922 // if one is found AND the appropriate extensions are enabled, create a
1923 // VkImageCompressionControlEXT structure to pass on to VkImageCreateInfo
1924 // TODO check for imageCompressionControlSwapchain feature is enabled
Trevor David Black2cc44682022-03-09 00:31:38 +00001925 void* usage_info_pNext = nullptr;
1926 VkImageCompressionControlEXT image_compression = {};
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001927 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1928 while (create_infos->pNext) {
1929 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(create_infos->pNext);
1930 switch (create_infos->sType) {
1931 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1932 const VkImageCompressionControlEXT* compression_infos =
1933 reinterpret_cast<const VkImageCompressionControlEXT*>(create_infos);
1934 image_compression = *compression_infos;
1935 image_compression.pNext = nullptr;
1936 usage_info_pNext = &image_compression;
1937 } break;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001938
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001939 default:
1940 // Ignore all other info structs
1941 break;
Trevor David Blackb6ca8422023-07-26 20:00:04 +00001942 }
Jesse Hall70f93352015-11-04 09:41:31 -08001943 }
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001944
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001945 // Get the appropriate native_usage for the images
1946 // Get the consumer usage
1947 uint64_t native_usage = surface.consumer_usage;
1948 // Determine if the swapchain is protected
1949 bool create_protected_swapchain = false;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001950 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001951 create_protected_swapchain = true;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001952 native_usage |= BufferUsage::PROTECTED;
1953 }
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001954 // Get the producer usage
1955 uint64_t producer_usage;
1956 result = getProducerUsage(device, create_info, swapchain_image_usage, create_protected_swapchain, &producer_usage);
1957 if (result != VK_SUCCESS) {
1958 return result;
1959 }
1960 native_usage |= producer_usage;
1961
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001962 err = native_window_set_usage(window, native_usage);
1963 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001964 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001965 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001966 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001967
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001968 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001969 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1970 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001971 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1972 strerror(-err), err);
1973 return VK_ERROR_SURFACE_LOST_KHR;
1974 }
1975
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001976 int64_t refresh_duration;
1977 err = native_window_get_refresh_cycle_duration(window, &refresh_duration);
1978 if (err != android::OK) {
1979 ALOGE("native_window_get_refresh_cycle_duration query failed: %s (%d)",
1980 strerror(-err), err);
1981 return VK_ERROR_SURFACE_LOST_KHR;
1982 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001983 // -- Allocate our Swapchain object --
1984 // After this point, we must deallocate the swapchain on error.
1985
Jesse Hall1f91d392015-12-11 16:28:44 -08001986 void* mem = allocator->pfnAllocation(allocator->pUserData,
1987 sizeof(Swapchain), alignof(Swapchain),
1988 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001989
Jesse Hall1356b0d2015-11-23 17:24:58 -08001990 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001991 return VK_ERROR_OUT_OF_HOST_MEMORY;
Trevor David Blackd7320ef2023-08-23 21:21:51 +00001992
silence_dogood73597592019-05-23 16:57:37 -07001993 Swapchain* swapchain = new (mem)
1994 Swapchain(surface, num_images, create_info->presentMode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001995 TranslateVulkanToNativeTransform(create_info->preTransform),
1996 refresh_duration);
Chris Forbesb56287a2017-01-12 14:28:58 +13001997 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1998#pragma clang diagnostic push
1999#pragma clang diagnostic ignored "-Wold-style-cast"
2000 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
2001#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00002002 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13002003 .usage = swapchain_image_usage,
2004 };
Jesse Halld7b994a2015-09-07 14:17:37 -07002005 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07002006#pragma clang diagnostic push
2007#pragma clang diagnostic ignored "-Wold-style-cast"
2008 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2009#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13002010 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07002011 };
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002012
Jesse Halld7b994a2015-09-07 14:17:37 -07002013 VkImageCreateInfo image_create = {
2014 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002015 .pNext = nullptr,
Trevor David Blackd7320ef2023-08-23 21:21:51 +00002016 .flags = create_protected_swapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07002017 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08002018 .format = create_info->imageFormat,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002019 .extent = {
2020 create_info->imageExtent.width,
2021 create_info->imageExtent.height,
2022 1
2023 },
Jesse Halld7b994a2015-09-07 14:17:37 -07002024 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08002025 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08002026 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07002027 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08002028 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08002029 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08002030 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07002031 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
2032 };
2033
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002034 // Note: don't do deferred allocation for shared present modes. There's only one buffer
2035 // involved so very little benefit.
2036 if ((create_info->flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT) &&
2037 !IsSharedPresentMode(create_info->presentMode)) {
2038 // Don't want to touch the underlying gralloc buffers yet;
2039 // instead just create unbound VkImages which will later be bound to memory inside
2040 // AcquireNextImage.
2041 VkImageSwapchainCreateInfoKHR image_swapchain_create = {
2042 .sType = VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR,
2043 .pNext = nullptr,
2044 .swapchain = HandleFromSwapchain(swapchain),
2045 };
2046 image_create.pNext = &image_swapchain_create;
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];
2050 img.buffer = nullptr;
2051 img.dequeued = false;
2052
2053 result = dispatch.CreateImage(device, &image_create, nullptr, &img.image);
2054 if (result != VK_SUCCESS) {
2055 ALOGD("vkCreateImage w/ for deferred swapchain image failed: %u", result);
2056 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08002057 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002058 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002059 } else {
2060 // -- Dequeue all buffers and create a VkImage for each --
2061 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07002062
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002063 for (uint32_t i = 0; i < num_images; i++) {
2064 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07002065
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002066 ANativeWindowBuffer* buffer;
2067 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
2068 if (err != android::OK) {
2069 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
2070 switch (-err) {
2071 case ENOMEM:
2072 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
2073 break;
2074 default:
2075 result = VK_ERROR_SURFACE_LOST_KHR;
2076 break;
2077 }
2078 break;
2079 }
2080 img.buffer = buffer;
2081 img.dequeued = true;
2082
2083 image_native_buffer.handle = img.buffer->handle;
2084 image_native_buffer.stride = img.buffer->stride;
2085 image_native_buffer.format = img.buffer->format;
2086 image_native_buffer.usage = int(img.buffer->usage);
2087 android_convertGralloc0To1Usage(int(img.buffer->usage),
2088 &image_native_buffer.usage2.producer,
2089 &image_native_buffer.usage2.consumer);
2090 image_native_buffer.usage3 = img.buffer->usage;
Trevor David Black0db7a092023-12-11 23:46:36 +00002091 image_native_buffer.ahb =
2092 ANativeWindowBuffer_getHardwareBuffer(img.buffer.get());
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002093 image_create.pNext = &image_native_buffer;
2094
2095 ATRACE_BEGIN("CreateImage");
2096 result =
2097 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
2098 ATRACE_END();
2099 if (result != VK_SUCCESS) {
2100 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
2101 break;
2102 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002103 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002104
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002105 // -- Cancel all buffers, returning them to the queue --
2106 // If an error occurred before, also destroy the VkImage and release the
2107 // buffer reference. Otherwise, we retain a strong reference to the buffer.
2108 for (uint32_t i = 0; i < num_images; i++) {
2109 Swapchain::Image& img = swapchain->images[i];
2110 if (img.dequeued) {
2111 if (!swapchain->shared) {
2112 window->cancelBuffer(window, img.buffer.get(),
2113 img.dequeue_fence);
2114 img.dequeue_fence = -1;
2115 img.dequeued = false;
2116 }
Chris Forbese0ced032017-03-30 19:44:15 +13002117 }
Chris Forbes31b85c22018-05-29 15:03:28 -07002118 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002119 }
2120
2121 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07002122 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
2123 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07002124 return result;
2125 }
2126
Yiwei Zhang69395cd2019-07-03 16:55:39 -07002127 if (transform_hint != swapchain->pre_transform) {
2128 // Log that the app is not doing pre-rotation.
2129 android::GraphicsEnv::getInstance().setTargetStats(
2130 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
2131 }
2132
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00002133 // Set stats for creating a Vulkan swapchain
2134 android::GraphicsEnv::getInstance().setTargetStats(
2135 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
2136
Yiwei Zhang3b88f312023-04-18 23:11:35 +00002137 surface.used_by_swapchain = true;
Jesse Halldc225072016-05-30 22:40:14 -07002138 surface.swapchain_handle = HandleFromSwapchain(swapchain);
2139 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002140 return VK_SUCCESS;
2141}
2142
Jesse Halle1b12782015-11-30 11:27:32 -08002143VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002144void DestroySwapchainKHR(VkDevice device,
2145 VkSwapchainKHR swapchain_handle,
2146 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002147 ATRACE_CALL();
2148
Yiwei Zhang533cea92019-06-03 18:43:24 -07002149 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07002150}
2151
Jesse Halle1b12782015-11-30 11:27:32 -08002152VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002153VkResult GetSwapchainImagesKHR(VkDevice,
2154 VkSwapchainKHR swapchain_handle,
2155 uint32_t* count,
2156 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002157 ATRACE_CALL();
2158
Jesse Halld7b994a2015-09-07 14:17:37 -07002159 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07002160 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
2161 "getting images for non-active swapchain 0x%" PRIx64
2162 "; only dequeued image handles are valid",
2163 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07002164 VkResult result = VK_SUCCESS;
2165 if (images) {
2166 uint32_t n = swapchain.num_images;
2167 if (*count < swapchain.num_images) {
2168 n = *count;
2169 result = VK_INCOMPLETE;
2170 }
2171 for (uint32_t i = 0; i < n; i++)
2172 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07002173 *count = n;
2174 } else {
2175 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07002176 }
Jesse Halld7b994a2015-09-07 14:17:37 -07002177 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002178}
2179
Jesse Halle1b12782015-11-30 11:27:32 -08002180VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002181VkResult AcquireNextImageKHR(VkDevice device,
2182 VkSwapchainKHR swapchain_handle,
2183 uint64_t timeout,
2184 VkSemaphore semaphore,
2185 VkFence vk_fence,
2186 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002187 ATRACE_CALL();
2188
Jesse Halld7b994a2015-09-07 14:17:37 -07002189 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08002190 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07002191 VkResult result;
2192 int err;
2193
Jesse Halldc225072016-05-30 22:40:14 -07002194 if (swapchain.surface.swapchain_handle != swapchain_handle)
2195 return VK_ERROR_OUT_OF_DATE_KHR;
2196
Chris Forbesc88409c2017-03-30 19:47:37 +13002197 if (swapchain.shared) {
2198 // In shared mode, we keep the buffer dequeued all the time, so we don't
2199 // want to dequeue a buffer here. Instead, just ask the driver to ensure
2200 // the semaphore and fence passed to us will be signalled.
2201 *image_index = 0;
2202 result = GetData(device).driver.AcquireImageANDROID(
2203 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
2204 return result;
2205 }
2206
Yiwei Zhang705c2e62019-12-18 23:12:43 -08002207 const nsecs_t acquire_next_image_timeout =
2208 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
2209 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
2210 // Cache the timeout to avoid the duplicate binder cost.
2211 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
2212 acquire_next_image_timeout);
2213 if (err != android::OK) {
2214 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
2215 strerror(-err), err);
2216 return VK_ERROR_SURFACE_LOST_KHR;
2217 }
2218 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
2219 }
2220
Jesse Halld7b994a2015-09-07 14:17:37 -07002221 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08002222 int fence_fd;
2223 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07002224 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08002225 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
2226 return timeout ? VK_TIMEOUT : VK_NOT_READY;
2227 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07002228 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07002229 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002230 }
2231
2232 uint32_t idx;
2233 for (idx = 0; idx < swapchain.num_images; idx++) {
2234 if (swapchain.images[idx].buffer.get() == buffer) {
2235 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08002236 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07002237 break;
2238 }
2239 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002240
2241 // If this is a deferred alloc swapchain, this may be the first time we've
2242 // seen a particular buffer. If so, there should be an empty slot. Find it,
2243 // and bind the gralloc buffer to the VkImage for that slot. If there is no
2244 // empty slot, then we dequeued an unexpected buffer. Non-deferred swapchains
2245 // will also take this path, but will never have an empty slot since we
2246 // populated them all upfront.
2247 if (idx == swapchain.num_images) {
2248 for (idx = 0; idx < swapchain.num_images; idx++) {
2249 if (!swapchain.images[idx].buffer) {
2250 // Note: this structure is technically required for
2251 // Vulkan correctness, even though the driver is probably going
2252 // to use everything from the VkNativeBufferANDROID below.
2253 // This is kindof silly, but it's how we did the ANB
2254 // side of VK_KHR_swapchain v69, so we're stuck with it unless
2255 // we want to go tinkering with the ANB spec some more.
2256 VkBindImageMemorySwapchainInfoKHR bimsi = {
2257 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR,
2258 .pNext = nullptr,
2259 .swapchain = swapchain_handle,
2260 .imageIndex = idx,
2261 };
2262 VkNativeBufferANDROID nb = {
2263 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2264 .pNext = &bimsi,
2265 .handle = buffer->handle,
2266 .stride = buffer->stride,
2267 .format = buffer->format,
2268 .usage = int(buffer->usage),
Trevor David Black0db7a092023-12-11 23:46:36 +00002269 .usage3 = buffer->usage,
2270 .ahb = ANativeWindowBuffer_getHardwareBuffer(buffer),
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002271 };
Trevor David Black0db7a092023-12-11 23:46:36 +00002272 android_convertGralloc0To1Usage(int(buffer->usage),
2273 &nb.usage2.producer,
2274 &nb.usage2.consumer);
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002275 VkBindImageMemoryInfo bimi = {
2276 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO,
2277 .pNext = &nb,
2278 .image = swapchain.images[idx].image,
2279 .memory = VK_NULL_HANDLE,
2280 .memoryOffset = 0,
2281 };
2282 result = GetData(device).driver.BindImageMemory2(device, 1, &bimi);
2283 if (result != VK_SUCCESS) {
2284 // This shouldn't really happen. If it does, something is probably
2285 // unrecoverably wrong with the swapchain and its images. Cancel
2286 // the buffer and declare the swapchain broken.
2287 ALOGE("failed to do deferred gralloc buffer bind");
2288 window->cancelBuffer(window, buffer, fence_fd);
2289 return VK_ERROR_OUT_OF_DATE_KHR;
2290 }
2291
2292 swapchain.images[idx].dequeued = true;
2293 swapchain.images[idx].dequeue_fence = fence_fd;
2294 swapchain.images[idx].buffer = buffer;
2295 break;
2296 }
2297 }
2298 }
2299
2300 // The buffer doesn't match any slot. This shouldn't normally happen, but is
2301 // possible if the bufferqueue is reconfigured behind libvulkan's back. If this
2302 // happens, just declare the swapchain to be broken and the app will recreate it.
Jesse Halld7b994a2015-09-07 14:17:37 -07002303 if (idx == swapchain.num_images) {
2304 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08002305 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002306 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07002307 }
2308
2309 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08002310 if (fence_fd != -1) {
2311 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002312 if (fence_clone == -1) {
2313 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
2314 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08002315 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07002316 }
2317 }
2318
Chia-I Wu4a6a9162016-03-26 07:17:34 +08002319 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08002320 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07002321 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08002322 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
2323 // even if the call fails. We could close it ourselves on failure, but
2324 // that would create a race condition if the driver closes it on a
2325 // failure path: some other thread might create an fd with the same
2326 // number between the time the driver closes it and the time we close
2327 // it. We must assume one of: the driver *always* closes it even on
2328 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08002329 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07002330 swapchain.images[idx].dequeued = false;
2331 swapchain.images[idx].dequeue_fence = -1;
2332 return result;
2333 }
2334
2335 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07002336 return VK_SUCCESS;
2337}
2338
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002339VKAPI_ATTR
2340VkResult AcquireNextImage2KHR(VkDevice device,
2341 const VkAcquireNextImageInfoKHR* pAcquireInfo,
2342 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002343 ATRACE_CALL();
2344
Daniel Kochf25f5bb2017-10-05 00:26:58 -04002345 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
2346 pAcquireInfo->timeout, pAcquireInfo->semaphore,
2347 pAcquireInfo->fence, pImageIndex);
2348}
2349
Jesse Halldc225072016-05-30 22:40:14 -07002350static VkResult WorstPresentResult(VkResult a, VkResult b) {
2351 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
2352 // (in spec version 1.0.14).
2353 static const VkResult kWorstToBest[] = {
2354 VK_ERROR_DEVICE_LOST,
2355 VK_ERROR_SURFACE_LOST_KHR,
2356 VK_ERROR_OUT_OF_DATE_KHR,
2357 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2358 VK_ERROR_OUT_OF_HOST_MEMORY,
2359 VK_SUBOPTIMAL_KHR,
2360 };
2361 for (auto result : kWorstToBest) {
2362 if (a == result || b == result)
2363 return result;
2364 }
2365 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
2366 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
2367 return a != VK_SUCCESS ? a : b;
2368}
2369
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002370// KHR_incremental_present aspect of QueuePresentKHR
2371static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
2372 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
2373 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
2374 auto const& rect = pRegion->pRectangles[i];
2375 if (rect.layer > 0) {
2376 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
2377 rect.layer);
2378 }
2379
2380 rects[i].left = rect.offset.x;
2381 rects[i].bottom = rect.offset.y;
2382 rects[i].right = rect.offset.x + rect.extent.width;
2383 rects[i].top = rect.offset.y + rect.extent.height;
2384 }
2385 native_window_set_surface_damage(window, rects.data(), rects.size());
2386}
2387
2388// GOOGLE_display_timing aspect of QueuePresentKHR
2389static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
2390 ANativeWindow *window = swapchain.surface.window.get();
2391
2392 // We don't know whether the app will actually use GOOGLE_display_timing
2393 // with a particular swapchain until QueuePresent; enable it on the BQ
2394 // now if needed
2395 if (!swapchain.frame_timestamps_enabled) {
2396 ALOGV("Calling native_window_enable_frame_timestamps(true)");
2397 native_window_enable_frame_timestamps(window, true);
2398 swapchain.frame_timestamps_enabled = true;
2399 }
2400
2401 // Record the nativeFrameId so it can be later correlated to
2402 // this present.
2403 uint64_t nativeFrameId = 0;
2404 int err = native_window_get_next_frame_id(
2405 window, &nativeFrameId);
2406 if (err != android::OK) {
2407 ALOGE("Failed to get next native frame ID.");
2408 }
2409
2410 // Add a new timing record with the user's presentID and
2411 // the nativeFrameId.
2412 swapchain.timing.emplace_back(pTime, nativeFrameId);
2413 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
2414 swapchain.timing.erase(
2415 swapchain.timing.begin(),
2416 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
2417 }
2418 if (pTime->desiredPresentTime) {
2419 ALOGV(
2420 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
2421 pTime->desiredPresentTime);
2422 native_window_set_buffers_timestamp(
2423 window,
2424 static_cast<int64_t>(pTime->desiredPresentTime));
2425 }
2426}
2427
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002428// EXT_swapchain_maintenance1 present mode change
2429static bool SetSwapchainPresentMode(ANativeWindow *window, VkPresentModeKHR mode) {
2430 // There is no dynamic switching between non-shared present modes.
2431 // All we support is switching between demand and continuous refresh.
2432 if (!IsSharedPresentMode(mode))
2433 return true;
2434
2435 int err = native_window_set_auto_refresh(window,
2436 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
2437 if (err != android::OK) {
2438 ALOGE("native_window_set_auto_refresh() failed: %s (%d)",
2439 strerror(-err), err);
2440 return false;
2441 }
2442
2443 return true;
2444}
2445
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002446static VkResult PresentOneSwapchain(
2447 VkQueue queue,
2448 Swapchain& swapchain,
2449 uint32_t imageIndex,
2450 const VkPresentRegionKHR *pRegion,
2451 const VkPresentTimeGOOGLE *pTime,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002452 VkFence presentFence,
2453 const VkPresentModeKHR *pPresentMode,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002454 uint32_t waitSemaphoreCount,
2455 const VkSemaphore *pWaitSemaphores) {
2456
2457 VkDevice device = GetData(queue).driver_device;
2458 const auto& dispatch = GetData(queue).driver;
2459
2460 Swapchain::Image& img = swapchain.images[imageIndex];
2461 VkResult swapchain_result = VK_SUCCESS;
2462 VkResult result;
2463 int err;
2464
2465 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
2466 // wait semaphores, so this doesn't actually work for the multiple swapchain
2467 // case.
2468 int fence = -1;
2469 result = dispatch.QueueSignalReleaseImageANDROID(
2470 queue, waitSemaphoreCount,
2471 pWaitSemaphores, img.image, &fence);
2472 if (result != VK_SUCCESS) {
2473 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
2474 swapchain_result = result;
2475 }
2476 if (img.release_fence >= 0)
2477 close(img.release_fence);
2478 img.release_fence = fence < 0 ? -1 : dup(fence);
2479
2480 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
2481 ANativeWindow* window = swapchain.surface.window.get();
2482 if (swapchain_result == VK_SUCCESS) {
2483
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002484 if (presentFence != VK_NULL_HANDLE) {
2485 int fence_copy = fence < 0 ? -1 : dup(fence);
2486 VkImportFenceFdInfoKHR iffi = {
2487 VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,
2488 nullptr,
2489 presentFence,
2490 VK_FENCE_IMPORT_TEMPORARY_BIT,
2491 VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,
2492 fence_copy,
2493 };
2494 if (VK_SUCCESS != dispatch.ImportFenceFdKHR(device, &iffi) && fence_copy >= 0) {
2495 // ImportFenceFdKHR takes ownership only if it succeeds
2496 close(fence_copy);
2497 }
2498 }
2499
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002500 if (pRegion) {
2501 SetSwapchainSurfaceDamage(window, pRegion);
2502 }
2503 if (pTime) {
2504 SetSwapchainFrameTimestamp(swapchain, pTime);
2505 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002506 if (pPresentMode) {
2507 if (!SetSwapchainPresentMode(window, *pPresentMode))
2508 swapchain_result = WorstPresentResult(swapchain_result,
2509 VK_ERROR_SURFACE_LOST_KHR);
2510 }
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002511
2512 err = window->queueBuffer(window, img.buffer.get(), fence);
2513 // queueBuffer always closes fence, even on error
2514 if (err != android::OK) {
2515 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
2516 swapchain_result = WorstPresentResult(
2517 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2518 } else {
2519 if (img.dequeue_fence >= 0) {
2520 close(img.dequeue_fence);
2521 img.dequeue_fence = -1;
2522 }
2523 img.dequeued = false;
2524 }
2525
2526 // If the swapchain is in shared mode, immediately dequeue the
2527 // buffer so it can be presented again without an intervening
2528 // call to AcquireNextImageKHR. We expect to get the same buffer
2529 // back from every call to dequeueBuffer in this mode.
2530 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
2531 ANativeWindowBuffer* buffer;
2532 int fence_fd;
2533 err = window->dequeueBuffer(window, &buffer, &fence_fd);
2534 if (err != android::OK) {
2535 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
2536 swapchain_result = WorstPresentResult(swapchain_result,
2537 VK_ERROR_SURFACE_LOST_KHR);
2538 } else if (img.buffer != buffer) {
2539 ALOGE("got wrong image back for shared swapchain");
2540 swapchain_result = WorstPresentResult(swapchain_result,
2541 VK_ERROR_SURFACE_LOST_KHR);
2542 } else {
2543 img.dequeue_fence = fence_fd;
2544 img.dequeued = true;
2545 }
2546 }
2547 }
2548 if (swapchain_result != VK_SUCCESS) {
2549 OrphanSwapchain(device, &swapchain);
2550 }
2551 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
2552 // and only when the window's transform/rotation changes. Extent
2553 // changes will not cause VK_SUBOPTIMAL_KHR because of the
2554 // application issues that were caused when the following transform
2555 // change was added.
2556 int window_transform_hint;
2557 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
2558 &window_transform_hint);
2559 if (err != android::OK) {
2560 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
2561 strerror(-err), err);
2562 swapchain_result = WorstPresentResult(
2563 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2564 }
2565 if (swapchain.pre_transform != window_transform_hint) {
2566 swapchain_result =
2567 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
2568 }
2569 } else {
2570 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
2571 img, true);
2572 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
2573 }
2574
2575 return swapchain_result;
2576}
2577
Jesse Halle1b12782015-11-30 11:27:32 -08002578VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002579VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002580 ATRACE_CALL();
2581
Jesse Halld7b994a2015-09-07 14:17:37 -07002582 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
2583 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
2584 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07002585
Jesse Halld7b994a2015-09-07 14:17:37 -07002586 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07002587
Ian Elliottcb351132016-12-13 10:30:40 -07002588 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002589 const VkPresentRegionsKHR* present_regions = nullptr;
2590 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002591 const VkSwapchainPresentFenceInfoEXT* present_fences = nullptr;
2592 const VkSwapchainPresentModeInfoEXT* present_modes = nullptr;
2593
Ian Elliottcb351132016-12-13 10:30:40 -07002594 const VkPresentRegionsKHR* next =
2595 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
2596 while (next) {
2597 switch (next->sType) {
2598 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
2599 present_regions = next;
2600 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07002601 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002602 present_times =
2603 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
2604 break;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002605 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT:
2606 present_fences =
2607 reinterpret_cast<const VkSwapchainPresentFenceInfoEXT*>(next);
2608 break;
2609 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT:
2610 present_modes =
2611 reinterpret_cast<const VkSwapchainPresentModeInfoEXT*>(next);
2612 break;
Ian Elliottcb351132016-12-13 10:30:40 -07002613 default:
2614 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
2615 next->sType);
2616 break;
2617 }
2618 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2619 }
2620 ALOGV_IF(
2621 present_regions &&
2622 present_regions->swapchainCount != present_info->swapchainCount,
2623 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002624 ALOGV_IF(present_times &&
2625 present_times->swapchainCount != present_info->swapchainCount,
2626 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2627 "VkPresentInfo::swapchainCount");
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002628 ALOGV_IF(present_fences &&
2629 present_fences->swapchainCount != present_info->swapchainCount,
2630 "VkSwapchainPresentFenceInfoEXT::swapchainCount != "
2631 "VkPresentInfo::swapchainCount");
2632 ALOGV_IF(present_modes &&
2633 present_modes->swapchainCount != present_info->swapchainCount,
2634 "VkSwapchainPresentModeInfoEXT::swapchainCount != "
2635 "VkPresentInfo::swapchainCount");
2636
Ian Elliottcb351132016-12-13 10:30:40 -07002637 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002638 (present_regions) ? present_regions->pRegions : nullptr;
2639 const VkPresentTimeGOOGLE* times =
2640 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002641
Jesse Halld7b994a2015-09-07 14:17:37 -07002642 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2643 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002644 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002645
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002646 VkResult swapchain_result = PresentOneSwapchain(
2647 queue,
2648 swapchain,
2649 present_info->pImageIndices[sc],
2650 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2651 times ? &times[sc] : nullptr,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002652 present_fences ? present_fences->pFences[sc] : VK_NULL_HANDLE,
2653 present_modes ? &present_modes->pPresentModes[sc] : nullptr,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002654 present_info->waitSemaphoreCount,
2655 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002656
Jesse Halla9e57032015-11-30 01:03:10 -08002657 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002658 present_info->pResults[sc] = swapchain_result;
2659
2660 if (swapchain_result != final_result)
2661 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002662 }
2663
2664 return final_result;
2665}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002666
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002667VKAPI_ATTR
2668VkResult GetRefreshCycleDurationGOOGLE(
2669 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002670 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002671 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002672 ATRACE_CALL();
2673
Ian Elliott62c48c92017-01-20 13:13:20 -07002674 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00002675 VkResult result = swapchain.get_refresh_duration(pDisplayTimingProperties->refreshDuration);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002676
2677 return result;
2678}
2679
2680VKAPI_ATTR
2681VkResult GetPastPresentationTimingGOOGLE(
2682 VkDevice,
2683 VkSwapchainKHR swapchain_handle,
2684 uint32_t* count,
2685 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002686 ATRACE_CALL();
2687
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002688 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002689 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2690 return VK_ERROR_OUT_OF_DATE_KHR;
2691 }
2692
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002693 ANativeWindow* window = swapchain.surface.window.get();
2694 VkResult result = VK_SUCCESS;
2695
2696 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002697 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002698 native_window_enable_frame_timestamps(window, true);
2699 swapchain.frame_timestamps_enabled = true;
2700 }
2701
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002702 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002703 // Get the latest ready timing count before copying, since the copied
2704 // timing info will be erased in copy_ready_timings function.
2705 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002706 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002707 // Check the *count here against the recorded ready timing count, since
2708 // *count can be overwritten per spec describes.
2709 if (*count < n) {
2710 result = VK_INCOMPLETE;
2711 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002712 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002713 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002714 }
2715
2716 return result;
2717}
2718
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002719VKAPI_ATTR
2720VkResult GetSwapchainStatusKHR(
2721 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002722 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002723 ATRACE_CALL();
2724
Chris Forbes4e18ba82017-01-20 12:50:17 +13002725 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002726 VkResult result = VK_SUCCESS;
2727
Chris Forbes4e18ba82017-01-20 12:50:17 +13002728 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2729 return VK_ERROR_OUT_OF_DATE_KHR;
2730 }
2731
Yiwei Zhanga885c062019-10-24 12:07:57 -07002732 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002733
2734 return result;
2735}
2736
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002737VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002738 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002739 uint32_t swapchainCount,
2740 const VkSwapchainKHR* pSwapchains,
2741 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002742 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002743
2744 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2745 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2746 if (!swapchain)
2747 continue;
2748
2749 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2750
2751 ANativeWindow* window = swapchain->surface.window.get();
2752
2753 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2754 const android_smpte2086_metadata smpteMetdata = {
2755 {vulkanMetadata.displayPrimaryRed.x,
2756 vulkanMetadata.displayPrimaryRed.y},
2757 {vulkanMetadata.displayPrimaryGreen.x,
2758 vulkanMetadata.displayPrimaryGreen.y},
2759 {vulkanMetadata.displayPrimaryBlue.x,
2760 vulkanMetadata.displayPrimaryBlue.y},
2761 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2762 vulkanMetadata.maxLuminance,
2763 vulkanMetadata.minLuminance};
2764 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2765
2766 const android_cta861_3_metadata cta8613Metadata = {
2767 vulkanMetadata.maxContentLightLevel,
2768 vulkanMetadata.maxFrameAverageLightLevel};
2769 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2770 }
2771
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002772 return;
2773}
2774
Yiwei Zhang0f475222019-04-11 19:38:00 -07002775static void InterceptBindImageMemory2(
2776 uint32_t bind_info_count,
2777 const VkBindImageMemoryInfo* bind_infos,
2778 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2779 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2780 out_native_buffers->clear();
2781 out_bind_infos->clear();
2782
2783 if (!bind_info_count)
2784 return;
2785
2786 std::unordered_set<uint32_t> intercepted_indexes;
2787
2788 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2789 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2790 bind_infos[idx].pNext);
2791 while (info &&
2792 info->sType !=
2793 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2794 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2795 info->pNext);
2796 }
2797
2798 if (!info)
2799 continue;
2800
2801 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2802 "swapchain handle must not be NULL");
2803 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2804 ALOG_ASSERT(
2805 info->imageIndex < swapchain->num_images,
2806 "imageIndex must be less than the number of images in swapchain");
2807
2808 ANativeWindowBuffer* buffer =
2809 swapchain->images[info->imageIndex].buffer.get();
2810 VkNativeBufferANDROID native_buffer = {
2811#pragma clang diagnostic push
2812#pragma clang diagnostic ignored "-Wold-style-cast"
2813 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2814#pragma clang diagnostic pop
2815 .pNext = bind_infos[idx].pNext,
2816 .handle = buffer->handle,
2817 .stride = buffer->stride,
2818 .format = buffer->format,
2819 .usage = int(buffer->usage),
Trevor David Black0db7a092023-12-11 23:46:36 +00002820 .usage3 = buffer->usage,
2821 .ahb = ANativeWindowBuffer_getHardwareBuffer(buffer),
Yiwei Zhang0f475222019-04-11 19:38:00 -07002822 };
Trevor David Black0db7a092023-12-11 23:46:36 +00002823 android_convertGralloc0To1Usage(int(buffer->usage),
2824 &native_buffer.usage2.producer,
2825 &native_buffer.usage2.consumer);
Yiwei Zhang0f475222019-04-11 19:38:00 -07002826 // Reserve enough space to avoid letting re-allocation invalidate the
2827 // addresses of the elements inside.
2828 out_native_buffers->reserve(bind_info_count);
2829 out_native_buffers->emplace_back(native_buffer);
2830
2831 // Reserve the space now since we know how much is needed now.
2832 out_bind_infos->reserve(bind_info_count);
2833 out_bind_infos->emplace_back(bind_infos[idx]);
2834 out_bind_infos->back().pNext = &out_native_buffers->back();
2835
2836 intercepted_indexes.insert(idx);
2837 }
2838
2839 if (intercepted_indexes.empty())
2840 return;
2841
2842 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2843 if (intercepted_indexes.count(idx))
2844 continue;
2845 out_bind_infos->emplace_back(bind_infos[idx]);
2846 }
2847}
2848
Yiwei Zhang23143102019-04-10 18:24:05 -07002849VKAPI_ATTR
2850VkResult BindImageMemory2(VkDevice device,
2851 uint32_t bindInfoCount,
2852 const VkBindImageMemoryInfo* pBindInfos) {
2853 ATRACE_CALL();
2854
Yiwei Zhang0f475222019-04-11 19:38:00 -07002855 // out_native_buffers is for maintaining the lifecycle of the constructed
2856 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2857 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.BindImageMemory2(
2862 device, bindInfoCount,
2863 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002864}
2865
2866VKAPI_ATTR
2867VkResult BindImageMemory2KHR(VkDevice device,
2868 uint32_t bindInfoCount,
2869 const VkBindImageMemoryInfo* pBindInfos) {
2870 ATRACE_CALL();
2871
Yiwei Zhang0f475222019-04-11 19:38:00 -07002872 std::vector<VkNativeBufferANDROID> out_native_buffers;
2873 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2874 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2875 &out_bind_infos);
2876 return GetData(device).driver.BindImageMemory2KHR(
2877 device, bindInfoCount,
2878 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002879}
2880
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002881VKAPI_ATTR
2882VkResult ReleaseSwapchainImagesEXT(VkDevice /*device*/,
2883 const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
2884 ATRACE_CALL();
2885
2886 Swapchain& swapchain = *SwapchainFromHandle(pReleaseInfo->swapchain);
2887 ANativeWindow* window = swapchain.surface.window.get();
2888
2889 // If in shared present mode, don't actually release the image back to the BQ.
2890 // Both sides share it forever.
2891 if (swapchain.shared)
2892 return VK_SUCCESS;
2893
2894 for (uint32_t i = 0; i < pReleaseInfo->imageIndexCount; i++) {
2895 Swapchain::Image& img = swapchain.images[pReleaseInfo->pImageIndices[i]];
2896 window->cancelBuffer(window, img.buffer.get(), img.dequeue_fence);
2897
2898 // cancelBuffer has taken ownership of the dequeue fence
2899 img.dequeue_fence = -1;
2900 // if we're still holding a release fence, get rid of it now
2901 if (img.release_fence >= 0) {
2902 close(img.release_fence);
2903 img.release_fence = -1;
2904 }
2905 img.dequeued = false;
2906 }
2907
2908 return VK_SUCCESS;
2909}
2910
Chia-I Wu62262232016-03-26 07:06:44 +08002911} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002912} // namespace vulkan