blob: 922a44fa05cf7f387f2b8dd9091ff50af8b4d852 [file] [log] [blame]
Jesse Hallb1352bc2015-09-04 16:12:33 -07001/*
2 * Copyright 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080017#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
Yiwei Zhang0f475222019-04-11 19:38:00 -070019#include <android/hardware/graphics/common/1.0/types.h>
Jesse Hall79927812017-03-23 11:03:23 -070020#include <grallocusage/GrallocUsageConversion.h>
Yiwei Zhang69395cd2019-07-03 16:55:39 -070021#include <graphicsenv/GraphicsEnv.h>
John Reck97678d42022-08-23 11:24:51 -040022#include <hardware/gralloc.h>
23#include <hardware/gralloc1.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070024#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070025#include <sync/sync.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070026#include <system/window.h>
27#include <ui/BufferQueueDefs.h>
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -050028#include <ui/DebugUtils.h>
29#include <ui/PixelFormat.h>
Chia-I Wue8e689f2016-04-18 08:21:31 +080030#include <utils/StrongPointer.h>
Yiwei Zhang705c2e62019-12-18 23:12:43 -080031#include <utils/Timers.h>
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080032#include <utils/Trace.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070033
34#include <algorithm>
35#include <unordered_set>
36#include <vector>
Jesse Halld7b994a2015-09-07 14:17:37 -070037
Chia-I Wu4a6a9162016-03-26 07:17:34 +080038#include "driver.h"
Jesse Halld7b994a2015-09-07 14:17:37 -070039
Daniel Kochf25f5bb2017-10-05 00:26:58 -040040using android::hardware::graphics::common::V1_0::BufferUsage;
41
Chia-I Wu62262232016-03-26 07:06:44 +080042namespace vulkan {
43namespace driver {
Jesse Hall5ae3abb2015-10-08 14:00:22 -070044
Jesse Halld7b994a2015-09-07 14:17:37 -070045namespace {
46
John Reck97678d42022-08-23 11:24:51 -040047static uint64_t convertGralloc1ToBufferUsage(uint64_t producerUsage,
48 uint64_t consumerUsage) {
49 static_assert(uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) ==
50 uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN),
51 "expected ConsumerUsage and ProducerUsage CPU_READ_OFTEN "
52 "bits to match");
53 uint64_t merged = producerUsage | consumerUsage;
54 if ((merged & (GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN)) ==
55 GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) {
56 merged &= ~uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN);
57 merged |= BufferUsage::CPU_READ_OFTEN;
58 }
59 if ((merged & (GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN)) ==
60 GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) {
61 merged &= ~uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN);
62 merged |= BufferUsage::CPU_WRITE_OFTEN;
63 }
64 return merged;
65}
66
Jesse Hall55bc0972016-02-23 16:43:29 -080067const VkSurfaceTransformFlagsKHR kSupportedTransforms =
68 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
69 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
70 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
71 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
Yiwei Zhang70a21962019-05-31 17:26:52 -070072 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
73 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
74 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
75 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
Jesse Hall55bc0972016-02-23 16:43:29 -080076 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
77
78VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
79 // Native and Vulkan transforms are isomorphic, but are represented
80 // differently. Vulkan transforms are built up of an optional horizontal
81 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
82 // transforms are built up from a horizontal flip, vertical flip, and
83 // 90-degree rotation, all optional but always in that order.
84
Jesse Hall55bc0972016-02-23 16:43:29 -080085 switch (native) {
Yiwei Zhang70a21962019-05-31 17:26:52 -070086 case 0:
Jesse Hall55bc0972016-02-23 16:43:29 -080087 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070088 case NATIVE_WINDOW_TRANSFORM_FLIP_H:
89 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
90 case NATIVE_WINDOW_TRANSFORM_FLIP_V:
91 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
92 case NATIVE_WINDOW_TRANSFORM_ROT_180:
Jesse Hall55bc0972016-02-23 16:43:29 -080093 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070094 case NATIVE_WINDOW_TRANSFORM_ROT_90:
Jesse Hall55bc0972016-02-23 16:43:29 -080095 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070096 case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
97 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
98 case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
99 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
100 case NATIVE_WINDOW_TRANSFORM_ROT_270:
Jesse Hall55bc0972016-02-23 16:43:29 -0800101 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
102 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
103 default:
104 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
105 }
106}
107
Yiwei Zhang70a21962019-05-31 17:26:52 -0700108int TranslateVulkanToNativeTransform(VkSurfaceTransformFlagBitsKHR transform) {
109 switch (transform) {
110 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
111 return NATIVE_WINDOW_TRANSFORM_ROT_90;
112 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
113 return NATIVE_WINDOW_TRANSFORM_ROT_180;
114 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
115 return NATIVE_WINDOW_TRANSFORM_ROT_270;
116 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
117 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
118 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
119 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
120 NATIVE_WINDOW_TRANSFORM_ROT_90;
121 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
122 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
123 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
124 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
125 NATIVE_WINDOW_TRANSFORM_ROT_90;
126 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
127 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
128 default:
129 return 0;
130 }
131}
132
Jesse Hall178b6962016-02-24 15:39:50 -0800133int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
134 switch (transform) {
135 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
136 return NATIVE_WINDOW_TRANSFORM_ROT_270;
137 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
138 return NATIVE_WINDOW_TRANSFORM_ROT_180;
139 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
140 return NATIVE_WINDOW_TRANSFORM_ROT_90;
Yiwei Zhang70a21962019-05-31 17:26:52 -0700141 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
142 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
143 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
144 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
145 NATIVE_WINDOW_TRANSFORM_ROT_90;
146 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
147 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
148 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
149 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
150 NATIVE_WINDOW_TRANSFORM_ROT_90;
Jesse Hall178b6962016-02-24 15:39:50 -0800151 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
152 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
153 default:
154 return 0;
155 }
156}
157
Ian Elliott8a977262017-01-19 09:05:58 -0700158class TimingInfo {
159 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800160 TimingInfo(const VkPresentTimeGOOGLE* qp, uint64_t nativeFrameId)
Ian Elliott2c6355d2017-01-19 11:02:13 -0700161 : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
Brian Anderson1049d1d2016-12-16 17:25:57 -0800162 native_frame_id_(nativeFrameId) {}
163 bool ready() const {
Brian Andersondc96fdf2017-03-20 16:54:25 -0700164 return (timestamp_desired_present_time_ !=
165 NATIVE_WINDOW_TIMESTAMP_PENDING &&
166 timestamp_actual_present_time_ !=
167 NATIVE_WINDOW_TIMESTAMP_PENDING &&
168 timestamp_render_complete_time_ !=
169 NATIVE_WINDOW_TIMESTAMP_PENDING &&
170 timestamp_composition_latch_time_ !=
171 NATIVE_WINDOW_TIMESTAMP_PENDING);
Ian Elliott8a977262017-01-19 09:05:58 -0700172 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700173 void calculate(int64_t rdur) {
174 bool anyTimestampInvalid =
175 (timestamp_actual_present_time_ ==
176 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
177 (timestamp_render_complete_time_ ==
178 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
179 (timestamp_composition_latch_time_ ==
180 NATIVE_WINDOW_TIMESTAMP_INVALID);
181 if (anyTimestampInvalid) {
182 ALOGE("Unexpectedly received invalid timestamp.");
183 vals_.actualPresentTime = 0;
184 vals_.earliestPresentTime = 0;
185 vals_.presentMargin = 0;
186 return;
187 }
188
189 vals_.actualPresentTime =
190 static_cast<uint64_t>(timestamp_actual_present_time_);
191 int64_t margin = (timestamp_composition_latch_time_ -
Ian Elliott8a977262017-01-19 09:05:58 -0700192 timestamp_render_complete_time_);
193 // Calculate vals_.earliestPresentTime, and potentially adjust
194 // vals_.presentMargin. The initial value of vals_.earliestPresentTime
195 // is vals_.actualPresentTime. If we can subtract rdur (the duration
196 // of a refresh cycle) from vals_.earliestPresentTime (and also from
197 // vals_.presentMargin) and still leave a positive margin, then we can
198 // report to the application that it could have presented earlier than
199 // it did (per the extension specification). If for some reason, we
200 // can do this subtraction repeatedly, we do, since
201 // vals_.earliestPresentTime really is supposed to be the "earliest".
Brian Andersondc96fdf2017-03-20 16:54:25 -0700202 int64_t early_time = timestamp_actual_present_time_;
Ian Elliott8a977262017-01-19 09:05:58 -0700203 while ((margin > rdur) &&
204 ((early_time - rdur) > timestamp_composition_latch_time_)) {
205 early_time -= rdur;
206 margin -= rdur;
207 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700208 vals_.earliestPresentTime = static_cast<uint64_t>(early_time);
209 vals_.presentMargin = static_cast<uint64_t>(margin);
Ian Elliott8a977262017-01-19 09:05:58 -0700210 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800211 void get_values(VkPastPresentationTimingGOOGLE* values) const {
212 *values = vals_;
213 }
Ian Elliott8a977262017-01-19 09:05:58 -0700214
215 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800216 VkPastPresentationTimingGOOGLE vals_ { 0, 0, 0, 0, 0 };
Ian Elliott8a977262017-01-19 09:05:58 -0700217
Brian Anderson1049d1d2016-12-16 17:25:57 -0800218 uint64_t native_frame_id_ { 0 };
Brian Andersondc96fdf2017-03-20 16:54:25 -0700219 int64_t timestamp_desired_present_time_{ NATIVE_WINDOW_TIMESTAMP_PENDING };
220 int64_t timestamp_actual_present_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
221 int64_t timestamp_render_complete_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
222 int64_t timestamp_composition_latch_time_
223 { NATIVE_WINDOW_TIMESTAMP_PENDING };
Ian Elliott8a977262017-01-19 09:05:58 -0700224};
225
Jesse Hall1356b0d2015-11-23 17:24:58 -0800226struct Surface {
Chia-I Wue8e689f2016-04-18 08:21:31 +0800227 android::sp<ANativeWindow> window;
Jesse Halldc225072016-05-30 22:40:14 -0700228 VkSwapchainKHR swapchain_handle;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700229 uint64_t consumer_usage;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800230};
231
232VkSurfaceKHR HandleFromSurface(Surface* surface) {
233 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
234}
235
236Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800237 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800238}
239
Ian Elliott8a977262017-01-19 09:05:58 -0700240// Maximum number of TimingInfo structs to keep per swapchain:
241enum { MAX_TIMING_INFOS = 10 };
242// Minimum number of frames to look for in the past (so we don't cause
243// syncronous requests to Surface Flinger):
244enum { MIN_NUM_FRAMES_AGO = 5 };
245
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300246bool IsSharedPresentMode(VkPresentModeKHR mode) {
247 return mode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
248 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR;
249}
250
Jesse Hall1356b0d2015-11-23 17:24:58 -0800251struct Swapchain {
Ian Elliottffedb652017-02-14 10:58:30 -0700252 Swapchain(Surface& surface_,
253 uint32_t num_images_,
silence_dogood73597592019-05-23 16:57:37 -0700254 VkPresentModeKHR present_mode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000255 int pre_transform_,
256 int64_t refresh_duration_)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700257 : surface(surface_),
258 num_images(num_images_),
Ian Elliottffedb652017-02-14 10:58:30 -0700259 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
silence_dogood73597592019-05-23 16:57:37 -0700260 pre_transform(pre_transform_),
Chris Forbesf8835642017-03-30 19:31:40 +1300261 frame_timestamps_enabled(false),
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000262 refresh_duration(refresh_duration_),
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800263 acquire_next_image_timeout(-1),
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300264 shared(IsSharedPresentMode(present_mode)) {
Ian Elliott8a977262017-01-19 09:05:58 -0700265 }
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000266
267 VkResult get_refresh_duration(uint64_t& outRefreshDuration)
Ian Elliott3568bfe2019-05-03 15:54:46 -0600268 {
269 ANativeWindow* window = surface.window.get();
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000270 int err = native_window_get_refresh_cycle_duration(
Ian Elliott3568bfe2019-05-03 15:54:46 -0600271 window,
272 &refresh_duration);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +0000273 if (err != android::OK) {
274 ALOGE("%s:native_window_get_refresh_cycle_duration failed: %s (%d)",
275 __func__, strerror(-err), err );
276 return VK_ERROR_SURFACE_LOST_KHR;
277 }
278 outRefreshDuration = refresh_duration;
279 return VK_SUCCESS;
Ian Elliott3568bfe2019-05-03 15:54:46 -0600280 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800281
282 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700283 uint32_t num_images;
Ian Elliottffedb652017-02-14 10:58:30 -0700284 bool mailbox_mode;
silence_dogood73597592019-05-23 16:57:37 -0700285 int pre_transform;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700286 bool frame_timestamps_enabled;
Brian Andersondc96fdf2017-03-20 16:54:25 -0700287 int64_t refresh_duration;
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800288 nsecs_t acquire_next_image_timeout;
Chris Forbesf8835642017-03-30 19:31:40 +1300289 bool shared;
Jesse Halld7b994a2015-09-07 14:17:37 -0700290
291 struct Image {
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700292 Image()
293 : image(VK_NULL_HANDLE),
294 dequeue_fence(-1),
295 release_fence(-1),
296 dequeued(false) {}
Jesse Halld7b994a2015-09-07 14:17:37 -0700297 VkImage image;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000298 // If the image is bound to memory, an sp to the underlying gralloc buffer.
299 // Otherwise, nullptr; the image will be bound to memory as part of
300 // AcquireNextImage.
Chia-I Wue8e689f2016-04-18 08:21:31 +0800301 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700302 // The fence is only valid when the buffer is dequeued, and should be
303 // -1 any other time. When valid, we own the fd, and must ensure it is
304 // closed: either by closing it explicitly when queueing the buffer,
305 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
306 int dequeue_fence;
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700307 // This fence is a dup of the sync fd returned from the driver via
308 // vkQueueSignalReleaseImageANDROID upon vkQueuePresentKHR. We must
309 // ensure it is closed upon re-presenting or releasing the image.
310 int release_fence;
Jesse Halld7b994a2015-09-07 14:17:37 -0700311 bool dequeued;
Pawin Vongmasa6e1193a2017-03-07 13:08:40 -0800312 } images[android::BufferQueueDefs::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700313
Yiwei Zhang5e862202019-06-21 14:59:16 -0700314 std::vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700315};
316
317VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
318 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
319}
320
321Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800322 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700323}
324
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700325static bool IsFencePending(int fd) {
326 if (fd < 0)
327 return false;
328
329 errno = 0;
330 return sync_wait(fd, 0 /* timeout */) == -1 && errno == ETIME;
331}
332
Jesse Halldc225072016-05-30 22:40:14 -0700333void ReleaseSwapchainImage(VkDevice device,
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000334 bool shared_present,
Jesse Halldc225072016-05-30 22:40:14 -0700335 ANativeWindow* window,
336 int release_fence,
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700337 Swapchain::Image& image,
338 bool defer_if_pending) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700339 ATRACE_CALL();
340
Jesse Halldc225072016-05-30 22:40:14 -0700341 ALOG_ASSERT(release_fence == -1 || image.dequeued,
342 "ReleaseSwapchainImage: can't provide a release fence for "
343 "non-dequeued images");
344
345 if (image.dequeued) {
346 if (release_fence >= 0) {
347 // We get here from vkQueuePresentKHR. The application is
348 // responsible for creating an execution dependency chain from
349 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
350 // (release_fence), so we can drop the dequeue_fence here.
351 if (image.dequeue_fence >= 0)
352 close(image.dequeue_fence);
353 } else {
354 // We get here during swapchain destruction, or various serious
355 // error cases e.g. when we can't create the release_fence during
356 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
357 // have already signalled, since the swapchain images are supposed
358 // to be idle before the swapchain is destroyed. In error cases,
359 // there may be rendering in flight to the image, but since we
360 // weren't able to create a release_fence, waiting for the
361 // dequeue_fence is about the best we can do.
362 release_fence = image.dequeue_fence;
363 }
364 image.dequeue_fence = -1;
365
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000366 // It's invalid to call cancelBuffer on a shared buffer
367 if (window && !shared_present) {
Jesse Halldc225072016-05-30 22:40:14 -0700368 window->cancelBuffer(window, image.buffer.get(), release_fence);
369 } else {
370 if (release_fence >= 0) {
371 sync_wait(release_fence, -1 /* forever */);
372 close(release_fence);
373 }
374 }
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700375 release_fence = -1;
Jesse Halldc225072016-05-30 22:40:14 -0700376 image.dequeued = false;
377 }
378
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700379 if (defer_if_pending && IsFencePending(image.release_fence))
380 return;
381
382 if (image.release_fence >= 0) {
383 close(image.release_fence);
384 image.release_fence = -1;
385 }
386
Jesse Halldc225072016-05-30 22:40:14 -0700387 if (image.image) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700388 ATRACE_BEGIN("DestroyImage");
Jesse Halldc225072016-05-30 22:40:14 -0700389 GetData(device).driver.DestroyImage(device, image.image, nullptr);
Yiwei Zhang533cea92019-06-03 18:43:24 -0700390 ATRACE_END();
Jesse Halldc225072016-05-30 22:40:14 -0700391 image.image = VK_NULL_HANDLE;
392 }
393
394 image.buffer.clear();
395}
396
397void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
398 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
399 return;
Jesse Halldc225072016-05-30 22:40:14 -0700400 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000401 if (!swapchain->images[i].dequeued) {
402 ReleaseSwapchainImage(device, swapchain->shared, nullptr, -1,
403 swapchain->images[i], true);
404 }
Jesse Halldc225072016-05-30 22:40:14 -0700405 }
406 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700407 swapchain->timing.clear();
408}
409
410uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800411 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
412 return 0;
413 }
Ian Elliott8a977262017-01-19 09:05:58 -0700414
Brian Anderson1049d1d2016-12-16 17:25:57 -0800415 uint32_t num_ready = 0;
416 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
417 for (uint32_t i = 0; i < num_timings; i++) {
Yiwei Zhang5e862202019-06-21 14:59:16 -0700418 TimingInfo& ti = swapchain.timing[i];
Brian Anderson1049d1d2016-12-16 17:25:57 -0800419 if (ti.ready()) {
420 // This TimingInfo is ready to be reported to the user. Add it
421 // to the num_ready.
422 num_ready++;
423 continue;
424 }
425 // This TimingInfo is not yet ready to be reported to the user,
426 // and so we should look for any available timestamps that
427 // might make it ready.
428 int64_t desired_present_time = 0;
429 int64_t render_complete_time = 0;
430 int64_t composition_latch_time = 0;
431 int64_t actual_present_time = 0;
432 // Obtain timestamps:
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800433 int err = native_window_get_frame_timestamps(
Brian Anderson1049d1d2016-12-16 17:25:57 -0800434 swapchain.surface.window.get(), ti.native_frame_id_,
435 &desired_present_time, &render_complete_time,
436 &composition_latch_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700437 nullptr, //&first_composition_start_time,
438 nullptr, //&last_composition_start_time,
439 nullptr, //&composition_finish_time,
Brian Anderson1049d1d2016-12-16 17:25:57 -0800440 &actual_present_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700441 nullptr, //&dequeue_ready_time,
442 nullptr /*&reads_done_time*/);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800443
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800444 if (err != android::OK) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800445 continue;
446 }
447
448 // Record the timestamp(s) we received, and then see if this TimingInfo
449 // is ready to be reported to the user:
Brian Andersondc96fdf2017-03-20 16:54:25 -0700450 ti.timestamp_desired_present_time_ = desired_present_time;
451 ti.timestamp_actual_present_time_ = actual_present_time;
452 ti.timestamp_render_complete_time_ = render_complete_time;
453 ti.timestamp_composition_latch_time_ = composition_latch_time;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800454
455 if (ti.ready()) {
456 // The TimingInfo has received enough timestamps, and should now
457 // use those timestamps to calculate the info that should be
458 // reported to the user:
459 ti.calculate(swapchain.refresh_duration);
460 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700461 }
462 }
463 return num_ready;
464}
465
Ian Elliott8a977262017-01-19 09:05:58 -0700466void copy_ready_timings(Swapchain& swapchain,
467 uint32_t* count,
468 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800469 if (swapchain.timing.empty()) {
470 *count = 0;
471 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700472 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800473
474 size_t last_ready = swapchain.timing.size() - 1;
475 while (!swapchain.timing[last_ready].ready()) {
476 if (last_ready == 0) {
477 *count = 0;
478 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700479 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800480 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700481 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800482
483 uint32_t num_copied = 0;
Yiwei Zhang5e862202019-06-21 14:59:16 -0700484 int32_t num_to_remove = 0;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800485 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
486 const TimingInfo& ti = swapchain.timing[i];
487 if (ti.ready()) {
488 ti.get_values(&timings[num_copied]);
489 num_copied++;
490 }
491 num_to_remove++;
492 }
493
494 // Discard old frames that aren't ready if newer frames are ready.
495 // We don't expect to get the timing info for those old frames.
Yiwei Zhang5e862202019-06-21 14:59:16 -0700496 swapchain.timing.erase(swapchain.timing.begin(),
497 swapchain.timing.begin() + num_to_remove);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800498
Ian Elliott8a977262017-01-19 09:05:58 -0700499 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700500}
501
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500502android::PixelFormat GetNativePixelFormat(VkFormat format) {
503 android::PixelFormat native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700504 switch (format) {
505 case VK_FORMAT_R8G8B8A8_UNORM:
506 case VK_FORMAT_R8G8B8A8_SRGB:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500507 native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700508 break;
509 case VK_FORMAT_R5G6B5_UNORM_PACK16:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500510 native_format = android::PIXEL_FORMAT_RGB_565;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700511 break;
512 case VK_FORMAT_R16G16B16A16_SFLOAT:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500513 native_format = android::PIXEL_FORMAT_RGBA_FP16;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700514 break;
Yiwei Zhangc1ea8152019-02-05 15:11:32 -0800515 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500516 native_format = android::PIXEL_FORMAT_RGBA_1010102;
517 break;
518 case VK_FORMAT_R8_UNORM:
519 native_format = android::PIXEL_FORMAT_R_8;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700520 break;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000521 case VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
522 native_format = android::PIXEL_FORMAT_RGBA_10101010;
523 break;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700524 default:
525 ALOGV("unsupported swapchain format %d", format);
526 break;
527 }
528 return native_format;
529}
530
531android_dataspace GetNativeDataspace(VkColorSpaceKHR colorspace) {
532 switch (colorspace) {
533 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
534 return HAL_DATASPACE_V0_SRGB;
535 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
536 return HAL_DATASPACE_DISPLAY_P3;
537 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
538 return HAL_DATASPACE_V0_SCRGB_LINEAR;
Courtney Goeltzenleuchterb52abee2017-08-07 17:13:04 -0600539 case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT:
540 return HAL_DATASPACE_V0_SCRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700541 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
542 return HAL_DATASPACE_DCI_P3_LINEAR;
543 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
544 return HAL_DATASPACE_DCI_P3;
545 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
546 return HAL_DATASPACE_V0_SRGB_LINEAR;
547 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
548 return HAL_DATASPACE_V0_SRGB;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600549 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
550 return HAL_DATASPACE_BT2020_LINEAR;
551 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700552 return static_cast<android_dataspace>(
553 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
554 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600555 case VK_COLOR_SPACE_DOLBYVISION_EXT:
556 return static_cast<android_dataspace>(
557 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
558 HAL_DATASPACE_RANGE_FULL);
559 case VK_COLOR_SPACE_HDR10_HLG_EXT:
560 return static_cast<android_dataspace>(
561 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_HLG |
562 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700563 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
564 return static_cast<android_dataspace>(
565 HAL_DATASPACE_STANDARD_ADOBE_RGB |
566 HAL_DATASPACE_TRANSFER_LINEAR | HAL_DATASPACE_RANGE_FULL);
567 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
568 return HAL_DATASPACE_ADOBE_RGB;
569
570 // Pass through is intended to allow app to provide data that is passed
571 // to the display system without modification.
572 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
573 return HAL_DATASPACE_ARBITRARY;
574
575 default:
576 // This indicates that we don't know about the
577 // dataspace specified and we should indicate that
578 // it's unsupported
579 return HAL_DATASPACE_UNKNOWN;
580 }
581}
582
Jesse Halld7b994a2015-09-07 14:17:37 -0700583} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700584
Jesse Halle1b12782015-11-30 11:27:32 -0800585VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800586VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800587 VkInstance instance,
588 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
589 const VkAllocationCallbacks* allocator,
590 VkSurfaceKHR* out_surface) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800591 ATRACE_CALL();
592
Jesse Hall1f91d392015-12-11 16:28:44 -0800593 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800594 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800595 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
596 alignof(Surface),
597 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800598 if (!mem)
599 return VK_ERROR_OUT_OF_HOST_MEMORY;
600 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700601
Chia-I Wue8e689f2016-04-18 08:21:31 +0800602 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700603 surface->swapchain_handle = VK_NULL_HANDLE;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700604 int err = native_window_get_consumer_usage(surface->window.get(),
605 &surface->consumer_usage);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800606 if (err != android::OK) {
Yiwei Zhang6435b322018-05-08 11:12:17 -0700607 ALOGE("native_window_get_consumer_usage() failed: %s (%d)",
608 strerror(-err), err);
609 surface->~Surface();
610 allocator->pfnFree(allocator->pUserData, surface);
Yiwei Zhang70a21962019-05-31 17:26:52 -0700611 return VK_ERROR_SURFACE_LOST_KHR;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700612 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700613
Yiwei Zhang6435b322018-05-08 11:12:17 -0700614 err =
Jesse Hall1356b0d2015-11-23 17:24:58 -0800615 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800616 if (err != android::OK) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800617 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
618 err);
619 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800620 allocator->pfnFree(allocator->pUserData, surface);
Mike Stroyan762c8132017-02-22 11:43:09 -0700621 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800622 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700623
Jesse Hall1356b0d2015-11-23 17:24:58 -0800624 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700625 return VK_SUCCESS;
626}
627
Jesse Halle1b12782015-11-30 11:27:32 -0800628VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800629void DestroySurfaceKHR(VkInstance instance,
630 VkSurfaceKHR surface_handle,
631 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800632 ATRACE_CALL();
633
Jesse Hall1356b0d2015-11-23 17:24:58 -0800634 Surface* surface = SurfaceFromHandle(surface_handle);
635 if (!surface)
636 return;
637 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700638 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700639 "destroyed VkSurfaceKHR 0x%" PRIx64
640 " has active VkSwapchainKHR 0x%" PRIx64,
641 reinterpret_cast<uint64_t>(surface_handle),
642 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800643 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800644 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800645 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800646 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800647}
648
Jesse Halle1b12782015-11-30 11:27:32 -0800649VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800650VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
651 uint32_t /*queue_family*/,
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000652 VkSurfaceKHR /*surface_handle*/,
Chia-I Wu62262232016-03-26 07:06:44 +0800653 VkBool32* supported) {
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000654 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800655 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800656}
657
Jesse Halle1b12782015-11-30 11:27:32 -0800658VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800659VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Ian Elliott1ce053f2022-03-16 09:49:53 -0600660 VkPhysicalDevice pdev,
Jesse Hallb00daad2015-11-29 19:46:20 -0800661 VkSurfaceKHR surface,
662 VkSurfaceCapabilitiesKHR* capabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800663 ATRACE_CALL();
664
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000665 // Implement in terms of GetPhysicalDeviceSurfaceCapabilities2KHR
666
667 VkPhysicalDeviceSurfaceInfo2KHR info2 = {
668 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
669 nullptr,
670 surface
671 };
672
673 VkSurfaceCapabilities2KHR caps2 = {
674 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
675 nullptr,
676 {},
677 };
678
679 VkResult result = GetPhysicalDeviceSurfaceCapabilities2KHR(pdev, &info2, &caps2);
680 *capabilities = caps2.surfaceCapabilities;
681 return result;
682}
683
684// Does the call-twice and VK_INCOMPLETE handling for querying lists
685// of things, where we already have the full set built in a vector.
686template <typename T>
687VkResult CopyWithIncomplete(std::vector<T> const& things,
688 T* callerPtr, uint32_t* callerCount) {
689 VkResult result = VK_SUCCESS;
690 if (callerPtr) {
691 if (things.size() > *callerCount)
692 result = VK_INCOMPLETE;
693 *callerCount = std::min(uint32_t(things.size()), *callerCount);
694 std::copy(things.begin(), things.begin() + *callerCount, callerPtr);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600695 } else {
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000696 *callerCount = things.size();
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800697 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000698 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700699}
700
Jesse Halle1b12782015-11-30 11:27:32 -0800701VKAPI_ATTR
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700702VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
703 VkSurfaceKHR surface_handle,
Chia-I Wu62262232016-03-26 07:06:44 +0800704 uint32_t* count,
705 VkSurfaceFormatKHR* formats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800706 ATRACE_CALL();
707
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700708 const InstanceData& instance_data = GetData(pdev);
709
Ian Elliott1ce053f2022-03-16 09:49:53 -0600710 uint64_t consumer_usage = 0;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000711 bool colorspace_ext =
Ian Elliottf6df08e2022-03-16 21:27:49 -0600712 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600713 if (surface_handle == VK_NULL_HANDLE) {
714 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
715 bool surfaceless_enabled =
716 instance_data.hook_extensions.test(surfaceless);
717 if (!surfaceless_enabled) {
718 return VK_ERROR_SURFACE_LOST_KHR;
719 }
Chris Forbesb1de3b12022-10-20 09:05:48 +1300720 // Support for VK_GOOGLE_surfaceless_query.
Ian Elliott1ce053f2022-03-16 09:49:53 -0600721
722 // TODO(b/203826952): research proper value; temporarily use the
723 // values seen on Pixel
724 consumer_usage = AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
725 } else {
726 Surface& surface = *SurfaceFromHandle(surface_handle);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600727 consumer_usage = surface.consumer_usage;
Ian Elliott6ba85d92022-02-18 16:44:58 -0700728 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700729
Charlie Lao324191f2019-12-13 11:03:16 -0800730 AHardwareBuffer_Desc desc = {};
731 desc.width = 1;
732 desc.height = 1;
733 desc.layers = 1;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600734 desc.usage = consumer_usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
Charlie Lao324191f2019-12-13 11:03:16 -0800735 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
736
737 // We must support R8G8B8A8
738 std::vector<VkSurfaceFormatKHR> all_formats = {
739 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000740 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000741 };
Charlie Lao324191f2019-12-13 11:03:16 -0800742
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000743 if (colorspace_ext) {
744 all_formats.emplace_back(VkSurfaceFormatKHR{
Jason Macnakca506332022-11-09 11:00:36 -0800745 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
746 all_formats.emplace_back(VkSurfaceFormatKHR{
747 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_PASS_THROUGH_EXT});
748 all_formats.emplace_back(VkSurfaceFormatKHR{
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000749 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_BT709_LINEAR_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800750 all_formats.emplace_back(VkSurfaceFormatKHR{
751 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
752 all_formats.emplace_back(VkSurfaceFormatKHR{
753 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
754 }
755
Ian Elliott1ce053f2022-03-16 09:49:53 -0600756 // NOTE: Any new formats that are added must be coordinated across different
757 // Android users. This includes the ANGLE team (a layered implementation of
758 // OpenGL-ES).
759
Charlie Lao324191f2019-12-13 11:03:16 -0800760 desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
761 if (AHardwareBuffer_isSupported(&desc)) {
762 all_formats.emplace_back(VkSurfaceFormatKHR{
763 VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800764 if (colorspace_ext) {
765 all_formats.emplace_back(
766 VkSurfaceFormatKHR{VK_FORMAT_R5G6B5_UNORM_PACK16,
767 VK_COLOR_SPACE_PASS_THROUGH_EXT});
768 }
Charlie Lao324191f2019-12-13 11:03:16 -0800769 }
770
771 desc.format = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
772 if (AHardwareBuffer_isSupported(&desc)) {
773 all_formats.emplace_back(VkSurfaceFormatKHR{
774 VK_FORMAT_R16G16B16A16_SFLOAT, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800775 if (colorspace_ext) {
776 all_formats.emplace_back(
777 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
778 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800779 all_formats.emplace_back(
780 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
781 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT});
782 all_formats.emplace_back(
783 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
784 VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT});
785 }
786 }
787
788 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
789 if (AHardwareBuffer_isSupported(&desc)) {
790 all_formats.emplace_back(
791 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
792 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800793 if (colorspace_ext) {
794 all_formats.emplace_back(
795 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
796 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800797 all_formats.emplace_back(
798 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
799 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
800 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700801 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700802
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500803 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
804 if (AHardwareBuffer_isSupported(&desc)) {
Jason Macnakca506332022-11-09 11:00:36 -0800805 if (colorspace_ext) {
806 all_formats.emplace_back(VkSurfaceFormatKHR{
807 VK_FORMAT_R8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
808 }
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500809 }
810
Trevor David Black67e9b102023-03-07 05:28:15 +0000811 bool rgba10x6_formats_ext = false;
812 uint32_t exts_count;
813 const auto& driver = GetData(pdev).driver;
814 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
815 nullptr);
816 std::vector<VkExtensionProperties> props(exts_count);
817 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
818 props.data());
819 for (uint32_t i = 0; i < exts_count; i++) {
820 VkExtensionProperties prop = props[i];
821 if (strcmp(prop.extensionName,
822 VK_EXT_RGBA10X6_FORMATS_EXTENSION_NAME) == 0) {
823 rgba10x6_formats_ext = true;
824 }
825 }
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000826 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM;
Trevor David Black67e9b102023-03-07 05:28:15 +0000827 if (AHardwareBuffer_isSupported(&desc) && rgba10x6_formats_ext) {
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000828 all_formats.emplace_back(
829 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
830 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
831 if (colorspace_ext) {
832 all_formats.emplace_back(
833 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
834 VK_COLOR_SPACE_PASS_THROUGH_EXT});
835 all_formats.emplace_back(
836 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
837 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
838 }
839 }
840
Ian Elliott6ba85d92022-02-18 16:44:58 -0700841 // NOTE: Any new formats that are added must be coordinated across different
842 // Android users. This includes the ANGLE team (a layered implementation of
843 // OpenGL-ES).
844
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000845 return CopyWithIncomplete(all_formats, formats, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700846}
847
Jesse Halle1b12782015-11-30 11:27:32 -0800848VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300849VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
850 VkPhysicalDevice physicalDevice,
851 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
852 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800853 ATRACE_CALL();
854
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000855 auto surface = pSurfaceInfo->surface;
856 auto capabilities = &pSurfaceCapabilities->surfaceCapabilities;
Chris Forbes2452cf72017-03-16 16:30:17 +1300857
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000858 VkSurfacePresentModeEXT const *pPresentMode = nullptr;
859 for (auto pNext = reinterpret_cast<VkBaseInStructure const *>(pSurfaceInfo->pNext);
860 pNext; pNext = reinterpret_cast<VkBaseInStructure const *>(pNext->pNext)) {
861 switch (pNext->sType) {
862 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT:
863 pPresentMode = reinterpret_cast<VkSurfacePresentModeEXT const *>(pNext);
864 break;
Chris Forbes06bc0092017-03-16 16:46:05 +1300865
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000866 default:
867 break;
868 }
869 }
870
871 int err;
872 int width, height;
873 int transform_hint;
874 int max_buffer_count;
875 if (surface == VK_NULL_HANDLE) {
876 const InstanceData& instance_data = GetData(physicalDevice);
877 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
878 bool surfaceless_enabled =
879 instance_data.hook_extensions.test(surfaceless);
880 if (!surfaceless_enabled) {
881 // It is an error to pass a surface==VK_NULL_HANDLE unless the
882 // VK_GOOGLE_surfaceless_query extension is enabled
883 return VK_ERROR_SURFACE_LOST_KHR;
884 }
885 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
886 // extension for this function is for
887 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
888 // four values cannot be known without a surface. Default values will
889 // be supplied anyway, but cannot be relied upon.
890 width = 0xFFFFFFFF;
891 height = 0xFFFFFFFF;
892 transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
893 capabilities->minImageCount = 0xFFFFFFFF;
894 capabilities->maxImageCount = 0xFFFFFFFF;
895 } else {
896 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
897
898 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
899 if (err != android::OK) {
900 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
901 strerror(-err), err);
902 return VK_ERROR_SURFACE_LOST_KHR;
903 }
904 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
905 if (err != android::OK) {
906 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
907 strerror(-err), err);
908 return VK_ERROR_SURFACE_LOST_KHR;
909 }
910
911 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
912 &transform_hint);
913 if (err != android::OK) {
914 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
915 strerror(-err), err);
916 return VK_ERROR_SURFACE_LOST_KHR;
917 }
918
919 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
920 &max_buffer_count);
921 if (err != android::OK) {
922 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
923 strerror(-err), err);
924 return VK_ERROR_SURFACE_LOST_KHR;
925 }
926
927 if (pPresentMode && IsSharedPresentMode(pPresentMode->presentMode)) {
928 capabilities->minImageCount = 1;
929 capabilities->maxImageCount = 1;
930 } else if (pPresentMode && pPresentMode->presentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
931 // TODO: use undequeued buffer requirement for more precise bound
932 capabilities->minImageCount = std::min(max_buffer_count, 4);
933 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
934 } else {
935 // TODO: if we're able to, provide better bounds on the number of buffers
936 // for other modes as well.
937 capabilities->minImageCount = std::min(max_buffer_count, 3);
938 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
939 }
940 }
941
942 capabilities->currentExtent =
943 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
944
945 // TODO(http://b/134182502): Figure out what the max extent should be.
946 capabilities->minImageExtent = VkExtent2D{1, 1};
947 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
948
949 if (capabilities->maxImageExtent.height <
950 capabilities->currentExtent.height) {
951 capabilities->maxImageExtent.height =
952 capabilities->currentExtent.height;
953 }
954
955 if (capabilities->maxImageExtent.width <
956 capabilities->currentExtent.width) {
957 capabilities->maxImageExtent.width = capabilities->currentExtent.width;
958 }
959
960 capabilities->maxImageArrayLayers = 1;
961
962 capabilities->supportedTransforms = kSupportedTransforms;
963 capabilities->currentTransform =
964 TranslateNativeToVulkanTransform(transform_hint);
965
966 // On Android, window composition is a WindowManager property, not something
967 // associated with the bufferqueue. It can't be changed from here.
968 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
969
970 capabilities->supportedUsageFlags =
971 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
972 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
973 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
974 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
975
976 for (auto pNext = reinterpret_cast<VkBaseOutStructure*>(pSurfaceCapabilities->pNext);
977 pNext; pNext = reinterpret_cast<VkBaseOutStructure*>(pNext->pNext)) {
978
979 switch (pNext->sType) {
Chris Forbes06bc0092017-03-16 16:46:05 +1300980 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
981 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000982 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(pNext);
Chris Forbes06bc0092017-03-16 16:46:05 +1300983 // Claim same set of usage flags are supported for
984 // shared present modes as for other modes.
985 shared_caps->sharedPresentSupportedUsageFlags =
986 pSurfaceCapabilities->surfaceCapabilities
987 .supportedUsageFlags;
988 } break;
989
Ian Elliottbb67b242022-03-16 09:52:28 -0600990 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
991 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000992 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(pNext);
Ian Elliottbb67b242022-03-16 09:52:28 -0600993 protected_caps->supportsProtected = VK_TRUE;
994 } break;
995
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000996 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_SCALING_CAPABILITIES_EXT: {
997 VkSurfacePresentScalingCapabilitiesEXT* scaling_caps =
998 reinterpret_cast<VkSurfacePresentScalingCapabilitiesEXT*>(pNext);
999 // By default, Android stretches the buffer to fit the window,
1000 // without preserving aspect ratio. Other modes are technically possible
1001 // but consult with CoGS team before exposing them here!
1002 scaling_caps->supportedPresentScaling = VK_PRESENT_SCALING_STRETCH_BIT_EXT;
1003
1004 // Since we always scale, we don't support any gravity.
1005 scaling_caps->supportedPresentGravityX = 0;
1006 scaling_caps->supportedPresentGravityY = 0;
1007
1008 // Scaled image limits are just the basic image limits
1009 scaling_caps->minScaledImageExtent = capabilities->minImageExtent;
1010 scaling_caps->maxScaledImageExtent = capabilities->maxImageExtent;
1011 } break;
1012
1013 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT: {
1014 VkSurfacePresentModeCompatibilityEXT* mode_caps =
1015 reinterpret_cast<VkSurfacePresentModeCompatibilityEXT*>(pNext);
1016
1017 ALOG_ASSERT(pPresentMode,
1018 "querying VkSurfacePresentModeCompatibilityEXT "
1019 "requires VkSurfacePresentModeEXT to be provided");
1020 std::vector<VkPresentModeKHR> compatibleModes;
1021 compatibleModes.push_back(pPresentMode->presentMode);
1022
1023 switch (pPresentMode->presentMode) {
1024 // Shared modes are both compatible with each other.
1025 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
1026 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
1027 break;
1028 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
1029 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1030 break;
1031 default:
1032 // Other modes are only compatible with themselves.
1033 // TODO: consider whether switching between FIFO and MAILBOX is reasonable
1034 break;
1035 }
1036
1037 // Note: this does not generate VK_INCOMPLETE since we're nested inside
1038 // a larger query and there would be no way to determine exactly where it came from.
1039 CopyWithIncomplete(compatibleModes, mode_caps->pPresentModes,
1040 &mode_caps->presentModeCount);
1041 } break;
1042
Chris Forbes06bc0092017-03-16 16:46:05 +13001043 default:
1044 // Ignore all other extension structs
1045 break;
1046 }
1047 }
1048
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001049 return VK_SUCCESS;
Chris Forbes2452cf72017-03-16 16:30:17 +13001050}
1051
1052VKAPI_ATTR
1053VkResult GetPhysicalDeviceSurfaceFormats2KHR(
1054 VkPhysicalDevice physicalDevice,
1055 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
1056 uint32_t* pSurfaceFormatCount,
1057 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001058 ATRACE_CALL();
1059
Chris Forbes2452cf72017-03-16 16:30:17 +13001060 if (!pSurfaceFormats) {
1061 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
1062 pSurfaceInfo->surface,
1063 pSurfaceFormatCount, nullptr);
Trevor David Black929e9cd2022-11-22 04:12:19 +00001064 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001065
Trevor David Black929e9cd2022-11-22 04:12:19 +00001066 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
1067 // after the call.
1068 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
1069 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
1070 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
1071 surface_formats.data());
Trevor David Black2cc44682022-03-09 00:31:38 +00001072
Trevor David Black929e9cd2022-11-22 04:12:19 +00001073 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
1074 return result;
1075 }
Trevor David Black2cc44682022-03-09 00:31:38 +00001076
Trevor David Black929e9cd2022-11-22 04:12:19 +00001077 const auto& driver = GetData(physicalDevice).driver;
1078
1079 // marshal results individually due to stride difference.
1080 uint32_t formats_to_marshal = *pSurfaceFormatCount;
1081 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
1082 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
1083
1084 // Query the compression properties for the surface format
1085 VkSurfaceFormat2KHR* pSurfaceFormat = &pSurfaceFormats[i];
1086 while (pSurfaceFormat->pNext) {
1087 pSurfaceFormat =
1088 reinterpret_cast<VkSurfaceFormat2KHR*>(pSurfaceFormat->pNext);
1089 switch (pSurfaceFormat->sType) {
1090 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT: {
Trevor David Black2cc44682022-03-09 00:31:38 +00001091 VkImageCompressionPropertiesEXT* surfaceCompressionProps =
1092 reinterpret_cast<VkImageCompressionPropertiesEXT*>(
Trevor David Black929e9cd2022-11-22 04:12:19 +00001093 pSurfaceFormat);
Trevor David Black2cc44682022-03-09 00:31:38 +00001094
1095 if (surfaceCompressionProps &&
1096 driver.GetPhysicalDeviceImageFormatProperties2KHR) {
1097 VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = {};
1098 imageFormatInfo.sType =
1099 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
1100 imageFormatInfo.format =
1101 pSurfaceFormats[i].surfaceFormat.format;
1102 imageFormatInfo.pNext = nullptr;
1103
1104 VkImageCompressionControlEXT compressionControl = {};
1105 compressionControl.sType =
1106 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT;
1107 compressionControl.pNext = imageFormatInfo.pNext;
1108
1109 imageFormatInfo.pNext = &compressionControl;
1110
1111 VkImageCompressionPropertiesEXT compressionProps = {};
1112 compressionProps.sType =
1113 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT;
1114 compressionProps.pNext = nullptr;
1115
1116 VkImageFormatProperties2KHR imageFormatProps = {};
1117 imageFormatProps.sType =
1118 VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
1119 imageFormatProps.pNext = &compressionProps;
1120
1121 VkResult compressionRes =
1122 driver.GetPhysicalDeviceImageFormatProperties2KHR(
1123 physicalDevice, &imageFormatInfo,
1124 &imageFormatProps);
1125 if (compressionRes == VK_SUCCESS) {
1126 surfaceCompressionProps->imageCompressionFlags =
1127 compressionProps.imageCompressionFlags;
1128 surfaceCompressionProps
1129 ->imageCompressionFixedRateFlags =
1130 compressionProps.imageCompressionFixedRateFlags;
1131 } else {
1132 return compressionRes;
1133 }
1134 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001135 } break;
1136
1137 default:
1138 // Ignore all other extension structs
1139 break;
Chris Forbes2452cf72017-03-16 16:30:17 +13001140 }
1141 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001142 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001143
1144 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +13001145}
1146
1147VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +13001148VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001149 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +08001150 uint32_t* count,
1151 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001152 ATRACE_CALL();
1153
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001154 int err;
1155 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -06001156 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -06001157 if (surface == VK_NULL_HANDLE) {
1158 const InstanceData& instance_data = GetData(pdev);
1159 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
1160 bool surfaceless_enabled =
1161 instance_data.hook_extensions.test(surfaceless);
1162 if (!surfaceless_enabled) {
1163 return VK_ERROR_SURFACE_LOST_KHR;
1164 }
1165 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
1166 // extension for this function is for
1167 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
1168 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
1169 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
Ian Elliott7e361142022-06-02 10:45:17 -06001170 // surface, and that cannot be relied upon. Therefore, don't return it.
Ian Elliott1ce053f2022-03-16 09:49:53 -06001171 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1172 } else {
1173 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1174
1175 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1176 &query_value);
1177 if (err != android::OK || query_value < 0) {
1178 ALOGE(
1179 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
1180 "value=%d",
1181 strerror(-err), err, query_value);
1182 return VK_ERROR_SURFACE_LOST_KHR;
1183 }
1184 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1185
1186 err =
1187 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
1188 if (err != android::OK || query_value < 0) {
1189 ALOGE(
1190 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
1191 strerror(-err), err, query_value);
1192 return VK_ERROR_SURFACE_LOST_KHR;
1193 }
1194 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
1195
1196 if (min_undequeued_buffers + 1 < max_buffer_count)
1197 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
1198 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1199 }
Chris Forbese8d79a62017-02-22 12:49:18 +13001200
1201 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -07001202 QueryPresentationProperties(pdev, &present_properties);
1203 if (present_properties.sharedImage) {
1204 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1205 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +13001206 }
1207
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001208 return CopyWithIncomplete(present_modes, modes, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001209}
1210
Jesse Halle1b12782015-11-30 11:27:32 -08001211VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001212VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001213 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001214 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001215 ATRACE_CALL();
1216
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001217 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
1218 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1219 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1220 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1221 pDeviceGroupPresentCapabilities->sType);
1222
1223 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1224 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1225
1226 // assume device group of size 1
1227 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1228 pDeviceGroupPresentCapabilities->modes =
1229 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1230
1231 return VK_SUCCESS;
1232}
1233
1234VKAPI_ATTR
1235VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001236 VkDevice,
1237 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001238 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001239 ATRACE_CALL();
1240
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001241 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1242 return VK_SUCCESS;
1243}
1244
1245VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001246VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001247 VkSurfaceKHR surface,
1248 uint32_t* pRectCount,
1249 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001250 ATRACE_CALL();
1251
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001252 if (!pRects) {
1253 *pRectCount = 1;
1254 } else {
1255 uint32_t count = std::min(*pRectCount, 1u);
1256 bool incomplete = *pRectCount < 1;
1257
1258 *pRectCount = count;
1259
1260 if (incomplete) {
1261 return VK_INCOMPLETE;
1262 }
1263
1264 int err;
1265 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1266
1267 int width = 0, height = 0;
1268 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001269 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001270 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1271 strerror(-err), err);
1272 }
1273 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001274 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001275 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1276 strerror(-err), err);
1277 }
1278
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001279 pRects[0].offset.x = 0;
1280 pRects[0].offset.y = 0;
1281 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1282 static_cast<uint32_t>(height)};
1283 }
1284 return VK_SUCCESS;
1285}
1286
Yiwei Zhang533cea92019-06-03 18:43:24 -07001287static void DestroySwapchainInternal(VkDevice device,
1288 VkSwapchainKHR swapchain_handle,
1289 const VkAllocationCallbacks* allocator) {
1290 ATRACE_CALL();
1291
1292 const auto& dispatch = GetData(device).driver;
1293 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1294 if (!swapchain) {
1295 return;
1296 }
1297
1298 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1299 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1300
1301 if (window && swapchain->frame_timestamps_enabled) {
1302 native_window_enable_frame_timestamps(window, false);
1303 }
1304
1305 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +00001306 ReleaseSwapchainImage(device, swapchain->shared, window, -1,
1307 swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001308 }
1309
1310 if (active) {
1311 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1312 }
1313
1314 if (!allocator) {
1315 allocator = &GetData(device).allocator;
1316 }
1317
1318 swapchain->~Swapchain();
1319 allocator->pfnFree(allocator->pUserData, swapchain);
1320}
1321
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001322VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001323VkResult CreateSwapchainKHR(VkDevice device,
1324 const VkSwapchainCreateInfoKHR* create_info,
1325 const VkAllocationCallbacks* allocator,
1326 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001327 ATRACE_CALL();
1328
Jesse Halld7b994a2015-09-07 14:17:37 -07001329 int err;
1330 VkResult result = VK_SUCCESS;
1331
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001332 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1333 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1334 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1335 " oldSwapchain=0x%" PRIx64,
1336 reinterpret_cast<uint64_t>(create_info->surface),
1337 create_info->minImageCount, create_info->imageFormat,
1338 create_info->imageColorSpace, create_info->imageExtent.width,
1339 create_info->imageExtent.height, create_info->imageUsage,
1340 create_info->preTransform, create_info->presentMode,
1341 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1342
Jesse Hall1f91d392015-12-11 16:28:44 -08001343 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001344 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001345
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001346 android::PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001347 GetNativePixelFormat(create_info->imageFormat);
1348 android_dataspace native_dataspace =
1349 GetNativeDataspace(create_info->imageColorSpace);
1350 if (native_dataspace == HAL_DATASPACE_UNKNOWN) {
1351 ALOGE(
1352 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1353 "failed: Unsupported color space",
1354 create_info->imageColorSpace);
1355 return VK_ERROR_INITIALIZATION_FAILED;
1356 }
1357
Jesse Hall42a9eec2016-06-03 12:39:49 -07001358 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001359 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001360 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001361 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001362 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001363 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001364 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001365 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001366 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1367 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001368 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001369 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001370
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001371 Surface& surface = *SurfaceFromHandle(create_info->surface);
1372
Jesse Halldc225072016-05-30 22:40:14 -07001373 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001374 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001375 " because it already has active swapchain 0x%" PRIx64
1376 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1377 reinterpret_cast<uint64_t>(create_info->surface),
1378 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1379 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1380 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1381 }
1382 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1383 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1384
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001385 // -- Reset the native window --
1386 // The native window might have been used previously, and had its properties
1387 // changed from defaults. That will affect the answer we get for queries
1388 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1389 // attempt such queries.
1390
Jesse Halldc225072016-05-30 22:40:14 -07001391 // The native window only allows dequeueing all buffers before any have
1392 // been queued, since after that point at least one is assumed to be in
1393 // non-FREE state at any given time. Disconnecting and re-connecting
1394 // orphans the previous buffers, getting us back to the state where we can
1395 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001396 //
1397 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001398 ANativeWindow* window = surface.window.get();
1399 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1400 ALOGW_IF(err != android::OK, "native_window_api_disconnect failed: %s (%d)",
Jesse Halldc225072016-05-30 22:40:14 -07001401 strerror(-err), err);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001402 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1403 ALOGW_IF(err != android::OK, "native_window_api_connect failed: %s (%d)",
Jesse Halldc225072016-05-30 22:40:14 -07001404 strerror(-err), err);
1405
Nicolas Capens147b7da2021-04-09 14:53:06 -04001406 err =
1407 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001408 if (err != android::OK) {
1409 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1410 strerror(-err), err);
1411 return VK_ERROR_SURFACE_LOST_KHR;
1412 }
1413
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301414 int swap_interval =
1415 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001416 err = window->setSwapInterval(window, swap_interval);
1417 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001418 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1419 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001420 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001421 }
1422
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001423 err = native_window_set_shared_buffer_mode(window, false);
1424 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001425 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1426 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001427 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001428 }
1429
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001430 err = native_window_set_auto_refresh(window, false);
1431 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001432 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1433 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001434 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001435 }
1436
Jesse Halld7b994a2015-09-07 14:17:37 -07001437 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001438
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001439 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001440
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001441 err = native_window_set_buffers_format(window, native_pixel_format);
1442 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001443 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
1444 decodePixelFormat(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001445 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001446 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001447
1448 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
1449 if (native_dataspace != HAL_DATASPACE_ARBITRARY) {
1450 err = native_window_set_buffers_data_space(window, native_dataspace);
1451 if (err != android::OK) {
1452 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1453 native_dataspace, strerror(-err), err);
1454 return VK_ERROR_SURFACE_LOST_KHR;
1455 }
Jesse Hall517274a2016-02-10 00:07:18 -08001456 }
1457
Jesse Hall3dd678a2016-01-08 21:52:01 -08001458 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001459 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001460 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001461 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001462 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1463 create_info->imageExtent.width, create_info->imageExtent.height,
1464 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001465 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001466 }
1467
Jesse Hall178b6962016-02-24 15:39:50 -08001468 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1469 // applied during rendering. native_window_set_transform() expects the
1470 // inverse: the transform the app is requesting that the compositor perform
1471 // during composition. With native windows, pre-transform works by rendering
1472 // with the same transform the compositor is applying (as in Vulkan), but
1473 // then requesting the inverse transform, so that when the compositor does
1474 // it's job the two transforms cancel each other out and the compositor ends
1475 // up applying an identity transform to the app's buffer.
1476 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001477 window, InvertTransformToNative(create_info->preTransform));
1478 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001479 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1480 InvertTransformToNative(create_info->preTransform),
1481 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001482 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001483 }
1484
Jesse Hallf64ca122015-11-03 16:11:10 -08001485 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001486 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1487 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001488 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1489 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001490 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001491 }
1492
Chris Forbes97ef4612017-03-30 19:37:50 +13001493 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001494 if (IsSharedPresentMode(create_info->presentMode)) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001495 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001496 err = native_window_set_shared_buffer_mode(window, true);
1497 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001498 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1499 return VK_ERROR_SURFACE_LOST_KHR;
1500 }
1501 }
1502
1503 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001504 err = native_window_set_auto_refresh(window, true);
1505 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001506 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1507 return VK_ERROR_SURFACE_LOST_KHR;
1508 }
1509 }
1510
Ian Elliott16c443c2021-11-30 17:10:32 -07001511 int query_value;
1512 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1513 &query_value);
1514 if (err != android::OK || query_value < 0) {
1515 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1516 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001517 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001518 }
Ian Elliott16c443c2021-11-30 17:10:32 -07001519 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1520 const auto mailbox_num_images = std::max(3u, create_info->minImageCount);
1521 const auto requested_images =
1522 swap_interval ? create_info->minImageCount : mailbox_num_images;
1523 uint32_t num_images = requested_images - 1 + min_undequeued_buffers;
Chris Forbes2c8fc752017-03-17 11:28:32 +13001524
Ian Elliott5396b702021-12-13 19:32:34 -07001525 // Lower layer insists that we have at least min_undequeued_buffers + 1
1526 // buffers. This is wasteful and we'd like to relax it in the shared case,
1527 // but not all the pieces are in place for that to work yet. Note we only
1528 // lie to the lower layer--we don't want to give the app back a swapchain
1529 // with extra images (which they can't actually use!).
1530 uint32_t min_buffer_count = min_undequeued_buffers + 1;
1531 err = native_window_set_buffer_count(
1532 window, std::max(min_buffer_count, num_images));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001533 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001534 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", num_images,
1535 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001536 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001537 }
1538
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001539 // In shared mode the num_images must be one regardless of how many
1540 // buffers were allocated for the buffer queue.
1541 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1542 num_images = 1;
1543 }
1544
Trevor David Black2cc44682022-03-09 00:31:38 +00001545 void* usage_info_pNext = nullptr;
1546 VkImageCompressionControlEXT image_compression = {};
John Reck97678d42022-08-23 11:24:51 -04001547 uint64_t native_usage = 0;
Trevor David Black2cc44682022-03-09 00:31:38 +00001548 if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
1549 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1550 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1551 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1552 gralloc_usage_info.format = create_info->imageFormat;
1553 gralloc_usage_info.imageUsage = create_info->imageUsage;
1554
1555 // Look through the pNext chain for an image compression control struct
1556 // if one is found AND the appropriate extensions are enabled,
1557 // append it to be the gralloc usage pNext chain
1558 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1559 while (create_infos->pNext) {
1560 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1561 create_infos->pNext);
1562 switch (create_infos->sType) {
1563 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1564 const VkImageCompressionControlEXT* compression_infos =
1565 reinterpret_cast<const VkImageCompressionControlEXT*>(
1566 create_infos);
1567 image_compression = *compression_infos;
1568 image_compression.pNext = nullptr;
1569 usage_info_pNext = &image_compression;
1570 } break;
1571
1572 default:
1573 // Ignore all other info structs
1574 break;
1575 }
1576 }
1577 gralloc_usage_info.pNext = usage_info_pNext;
1578
1579 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1580 device, &gralloc_usage_info, &native_usage);
1581 ATRACE_END();
1582 if (result != VK_SUCCESS) {
1583 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
1584 return VK_ERROR_SURFACE_LOST_KHR;
1585 }
1586 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
Jesse Halld1abd742017-02-09 21:45:51 -08001587 uint64_t consumer_usage, producer_usage;
Yiwei Zhang533cea92019-06-03 18:43:24 -07001588 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
Courtney Goeltzenleuchter894780b2017-04-03 16:11:30 -06001589 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1590 device, create_info->imageFormat, create_info->imageUsage,
1591 swapchain_image_usage, &consumer_usage, &producer_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001592 ATRACE_END();
Chris Forbes8c47dc92017-01-12 11:13:58 +13001593 if (result != VK_SUCCESS) {
1594 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001595 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbes8c47dc92017-01-12 11:13:58 +13001596 }
John Reck97678d42022-08-23 11:24:51 -04001597 native_usage =
Trevor David Black2cc44682022-03-09 00:31:38 +00001598 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
Chris Forbes8c47dc92017-01-12 11:13:58 +13001599 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001600 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
John Reck97678d42022-08-23 11:24:51 -04001601 int32_t legacy_usage = 0;
Jesse Hall1f91d392015-12-11 16:28:44 -08001602 result = dispatch.GetSwapchainGrallocUsageANDROID(
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001603 device, create_info->imageFormat, create_info->imageUsage,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001604 &legacy_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001605 ATRACE_END();
Jesse Hall70f93352015-11-04 09:41:31 -08001606 if (result != VK_SUCCESS) {
1607 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001608 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001609 }
John Reck97678d42022-08-23 11:24:51 -04001610 native_usage = static_cast<uint64_t>(legacy_usage);
Jesse Hall70f93352015-11-04 09:41:31 -08001611 }
John Reck97678d42022-08-23 11:24:51 -04001612 native_usage |= surface.consumer_usage;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001613
1614 bool createProtectedSwapchain = false;
1615 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
1616 createProtectedSwapchain = true;
1617 native_usage |= BufferUsage::PROTECTED;
1618 }
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001619 err = native_window_set_usage(window, native_usage);
1620 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001621 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001622 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001623 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001624
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001625 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001626 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1627 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001628 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1629 strerror(-err), err);
1630 return VK_ERROR_SURFACE_LOST_KHR;
1631 }
1632
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001633 int64_t refresh_duration;
1634 err = native_window_get_refresh_cycle_duration(window, &refresh_duration);
1635 if (err != android::OK) {
1636 ALOGE("native_window_get_refresh_cycle_duration query failed: %s (%d)",
1637 strerror(-err), err);
1638 return VK_ERROR_SURFACE_LOST_KHR;
1639 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001640 // -- Allocate our Swapchain object --
1641 // After this point, we must deallocate the swapchain on error.
1642
Jesse Hall1f91d392015-12-11 16:28:44 -08001643 void* mem = allocator->pfnAllocation(allocator->pUserData,
1644 sizeof(Swapchain), alignof(Swapchain),
1645 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001646 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001647 return VK_ERROR_OUT_OF_HOST_MEMORY;
silence_dogood73597592019-05-23 16:57:37 -07001648 Swapchain* swapchain = new (mem)
1649 Swapchain(surface, num_images, create_info->presentMode,
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00001650 TranslateVulkanToNativeTransform(create_info->preTransform),
1651 refresh_duration);
Chris Forbesb56287a2017-01-12 14:28:58 +13001652 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1653#pragma clang diagnostic push
1654#pragma clang diagnostic ignored "-Wold-style-cast"
1655 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1656#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00001657 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13001658 .usage = swapchain_image_usage,
1659 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001660 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001661#pragma clang diagnostic push
1662#pragma clang diagnostic ignored "-Wold-style-cast"
1663 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1664#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001665 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001666 };
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001667
Jesse Halld7b994a2015-09-07 14:17:37 -07001668 VkImageCreateInfo image_create = {
1669 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001670 .pNext = nullptr,
Nick Desaulnierse745a3e2019-10-18 10:38:45 -07001671 .flags = createProtectedSwapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07001672 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08001673 .format = create_info->imageFormat,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001674 .extent = {
1675 create_info->imageExtent.width,
1676 create_info->imageExtent.height,
1677 1
1678 },
Jesse Halld7b994a2015-09-07 14:17:37 -07001679 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08001680 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08001681 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07001682 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001683 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001684 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08001685 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07001686 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1687 };
1688
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001689 // Note: don't do deferred allocation for shared present modes. There's only one buffer
1690 // involved so very little benefit.
1691 if ((create_info->flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT) &&
1692 !IsSharedPresentMode(create_info->presentMode)) {
1693 // Don't want to touch the underlying gralloc buffers yet;
1694 // instead just create unbound VkImages which will later be bound to memory inside
1695 // AcquireNextImage.
1696 VkImageSwapchainCreateInfoKHR image_swapchain_create = {
1697 .sType = VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR,
1698 .pNext = nullptr,
1699 .swapchain = HandleFromSwapchain(swapchain),
1700 };
1701 image_create.pNext = &image_swapchain_create;
Jesse Halld7b994a2015-09-07 14:17:37 -07001702
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001703 for (uint32_t i = 0; i < num_images; i++) {
1704 Swapchain::Image& img = swapchain->images[i];
1705 img.buffer = nullptr;
1706 img.dequeued = false;
1707
1708 result = dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1709 if (result != VK_SUCCESS) {
1710 ALOGD("vkCreateImage w/ for deferred swapchain image failed: %u", result);
1711 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08001712 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001713 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001714 } else {
1715 // -- Dequeue all buffers and create a VkImage for each --
1716 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07001717
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001718 for (uint32_t i = 0; i < num_images; i++) {
1719 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07001720
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001721 ANativeWindowBuffer* buffer;
1722 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
1723 if (err != android::OK) {
1724 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
1725 switch (-err) {
1726 case ENOMEM:
1727 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
1728 break;
1729 default:
1730 result = VK_ERROR_SURFACE_LOST_KHR;
1731 break;
1732 }
1733 break;
1734 }
1735 img.buffer = buffer;
1736 img.dequeued = true;
1737
1738 image_native_buffer.handle = img.buffer->handle;
1739 image_native_buffer.stride = img.buffer->stride;
1740 image_native_buffer.format = img.buffer->format;
1741 image_native_buffer.usage = int(img.buffer->usage);
1742 android_convertGralloc0To1Usage(int(img.buffer->usage),
1743 &image_native_buffer.usage2.producer,
1744 &image_native_buffer.usage2.consumer);
1745 image_native_buffer.usage3 = img.buffer->usage;
1746 image_create.pNext = &image_native_buffer;
1747
1748 ATRACE_BEGIN("CreateImage");
1749 result =
1750 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1751 ATRACE_END();
1752 if (result != VK_SUCCESS) {
1753 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
1754 break;
1755 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001756 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001757
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001758 // -- Cancel all buffers, returning them to the queue --
1759 // If an error occurred before, also destroy the VkImage and release the
1760 // buffer reference. Otherwise, we retain a strong reference to the buffer.
1761 for (uint32_t i = 0; i < num_images; i++) {
1762 Swapchain::Image& img = swapchain->images[i];
1763 if (img.dequeued) {
1764 if (!swapchain->shared) {
1765 window->cancelBuffer(window, img.buffer.get(),
1766 img.dequeue_fence);
1767 img.dequeue_fence = -1;
1768 img.dequeued = false;
1769 }
Chris Forbese0ced032017-03-30 19:44:15 +13001770 }
Chris Forbes31b85c22018-05-29 15:03:28 -07001771 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001772 }
1773
1774 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001775 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
1776 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07001777 return result;
1778 }
1779
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001780 if (transform_hint != swapchain->pre_transform) {
1781 // Log that the app is not doing pre-rotation.
1782 android::GraphicsEnv::getInstance().setTargetStats(
1783 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
1784 }
1785
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00001786 // Set stats for creating a Vulkan swapchain
1787 android::GraphicsEnv::getInstance().setTargetStats(
1788 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
1789
Jesse Halldc225072016-05-30 22:40:14 -07001790 surface.swapchain_handle = HandleFromSwapchain(swapchain);
1791 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001792 return VK_SUCCESS;
1793}
1794
Jesse Halle1b12782015-11-30 11:27:32 -08001795VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001796void DestroySwapchainKHR(VkDevice device,
1797 VkSwapchainKHR swapchain_handle,
1798 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001799 ATRACE_CALL();
1800
Yiwei Zhang533cea92019-06-03 18:43:24 -07001801 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001802}
1803
Jesse Halle1b12782015-11-30 11:27:32 -08001804VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001805VkResult GetSwapchainImagesKHR(VkDevice,
1806 VkSwapchainKHR swapchain_handle,
1807 uint32_t* count,
1808 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001809 ATRACE_CALL();
1810
Jesse Halld7b994a2015-09-07 14:17:37 -07001811 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07001812 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
1813 "getting images for non-active swapchain 0x%" PRIx64
1814 "; only dequeued image handles are valid",
1815 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07001816 VkResult result = VK_SUCCESS;
1817 if (images) {
1818 uint32_t n = swapchain.num_images;
1819 if (*count < swapchain.num_images) {
1820 n = *count;
1821 result = VK_INCOMPLETE;
1822 }
1823 for (uint32_t i = 0; i < n; i++)
1824 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07001825 *count = n;
1826 } else {
1827 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07001828 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001829 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001830}
1831
Jesse Halle1b12782015-11-30 11:27:32 -08001832VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001833VkResult AcquireNextImageKHR(VkDevice device,
1834 VkSwapchainKHR swapchain_handle,
1835 uint64_t timeout,
1836 VkSemaphore semaphore,
1837 VkFence vk_fence,
1838 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001839 ATRACE_CALL();
1840
Jesse Halld7b994a2015-09-07 14:17:37 -07001841 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001842 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07001843 VkResult result;
1844 int err;
1845
Jesse Halldc225072016-05-30 22:40:14 -07001846 if (swapchain.surface.swapchain_handle != swapchain_handle)
1847 return VK_ERROR_OUT_OF_DATE_KHR;
1848
Chris Forbesc88409c2017-03-30 19:47:37 +13001849 if (swapchain.shared) {
1850 // In shared mode, we keep the buffer dequeued all the time, so we don't
1851 // want to dequeue a buffer here. Instead, just ask the driver to ensure
1852 // the semaphore and fence passed to us will be signalled.
1853 *image_index = 0;
1854 result = GetData(device).driver.AcquireImageANDROID(
1855 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
1856 return result;
1857 }
1858
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001859 const nsecs_t acquire_next_image_timeout =
1860 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
1861 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
1862 // Cache the timeout to avoid the duplicate binder cost.
1863 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
1864 acquire_next_image_timeout);
1865 if (err != android::OK) {
1866 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1867 strerror(-err), err);
1868 return VK_ERROR_SURFACE_LOST_KHR;
1869 }
1870 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
1871 }
1872
Jesse Halld7b994a2015-09-07 14:17:37 -07001873 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08001874 int fence_fd;
1875 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07001876 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001877 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
1878 return timeout ? VK_TIMEOUT : VK_NOT_READY;
1879 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001880 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001881 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001882 }
1883
1884 uint32_t idx;
1885 for (idx = 0; idx < swapchain.num_images; idx++) {
1886 if (swapchain.images[idx].buffer.get() == buffer) {
1887 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08001888 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07001889 break;
1890 }
1891 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001892
1893 // If this is a deferred alloc swapchain, this may be the first time we've
1894 // seen a particular buffer. If so, there should be an empty slot. Find it,
1895 // and bind the gralloc buffer to the VkImage for that slot. If there is no
1896 // empty slot, then we dequeued an unexpected buffer. Non-deferred swapchains
1897 // will also take this path, but will never have an empty slot since we
1898 // populated them all upfront.
1899 if (idx == swapchain.num_images) {
1900 for (idx = 0; idx < swapchain.num_images; idx++) {
1901 if (!swapchain.images[idx].buffer) {
1902 // Note: this structure is technically required for
1903 // Vulkan correctness, even though the driver is probably going
1904 // to use everything from the VkNativeBufferANDROID below.
1905 // This is kindof silly, but it's how we did the ANB
1906 // side of VK_KHR_swapchain v69, so we're stuck with it unless
1907 // we want to go tinkering with the ANB spec some more.
1908 VkBindImageMemorySwapchainInfoKHR bimsi = {
1909 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR,
1910 .pNext = nullptr,
1911 .swapchain = swapchain_handle,
1912 .imageIndex = idx,
1913 };
1914 VkNativeBufferANDROID nb = {
1915 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1916 .pNext = &bimsi,
1917 .handle = buffer->handle,
1918 .stride = buffer->stride,
1919 .format = buffer->format,
1920 .usage = int(buffer->usage),
1921 };
1922 VkBindImageMemoryInfo bimi = {
1923 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO,
1924 .pNext = &nb,
1925 .image = swapchain.images[idx].image,
1926 .memory = VK_NULL_HANDLE,
1927 .memoryOffset = 0,
1928 };
1929 result = GetData(device).driver.BindImageMemory2(device, 1, &bimi);
1930 if (result != VK_SUCCESS) {
1931 // This shouldn't really happen. If it does, something is probably
1932 // unrecoverably wrong with the swapchain and its images. Cancel
1933 // the buffer and declare the swapchain broken.
1934 ALOGE("failed to do deferred gralloc buffer bind");
1935 window->cancelBuffer(window, buffer, fence_fd);
1936 return VK_ERROR_OUT_OF_DATE_KHR;
1937 }
1938
1939 swapchain.images[idx].dequeued = true;
1940 swapchain.images[idx].dequeue_fence = fence_fd;
1941 swapchain.images[idx].buffer = buffer;
1942 break;
1943 }
1944 }
1945 }
1946
1947 // The buffer doesn't match any slot. This shouldn't normally happen, but is
1948 // possible if the bufferqueue is reconfigured behind libvulkan's back. If this
1949 // happens, just declare the swapchain to be broken and the app will recreate it.
Jesse Halld7b994a2015-09-07 14:17:37 -07001950 if (idx == swapchain.num_images) {
1951 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08001952 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001953 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001954 }
1955
1956 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08001957 if (fence_fd != -1) {
1958 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001959 if (fence_clone == -1) {
1960 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
1961 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08001962 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07001963 }
1964 }
1965
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001966 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08001967 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001968 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001969 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
1970 // even if the call fails. We could close it ourselves on failure, but
1971 // that would create a race condition if the driver closes it on a
1972 // failure path: some other thread might create an fd with the same
1973 // number between the time the driver closes it and the time we close
1974 // it. We must assume one of: the driver *always* closes it even on
1975 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08001976 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001977 swapchain.images[idx].dequeued = false;
1978 swapchain.images[idx].dequeue_fence = -1;
1979 return result;
1980 }
1981
1982 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001983 return VK_SUCCESS;
1984}
1985
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001986VKAPI_ATTR
1987VkResult AcquireNextImage2KHR(VkDevice device,
1988 const VkAcquireNextImageInfoKHR* pAcquireInfo,
1989 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001990 ATRACE_CALL();
1991
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001992 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
1993 pAcquireInfo->timeout, pAcquireInfo->semaphore,
1994 pAcquireInfo->fence, pImageIndex);
1995}
1996
Jesse Halldc225072016-05-30 22:40:14 -07001997static VkResult WorstPresentResult(VkResult a, VkResult b) {
1998 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
1999 // (in spec version 1.0.14).
2000 static const VkResult kWorstToBest[] = {
2001 VK_ERROR_DEVICE_LOST,
2002 VK_ERROR_SURFACE_LOST_KHR,
2003 VK_ERROR_OUT_OF_DATE_KHR,
2004 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2005 VK_ERROR_OUT_OF_HOST_MEMORY,
2006 VK_SUBOPTIMAL_KHR,
2007 };
2008 for (auto result : kWorstToBest) {
2009 if (a == result || b == result)
2010 return result;
2011 }
2012 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
2013 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
2014 return a != VK_SUCCESS ? a : b;
2015}
2016
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002017// KHR_incremental_present aspect of QueuePresentKHR
2018static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
2019 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
2020 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
2021 auto const& rect = pRegion->pRectangles[i];
2022 if (rect.layer > 0) {
2023 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
2024 rect.layer);
2025 }
2026
2027 rects[i].left = rect.offset.x;
2028 rects[i].bottom = rect.offset.y;
2029 rects[i].right = rect.offset.x + rect.extent.width;
2030 rects[i].top = rect.offset.y + rect.extent.height;
2031 }
2032 native_window_set_surface_damage(window, rects.data(), rects.size());
2033}
2034
2035// GOOGLE_display_timing aspect of QueuePresentKHR
2036static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
2037 ANativeWindow *window = swapchain.surface.window.get();
2038
2039 // We don't know whether the app will actually use GOOGLE_display_timing
2040 // with a particular swapchain until QueuePresent; enable it on the BQ
2041 // now if needed
2042 if (!swapchain.frame_timestamps_enabled) {
2043 ALOGV("Calling native_window_enable_frame_timestamps(true)");
2044 native_window_enable_frame_timestamps(window, true);
2045 swapchain.frame_timestamps_enabled = true;
2046 }
2047
2048 // Record the nativeFrameId so it can be later correlated to
2049 // this present.
2050 uint64_t nativeFrameId = 0;
2051 int err = native_window_get_next_frame_id(
2052 window, &nativeFrameId);
2053 if (err != android::OK) {
2054 ALOGE("Failed to get next native frame ID.");
2055 }
2056
2057 // Add a new timing record with the user's presentID and
2058 // the nativeFrameId.
2059 swapchain.timing.emplace_back(pTime, nativeFrameId);
2060 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
2061 swapchain.timing.erase(
2062 swapchain.timing.begin(),
2063 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
2064 }
2065 if (pTime->desiredPresentTime) {
2066 ALOGV(
2067 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
2068 pTime->desiredPresentTime);
2069 native_window_set_buffers_timestamp(
2070 window,
2071 static_cast<int64_t>(pTime->desiredPresentTime));
2072 }
2073}
2074
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002075// EXT_swapchain_maintenance1 present mode change
2076static bool SetSwapchainPresentMode(ANativeWindow *window, VkPresentModeKHR mode) {
2077 // There is no dynamic switching between non-shared present modes.
2078 // All we support is switching between demand and continuous refresh.
2079 if (!IsSharedPresentMode(mode))
2080 return true;
2081
2082 int err = native_window_set_auto_refresh(window,
2083 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
2084 if (err != android::OK) {
2085 ALOGE("native_window_set_auto_refresh() failed: %s (%d)",
2086 strerror(-err), err);
2087 return false;
2088 }
2089
2090 return true;
2091}
2092
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002093static VkResult PresentOneSwapchain(
2094 VkQueue queue,
2095 Swapchain& swapchain,
2096 uint32_t imageIndex,
2097 const VkPresentRegionKHR *pRegion,
2098 const VkPresentTimeGOOGLE *pTime,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002099 VkFence presentFence,
2100 const VkPresentModeKHR *pPresentMode,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002101 uint32_t waitSemaphoreCount,
2102 const VkSemaphore *pWaitSemaphores) {
2103
2104 VkDevice device = GetData(queue).driver_device;
2105 const auto& dispatch = GetData(queue).driver;
2106
2107 Swapchain::Image& img = swapchain.images[imageIndex];
2108 VkResult swapchain_result = VK_SUCCESS;
2109 VkResult result;
2110 int err;
2111
2112 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
2113 // wait semaphores, so this doesn't actually work for the multiple swapchain
2114 // case.
2115 int fence = -1;
2116 result = dispatch.QueueSignalReleaseImageANDROID(
2117 queue, waitSemaphoreCount,
2118 pWaitSemaphores, img.image, &fence);
2119 if (result != VK_SUCCESS) {
2120 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
2121 swapchain_result = result;
2122 }
2123 if (img.release_fence >= 0)
2124 close(img.release_fence);
2125 img.release_fence = fence < 0 ? -1 : dup(fence);
2126
2127 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
2128 ANativeWindow* window = swapchain.surface.window.get();
2129 if (swapchain_result == VK_SUCCESS) {
2130
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002131 if (presentFence != VK_NULL_HANDLE) {
2132 int fence_copy = fence < 0 ? -1 : dup(fence);
2133 VkImportFenceFdInfoKHR iffi = {
2134 VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,
2135 nullptr,
2136 presentFence,
2137 VK_FENCE_IMPORT_TEMPORARY_BIT,
2138 VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,
2139 fence_copy,
2140 };
2141 if (VK_SUCCESS != dispatch.ImportFenceFdKHR(device, &iffi) && fence_copy >= 0) {
2142 // ImportFenceFdKHR takes ownership only if it succeeds
2143 close(fence_copy);
2144 }
2145 }
2146
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002147 if (pRegion) {
2148 SetSwapchainSurfaceDamage(window, pRegion);
2149 }
2150 if (pTime) {
2151 SetSwapchainFrameTimestamp(swapchain, pTime);
2152 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002153 if (pPresentMode) {
2154 if (!SetSwapchainPresentMode(window, *pPresentMode))
2155 swapchain_result = WorstPresentResult(swapchain_result,
2156 VK_ERROR_SURFACE_LOST_KHR);
2157 }
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002158
2159 err = window->queueBuffer(window, img.buffer.get(), fence);
2160 // queueBuffer always closes fence, even on error
2161 if (err != android::OK) {
2162 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
2163 swapchain_result = WorstPresentResult(
2164 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2165 } else {
2166 if (img.dequeue_fence >= 0) {
2167 close(img.dequeue_fence);
2168 img.dequeue_fence = -1;
2169 }
2170 img.dequeued = false;
2171 }
2172
2173 // If the swapchain is in shared mode, immediately dequeue the
2174 // buffer so it can be presented again without an intervening
2175 // call to AcquireNextImageKHR. We expect to get the same buffer
2176 // back from every call to dequeueBuffer in this mode.
2177 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
2178 ANativeWindowBuffer* buffer;
2179 int fence_fd;
2180 err = window->dequeueBuffer(window, &buffer, &fence_fd);
2181 if (err != android::OK) {
2182 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
2183 swapchain_result = WorstPresentResult(swapchain_result,
2184 VK_ERROR_SURFACE_LOST_KHR);
2185 } else if (img.buffer != buffer) {
2186 ALOGE("got wrong image back for shared swapchain");
2187 swapchain_result = WorstPresentResult(swapchain_result,
2188 VK_ERROR_SURFACE_LOST_KHR);
2189 } else {
2190 img.dequeue_fence = fence_fd;
2191 img.dequeued = true;
2192 }
2193 }
2194 }
2195 if (swapchain_result != VK_SUCCESS) {
2196 OrphanSwapchain(device, &swapchain);
2197 }
2198 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
2199 // and only when the window's transform/rotation changes. Extent
2200 // changes will not cause VK_SUBOPTIMAL_KHR because of the
2201 // application issues that were caused when the following transform
2202 // change was added.
2203 int window_transform_hint;
2204 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
2205 &window_transform_hint);
2206 if (err != android::OK) {
2207 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
2208 strerror(-err), err);
2209 swapchain_result = WorstPresentResult(
2210 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2211 }
2212 if (swapchain.pre_transform != window_transform_hint) {
2213 swapchain_result =
2214 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
2215 }
2216 } else {
2217 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
2218 img, true);
2219 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
2220 }
2221
2222 return swapchain_result;
2223}
2224
Jesse Halle1b12782015-11-30 11:27:32 -08002225VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002226VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002227 ATRACE_CALL();
2228
Jesse Halld7b994a2015-09-07 14:17:37 -07002229 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
2230 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
2231 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07002232
Jesse Halld7b994a2015-09-07 14:17:37 -07002233 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07002234
Ian Elliottcb351132016-12-13 10:30:40 -07002235 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002236 const VkPresentRegionsKHR* present_regions = nullptr;
2237 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002238 const VkSwapchainPresentFenceInfoEXT* present_fences = nullptr;
2239 const VkSwapchainPresentModeInfoEXT* present_modes = nullptr;
2240
Ian Elliottcb351132016-12-13 10:30:40 -07002241 const VkPresentRegionsKHR* next =
2242 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
2243 while (next) {
2244 switch (next->sType) {
2245 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
2246 present_regions = next;
2247 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07002248 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002249 present_times =
2250 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
2251 break;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002252 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT:
2253 present_fences =
2254 reinterpret_cast<const VkSwapchainPresentFenceInfoEXT*>(next);
2255 break;
2256 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT:
2257 present_modes =
2258 reinterpret_cast<const VkSwapchainPresentModeInfoEXT*>(next);
2259 break;
Ian Elliottcb351132016-12-13 10:30:40 -07002260 default:
2261 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
2262 next->sType);
2263 break;
2264 }
2265 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2266 }
2267 ALOGV_IF(
2268 present_regions &&
2269 present_regions->swapchainCount != present_info->swapchainCount,
2270 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002271 ALOGV_IF(present_times &&
2272 present_times->swapchainCount != present_info->swapchainCount,
2273 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2274 "VkPresentInfo::swapchainCount");
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002275 ALOGV_IF(present_fences &&
2276 present_fences->swapchainCount != present_info->swapchainCount,
2277 "VkSwapchainPresentFenceInfoEXT::swapchainCount != "
2278 "VkPresentInfo::swapchainCount");
2279 ALOGV_IF(present_modes &&
2280 present_modes->swapchainCount != present_info->swapchainCount,
2281 "VkSwapchainPresentModeInfoEXT::swapchainCount != "
2282 "VkPresentInfo::swapchainCount");
2283
Ian Elliottcb351132016-12-13 10:30:40 -07002284 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002285 (present_regions) ? present_regions->pRegions : nullptr;
2286 const VkPresentTimeGOOGLE* times =
2287 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002288
Jesse Halld7b994a2015-09-07 14:17:37 -07002289 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2290 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002291 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002292
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002293 VkResult swapchain_result = PresentOneSwapchain(
2294 queue,
2295 swapchain,
2296 present_info->pImageIndices[sc],
2297 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2298 times ? &times[sc] : nullptr,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002299 present_fences ? present_fences->pFences[sc] : VK_NULL_HANDLE,
2300 present_modes ? &present_modes->pPresentModes[sc] : nullptr,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002301 present_info->waitSemaphoreCount,
2302 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002303
Jesse Halla9e57032015-11-30 01:03:10 -08002304 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002305 present_info->pResults[sc] = swapchain_result;
2306
2307 if (swapchain_result != final_result)
2308 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002309 }
2310
2311 return final_result;
2312}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002313
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002314VKAPI_ATTR
2315VkResult GetRefreshCycleDurationGOOGLE(
2316 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002317 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002318 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002319 ATRACE_CALL();
2320
Ian Elliott62c48c92017-01-20 13:13:20 -07002321 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Alina Kalyakina3d6f3632023-03-22 17:13:47 +00002322 VkResult result = swapchain.get_refresh_duration(pDisplayTimingProperties->refreshDuration);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002323
2324 return result;
2325}
2326
2327VKAPI_ATTR
2328VkResult GetPastPresentationTimingGOOGLE(
2329 VkDevice,
2330 VkSwapchainKHR swapchain_handle,
2331 uint32_t* count,
2332 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002333 ATRACE_CALL();
2334
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002335 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002336 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2337 return VK_ERROR_OUT_OF_DATE_KHR;
2338 }
2339
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002340 ANativeWindow* window = swapchain.surface.window.get();
2341 VkResult result = VK_SUCCESS;
2342
2343 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002344 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002345 native_window_enable_frame_timestamps(window, true);
2346 swapchain.frame_timestamps_enabled = true;
2347 }
2348
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002349 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002350 // Get the latest ready timing count before copying, since the copied
2351 // timing info will be erased in copy_ready_timings function.
2352 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002353 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002354 // Check the *count here against the recorded ready timing count, since
2355 // *count can be overwritten per spec describes.
2356 if (*count < n) {
2357 result = VK_INCOMPLETE;
2358 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002359 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002360 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002361 }
2362
2363 return result;
2364}
2365
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002366VKAPI_ATTR
2367VkResult GetSwapchainStatusKHR(
2368 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002369 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002370 ATRACE_CALL();
2371
Chris Forbes4e18ba82017-01-20 12:50:17 +13002372 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002373 VkResult result = VK_SUCCESS;
2374
Chris Forbes4e18ba82017-01-20 12:50:17 +13002375 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2376 return VK_ERROR_OUT_OF_DATE_KHR;
2377 }
2378
Yiwei Zhanga885c062019-10-24 12:07:57 -07002379 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002380
2381 return result;
2382}
2383
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002384VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002385 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002386 uint32_t swapchainCount,
2387 const VkSwapchainKHR* pSwapchains,
2388 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002389 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002390
2391 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2392 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2393 if (!swapchain)
2394 continue;
2395
2396 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2397
2398 ANativeWindow* window = swapchain->surface.window.get();
2399
2400 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2401 const android_smpte2086_metadata smpteMetdata = {
2402 {vulkanMetadata.displayPrimaryRed.x,
2403 vulkanMetadata.displayPrimaryRed.y},
2404 {vulkanMetadata.displayPrimaryGreen.x,
2405 vulkanMetadata.displayPrimaryGreen.y},
2406 {vulkanMetadata.displayPrimaryBlue.x,
2407 vulkanMetadata.displayPrimaryBlue.y},
2408 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2409 vulkanMetadata.maxLuminance,
2410 vulkanMetadata.minLuminance};
2411 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2412
2413 const android_cta861_3_metadata cta8613Metadata = {
2414 vulkanMetadata.maxContentLightLevel,
2415 vulkanMetadata.maxFrameAverageLightLevel};
2416 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2417 }
2418
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002419 return;
2420}
2421
Yiwei Zhang0f475222019-04-11 19:38:00 -07002422static void InterceptBindImageMemory2(
2423 uint32_t bind_info_count,
2424 const VkBindImageMemoryInfo* bind_infos,
2425 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2426 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2427 out_native_buffers->clear();
2428 out_bind_infos->clear();
2429
2430 if (!bind_info_count)
2431 return;
2432
2433 std::unordered_set<uint32_t> intercepted_indexes;
2434
2435 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2436 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2437 bind_infos[idx].pNext);
2438 while (info &&
2439 info->sType !=
2440 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2441 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2442 info->pNext);
2443 }
2444
2445 if (!info)
2446 continue;
2447
2448 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2449 "swapchain handle must not be NULL");
2450 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2451 ALOG_ASSERT(
2452 info->imageIndex < swapchain->num_images,
2453 "imageIndex must be less than the number of images in swapchain");
2454
2455 ANativeWindowBuffer* buffer =
2456 swapchain->images[info->imageIndex].buffer.get();
2457 VkNativeBufferANDROID native_buffer = {
2458#pragma clang diagnostic push
2459#pragma clang diagnostic ignored "-Wold-style-cast"
2460 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2461#pragma clang diagnostic pop
2462 .pNext = bind_infos[idx].pNext,
2463 .handle = buffer->handle,
2464 .stride = buffer->stride,
2465 .format = buffer->format,
2466 .usage = int(buffer->usage),
2467 };
2468 // Reserve enough space to avoid letting re-allocation invalidate the
2469 // addresses of the elements inside.
2470 out_native_buffers->reserve(bind_info_count);
2471 out_native_buffers->emplace_back(native_buffer);
2472
2473 // Reserve the space now since we know how much is needed now.
2474 out_bind_infos->reserve(bind_info_count);
2475 out_bind_infos->emplace_back(bind_infos[idx]);
2476 out_bind_infos->back().pNext = &out_native_buffers->back();
2477
2478 intercepted_indexes.insert(idx);
2479 }
2480
2481 if (intercepted_indexes.empty())
2482 return;
2483
2484 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2485 if (intercepted_indexes.count(idx))
2486 continue;
2487 out_bind_infos->emplace_back(bind_infos[idx]);
2488 }
2489}
2490
Yiwei Zhang23143102019-04-10 18:24:05 -07002491VKAPI_ATTR
2492VkResult BindImageMemory2(VkDevice device,
2493 uint32_t bindInfoCount,
2494 const VkBindImageMemoryInfo* pBindInfos) {
2495 ATRACE_CALL();
2496
Yiwei Zhang0f475222019-04-11 19:38:00 -07002497 // out_native_buffers is for maintaining the lifecycle of the constructed
2498 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2499 std::vector<VkNativeBufferANDROID> out_native_buffers;
2500 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2501 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2502 &out_bind_infos);
2503 return GetData(device).driver.BindImageMemory2(
2504 device, bindInfoCount,
2505 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002506}
2507
2508VKAPI_ATTR
2509VkResult BindImageMemory2KHR(VkDevice device,
2510 uint32_t bindInfoCount,
2511 const VkBindImageMemoryInfo* pBindInfos) {
2512 ATRACE_CALL();
2513
Yiwei Zhang0f475222019-04-11 19:38:00 -07002514 std::vector<VkNativeBufferANDROID> out_native_buffers;
2515 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2516 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2517 &out_bind_infos);
2518 return GetData(device).driver.BindImageMemory2KHR(
2519 device, bindInfoCount,
2520 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002521}
2522
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002523VKAPI_ATTR
2524VkResult ReleaseSwapchainImagesEXT(VkDevice /*device*/,
2525 const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
2526 ATRACE_CALL();
2527
2528 Swapchain& swapchain = *SwapchainFromHandle(pReleaseInfo->swapchain);
2529 ANativeWindow* window = swapchain.surface.window.get();
2530
2531 // If in shared present mode, don't actually release the image back to the BQ.
2532 // Both sides share it forever.
2533 if (swapchain.shared)
2534 return VK_SUCCESS;
2535
2536 for (uint32_t i = 0; i < pReleaseInfo->imageIndexCount; i++) {
2537 Swapchain::Image& img = swapchain.images[pReleaseInfo->pImageIndices[i]];
2538 window->cancelBuffer(window, img.buffer.get(), img.dequeue_fence);
2539
2540 // cancelBuffer has taken ownership of the dequeue fence
2541 img.dequeue_fence = -1;
2542 // if we're still holding a release fence, get rid of it now
2543 if (img.release_fence >= 0) {
2544 close(img.release_fence);
2545 img.release_fence = -1;
2546 }
2547 img.dequeued = false;
2548 }
2549
2550 return VK_SUCCESS;
2551}
2552
Chia-I Wu62262232016-03-26 07:06:44 +08002553} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002554} // namespace vulkan